"{\"inputs\":\"def GetBase64EncodedHTML5ZipFromUrl(url):\",\"targets\":\"\\\"\\\"\\\"Retrieve zip file from the given URL.\\n \\\"\\\"\\\"\\n response = urllib2.urlopen(url)\\n return base64.b64encode(response.read())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef flavor_create(name, flavor_id=0, ram=0, disk=0, vcpus=1, profile=None):\\n\\n ''''Add a flavor to nova (nova flavor-create). The following parameters are\\n required:\\n name\\n Name of the new flavor (must be first)\\n flavor_id\\n Unique integer ID for the new flavor\\n ram\\n Memory size in MB\\n disk\\n Disk size in GB\\n vcpus\\n Number of vcpus\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' nova.flavor_create myflavor flavor_id=6 ram=4096 disk=10 vcpus=1'\\n '''\",\"targets\":\"conn = _auth(profile)\\n return conn.flavor_create(name, flavor_id, ram, disk, vcpus)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef mac_change_back():\\n\\n ''''Changes MAC address back to what it was before attacks began.'\\n '''\",\"targets\":\"global RUN_CONFIG\\n iface = RUN_CONFIG.ORIGINAL_IFACE_MAC[0]\\n old_mac = RUN_CONFIG.ORIGINAL_IFACE_MAC[1]\\n if ((iface == '') or (old_mac == '')):\\n return\\n print (((GR + ' [+]') + W) + (\\\" changing %s's mac back to %s...\\\" % (((G + iface) + W), ((G + old_mac) + W)))),\\n stdout.flush()\\n call(['ifconfig', iface, 'down'], stdout=DN, stderr=DN)\\n proc = Popen(['ifconfig', iface, 'hw', 'ether', old_mac], stdout=PIPE, stderr=DN)\\n proc.wait()\\n call(['ifconfig', iface, 'up'], stdout=DN, stderr=DN)\\n print 'done'\",\"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 = [_get_cmd(), '--display', name]\\n out = __salt__['cmd.run_all'](cmd, python_shell=False)\\n if ((out['retcode'] > 0) and (out['stderr'] != '')):\\n return False\\n return any((line.startswith(path) for line in out['stdout'].splitlines()))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_exists(name, path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n funcs = {}\\n for plugin in find_plugins():\\n if plugin.template_fields:\\n funcs.update(plugin.template_fields)\\n return funcs\\n\\n\\nWhat's a good function header?\",\"targets\":\"def item_field_getters():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef driver_initiator_data_insert_by_key(context, initiator, namespace, key, value):\\n\\n ''''Updates DriverInitiatorData entry.\\n Sets the value for the specified key within the namespace.\\n If the entry already exists return False, if it inserted successfully\\n return True.'\\n '''\",\"targets\":\"return IMPL.driver_initiator_data_insert_by_key(context, initiator, namespace, key, 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 old = trigger.nick\\n new = Identifier(trigger)\\n if ((old == bot.nick) and (new != bot.nick)):\\n privmsg = (u\\\"Hi, I'm your bot, %s.Something has made my nick change. This can cause some problems for me, and make me do weird things. You'll probably want to restart me, and figure out what made that happen so you can stop it happening again. (Usually, it means you tried to give me a nick that's protected by NickServ.)\\\" % bot.nick)\\n debug_msg = u'Nick changed by server. This can cause unexpected behavior. Please restart the bot.'\\n LOGGER.critical(debug_msg)\\n bot.msg(bot.config.core.owner, privmsg)\\n return\\n for channel in bot.privileges:\\n channel = Identifier(channel)\\n if (old in bot.privileges[channel]):\\n value = bot.privileges[channel].pop(old)\\n bot.privileges[channel][new] = value\\n for channel in bot.channels.values():\\n channel.rename_user(old, new)\\n if (old in bot.users):\\n bot.users[new] = bot.users.pop(old)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@sopel.module.rule(u'.*')\\n@sopel.module.event(u'NICK')\\n@sopel.module.priority(u'high')\\n@sopel.module.thread(False)\\n@sopel.module.unblockable\\ndef track_nicks(bot, trigger):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef cast(context, topic, msg):\\n\\n ''''Invoke a remote method that does not return anything.\\n :param context: Information that identifies the user that has made this\\n request.\\n :param topic: The topic to send the rpc message to. This correlates to the\\n topic argument of\\n openstack.common.rpc.common.Connection.create_consumer()\\n and only applies when the consumer was created with\\n fanout=False.\\n :param msg: This is a dict in the form { \\\"method\\\" : \\\"method_to_invoke\\\",\\n \\\"args\\\" : dict_of_kwargs }\\n :returns: None'\\n '''\",\"targets\":\"return _get_impl().cast(CONF, context, topic, msg)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getmembers(object, predicate=None):\",\"targets\":\"\\\"\\\"\\\"Return all members of an object as (name, value) pairs sorted by name.\\n Optionally, only return members that satisfy a given predicate.\\n \\\"\\\"\\\"\\n results = []\\n for key in dir(object):\\n try:\\n value = getattr(object, key)\\n except AttributeError:\\n continue\\n if ((not predicate) or predicate(value)):\\n results.append((key, value))\\n results.sort()\\n return results\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for flag_name in DECLARED_KEY_FLAGS:\\n gflags.DECLARE_key_flag(flag_name, flag_values=flag_values)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def DeclareKeyFlags(flag_values=FLAGS):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not isinstance(serialized, basestring)):\\n raise TypeError(('serialized must be a string; received %r' % serialized))\\n elif isinstance(serialized, unicode):\\n serialized = serialized.encode('utf8')\\n return entity_pb.Reference(serialized)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _ReferenceFromSerialized(serialized):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def find_maltparser(parser_dirname):\",\"targets\":\"\\\"\\\"\\\"A module to find MaltParser .jar file and its dependencies.\\n \\\"\\\"\\\"\\n if os.path.exists(parser_dirname):\\n _malt_dir = parser_dirname\\n else:\\n _malt_dir = find_dir(parser_dirname, env_vars=(u'MALT_PARSER',))\\n malt_dependencies = [u'', u'', u'']\\n _malt_jars = set(find_jars_within_path(_malt_dir))\\n _jars = set((os.path.split(jar)[1] for jar in _malt_jars))\\n malt_dependencies = set([u'log4j.jar', u'libsvm.jar', u'liblinear-1.8.jar'])\\n assert malt_dependencies.issubset(_jars)\\n assert any(filter((lambda i: (i.startswith(u'maltparser-') and i.endswith(u'.jar'))), _jars))\\n return list(_malt_jars)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef import_set(dset, in_stream, headers=True):\\n\\n ''''Returns dataset from TSV stream.'\\n '''\",\"targets\":\"return import_set_wrapper(dset, in_stream, headers=headers, delimiter=DELIMITER)\",\"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(node_or_string, str):\\n node_or_string = parse(node_or_string, mode='eval')\\n if isinstance(node_or_string, Expression):\\n node_or_string = node_or_string.body\\n def _convert(node):\\n if isinstance(node, (Str, Bytes)):\\n return node.s\\n elif isinstance(node, Num):\\n return node.n\\n elif isinstance(node, Tuple):\\n return tuple(map(_convert, node.elts))\\n elif isinstance(node, List):\\n return list(map(_convert, node.elts))\\n elif isinstance(node, Set):\\n return set(map(_convert, node.elts))\\n elif isinstance(node, Dict):\\n return dict(((_convert(k), _convert(v)) for (k, v) in zip(node.keys, node.values)))\\n elif isinstance(node, NameConstant):\\n return node.value\\n elif (isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)) and isinstance(node.operand, (Num, UnaryOp, BinOp))):\\n operand = _convert(node.operand)\\n if isinstance(node.op, UAdd):\\n return (+ operand)\\n else:\\n return (- operand)\\n elif (isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)) and isinstance(node.right, (Num, UnaryOp, BinOp)) and isinstance(node.left, (Num, UnaryOp, BinOp))):\\n left = _convert(node.left)\\n right = _convert(node.right)\\n if isinstance(node.op, Add):\\n return (left + right)\\n else:\\n return (left - right)\\n raise ValueError(('malformed node or string: ' + repr(node)))\\n return _convert(node_or_string)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def literal_eval(node_or_string):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def list():\",\"targets\":\"\\\"\\\"\\\"Returns the list of all users\\\\ dashboards.\\n \\\"\\\"\\\"\\n url = build_url(RESOURCE)\\n return request('get', url)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef MultiCallCreator(widget):\\n\\n ''''Return a MultiCall class which inherits its methods from the\\n given widget class (for example, Tkinter.Text). This is used\\n instead of a templating mechanism.'\\n '''\",\"targets\":\"if (widget in _multicall_dict):\\n return _multicall_dict[widget]\\n class MultiCall(widget, ):\\n def __init__(self, *args, **kwargs):\\n widget.__init__(self, *args, **kwargs)\\n self.__eventinfo = {}\\n self.__binders = [_binder_classes[i](i, widget, self) for i in range(len(_types))]\\n def bind(self, sequence=None, func=None, add=None):\\n if ((type(sequence) is str) and (len(sequence) > 2) and (sequence[:2] == '<<') and (sequence[(-2):] == '>>')):\\n if (sequence in self.__eventinfo):\\n ei = self.__eventinfo[sequence]\\n if (ei[0] is not None):\\n for triplet in ei[1]:\\n self.__binders[triplet[1]].unbind(triplet, ei[0])\\n ei[0] = func\\n if (ei[0] is not None):\\n for triplet in ei[1]:\\n self.__binders[triplet[1]].bind(triplet, func)\\n else:\\n self.__eventinfo[sequence] = [func, []]\\n return widget.bind(self, sequence, func, add)\\n def unbind(self, sequence, funcid=None):\\n if ((type(sequence) is str) and (len(sequence) > 2) and (sequence[:2] == '<<') and (sequence[(-2):] == '>>') and (sequence in self.__eventinfo)):\\n (func, triplets) = self.__eventinfo[sequence]\\n if (func is not None):\\n for triplet in triplets:\\n self.__binders[triplet[1]].unbind(triplet, func)\\n self.__eventinfo[sequence][0] = None\\n return widget.unbind(self, sequence, funcid)\\n def event_add(self, virtual, *sequences):\\n if (virtual not in self.__eventinfo):\\n self.__eventinfo[virtual] = [None, []]\\n (func, triplets) = self.__eventinfo[virtual]\\n for seq in sequences:\\n triplet = _parse_sequence(seq)\\n if (triplet is None):\\n widget.event_add(self,...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@post('\\/option\\/\\/get')\\ndef option_get(taskid):\",\"targets\":\"\\\"\\\"\\\"Get the value of an option (command line switch) for a certain task ID\\n \\\"\\\"\\\"\\n if (taskid not in DataStore.tasks):\\n logger.warning(('[%s] Invalid task ID provided to option_get()' % taskid))\\n return jsonize({'success': False, 'message': 'Invalid task ID'})\\n option = request.json.get('option', '')\\n if (option in DataStore.tasks[taskid].options):\\n logger.debug(('[%s] Retrieved value for option %s' % (taskid, option)))\\n return jsonize({'success': True, option: DataStore.tasks[taskid].get_option(option)})\\n else:\\n logger.debug(('[%s] Requested value for unknown option %s' % (taskid, option)))\\n return jsonize({'success': False, 'message': 'Unknown option', option: 'not set'})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n box_file = os.path.join(cfg.ROOT_DIR, 'data', 'demo', (image_name + '_boxes.mat'))\\n obj_proposals = sio.loadmat(box_file)['boxes']\\n im_file = os.path.join(cfg.ROOT_DIR, 'data', 'demo', (image_name + '.jpg'))\\n im = cv2.imread(im_file)\\n timer = Timer()\\n timer.tic()\\n (scores, boxes) = im_detect(net, im, obj_proposals)\\n timer.toc()\\n print 'Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time, boxes.shape[0])\\n CONF_THRESH = 0.8\\n NMS_THRESH = 0.3\\n for cls in classes:\\n cls_ind = CLASSES.index(cls)\\n cls_boxes = boxes[:, (4 * cls_ind):(4 * (cls_ind + 1))]\\n cls_scores = scores[:, cls_ind]\\n keep = np.where((cls_scores >= CONF_THRESH))[0]\\n cls_boxes = cls_boxes[keep, :]\\n cls_scores = cls_scores[keep]\\n dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])).astype(np.float32)\\n keep = nms(dets, NMS_THRESH)\\n dets = dets[keep, :]\\n print 'All {} detections with p({} | box) >= {:.1f}'.format(cls, cls, CONF_THRESH)\\n vis_detections(im, cls, dets, thresh=CONF_THRESH)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def demo(net, image_name, classes):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@require_http_methods(['GET', 'POST'])\\n@login_required\\ndef translate(request, document_slug, revision_id=None):\\n\\n ''''Create a new translation of a wiki document.\\n * document_slug is for the default locale\\n * translation is to the request.LANGUAGE_CODE'\\n '''\",\"targets\":\"parent_doc = get_object_or_404(Document, locale=settings.WIKI_DEFAULT_LANGUAGE, slug=document_slug)\\n user = request.user\\n if (settings.WIKI_DEFAULT_LANGUAGE == request.LANGUAGE_CODE):\\n return HttpResponseRedirect(reverse('wiki.edit_document', locale=settings.WIKI_DEFAULT_LANGUAGE, args=[parent_doc.slug]))\\n if (not parent_doc.is_localizable):\\n message = _lazy(u'You cannot translate this document.')\\n return render(request, 'handlers\\/400.html', {'message': message}, status=400)\\n based_on_rev = parent_doc.localizable_or_latest_revision(include_rejected=True)\\n disclose_description = bool(request.GET.get('opendescription'))\\n try:\\n doc = parent_doc.translations.get(locale=request.LANGUAGE_CODE)\\n except Document.DoesNotExist:\\n doc = None\\n disclose_description = True\\n user_has_doc_perm = ((not doc) or doc.allows(user, 'edit'))\\n user_has_rev_perm = ((not doc) or doc.allows(user, 'create_revision'))\\n if ((not user_has_doc_perm) and (not user_has_rev_perm)):\\n raise PermissionDenied\\n draft = DraftRevision.objects.filter(creator=user, document=parent_doc, locale=request.LANGUAGE_CODE)\\n doc_form = rev_form = None\\n base_rev = None\\n restore_draft = None\\n draft_request = (request.GET.get('restore') or request.GET.get('discard'))\\n draft_revision = None\\n if (draft_request and draft.exists()):\\n restore_draft = request.GET.get('restore')\\n discard_draft = request.GET.get('discard')\\n if (discard_draft and (not restore_draft)):\\n draft[0].delete()\\n elif draft.exists():\\n draft_revision = draft[0]\\n if user_has_doc_perm:\\n if restore_draft:\\n doc_initial = _draft_initial_doc(draft_revision=draft[0])\\n else:\\n doc_initial = (_document_form_initial(doc) if doc else None)\\n doc_form = DocumentForm(initial=doc_initial)\\n if user_has_rev_perm:\\n if restore_draft:\\n initial = _draft_initial_rev(draft_revision=draft[0])\\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 def implementer(context, builder, sig, args):\\n (val,) = args\\n input_type = sig.args[0]\\n fpval = context.cast(builder, val, input_type, types.float64)\\n inner_sig = signature(types.float64, types.float64)\\n res = wrapped_impl(context, builder, inner_sig, (fpval,))\\n return context.cast(builder, res, types.float64, sig.return_type)\\n return implementer\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _unary_int_input_wrapper_impl(wrapped_impl):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def is_undefined(obj):\",\"targets\":\"\\\"\\\"\\\"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 \\\"\\\"\\\"\\n from jinja2.runtime import Undefined\\n return isinstance(obj, Undefined)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n global ENGINE\\n global SESSION\\n ENGINE = create_engine('sqlite:\\/\\/')\\n Base.metadata.create_all(ENGINE)\\n session_factory = sessionmaker(bind=ENGINE)\\n SESSION = scoped_session(session_factory)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def setUpModule():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_csrf_token():\",\"targets\":\"\\\"\\\"\\\":rtype: str\\n \\\"\\\"\\\"\\n csrf_token = soup.find(id='csrf_token').attrs['value']\\n return csrf_token\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef DeleteCampaignFeed(client, campaign_feed):\\n\\n ''''Deletes a campaign feed.\\n Args:\\n client: an AdWordsClient instance.\\n campaign_feed: the campaign feed to delete.'\\n '''\",\"targets\":\"campaign_feed_service = client.GetService('CampaignFeedService', 'v201609')\\n operation = {'operand': campaign_feed, 'operator': 'REMOVE'}\\n campaign_feed_service.mutate([operation])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef davis_southern_women_graph():\\n\\n ''''Return Davis Southern women social network.\\n This is a bipartite graph.\\n References\\n .. [1] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South.\\n University of Chicago Press, Chicago, IL.'\\n '''\",\"targets\":\"G = nx.Graph()\\n women = ['Evelyn Jefferson', 'Laura Mandeville', 'Theresa Anderson', 'Brenda Rogers', 'Charlotte McDowd', 'Frances Anderson', 'Eleanor Nye', 'Pearl Oglethorpe', 'Ruth DeSand', 'Verne Sanderson', 'Myra Liddel', 'Katherina Rogers', 'Sylvia Avondale', 'Nora Fayette', 'Helen Lloyd', 'Dorothy Murchison', 'Olivia Carleton', 'Flora Price']\\n G.add_nodes_from(women, bipartite=0)\\n events = ['E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9', 'E10', 'E11', 'E12', 'E13', 'E14']\\n G.add_nodes_from(events, bipartite=1)\\n G.add_edges_from([('Evelyn Jefferson', 'E1'), ('Evelyn Jefferson', 'E2'), ('Evelyn Jefferson', 'E3'), ('Evelyn Jefferson', 'E4'), ('Evelyn Jefferson', 'E5'), ('Evelyn Jefferson', 'E6'), ('Evelyn Jefferson', 'E8'), ('Evelyn Jefferson', 'E9'), ('Laura Mandeville', 'E1'), ('Laura Mandeville', 'E2'), ('Laura Mandeville', 'E3'), ('Laura Mandeville', 'E5'), ('Laura Mandeville', 'E6'), ('Laura Mandeville', 'E7'), ('Laura Mandeville', 'E8'), ('Theresa Anderson', 'E2'), ('Theresa Anderson', 'E3'), ('Theresa Anderson', 'E4'), ('Theresa Anderson', 'E5'), ('Theresa Anderson', 'E6'), ('Theresa Anderson', 'E7'), ('Theresa Anderson', 'E8'), ('Theresa Anderson', 'E9'), ('Brenda Rogers', 'E1'), ('Brenda Rogers', 'E3'), ('Brenda Rogers', 'E4'), ('Brenda Rogers', 'E5'), ('Brenda Rogers', 'E6'), ('Brenda Rogers', 'E7'), ('Brenda Rogers', 'E8'), ('Charlotte McDowd', 'E3'), ('Charlotte McDowd', 'E4'), ('Charlotte McDowd', 'E5'), ('Charlotte McDowd', 'E7'), ('Frances Anderson', 'E3'), ('Frances Anderson', 'E5'), ('Frances Anderson', 'E6'), ('Frances Anderson', 'E8'), ('Eleanor Nye', 'E5'), ('Eleanor Nye', 'E6'), ('Eleanor Nye', 'E7'), ('Eleanor Nye', 'E8'), ('Pearl Oglethorpe', 'E6'), ('Pearl Oglethorpe', 'E8'), ('Pearl Oglethorpe', 'E9'), ('Ruth DeSand', 'E5'), ('Ruth DeSand', 'E7'), ('Ruth DeSand',...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef dump_objects():\\n\\n ''''This is a thread target which every X minutes'\\n '''\",\"targets\":\"from meliae import scanner\\n scanner.dump_all_objects((PROFILING_OUTPUT_FMT % get_filename_fmt()))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def distros_for_filename(filename, metadata=None):\",\"targets\":\"\\\"\\\"\\\"Yield possible egg or source distribution objects based on a filename\\n \\\"\\\"\\\"\\n return distros_for_location(normalize_path(filename), os.path.basename(filename), metadata)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def instance_metadata_delete(context, instance_uuid, key):\",\"targets\":\"\\\"\\\"\\\"Delete the given metadata item.\\n \\\"\\\"\\\"\\n IMPL.instance_metadata_delete(context, instance_uuid, key)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef make_headers(keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None):\\n\\n ''''Shortcuts for generating request headers.\\n :param keep_alive:\\n If ``True``, adds \\\\'connection: keep-alive\\\\' header.\\n :param accept_encoding:\\n Can be a boolean, list, or string.\\n ``True`` translates to \\\\'gzip,deflate\\\\'.\\n List will get joined by comma.\\n String will be used as provided.\\n :param user_agent:\\n String representing the user-agent you want, such as\\n \\\"python-urllib3\\/0.6\\\"\\n :param basic_auth:\\n Colon-separated username:password string for \\\\'authorization: basic ...\\\\'\\n auth header.\\n :param proxy_basic_auth:\\n Colon-separated username:password string for \\\\'proxy-authorization: basic ...\\\\'\\n auth header.\\n :param disable_cache:\\n If ``True``, adds \\\\'cache-control: no-cache\\\\' header.\\n Example::\\n >>> make_headers(keep_alive=True, user_agent=\\\"Batman\\/1.0\\\")\\n {\\\\'connection\\\\': \\\\'keep-alive\\\\', \\\\'user-agent\\\\': \\\\'Batman\\/1.0\\\\'}\\n >>> make_headers(accept_encoding=True)\\n {\\\\'accept-encoding\\\\': \\\\'gzip,deflate\\\\'}'\\n '''\",\"targets\":\"headers = {}\\n if accept_encoding:\\n if isinstance(accept_encoding, str):\\n pass\\n elif isinstance(accept_encoding, list):\\n accept_encoding = ','.join(accept_encoding)\\n else:\\n accept_encoding = ACCEPT_ENCODING\\n headers['accept-encoding'] = accept_encoding\\n if user_agent:\\n headers['user-agent'] = user_agent\\n if keep_alive:\\n headers['connection'] = 'keep-alive'\\n if basic_auth:\\n headers['authorization'] = ('Basic ' + b64encode(b(basic_auth)).decode('utf-8'))\\n if proxy_basic_auth:\\n headers['proxy-authorization'] = ('Basic ' + b64encode(b(proxy_basic_auth)).decode('utf-8'))\\n if disable_cache:\\n headers['cache-control'] = 'no-cache'\\n return headers\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (settings is None):\\n if (not allow_none):\\n raise TypeError(('%s is None, which is not allowed.' % name))\\n return settings\\n if (not isinstance(settings, (tuple, list))):\\n raise TypeError(('%s is not a list.' % name))\\n if (not all((isinstance(i, allowed_type) for i in settings))):\\n type_list = list(set((type(setting) for setting in settings)))\\n raise TypeError((\\\"%s contains types that don't match %s: %s\\\" % (name, allowed_type.__name__, type_list)))\\n return settings\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _CheckListType(settings, allowed_type, name, allow_none=True):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef default_dqn_hparams():\\n\\n ''''Generates the default hparams for RLTuner DQN model.'\\n '''\",\"targets\":\"return tf.contrib.training.HParams(random_action_probability=0.1, store_every_nth=1, train_every_nth=5, minibatch_size=32, discount_rate=0.95, max_experience=100000, target_network_update_rate=0.01)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def decrypt_master_key(master_key_cipher, private_key):\",\"targets\":\"\\\"\\\"\\\"Decrypt a secret key with the provided private RSA key.\\n \\\"\\\"\\\"\\n key = RSA.importKey(private_key)\\n cipher = PKCS1_OAEP.new(key)\\n return cipher.decrypt(master_key_cipher)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_imap_connection(host, port, ssl_required, use_timeout=True):\",\"targets\":\"\\\"\\\"\\\"Return a connection to the IMAP server.\\n The connection is encrypted if the specified port is the default IMAP\\n SSL port (993) or the server supports STARTTLS.\\n IFF neither condition is met and SSL is not required, an insecure connection\\n is returned. Otherwise, an exception is raised.\\n \\\"\\\"\\\"\\n use_ssl = (port == 993)\\n timeout = (120 if use_timeout else None)\\n context = create_default_context()\\n conn = IMAPClient(host, port=port, use_uid=True, ssl=use_ssl, ssl_context=context, timeout=timeout)\\n if (not use_ssl):\\n if conn.has_capability('STARTTLS'):\\n try:\\n conn.starttls(context)\\n except Exception:\\n if (not ssl_required):\\n log.warning('STARTTLS supported but failed for SSL NOT required authentication', exc_info=True)\\n else:\\n raise\\n elif ssl_required:\\n raise SSLNotSupportedError('Required IMAP STARTTLS not supported.')\\n return conn\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _parse_repos(module):\",\"targets\":\"\\\"\\\"\\\"parses the output of zypper --xmlout repos and return a parse repo dictionary\\n \\\"\\\"\\\"\\n cmd = _get_cmd('--xmlout', 'repos')\\n from xml.dom.minidom import parseString as parseXML\\n (rc, stdout, stderr) = module.run_command(cmd, check_rc=False)\\n if (rc == 0):\\n repos = []\\n dom = parseXML(stdout)\\n repo_list = dom.getElementsByTagName('repo')\\n for repo in repo_list:\\n opts = {}\\n for o in REPO_OPTS:\\n opts[o] = repo.getAttribute(o)\\n opts['url'] = repo.getElementsByTagName('url')[0].firstChild.data\\n repos.append(opts)\\n return repos\\n elif (rc == 6):\\n return []\\n else:\\n module.fail_json(msg=('Failed to execute \\\"%s\\\"' % ' '.join(cmd)), rc=rc, stdout=stdout, stderr=stderr)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n options = _get_options(ret=None)\\n new_doc = {}\\n new_doc['views'] = get_valid_salt_views()\\n new_doc['language'] = 'javascript'\\n _response = _request('PUT', ((options['url'] + options['db']) + '\\/_design\\/salt'), 'application\\/json', json.dumps(new_doc))\\n if ('error' in _response):\\n log.warning('Unable to set the salt design document: {0}'.format(_response['error']))\\n return False\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def set_salt_view():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef isnan(a):\\n\\n ''''y = isnan(x) returns True where x is Not-A-Number'\\n '''\",\"targets\":\"return reshape(array([_isnan(i) for i in ravel(a)], 'b'), shape(a))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (shape, (name, inp_gen)) = shape_inp\\n (ng, nc) = backend_pair_dtype\\n np_inp = inp_gen(shape).astype(nc.default_dtype)\\n ndims = len(shape)\\n axes = ([None] + list(itt.permutations(range(ndims), ndims)))\\n axes.remove(tuple(range(ndims)))\\n for (be, ax) in itt.product([ng, nc], axes):\\n be_inp = be.array(np_inp)\\n np_trans = np.transpose(np_inp, axes=ax)\\n be_trans = be.zeros(np_trans.shape)\\n be.copy_transpose(be_inp, be_trans, axes=ax)\\n assert tensors_allclose(np_trans, be_trans)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.mark.hasgpu\\ndef test_copy_transpose(shape_inp, backend_pair_dtype):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_cached_clients():\\n\\n ''''Gets the cached clients dictionary in current context.'\\n '''\",\"targets\":\"if (OAuth.state_key not in current_app.extensions):\\n raise RuntimeError(('%r is not initialized.' % current_app))\\n state = current_app.extensions[OAuth.state_key]\\n return state.cached_clients\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_relative_path(path, reference):\\n\\n ''''Given 2 absolute paths \\\"path\\\" and \\\"reference\\\", compute the path of\\n \\\"path\\\" as relative to the directory \\\"reference\\\".\\n :param path the absolute path to convert to a relative path\\n :param reference an absolute directory path to which the relative\\n path will be computed'\\n '''\",\"targets\":\"assert os.path.isabs(path)\\n assert os.path.isabs(reference)\\n path = os.path.normpath(path)\\n reference = os.path.normpath(reference)\\n path_list = path.split(os.path.sep)[1:]\\n ref_list = reference.split(os.path.sep)[1:]\\n for i in xrange(min(len(path_list), len(ref_list))):\\n if (path_list[i] != ref_list[i]):\\n i -= 1\\n break\\n i += 1\\n del path_list[:i]\\n path_list[:0] = (['..'] * (len(ref_list) - i))\\n return os.path.join(*path_list)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n orig_state = state(name, path=path)\\n try:\\n if attachable(name, path=path):\\n ret = __salt__['container_resource.run'](name, cmd, path=path, container_type=__virtualname__, exec_driver=EXEC_DRIVER, output=output, no_start=no_start, stdin=stdin, python_shell=python_shell, output_loglevel=output_loglevel, ignore_retcode=ignore_retcode, use_vt=use_vt, keep_env=keep_env)\\n else:\\n if (not chroot_fallback):\\n raise CommandExecutionError('{0} is not attachable.'.format(name))\\n rootfs = info(name, path=path).get('rootfs')\\n __context__['cmd.run_chroot.func'] = __salt__['cmd.run']\\n ret = __salt__['cmd.run_chroot'](rootfs, cmd, stdin=stdin, python_shell=python_shell, output_loglevel=output_loglevel, ignore_retcode=ignore_retcode)\\n except Exception:\\n raise\\n finally:\\n new_state = state(name, path=path)\\n if preserve_state:\\n if ((orig_state == 'stopped') and (new_state != 'stopped')):\\n stop(name, path=path)\\n elif ((orig_state == 'frozen') and (new_state != 'frozen')):\\n freeze(name, start=True, path=path)\\n if (output in (None, 'all')):\\n return ret\\n else:\\n return ret[output]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _run(name, cmd, output=None, no_start=False, preserve_state=True, stdin=None, python_shell=True, output_loglevel='debug', use_vt=False, path=None, ignore_retcode=False, chroot_fallback=None, keep_env='http_proxy,https_proxy,no_proxy'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def main():\",\"targets\":\"\\\"\\\"\\\"Main function\\n :return: None\\n \\\"\\\"\\\"\\n module = AnsibleModule(argument_spec=ClcBlueprintPackage.define_argument_spec(), supports_check_mode=True)\\n clc_blueprint_package = ClcBlueprintPackage(module)\\n clc_blueprint_package.process_request()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.assignment_tag\\ndef assignment_unlimited_args(one, two='hi', *args):\\n\\n ''''Expected assignment_unlimited_args __doc__'\\n '''\",\"targets\":\"return ('assignment_unlimited_args - Expected result: %s' % ', '.join([six.text_type(arg) for arg in ([one, two] + list(args))]))\",\"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 settings.USE_L10N:\\n decimal_separator = get_format('DECIMAL_SEPARATOR')\\n if isinstance(value, six.string_types):\\n parts = []\\n if (decimal_separator in value):\\n (value, decimals) = value.split(decimal_separator, 1)\\n parts.append(decimals)\\n if settings.USE_THOUSAND_SEPARATOR:\\n parts.append(value.replace(get_format('THOUSAND_SEPARATOR'), ''))\\n else:\\n parts.append(value)\\n value = '.'.join(reversed(parts))\\n return value\\n\\n\\nWhat's a good function header?\",\"targets\":\"def sanitize_separators(value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None, dump=False):\",\"targets\":\"\\\"\\\"\\\"Bisection algorithm that can be used to perform blind SQL injection\\n on an affected host\\n \\\"\\\"\\\"\\n abortedFlag = False\\n showEta = False\\n partialValue = u''\\n finalValue = None\\n retrievedLength = 0\\n asciiTbl = getCharset(charsetType)\\n threadData = getCurrentThreadData()\\n timeBasedCompare = (kb.technique in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))\\n retVal = hashDBRetrieve(expression, checkConf=True)\\n if retVal:\\n if (PARTIAL_HEX_VALUE_MARKER in retVal):\\n retVal = retVal.replace(PARTIAL_HEX_VALUE_MARKER, '')\\n if (retVal and conf.hexConvert):\\n partialValue = retVal\\n infoMsg = ('resuming partial value: %s' % safecharencode(partialValue))\\n logger.info(infoMsg)\\n elif (PARTIAL_VALUE_MARKER in retVal):\\n retVal = retVal.replace(PARTIAL_VALUE_MARKER, '')\\n if (retVal and (not conf.hexConvert)):\\n partialValue = retVal\\n infoMsg = ('resuming partial value: %s' % safecharencode(partialValue))\\n logger.info(infoMsg)\\n else:\\n infoMsg = ('resumed: %s' % safecharencode(retVal))\\n logger.info(infoMsg)\\n return (0, retVal)\\n try:\\n if conf.predictOutput:\\n kb.partRun = getPartRun()\\n elif conf.api:\\n kb.partRun = getPartRun(alias=False)\\n else:\\n kb.partRun = None\\n if partialValue:\\n firstChar = len(partialValue)\\n elif (('LENGTH(' in expression.upper()) or ('LEN(' in expression.upper())):\\n firstChar = 0\\n elif ((kb.fileReadMode or dump) and (conf.firstChar is not None) and (isinstance(conf.firstChar, int) or (isinstance(conf.firstChar, basestring) and conf.firstChar.isdigit()))):\\n firstChar = (int(conf.firstChar) - 1)\\n if kb.fileReadMode:\\n firstChar *= 2\\n elif ((isinstance(firstChar, basestring) and firstChar.isdigit()) or isinstance(firstChar, int)):\\n firstChar = (int(firstChar) - 1)\\n else:\\n firstChar = 0\\n if...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_archive_formats():\\n\\n ''''Returns a list of supported formats for archiving and unarchiving.\\n Each element of the returned sequence is a tuple (name, description)'\\n '''\",\"targets\":\"formats = [(name, registry[2]) for (name, registry) in _ARCHIVE_FORMATS.items()]\\n formats.sort()\\n return formats\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n data = parse_stories(f.readlines(), only_supporting=only_supporting)\\n flatten = (lambda data: reduce((lambda x, y: (x + y)), data))\\n data = [(flatten(story), q, answer) for (story, q, answer) in data if ((not max_length) or (len(flatten(story)) < max_length))]\\n return data\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_stories(f, only_supporting=False, max_length=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def _merge_data(summary, fault):\\n result = {}\\n uuid = summary['event-id']\\n del summary['event-id']\\n result[uuid] = OrderedDict()\\n result[uuid]['summary'] = summary\\n result[uuid]['fault'] = fault\\n return result\\n result = {}\\n summary = []\\n summary_data = {}\\n fault_data = {}\\n data_key = None\\n for line in output.split('\\\\n'):\\n if line.startswith('-'):\\n if (summary and summary_data and fault_data):\\n result.update(_merge_data(summary_data, fault_data))\\n summary = []\\n summary_data = {}\\n fault_data = {}\\n continue\\n else:\\n continue\\n if (not summary):\\n summary.append(line)\\n continue\\n if (summary and (not summary_data)):\\n summary.append(line)\\n summary_data = _parse_fmdump('\\\\n'.join(summary))[0]\\n continue\\n if (summary and summary_data):\\n if (line.startswith(' ') and data_key):\\n fault_data[data_key] = '{0}\\\\n{1}'.format(fault_data[data_key], line.strip())\\n elif (':' in line):\\n line = line.split(':')\\n data_key = line[0].strip()\\n fault_data[data_key] = ':'.join(line[1:]).strip()\\n if (data_key == 'Platform'):\\n fault_data['Chassis_id'] = fault_data[data_key][fault_data[data_key].index('Chassis_id'):].split(':')[(-1)].strip()\\n fault_data[data_key] = fault_data[data_key][0:fault_data[data_key].index('Chassis_id')].strip()\\n result.update(_merge_data(summary_data, fault_data))\\n return result\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _parse_fmadm_faulty(output):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"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\":\"I wrote the below code\\n\\n from ansible.module_utils import basic\\n args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))\\n with swap_stdin_and_argv(stdin_data=args):\\n basic._ANSIBLE_ARGS = None\\n module = basic.AnsibleModule(argument_spec=dict())\\n _test_one_distribution(module, testcase)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.mark.parametrize('testcase', TESTSETS, ids=(lambda x: x['name']))\\ndef test_distribution_version(testcase):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if isinstance(e, Add):\\n return Add(*[tensor_product_simp(arg) for arg in e.args])\\n elif isinstance(e, Pow):\\n return (tensor_product_simp(e.base) ** e.exp)\\n elif isinstance(e, Mul):\\n return tensor_product_simp_Mul(e)\\n elif isinstance(e, Commutator):\\n return Commutator(*[tensor_product_simp(arg) for arg in e.args])\\n elif isinstance(e, AntiCommutator):\\n return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args])\\n else:\\n return e\\n\\n\\nWhat's a good function header?\",\"targets\":\"def tensor_product_simp(e, **hints):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n finder = DocTestFinder(verbose=verbose, recurse=False)\\n runner = DocTestRunner(verbose=verbose, optionflags=optionflags)\\n for test in finder.find(f, name, globs=globs):\\n runner.run(test, compileflags=compileflags)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def run_docstring_examples(f, globs, verbose=False, name='NoName', compileflags=None, optionflags=0):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_varname(rpc_call):\",\"targets\":\"\\\"\\\"\\\"Transform rpc method into variable name.\\n @newfield example: Example\\n @example: if the name of the rpc method is \\\\p.get_down_rate\\\\, the variable\\n name will be \\\\down_rate\\\\\\n \\\"\\\"\\\"\\n r = re.search('([ptdf]\\\\\\\\.|system\\\\\\\\.|get\\\\\\\\_|is\\\\\\\\_|set\\\\\\\\_)+([^=]*)', rpc_call, re.I)\\n if r:\\n return r.groups()[(-1)]\\n else:\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@nottest\\ndef tests_dir():\\n\\n ''''Return a path to the \\\"tests\\\" directory.'\\n '''\",\"targets\":\"return dirname(abspath(__file__))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_own_device():\\n\\n ''''To allow imports to resolve... the only ugly thing of this code separation.'\\n '''\",\"targets\":\"from ..devices.models import Device\\n return Device.get_own_device()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _ValidateSourcesForMSVSProject(spec, version):\\n\\n ''''Makes sure if duplicate basenames are not specified in the source list.\\n Arguments:\\n spec: The target dictionary containing the properties of the target.\\n version: The VisualStudioVersion object.'\\n '''\",\"targets\":\"assert (not version.UsesVcxproj())\\n if (spec.get('type', None) not in ('static_library', 'shared_library')):\\n return\\n sources = spec.get('sources', [])\\n basenames = {}\\n for source in sources:\\n (name, ext) = os.path.splitext(source)\\n is_compiled_file = (ext in ['.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S'])\\n if (not is_compiled_file):\\n continue\\n basename = os.path.basename(name)\\n basenames.setdefault(basename, []).append(source)\\n error = ''\\n for (basename, files) in basenames.iteritems():\\n if (len(files) > 1):\\n error += (' %s: %s\\\\n' % (basename, ' '.join(files)))\\n if error:\\n print ((('static library %s has several files with the same basename:\\\\n' % spec['target_name']) + error) + 'MSVC08 cannot handle that.')\\n raise GypError('Duplicate basenames in sources section, see list above')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _relative_timestamp(dt):\",\"targets\":\"\\\"\\\"\\\"Format a human readable relative time for timestamps up to 30 days old\\n \\\"\\\"\\\"\\n delta = (datetime.utcnow() - dt)\\n diff = ((delta.microseconds + ((delta.seconds + ((delta.days * 24) * 3600)) * 1000000.0)) \\/ 1000000.0)\\n if (diff < 45):\\n return '{} second{}'.format(int(diff), ('' if (int(diff) == 1) else 's'))\\n elif (diff < 90):\\n return 'a minute'\\n elif (diff < 2700):\\n return '{} minutes'.format(int(max((diff \\/ 60), 2)))\\n elif (diff < 5400):\\n return 'an hour'\\n elif (diff < 79200):\\n return '{} hours'.format(int(max((diff \\/ 3600), 2)))\\n elif (diff < 129600):\\n return 'a day'\\n elif (diff < 2592000):\\n return '{} days'.format(int(max((diff \\/ 86400), 2)))\\n else:\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef call(*popenargs, **kwargs):\\n\\n ''''Run command with arguments. Wait for command to complete, then\\n return the returncode attribute.\\n The arguments are the same as for the Popen constructor. Example:\\n retcode = call([\\\"ls\\\", \\\"-l\\\"])'\\n '''\",\"targets\":\"return Popen(*popenargs, **kwargs).wait()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def allow_lazy(func, *resultclasses):\",\"targets\":\"\\\"\\\"\\\"A decorator that allows a function to be called with one or more lazy\\n arguments. If none of the args are lazy, the function is evaluated\\n immediately, otherwise a __proxy__ is returned that will evaluate the\\n function when needed.\\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)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef dump_all(documents, stream=None, Dumper=Dumper, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding='utf-8', explicit_start=None, explicit_end=None, version=None, tags=None):\\n\\n ''''Serialize a sequence of Python objects into a YAML stream.\\n If stream is None, return the produced string instead.'\\n '''\",\"targets\":\"getvalue = None\\n if (stream is None):\\n if (encoding is None):\\n from StringIO import StringIO\\n else:\\n from cStringIO import StringIO\\n stream = StringIO()\\n getvalue = stream.getvalue\\n dumper = Dumper(stream, default_style=default_style, default_flow_style=default_flow_style, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, encoding=encoding, version=version, tags=tags, explicit_start=explicit_start, explicit_end=explicit_end)\\n try:\\n dumper.open()\\n for data in documents:\\n dumper.represent(data)\\n dumper.close()\\n finally:\\n dumper.dispose()\\n if getvalue:\\n return getvalue()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@require_context\\ndef instance_get_all_by_filters(context, filters, sort_key, sort_dir, limit=None, marker=None, columns_to_join=None, session=None):\",\"targets\":\"\\\"\\\"\\\"Return instances that match all filters. Deleted instances\\n will be returned by default, unless there\\\\s a filter that says\\n otherwise\\n \\\"\\\"\\\"\\n sort_fn = {'desc': desc, 'asc': asc}\\n if (not session):\\n session = get_session()\\n if (columns_to_join is None):\\n columns_to_join = ['info_cache', 'security_groups']\\n manual_joins = ['metadata', 'system_metadata']\\n else:\\n (manual_joins, columns_to_join) = _manual_join_columns(columns_to_join)\\n query_prefix = session.query(models.Instance)\\n for column in columns_to_join:\\n query_prefix = query_prefix.options(joinedload(column))\\n query_prefix = query_prefix.order_by(sort_fn[sort_dir](getattr(models.Instance, sort_key)))\\n filters = filters.copy()\\n if ('changes-since' in filters):\\n changes_since = timeutils.normalize_time(filters['changes-since'])\\n query_prefix = query_prefix.filter((models.Instance.updated_at > changes_since))\\n if ('deleted' in filters):\\n if filters.pop('deleted'):\\n deleted = or_((models.Instance.deleted == models.Instance.id), (models.Instance.vm_state == vm_states.SOFT_DELETED))\\n query_prefix = query_prefix.filter(deleted)\\n else:\\n query_prefix = query_prefix.filter_by(deleted=0).filter((models.Instance.vm_state != vm_states.SOFT_DELETED))\\n if (not context.is_admin):\\n if context.project_id:\\n filters['project_id'] = context.project_id\\n else:\\n filters['user_id'] = context.user_id\\n exact_match_filter_names = ['project_id', 'user_id', 'image_ref', 'vm_state', 'instance_type_id', 'uuid', 'metadata']\\n query_prefix = exact_filter(query_prefix, models.Instance, filters, exact_match_filter_names)\\n query_prefix = regex_filter(query_prefix, models.Instance, filters)\\n if (marker is not None):\\n try:\\n marker = _instance_get_by_uuid(context, marker, session=session)\\n except exception.InstanceNotFound:\\n raise exception.MarkerNotFound(marker)\\n query_prefix = sqlalchemyutils.paginate_query(query_prefix, models.Instance, limit, [sort_key, 'created_at', 'id'], marker=marker, sort_dir=sort_dir)\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef __virtual__():\\n\\n ''''Load load if python-requests is installed.'\\n '''\",\"targets\":\"return __virtualname__\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef list_languages():\\n\\n ''''Lists all available languages.'\\n '''\",\"targets\":\"translate_client = translate.Client()\\n results = translate_client.get_languages()\\n for language in results:\\n print u'{name} ({language})'.format(**language)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n db = current.db\\n qtable = current.s3db.survey_question\\n headers = []\\n happend = headers.append\\n types = []\\n items = []\\n qstn_posn = 0\\n row_len = len(question_id_list)\\n complete_lookup = {}\\n for question_id in question_id_list:\\n answers = survey_getAllAnswersForQuestionInSeries(question_id, series_id)\\n widget_obj = survey_getWidgetFromQuestion(question_id)\\n question = db((qtable.id == question_id)).select(qtable.name, limitby=(0, 1)).first()\\n happend(question.name)\\n types.append(widget_obj.db_type())\\n for answer in answers:\\n complete_id = answer['complete_id']\\n if (complete_id in complete_lookup):\\n row = complete_lookup[complete_id]\\n else:\\n row = len(complete_lookup)\\n complete_lookup[complete_id] = row\\n items.append(([''] * row_len))\\n items[row][qstn_posn] = widget_obj.repr(answer['value'])\\n qstn_posn += 1\\n return (([headers] + [types]) + items)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def buildCompletedList(series_id, question_id_list):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef __virtual__():\\n\\n ''''Only work on Windows'\\n '''\",\"targets\":\"if (__grains__['os'] == 'Windows'):\\n return __virtualname__\\n return (False, 'Module only works on Windows.')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ip_extract():\",\"targets\":\"\\\"\\\"\\\"Return list of IP addresses of this system\\n \\\"\\\"\\\"\\n ips = []\\n program = find_on_path('ip')\\n if program:\\n program = [program, 'a']\\n else:\\n program = find_on_path('ifconfig')\\n if program:\\n program = [program]\\n if (sabnzbd.WIN32 or (not program)):\\n try:\\n info = socket.getaddrinfo(socket.gethostname(), None)\\n except:\\n info = socket.getaddrinfo('localhost', None)\\n for item in info:\\n ips.append(item[4][0])\\n else:\\n p = subprocess.Popen(program, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=None, creationflags=0)\\n output = p.stdout.read()\\n p.wait()\\n for line in output.split('\\\\n'):\\n m = _RE_IP4.search(line)\\n if (not (m and m.group(2))):\\n m = _RE_IP6.search(line)\\n if (m and m.group(2)):\\n ips.append(m.group(2))\\n return ips\",\"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 is_string(item):\\n return (item.upper() not in ('FALSE', 'NO', ''))\\n return bool(item)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def is_truthy(item):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _addHook(klass, name, phase, func):\\n\\n ''''(private) adds a hook to a method on a class'\\n '''\",\"targets\":\"_enhook(klass, name)\\n if (not hasattr(klass, phase(klass, name))):\\n setattr(klass, phase(klass, name), [])\\n phaselist = getattr(klass, phase(klass, name))\\n phaselist.append(func)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef create_inspector(win, ctx, *l):\\n\\n ''''Create an Inspector instance attached to the *ctx* and bound to the\\n Window\\\\'s :meth:`~kivy.core.window.WindowBase.on_keyboard` event for\\n capturing the keyboard shortcut.\\n :Parameters:\\n `win`: A :class:`Window `\\n The application Window to bind to.\\n `ctx`: A :class:`~kivy.uix.widget.Widget` or subclass\\n The Widget to be inspected.'\\n '''\",\"targets\":\"ctx.inspector = Inspector(win=win)\\n win.bind(children=ctx.inspector.on_window_children, on_keyboard=ctx.inspector.keyboard_shortcut)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@docfiller\\ndef convolve1d(input, weights, axis=(-1), output=None, mode='reflect', cval=0.0, origin=0):\\n\\n ''''Calculate a one-dimensional convolution along the given axis.\\n The lines of the array along the given axis are convolved with the\\n given weights.\\n Parameters\\n %(input)s\\n weights : ndarray\\n One-dimensional sequence of numbers.\\n %(axis)s\\n %(output)s\\n %(mode)s\\n %(cval)s\\n %(origin)s\\n Returns\\n convolve1d : ndarray\\n Convolved array with same shape as input\\n Examples\\n >>> from scipy.ndimage import convolve1d\\n >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])\\n array([14, 24, 4, 13, 12, 36, 27, 0])'\\n '''\",\"targets\":\"weights = weights[::(-1)]\\n origin = (- origin)\\n if (not (len(weights) & 1)):\\n origin -= 1\\n return correlate1d(input, weights, axis, output, mode, cval, origin)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n fobj.seek(0, 2)\\n filesize = fobj.tell()\\n if (diff < 0):\\n if ((filesize + diff) < 0):\\n raise ValueError\\n fobj.truncate((filesize + diff))\\n elif (diff > 0):\\n try:\\n while diff:\\n addsize = min(BUFFER_SIZE, diff)\\n fobj.write(('\\\\x00' * addsize))\\n diff -= addsize\\n fobj.flush()\\n except IOError as e:\\n if (e.errno == errno.ENOSPC):\\n fobj.truncate(filesize)\\n raise\\n\\n\\nWhat's a good function header?\",\"targets\":\"def resize_file(fobj, diff, BUFFER_SIZE=(2 ** 16)):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n bom_encoding = u''\\n xml_encoding = u''\\n rfc3023_encoding = u''\\n if (data[:4] == codecs.BOM_UTF32_BE):\\n bom_encoding = u'utf-32be'\\n data = data[4:]\\n elif (data[:4] == codecs.BOM_UTF32_LE):\\n bom_encoding = u'utf-32le'\\n data = data[4:]\\n elif ((data[:2] == codecs.BOM_UTF16_BE) and (data[2:4] != ZERO_BYTES)):\\n bom_encoding = u'utf-16be'\\n data = data[2:]\\n elif ((data[:2] == codecs.BOM_UTF16_LE) and (data[2:4] != ZERO_BYTES)):\\n bom_encoding = u'utf-16le'\\n data = data[2:]\\n elif (data[:3] == codecs.BOM_UTF8):\\n bom_encoding = u'utf-8'\\n data = data[3:]\\n elif (data[:4] == EBCDIC_MARKER):\\n bom_encoding = u'cp037'\\n elif (data[:4] == UTF16BE_MARKER):\\n bom_encoding = u'utf-16be'\\n elif (data[:4] == UTF16LE_MARKER):\\n bom_encoding = u'utf-16le'\\n elif (data[:4] == UTF32BE_MARKER):\\n bom_encoding = u'utf-32be'\\n elif (data[:4] == UTF32LE_MARKER):\\n bom_encoding = u'utf-32le'\\n tempdata = data\\n try:\\n if bom_encoding:\\n tempdata = data.decode(bom_encoding).encode('utf-8')\\n except (UnicodeDecodeError, LookupError):\\n xml_encoding_match = None\\n else:\\n xml_encoding_match = RE_XML_PI_ENCODING.match(tempdata)\\n if xml_encoding_match:\\n xml_encoding = xml_encoding_match.groups()[0].decode('utf-8').lower()\\n if (bom_encoding and (xml_encoding in (u'u16', u'utf-16', u'utf16', u'utf_16', u'u32', u'utf-32', u'utf32', u'utf_32', u'iso-10646-ucs-2', u'iso-10646-ucs-4', u'csucs4', u'csunicode', u'ucs-2', u'ucs-4'))):\\n xml_encoding = bom_encoding\\n http_content_type = (http_headers.get('content-type') or '')\\n (http_content_type, params) = cgi.parse_header(http_content_type)\\n http_encoding = params.get('charset', '').replace(\\\"'\\\", '')\\n if (not isinstance(http_encoding, unicode)):\\n http_encoding = http_encoding.decode('utf-8', 'ignore')\\n acceptable_content_type = 0\\n application_content_types = (u'application\\/xml',...\\n\\nWhat's a good function header?\",\"targets\":\"def convert_to_utf8(http_headers, data):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n lookup_kwargs = {}\\n if object_id:\\n lookup_kwargs[('%s__exact' % model._meta.pk.name)] = object_id\\n elif (slug and slug_field):\\n lookup_kwargs[('%s__exact' % slug_field)] = slug\\n else:\\n raise GenericViewError('Generic view must be called with either an object_id or a slug\\/slug_field.')\\n try:\\n return model.objects.get(**lookup_kwargs)\\n except ObjectDoesNotExist:\\n raise Http404(('No %s found for %s' % (model._meta.verbose_name, lookup_kwargs)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def lookup_object(model, object_id, slug, slug_field):\",\"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 isinstance(values, dict), ('VALUE has invalid type: %s' % type(values))\\n encoded = [str(len(values)).encode('UTF-8'), 'd']\\n extend = encoded.extend\\n for (key, value) in sorted(values.items()):\\n assert (type(key) in mapping), (key, values)\\n assert (type(value) in mapping), (value, values)\\n extend(mapping[type(key)](key, mapping))\\n extend(mapping[type(value)](value, mapping))\\n return encoded\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _a_encode_dictionary(values, mapping):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _add_new_ide_controller_helper(ide_controller_label, controller_key, bus_number):\",\"targets\":\"\\\"\\\"\\\"Helper function for adding new IDE controllers\\n .. versionadded:: 2016.3.0\\n Args:\\n ide_controller_label: label of the IDE controller\\n controller_key: if not None, the controller key to use; otherwise it is randomly generated\\n bus_number: bus number\\n Returns: created device spec for an IDE controller\\n \\\"\\\"\\\"\\n if (controller_key is None):\\n controller_key = randint((-200), 250)\\n ide_spec = vim.vm.device.VirtualDeviceSpec()\\n ide_spec.device = vim.vm.device.VirtualIDEController()\\n ide_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add\\n ide_spec.device.key = controller_key\\n ide_spec.device.busNumber = bus_number\\n ide_spec.device.deviceInfo = vim.Description()\\n ide_spec.device.deviceInfo.label = ide_controller_label\\n ide_spec.device.deviceInfo.summary = ide_controller_label\\n return ide_spec\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n module = AnsibleModule(argument_spec=dict(state=dict(default='present', type='str', choices=['present']), debug=dict(default=False, type='bool'), kubeconfig=dict(default='\\/etc\\/origin\\/master\\/admin.kubeconfig', type='str'), backup=dict(default=True, type='bool'), force=dict(default=False, type='bool'), cert=dict(default=None, type='str'), key=dict(default=None, type='str'), signer_cert=dict(default='\\/etc\\/origin\\/master\\/ca.crt', type='str'), signer_key=dict(default='\\/etc\\/origin\\/master\\/ca.key', type='str'), signer_serial=dict(default='\\/etc\\/origin\\/master\\/ca.serial.txt', type='str'), hostnames=dict(default=[], type='list'), expire_days=dict(default=None, type='int')), supports_check_mode=True)\\n results = CAServerCert.run_ansible(module.params, module.check_mode)\\n if ('failed' in results):\\n return module.fail_json(**results)\\n return module.exit_json(**results)\\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 conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\\n try:\\n ret = conn.get_all_volumes(volume_ids=volume_ids, filters=filters)\\n return (ret if return_objs else [r.id for r in ret])\\n except boto.exception.BotoServerError as e:\\n log.error(e)\\n return []\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_all_volumes(volume_ids=None, filters=None, return_objs=False, 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 flat = (len(input_shape) == 1)\\n train = mx.io.MNISTIter(image='data\\/mnist\\/train-images-idx3-ubyte', label='data\\/mnist\\/train-labels-idx1-ubyte', data_shape=input_shape, batch_size=batch_size, shuffle=False, flat=flat, silent=True)\\n val = mx.io.MNISTIter(image='data\\/mnist\\/t10k-images-idx3-ubyte', label='data\\/mnist\\/t10k-labels-idx1-ubyte', data_shape=input_shape, batch_size=batch_size, shuffle=False, flat=flat, silent=True)\\n return (train, val)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def mnist(batch_size, input_shape):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n merged = list(params)\\n merged.extend(oauth_params)\\n merged.sort(key=(lambda i: i[0].startswith(u'oauth_')))\\n return merged\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _append_params(oauth_params, params):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef libxml2debug(testfunction):\\n\\n ''''Decorator for debugging libxml2 memory leaks inside a function.\\n We\\\\'ve found libxml2 memory leaks are something very weird, and can happen\\n sometimes depending on the order where tests are run. So this decorator\\n enables libxml2 memory leaks debugging only when the environment variable\\n LIBXML2_DEBUGLEAKS is set.'\\n '''\",\"targets\":\"try:\\n import libxml2\\n except ImportError:\\n return testfunction\\n def newfunc(*args, **kwargs):\\n libxml2.debugMemory(1)\\n testfunction(*args, **kwargs)\\n libxml2.cleanupParser()\\n leaked_bytes = libxml2.debugMemory(0)\\n assert (leaked_bytes == 0), ('libxml2 memory leak detected: %d bytes' % leaked_bytes)\\n if ('LIBXML2_DEBUGLEAKS' in os.environ):\\n return newfunc\\n else:\\n return testfunction\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_level_tags():\\n\\n ''''Returns the message level tags.'\\n '''\",\"targets\":\"level_tags = constants.DEFAULT_TAGS.copy()\\n level_tags.update(getattr(settings, 'MESSAGE_TAGS', {}))\\n return level_tags\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def main():\",\"targets\":\"\\\"\\\"\\\"This is the mainline.\\n It first invokes the pipermail archiver to add the message to the archive,\\n then calls the function above to do whatever with the archived message\\n after it\\\\s URL and path are known.\\n \\\"\\\"\\\"\\n listname = sys.argv[2]\\n hostname = sys.argv[1]\\n mlist = MailList.MailList(listname, lock=False)\\n f = StringIO(sys.stdin.read())\\n msg = email.message_from_file(f, Message.Message)\\n h = HyperArch.HyperArchive(mlist)\\n sequence = h.sequence\\n h.processUnixMailbox(f)\\n f.close()\\n archive = h.archive\\n msgno = ('%06d' % sequence)\\n filename = (msgno + '.html')\\n filepath = os.path.join(h.basedir, archive, filename)\\n h.close()\\n url = ('%s%s\\/%s' % (mlist.GetBaseArchiveURL(), archive, filename))\\n ext_process(listname, hostname, url, filepath, msg)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@step('I send a test email with the following set:$')\\ndef mail_send_yaml(step):\\n\\n ''''Send a test email from loaded yaml'\\n '''\",\"targets\":\"mail_send(yaml.load(step.multiline))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dataset_purge(context, data_dict):\",\"targets\":\"\\\"\\\"\\\"Purge a dataset.\\n .. warning:: Purging a dataset cannot be undone!\\n Purging a database completely removes the dataset from the CKAN database,\\n whereas deleting a dataset simply marks the dataset as deleted (it will no\\n longer show up in the front-end, but is still in the db).\\n You must be authorized to purge the dataset.\\n :param id: the name or id of the dataset to be purged\\n :type id: string\\n \\\"\\\"\\\"\\n from sqlalchemy import or_\\n model = context['model']\\n id = _get_or_bust(data_dict, 'id')\\n pkg = model.Package.get(id)\\n context['package'] = pkg\\n if (pkg is None):\\n raise NotFound('Dataset was not found')\\n _check_access('dataset_purge', context, data_dict)\\n members = model.Session.query(model.Member).filter((model.Member.table_id == pkg.id)).filter((model.Member.table_name == 'package'))\\n if (members.count() > 0):\\n for m in members.all():\\n m.purge()\\n for r in model.Session.query(model.PackageRelationship).filter(or_((model.PackageRelationship.subject_package_id == pkg.id), (model.PackageRelationship.object_package_id == pkg.id))).all():\\n r.purge()\\n pkg = model.Package.get(id)\\n pkg.purge()\\n model.repo.commit_and_remove()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.inclusion_tag('customer\\/history\\/recently_viewed_products.html', takes_context=True)\\ndef recently_viewed_products(context, current_product=None):\\n\\n ''''Inclusion tag listing the most recently viewed products'\\n '''\",\"targets\":\"request = context['request']\\n products = history.get(request)\\n if current_product:\\n products = [p for p in products if (p != current_product)]\\n return {'products': products, 'request': request}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_organization(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(organization_id)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@utils.arg('server', metavar='', help=_('Name or ID of server.'))\\ndef do_volume_attachments(cs, args):\\n\\n ''''List all the volumes attached to a server.'\\n '''\",\"targets\":\"volumes = cs.volumes.get_server_volumes(_find_server(cs, args.server).id)\\n _translate_volume_attachments_keys(volumes)\\n utils.print_list(volumes, ['ID', 'DEVICE', 'SERVER ID', 'VOLUME ID'])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n get = re.findall('source ip [0-9]+.[0-9]+.[0-9]+.[0-9]+ vpn-instance (\\\\\\\\S+)', config)\\n if (not get):\\n return None\\n else:\\n return get[0]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_dfs_source_vpn(config):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef import_key(extern_key, passphrase=None):\\n\\n ''''Import a DSA key (public or private).\\n :Parameters:\\n extern_key : (byte) string\\n The DSA key to import.\\n An DSA *public* key can be in any of the following formats:\\n - X.509 certificate (binary or PEM format)\\n - X.509 ``subjectPublicKeyInfo`` (binary or PEM)\\n - OpenSSH (one line of text, see `RFC4253`_)\\n A DSA *private* key can be in any of the following formats:\\n - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``\\n DER SEQUENCE (binary or PEM encoding)\\n - OpenSSL\\/OpenSSH (binary or PEM)\\n For details about the PEM encoding, see `RFC1421`_\\/`RFC1423`_.\\n The private key may be encrypted by means of a certain pass phrase\\n either at the PEM level or at the PKCS#8 level.\\n passphrase : string\\n In case of an encrypted private key, this is the pass phrase\\n from which the decryption key is derived.\\n :Return: A DSA key object (`DsaKey`).\\n :Raise ValueError:\\n When the given key cannot be parsed (possibly because\\n the pass phrase is wrong).\\n .. _RFC1421: http:\\/\\/www.ietf.org\\/rfc\\/rfc1421.txt\\n .. _RFC1423: http:\\/\\/www.ietf.org\\/rfc\\/rfc1423.txt\\n .. _RFC4253: http:\\/\\/www.ietf.org\\/rfc\\/rfc4253.txt\\n .. _PKCS#8: http:\\/\\/www.ietf.org\\/rfc\\/rfc5208.txt'\\n '''\",\"targets\":\"extern_key = tobytes(extern_key)\\n if (passphrase is not None):\\n passphrase = tobytes(passphrase)\\n if extern_key.startswith(b('-----')):\\n (der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)\\n if enc_flag:\\n passphrase = None\\n return _import_key_der(der, passphrase, None)\\n if extern_key.startswith(b('ssh-dss ')):\\n keystring = binascii.a2b_base64(extern_key.split(b(' '))[1])\\n keyparts = []\\n while (len(keystring) > 4):\\n length = struct.unpack('>I', keystring[:4])[0]\\n keyparts.append(keystring[4:(4 + length)])\\n keystring = keystring[(4 + length):]\\n if (keyparts[0] == b('ssh-dss')):\\n tup = [Integer.from_bytes(keyparts[x]) for x in (4, 3, 1, 2)]\\n return construct(tup)\\n if (bord(extern_key[0]) == 48):\\n return _import_key_der(extern_key, passphrase, None)\\n raise ValueError('DSA key format is not supported')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def figure_nobar(*args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Make matplotlib figure with no toolbar.\\n \\\"\\\"\\\"\\n from matplotlib import rcParams, pyplot as plt\\n old_val = rcParams['toolbar']\\n try:\\n rcParams['toolbar'] = 'none'\\n fig = plt.figure(*args, **kwargs)\\n cbs = list(fig.canvas.callbacks.callbacks['key_press_event'].keys())\\n for key in cbs:\\n fig.canvas.callbacks.disconnect(key)\\n finally:\\n rcParams['toolbar'] = old_val\\n return fig\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n i18n = video_descriptor.runtime.service(video_descriptor, 'i18n')\\n _ = i18n.ugettext\\n subs = get_transcripts_from_youtube(youtube_id, settings, i18n)\\n save_subs_to_store(subs, youtube_id, video_descriptor)\\n log.info('Transcripts for youtube_id %s for 1.0 speed are downloaded and saved.', youtube_id)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def download_youtube_subs(youtube_id, video_descriptor, settings):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n output = []\\n app_models = get_models(app)\\n for model in app_models:\\n output.extend(custom_sql_for_model(model, style, connection))\\n return output\\n\\n\\nWhat's a good function header?\",\"targets\":\"def sql_custom(app, style, connection):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef LoadPagespeedEntry(pagespeed_entry, open_fn=None):\\n\\n ''''Load a yaml file or string and return a PagespeedEntry.\\n Args:\\n pagespeed_entry: The contents of a pagespeed entry from a yaml file\\n as a string, or an open file object.\\n open_fn: Function for opening files. Unused.\\n Returns:\\n A PagespeedEntry instance which represents the contents of the parsed yaml.\\n Raises:\\n yaml_errors.EventError: An error occured while parsing the yaml.\\n MalformedPagespeedConfiguration: The configuration is parseable but invalid.'\\n '''\",\"targets\":\"builder = yaml_object.ObjectBuilder(PagespeedEntry)\\n handler = yaml_builder.BuilderHandler(builder)\\n listener = yaml_listener.EventListener(handler)\\n listener.Parse(pagespeed_entry)\\n parsed_yaml = handler.GetResults()\\n if (not parsed_yaml):\\n return PagespeedEntry()\\n if (len(parsed_yaml) > 1):\\n raise MalformedPagespeedConfiguration('Multiple configuration sections in the yaml')\\n return parsed_yaml[0]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_checkbox(state):\\n\\n ''''Get checkbox tag.'\\n '''\",\"targets\":\"return (u' ' % (u' checked' if (state.lower() == u'x') else u''))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef dump_all(documents, stream=None, Dumper=Dumper, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding='utf-8', explicit_start=None, explicit_end=None, version=None, tags=None):\\n\\n ''''Serialize a sequence of Python objects into a YAML stream.\\n If stream is None, return the produced string instead.'\\n '''\",\"targets\":\"getvalue = None\\n if (stream is None):\\n if (encoding is None):\\n from StringIO import StringIO\\n else:\\n from cStringIO import StringIO\\n stream = StringIO()\\n getvalue = stream.getvalue\\n dumper = Dumper(stream, default_style=default_style, default_flow_style=default_flow_style, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, encoding=encoding, version=version, tags=tags, explicit_start=explicit_start, explicit_end=explicit_end)\\n try:\\n dumper.open()\\n for data in documents:\\n dumper.represent(data)\\n dumper.close()\\n finally:\\n dumper.dispose()\\n if getvalue:\\n return getvalue()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n existing = (existing or [])\\n if changes:\\n for c in changes:\\n if (len([x for x in existing if (x.key == c.key)]) > 0):\\n extraConf = [x for x in existing if (x.key == c.key)][0]\\n extraConf.value = c.value\\n else:\\n existing.append(c)\\n return existing\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _merge_extraconfig(existing, changes):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _is_pid_running_on_unix(pid):\\n\\n ''''Check if a process is running on unix systems based on the pid.'\\n '''\",\"targets\":\"try:\\n os.kill(pid, 0)\\n except OSError:\\n return False\\n else:\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _upload_media(task_handle, event_id, base_path):\\n\\n ''''Actually uploads the resources'\\n '''\",\"targets\":\"global UPLOAD_QUEUE\\n total = len(UPLOAD_QUEUE)\\n ct = 0\\n for i in UPLOAD_QUEUE:\\n ct += 1\\n update_state(task_handle, ('Uploading media (%d\\/%d)' % (ct, total)))\\n (name, dao) = i['srv']\\n id_ = i['id']\\n if (name == 'event'):\\n item = dao.get(event_id)\\n else:\\n item = dao.get(event_id, id_)\\n field = i['field']\\n path = getattr(item, field)\\n if path.startswith('\\/'):\\n path = (base_path + path)\\n if os.path.isfile(path):\\n filename = path.rsplit('\\/', 1)[1]\\n file = UploadedFile(path, filename)\\n else:\\n file = ''\\n else:\\n try:\\n filename = UPLOAD_PATHS[name][field].rsplit('\\/', 1)[1]\\n if is_downloadable(path):\\n r = requests.get(path, allow_redirects=True)\\n file = UploadedMemory(r.content, filename)\\n else:\\n file = None\\n except:\\n file = None\\n if (file is None):\\n continue\\n try:\\n if (file == ''):\\n raise Exception()\\n key = UPLOAD_PATHS[name][field]\\n if (name == 'event'):\\n key = key.format(event_id=event_id)\\n else:\\n key = key.format(event_id=event_id, id=id_)\\n print key\\n new_url = upload(file, key)\\n except Exception:\\n print traceback.format_exc()\\n new_url = None\\n setattr(item, field, new_url)\\n save_to_db(item, msg='Url updated')\\n UPLOAD_QUEUE = []\\n return\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (X1, W1) = dXW1\\n (X2, W2) = dXW2\\n X = numpy.r_[(X1, X2)]\\n W = numpy.r_[(W1, W2)]\\n sort_ind = numpy.argsort(X)\\n (X, W) = (X[sort_ind], W[sort_ind])\\n (unique, uniq_index) = numpy.unique(X, return_index=True)\\n spans = numpy.diff(numpy.r_[(uniq_index, len(X))])\\n W = [numpy.sum(W[start:(start + span)]) for (start, span) in zip(uniq_index, spans)]\\n W = numpy.array(W)\\n assert (W.shape[0] == unique.shape[0])\\n return (unique, W)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def dist_sum(dXW1, dXW2):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def do_reverse(value):\",\"targets\":\"\\\"\\\"\\\"Reverse the object or return an iterator the iterates over it the other\\n way round.\\n \\\"\\\"\\\"\\n if isinstance(value, basestring):\\n return value[::(-1)]\\n try:\\n return reversed(value)\\n except TypeError:\\n try:\\n rv = list(value)\\n rv.reverse()\\n return rv\\n except TypeError:\\n raise FilterArgumentError('argument must be iterable')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@deprecated\\ndef get_master():\",\"targets\":\"\\\"\\\"\\\"Get an XMLRPC handle to the Master. It is recommended to use the\\n `rosgraph.masterapi` library instead, as it provides many\\n conveniences.\\n @return: XML-RPC proxy to ROS master\\n @rtype: xmlrpclib.ServerProxy\\n @raises ValueError if master URI is invalid\\n \\\"\\\"\\\"\\n try:\\n import xmlrpc.client as xmlrpcclient\\n except ImportError:\\n import xmlrpclib as xmlrpcclient\\n uri = os.environ['ROS_MASTER_URI']\\n return xmlrpcclient.ServerProxy(uri)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef bw_silverman(x, kernel=None):\\n\\n ''''Silverman\\\\'s Rule of Thumb\\n Parameters\\n x : array-like\\n Array for which to get the bandwidth\\n kernel : CustomKernel object\\n Unused\\n Returns\\n bw : float\\n The estimate of the bandwidth\\n Notes\\n Returns .9 * A * n ** (-1\\/5.) where ::\\n A = min(std(x, ddof=1), IQR\\/1.349)\\n IQR = np.subtract.reduce(np.percentile(x, [75,25]))\\n References\\n Silverman, B.W. (1986) `Density Estimation.`'\\n '''\",\"targets\":\"A = _select_sigma(x)\\n n = len(x)\\n return ((0.9 * A) * (n ** (-0.2)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef log_to_stderr(level=None):\\n\\n ''''Turn on logging and add a handler which prints to stderr'\\n '''\",\"targets\":\"global _log_to_stderr\\n import logging\\n logger = get_logger()\\n formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)\\n handler = logging.StreamHandler()\\n handler.setFormatter(formatter)\\n logger.addHandler(handler)\\n if level:\\n logger.setLevel(level)\\n _log_to_stderr = True\\n return _logger\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef inline_functions(dsk, output, fast_functions=None, inline_constants=False, dependencies=None):\\n\\n ''''Inline cheap functions into larger operations\\n Examples\\n >>> dsk = {\\\\'out\\\\': (add, \\\\'i\\\\', \\\\'d\\\\'), # doctest: +SKIP\\n ... \\\\'i\\\\': (inc, \\\\'x\\\\'),\\n ... \\\\'d\\\\': (double, \\\\'y\\\\'),\\n ... \\\\'x\\\\': 1, \\\\'y\\\\': 1}\\n >>> inline_functions(dsk, [], [inc]) # doctest: +SKIP\\n {\\\\'out\\\\': (add, (inc, \\\\'x\\\\'), \\\\'d\\\\'),\\n \\\\'d\\\\': (double, \\\\'y\\\\'),\\n \\\\'x\\\\': 1, \\\\'y\\\\': 1}\\n Protect output keys. In the example below ``i`` is not inlined because it\\n is marked as an output key.\\n >>> inline_functions(dsk, [\\\\'i\\\\', \\\\'out\\\\'], [inc, double]) # doctest: +SKIP\\n {\\\\'out\\\\': (add, \\\\'i\\\\', (double, \\\\'y\\\\')),\\n \\\\'i\\\\': (inc, \\\\'x\\\\'),\\n \\\\'x\\\\': 1, \\\\'y\\\\': 1}'\\n '''\",\"targets\":\"if (not fast_functions):\\n return dsk\\n output = set(output)\\n fast_functions = set(fast_functions)\\n if (dependencies is None):\\n dependencies = {k: get_dependencies(dsk, k) for k in dsk}\\n dependents = reverse_dict(dependencies)\\n keys = [k for (k, v) in dsk.items() if (istask(v) and functions_of(v).issubset(fast_functions) and dependents[k] and (k not in output))]\\n if keys:\\n dsk = inline(dsk, keys, inline_constants=inline_constants, dependencies=dependencies)\\n for k in keys:\\n del dsk[k]\\n return dsk\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not isinstance(headers, httplib.HTTPMessage)):\\n raise TypeError('expected httplib.Message, got {0}.'.format(type(headers)))\\n defects = getattr(headers, 'defects', None)\\n get_payload = getattr(headers, 'get_payload', None)\\n unparsed_data = None\\n if get_payload:\\n unparsed_data = get_payload()\\n if (defects or unparsed_data):\\n raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def assert_header_parsing(headers):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _flatten_artist_credit(credit):\\n\\n ''''Given a list representing an ``artist-credit`` block, flatten the\\n data into a triple of joined artist name strings: canonical, sort, and\\n credit.'\\n '''\",\"targets\":\"artist_parts = []\\n artist_sort_parts = []\\n artist_credit_parts = []\\n for el in credit:\\n if isinstance(el, six.string_types):\\n artist_parts.append(el)\\n artist_credit_parts.append(el)\\n artist_sort_parts.append(el)\\n else:\\n alias = _preferred_alias(el['artist'].get('alias-list', ()))\\n if alias:\\n cur_artist_name = alias['alias']\\n else:\\n cur_artist_name = el['artist']['name']\\n artist_parts.append(cur_artist_name)\\n if alias:\\n artist_sort_parts.append(alias['sort-name'])\\n elif ('sort-name' in el['artist']):\\n artist_sort_parts.append(el['artist']['sort-name'])\\n else:\\n artist_sort_parts.append(cur_artist_name)\\n if ('name' in el):\\n artist_credit_parts.append(el['name'])\\n else:\\n artist_credit_parts.append(cur_artist_name)\\n return (''.join(artist_parts), ''.join(artist_sort_parts), ''.join(artist_credit_parts))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def exp(mat, target=None):\",\"targets\":\"\\\"\\\"\\\"Apply the exponential function to each element of the matrix mat.\\n \\\"\\\"\\\"\\n if (not target):\\n target = mat\\n err_code = _cudamat.apply_exp(mat.p_mat, target.p_mat)\\n if err_code:\\n raise generate_exception(err_code)\\n return target\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n image_dir = 'result_images'\\n _subdirs = (name for name in os.listdir(image_dir) if os.path.isdir(os.path.join(image_dir, name)))\\n failed_rows = []\\n body_sections = []\\n for subdir in sorted(_subdirs):\\n if (subdir == 'test_compare_images'):\\n continue\\n pictures = defaultdict(dict)\\n for file in os.listdir(os.path.join(image_dir, subdir)):\\n if os.path.isdir(os.path.join(image_dir, subdir, file)):\\n continue\\n (fn, fext) = os.path.splitext(file)\\n if (fext != '.png'):\\n continue\\n if ('-failed-diff' in fn):\\n pictures[fn[:(-12)]]['f'] = '\\/'.join((subdir, file))\\n elif ('-expected' in fn):\\n pictures[fn[:(-9)]]['e'] = '\\/'.join((subdir, file))\\n else:\\n pictures[fn]['c'] = '\\/'.join((subdir, file))\\n subdir_rows = []\\n for (name, test) in sorted(pictures.items()):\\n expected_image = test.get('e', '')\\n actual_image = test.get('c', '')\\n if ('f' in test):\\n status = ' (failed)'\\n failed = 'diff<\\/a>'.format(test['f'])\\n current = linked_image_template.format(actual_image)\\n failed_rows.append(row_template.format(name, '', current, expected_image, failed))\\n elif ('c' not in test):\\n status = ' (failed)'\\n failed = '--'\\n current = '(Failure in test, no image produced)'\\n failed_rows.append(row_template.format(name, '', current, expected_image, failed))\\n else:\\n status = ' (passed)'\\n failed = '--'\\n current = linked_image_template.format(actual_image)\\n subdir_rows.append(row_template.format(name, status, current, expected_image, failed))\\n body_sections.append(subdir_template.format(subdir=subdir, rows='\\\\n'.join(subdir_rows)))\\n if failed_rows:\\n failed =...\\n\\nWhat's a good function header?\",\"targets\":\"def run(show_browser=True):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def host_is_ipv6(hostname):\",\"targets\":\"\\\"\\\"\\\"Detect (naively) if the hostname is an IPV6 host.\\n Return a boolean.\\n \\\"\\\"\\\"\\n if ((not hostname) or (not isinstance(hostname, str))):\\n return False\\n if hostname.startswith('['):\\n return True\\n if (len(hostname.split(':')) > 2):\\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 con = lite.connect('db.db')\\n with con:\\n cur = con.cursor()\\n cur.execute(\\\"SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'XXE'\\\")\\n tbl_exists = cur.fetchone()[0]\\n if (tbl_exists == 0):\\n cur.execute('CREATE TABLE XXE(payload TEXT, ts timestamp)')\\n con.commit()\\n cur.execute(\\\"SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'SSRF'\\\")\\n tbl_exists = cur.fetchone()[0]\\n if (tbl_exists == 0):\\n cur.execute('CREATE TABLE SSRF(ip TEXT, ts timestamp)')\\n con.commit()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def create_db():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef LJHash(hashStr, size):\\n\\n ''''An approximation of the md5 hashing algorithms.\\n For Windows\\n An approximation of the md5 hashing algorithm. Used\\n for authorizations on UE9 version 1.73 and higher and u3\\n version 1.35 and higher.\\n @type hashStr: String\\n @param hashStr: String to be hashed.\\n @type size: number\\n @param size: Amount of bytes to hash from the hashStr\\n @rtype: String\\n @return: The hashed string.'\\n '''\",\"targets\":\"print(('Hash String:' + str(hashStr)))\\n outBuff = (ctypes.c_char * 16)()\\n retBuff = ''\\n staticLib = ctypes.windll.LoadLibrary('labjackud')\\n ec = staticLib.LJHash(ctypes.cast(hashStr, ctypes.POINTER(ctypes.c_char)), size, ctypes.cast(outBuff, ctypes.POINTER(ctypes.c_char)), 0)\\n if (ec != 0):\\n raise LabJackException(ec)\\n for i in range(16):\\n retBuff += outBuff[i]\\n return retBuff\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):\\n\\n ''''Generate linker options for searching library directories and\\n linking with specific libraries.\\n \\\\'libraries\\\\' and \\\\'library_dirs\\\\' are, respectively, lists of library names\\n (not filenames!) and search directories. Returns a list of command-line\\n options suitable for use with some compiler (depending on the two format\\n strings passed in).'\\n '''\",\"targets\":\"lib_opts = []\\n for dir in library_dirs:\\n lib_opts.append(compiler.library_dir_option(dir))\\n for dir in runtime_library_dirs:\\n opt = compiler.runtime_library_dir_option(dir)\\n if isinstance(opt, list):\\n lib_opts.extend(opt)\\n else:\\n lib_opts.append(opt)\\n for lib in libraries:\\n (lib_dir, lib_name) = os.path.split(lib)\\n if (lib_dir != ''):\\n lib_file = compiler.find_library_file([lib_dir], lib_name)\\n if (lib_file is not None):\\n lib_opts.append(lib_file)\\n else:\\n compiler.warn((\\\"no library file corresponding to '%s' found (skipping)\\\" % lib))\\n else:\\n lib_opts.append(compiler.library_option(lib))\\n return lib_opts\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_access_token_model():\",\"targets\":\"\\\"\\\"\\\"Return the AccessToken model that is active in this project.\\n \\\"\\\"\\\"\\n return apps.get_model(oauth2_settings.ACCESS_TOKEN_MODEL)\",\"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 (branch_factor > 1):\\n branched_entries = (beam_entries * branch_factor)\\n all_sequences = [copy.deepcopy(entry.sequence) for entry in branched_entries]\\n all_states = [copy.deepcopy(entry.state) for entry in branched_entries]\\n all_scores = [entry.score for entry in branched_entries]\\n else:\\n all_sequences = [entry.sequence for entry in beam_entries]\\n all_states = [entry.state for entry in beam_entries]\\n all_scores = [entry.score for entry in beam_entries]\\n for _ in range(num_steps):\\n (all_sequences, all_states, all_scores) = generate_step_fn(all_sequences, all_states, all_scores)\\n return [BeamEntry(sequence, state, score) for (sequence, state, score) in zip(all_sequences, all_states, all_scores)]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _generate_branches(beam_entries, generate_step_fn, branch_factor, num_steps):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def gen_preprocess_options(macros, include_dirs):\",\"targets\":\"\\\"\\\"\\\"Generate C pre-processor options (-D, -U, -I) as used by at least\\n two types of compilers: the typical Unix compiler and Visual C++.\\n \\\\macros\\\\ is the usual thing, a list of 1- or 2-tuples, where (name,)\\n means undefine (-U) macro \\\\name\\\\, and (name,value) means define (-D)\\n macro \\\\name\\\\ to \\\\value\\\\. \\\\include_dirs\\\\ is just a list of directory\\n names to be added to the header file search path (-I). Returns a list\\n of command-line options suitable for either Unix compilers or Visual\\n C++.\\n \\\"\\\"\\\"\\n pp_opts = []\\n for macro in macros:\\n if (not (isinstance(macro, tuple) and (1 <= len(macro) <= 2))):\\n raise TypeError, ((\\\"bad macro definition '%s': \\\" + \\\"each element of 'macros' list must be a 1- or 2-tuple\\\") % macro)\\n if (len(macro) == 1):\\n pp_opts.append(('-U%s' % macro[0]))\\n elif (len(macro) == 2):\\n if (macro[1] is None):\\n pp_opts.append(('-D%s' % macro[0]))\\n else:\\n pp_opts.append(('-D%s=%s' % macro))\\n for dir in include_dirs:\\n pp_opts.append(('-I%s' % dir))\\n return pp_opts\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def by_chat_command(prefix=('\\/',), separator=' ', pass_args=False):\",\"targets\":\"\\\"\\\"\\\":param prefix:\\n a list of special characters expected to indicate the head of a command.\\n :param separator:\\n a command may be followed by arguments separated by ``separator``.\\n :type pass_args: bool\\n :param pass_args:\\n If ``True``, arguments following a command will be passed to the handler\\n function.\\n :return:\\n a key function that interprets a chat message\\\\s text and returns\\n the embedded command, optionally followed by arguments. If the text is\\n not preceded by any of the specified ``prefix``, it returns a 1-tuple\\n ``(None,)`` as the key. This is to distinguish with the special\\n ``None`` key in routing table.\\n \\\"\\\"\\\"\\n return by_command((lambda msg: msg['text']), prefix, separator, pass_args)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ellipse(r, c, r_radius, c_radius, shape=None, rotation=0.0):\",\"targets\":\"\\\"\\\"\\\"Generate coordinates of pixels within ellipse.\\n Parameters\\n r, c : double\\n Centre coordinate of ellipse.\\n r_radius, c_radius : double\\n Minor and major semi-axes. ``(r\\/r_radius)**2 + (c\\/c_radius)**2 = 1``.\\n shape : tuple, optional\\n Image shape which is used to determine the maximum extent of output pixel\\n coordinates. This is useful for ellipses which exceed the image size.\\n By default the full extent of the ellipse are used.\\n rotation : float, optional (default 0.)\\n Set the ellipse rotation (rotation) in range (-PI, PI)\\n in contra clock wise direction, so PI\\/2 degree means swap ellipse axis\\n Returns\\n rr, cc : ndarray of int\\n Pixel coordinates of ellipse.\\n May be used to directly index into an array, e.g.\\n ``img[rr, cc] = 1``.\\n Examples\\n >>> from skimage.draw import ellipse\\n >>> img = np.zeros((10, 12), dtype=np.uint8)\\n >>> rr, cc = ellipse(5, 6, 3, 5, rotation=np.deg2rad(30))\\n >>> img[rr, cc] = 1\\n >>> img\\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\\n [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0],\\n [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0],\\n [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0],\\n [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],\\n [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],\\n [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],\\n [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0],\\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\\n Notes\\n The ellipse equation::\\n ((x * cos(alpha) + y * sin(alpha)) \\/ x_radius) ** 2 +\\n ((x * sin(alpha) - y * cos(alpha)) \\/ y_radius) ** 2 = 1\\n Note that the positions of `ellipse` without specified `shape` can have\\n also, negative values, as this is correct on the plane. On the other hand\\n using these ellipse positions for an image afterwards may lead to appearing\\n on the other side of image, because ``image[-1, -1] = image[end-1, end-1]``\\n >>> rr, cc = ellipse(1, 2, 3, 6)\\n >>> img = np.zeros((6, 12), dtype=np.uint8)\\n >>> img[rr, cc] = 1\\n >>> img\\n array([[1, 1, 1, 1,...\\\"\\\"\\\"\\n center = np.array([r, c])\\n radii = np.array([r_radius, c_radius])\\n rotation %= np.pi\\n r_radius_rot = (abs((r_radius * np.cos(rotation))) + (c_radius * np.sin(rotation)))\\n c_radius_rot = ((r_radius * np.sin(rotation)) + abs((c_radius * np.cos(rotation))))\\n radii_rot = np.array([r_radius_rot, c_radius_rot])\\n upper_left = np.ceil((center - radii_rot)).astype(int)\\n lower_right = np.floor((center + radii_rot)).astype(int)\\n if (shape is not None):\\n upper_left = np.maximum(upper_left, np.array([0, 0]))\\n lower_right = np.minimum(lower_right, (np.array(shape[:2]) - 1))\\n shifted_center = (center - upper_left)\\n bounding_shape = ((lower_right - upper_left) + 1)\\n (rr, cc) = _ellipse_in_shape(bounding_shape, shifted_center, radii, rotation)\\n rr.flags.writeable = True\\n cc.flags.writeable = True\\n rr += upper_left[0]\\n cc += upper_left[1]\\n return (rr, cc)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (call == 'function'):\\n raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.')\\n __utils__['cloud.fire_event']('event', 'destroying instance', 'salt\\/cloud\\/{0}\\/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])\\n node = show_instance(name, call='action')\\n if (node['state'] == 'STARTED'):\\n stop(name, call='action')\\n if (not wait_until(name, 'STOPPED')):\\n return {'Error': 'Unable to destroy {0}, command timed out'.format(name)}\\n data = query(action='ve', command=name, method='DELETE')\\n if ('error' in data):\\n return data['error']\\n __utils__['cloud.fire_event']('event', 'destroyed instance', 'salt\\/cloud\\/{0}\\/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])\\n if (__opts__.get('update_cachedir', False) is True):\\n __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)\\n return {'Destroyed': '{0} was destroyed.'.format(name)}\\n\\n\\nWhat's a good function header?\",\"targets\":\"def destroy(name, call=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if parser_return.tree:\\n node = SimplifyNode(parser_return.tree)\\n ValidateNode(node)\\n return node\\n return parser_return\\n\\n\\nWhat's a good function header?\",\"targets\":\"def Simplify(parser_return):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n Y = np.zeros((len(labels), nclass)).astype('float32')\\n for (j, y) in enumerate(labels):\\n for i in range(nclass):\\n if ((i + 1) == (np.floor(y) + 1)):\\n Y[(j, i)] = (y - np.floor(y))\\n if ((i + 1) == np.floor(y)):\\n Y[(j, i)] = ((np.floor(y) - y) + 1)\\n return Y\\n\\n\\nWhat's a good function header?\",\"targets\":\"def encode_labels(labels, nclass=5):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef chain_dot(*arrs):\\n\\n ''''Returns the dot product of the given matrices.\\n Parameters\\n arrs: argument list of ndarray\\n Returns\\n Dot product of all arguments.\\n Examples\\n >>> import numpy as np\\n >>> from statsmodels.tools import chain_dot\\n >>> A = np.arange(1,13).reshape(3,4)\\n >>> B = np.arange(3,15).reshape(4,3)\\n >>> C = np.arange(5,8).reshape(3,1)\\n >>> chain_dot(A,B,C)\\n array([[1820],\\n [4300],\\n [6780]])'\\n '''\",\"targets\":\"return reduce((lambda x, y: np.dot(y, x)), arrs[::(-1)])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (sys.platform in ('dos', 'win32', 'win16', 'os2')):\\n return default\\n try:\\n f = os.popen(('uname %s 2> %s' % (option, DEV_NULL)))\\n except (AttributeError, os.error):\\n return default\\n output = string.strip(f.read())\\n rc = f.close()\\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_uname(option, default=''):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef makeHTMLTags(tagStr):\\n\\n ''''Helper to construct opening and closing tag expressions for HTML, given a tag name'\\n '''\",\"targets\":\"return _makeTags(tagStr, False)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _import_keyDER(extern_key, passphrase):\\n\\n ''''Import an RSA key (public or private half), encoded in DER form.'\\n '''\",\"targets\":\"decodings = (_import_pkcs1_private, _import_pkcs1_public, _import_subjectPublicKeyInfo, _import_x509_cert, _import_pkcs8)\\n for decoding in decodings:\\n try:\\n return decoding(extern_key, passphrase)\\n except ValueError:\\n pass\\n raise ValueError('RSA key format is not supported')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n firstbits = token.contents.split(None, 3)\\n if (len(firstbits) != 4):\\n raise TemplateSyntaxError(u\\\"'regroup' tag takes five arguments\\\")\\n target = parser.compile_filter(firstbits[1])\\n if (firstbits[2] != u'by'):\\n raise TemplateSyntaxError(u\\\"second argument to 'regroup' tag must be 'by'\\\")\\n lastbits_reversed = firstbits[3][::(-1)].split(None, 2)\\n if (lastbits_reversed[1][::(-1)] != u'as'):\\n raise TemplateSyntaxError(u\\\"next-to-last argument to 'regroup' tag must be 'as'\\\")\\n var_name = lastbits_reversed[0][::(-1)]\\n expression = parser.compile_filter(((var_name + VARIABLE_ATTRIBUTE_SEPARATOR) + lastbits_reversed[2][::(-1)]))\\n return RegroupNode(target, expression, var_name)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@register.tag\\ndef regroup(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 context.headers.append((hdr, value))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def header(hdr, 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 mounts = {}\\n with salt.utils.files.fopen('\\/proc\\/mounts') as fhr:\\n for line in fhr.readlines():\\n (device, mntpnt, fstype, options, fs_freq, fs_passno) = line.strip().split(' ')\\n if (fstype != 'xfs'):\\n continue\\n mounts[device] = {'mount_point': mntpnt, 'options': options.split(',')}\\n return mounts\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_mounts():\",\"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 filename in glob.glob(os.path.join(REQ_DIR, 'requirements-*.txt-raw')):\\n basename = os.path.basename(filename)\\n (yield basename[len('requirements-'):(- len('.txt-raw'))])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_all_names():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@hooks.before('Users > Get User Details for a Speaker > Get User Details for a Speaker')\\ndef user_speaker(transaction):\\n\\n ''''GET \\/speakers\\/1\\/user\\n :param transaction:\\n :return:'\\n '''\",\"targets\":\"with stash['app'].app_context():\\n speaker = SpeakerFactory()\\n db.session.add(speaker)\\n db.session.commit()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def group():\",\"targets\":\"\\\"\\\"\\\"RESTful CRUD controller\\n \\\"\\\"\\\"\\n FS = s3base.S3FieldSelector\\n s3.filter = (FS('group.system') == False)\\n table = s3db.pr_group_membership\\n s3db.configure('pr_group_membership', list_fields=['id', 'person_id', 'group_head', 'comments'])\\n rheader = (lambda r: s3db.pr_rheader(r, tabs=[(T('Group Details'), None), (T('Address'), 'address'), (T('Contact Data'), 'contact'), (T('Members'), 'group_membership')]))\\n output = s3_rest_controller(rheader=rheader)\\n return output\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _split_fragment(frag):\",\"targets\":\"\\\"\\\"\\\"Splits one HSPFragment containing frame-shifted alignment into two.\\n \\\"\\\"\\\"\\n simil = frag.aln_annotation['similarity']\\n assert (simil.count('#') > 0)\\n split_frags = []\\n qstep = (1 if (frag.query_strand >= 0) else (-1))\\n hstep = (1 if (frag.hit_strand >= 0) else (-1))\\n qpos = (min(frag.query_range) if (qstep >= 0) else max(frag.query_range))\\n hpos = (min(frag.hit_range) if (qstep >= 0) else max(frag.hit_range))\\n abs_pos = 0\\n while simil:\\n try:\\n shifts = re.search(_RE_SHIFTS, simil).group(1)\\n s_start = simil.find(shifts)\\n s_stop = (s_start + len(shifts))\\n split = frag[abs_pos:(abs_pos + s_start)]\\n except AttributeError:\\n shifts = ''\\n s_start = 0\\n s_stop = len(simil)\\n split = frag[abs_pos:]\\n (qstart, hstart) = (qpos, hpos)\\n qpos += ((len(split) - sum((str(split.query.seq).count(x) for x in ('-', '<', '>')))) * qstep)\\n hpos += ((len(split) - sum((str(split.hit.seq).count(x) for x in ('-', '<', '>')))) * hstep)\\n split.hit_start = min(hstart, hpos)\\n split.query_start = min(qstart, qpos)\\n split.hit_end = max(hstart, hpos)\\n split.query_end = max(qstart, qpos)\\n abs_slice = slice((abs_pos + s_start), (abs_pos + s_stop))\\n if (len(frag.aln_annotation) == 2):\\n seqs = (str(frag[abs_slice].query.seq), str(frag[abs_slice].hit.seq))\\n elif (len(frag.aln_annotation) == 3):\\n seqs = (frag[abs_slice].aln_annotation['query_annotation'], frag[abs_slice].aln_annotation['hit_annotation'])\\n if ('#' in seqs[0]):\\n qpos += (len(shifts) * qstep)\\n elif ('#' in seqs[1]):\\n hpos += (len(shifts) * hstep)\\n _set_frame(split)\\n split_frags.append(split)\\n simil = simil[s_stop:]\\n abs_pos += s_stop\\n return split_frags\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def add_actions(target, actions, insert_before=None):\",\"targets\":\"\\\"\\\"\\\"Add actions to a QMenu or a QToolBar.\\n \\\"\\\"\\\"\\n previous_action = None\\n target_actions = list(target.actions())\\n if target_actions:\\n previous_action = target_actions[(-1)]\\n if previous_action.isSeparator():\\n previous_action = None\\n for action in actions:\\n if ((action is None) and (previous_action is not None)):\\n if (insert_before is None):\\n target.addSeparator()\\n else:\\n target.insertSeparator(insert_before)\\n elif isinstance(action, QMenu):\\n if (insert_before is None):\\n target.addMenu(action)\\n else:\\n target.insertMenu(insert_before, action)\\n elif isinstance(action, QAction):\\n if isinstance(action, SpyderAction):\\n if (isinstance(target, QMenu) or (not isinstance(target, QToolBar))):\\n try:\\n action = action.no_icon_action\\n except RuntimeError:\\n continue\\n if (insert_before is None):\\n target.addAction(action)\\n else:\\n target.insertAction(insert_before, action)\\n previous_action = action\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n assert (len(xs) == len(ys))\\n if (in_xs is None):\\n in_xs = []\\n if (in_ys is None):\\n in_ys = []\\n for (x, y) in izip(xs, ys):\\n if (x.owner and (not y.owner)):\\n return False\\n if (y.owner and (not x.owner)):\\n return False\\n if x.owner:\\n if (x.owner.outputs.index(x) != y.owner.outputs.index(y)):\\n return False\\n if ((x not in in_xs) and (x.type != y.type)):\\n return False\\n if (len(in_xs) != len(in_ys)):\\n return False\\n for (_x, _y) in izip(in_xs, in_ys):\\n if (_x.type != _y.type):\\n return False\\n common = set(zip(in_xs, in_ys))\\n different = set()\\n for (dx, dy) in izip(xs, ys):\\n if (not dx.owner):\\n if (isinstance(dx, tensor.Constant) and isinstance(dy, tensor.Constant)):\\n if (not dx.equals(dy)):\\n return False\\n else:\\n pass\\n elif (((dx, dy) not in common) and (dx != dy)):\\n return False\\n def compare_nodes(nd_x, nd_y, common, different):\\n '\\\\n Compare two nodes to determine if they perform equal computation.\\\\n This is done by comparing the ops, the number of inputs, outputs and\\\\n by ensuring that the inputs themselves are the result of equal\\\\n computation.\\\\n\\\\n NOTE : This function relies on the variable common to cache\\\\n results to be more efficient.\\\\n\\\\n '\\n if (nd_x.op != nd_y.op):\\n return False\\n elif (len(nd_x.inputs) != len(nd_y.inputs)):\\n return False\\n elif (len(nd_x.outputs) != len(nd_y.outputs)):\\n return False\\n else:\\n all_in_common =...\\n\\nWhat's a good function header?\",\"targets\":\"def equal_computations(xs, ys, in_xs=None, in_ys=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.filter(is_safe=True)\\n@stringfilter\\ndef safe(value):\\n\\n ''''Marks the value as a string that should not be auto-escaped.'\\n '''\",\"targets\":\"return mark_safe(value)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef connect(dbn, **keywords):\\n\\n ''''Connects to the specified database.\\n db currently must be \\\"postgres\\\" or \\\"mysql\\\".\\n If DBUtils is installed, connection pooling will be used.'\\n '''\",\"targets\":\"if (dbn == 'postgres'):\\n try:\\n import psycopg2 as db\\n except ImportError:\\n try:\\n import psycopg as db\\n except ImportError:\\n import pgdb as db\\n keywords['password'] = keywords['pw']\\n del keywords['pw']\\n keywords['database'] = keywords['db']\\n del keywords['db']\\n elif (dbn == 'mysql'):\\n import MySQLdb as db\\n keywords['passwd'] = keywords['pw']\\n del keywords['pw']\\n db.paramstyle = 'pyformat'\\n elif (dbn == 'sqlite'):\\n try:\\n from pysqlite2 import dbapi2 as db\\n db.paramstyle = 'qmark'\\n except ImportError:\\n import sqlite as db\\n keywords['database'] = keywords['db']\\n del keywords['db']\\n else:\\n raise UnknownDB, dbn\\n ctx.db_name = dbn\\n ctx.db_module = db\\n ctx.db_transaction = False\\n if _hasPooling:\\n if ('db' not in globals()):\\n globals()['db'] = PooledDB(dbapi=db, **keywords)\\n ctx.db = globals()['db'].connection()\\n else:\\n ctx.db = db.connect(**keywords)\\n ctx.dbq_count = 0\\n if globals().get('db_printing'):\\n def db_execute(cur, sql_query, d=None):\\n 'executes an sql query'\\n def sqlquote(obj):\\n 'converts `obj` to its proper SQL version'\\n if (obj is None):\\n return 'NULL'\\n elif (obj is True):\\n return \\\"'t'\\\"\\n elif (obj is False):\\n return \\\"'f'\\\"\\n elif isinstance(obj, datetime.datetime):\\n return repr(obj.isoformat())\\n else:\\n return repr(obj)\\n ctx.dbq_count += 1\\n try:\\n outq = (sql_query % tuple(map(sqlquote, d)))\\n except TypeError:\\n outq = sql_query\\n print >>debug, (str(ctx.dbq_count) + ':'), outq\\n a = time.time()\\n out =...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _postprocess_conv2d_output(x, data_format):\",\"targets\":\"\\\"\\\"\\\"Transpose and cast the output from conv2d if needed.\\n # Arguments\\n x: A tensor.\\n data_format: string, `\\\"channels_last\\\"` or `\\\"channels_first\\\"`.\\n # Returns\\n A tensor.\\n \\\"\\\"\\\"\\n if (data_format == 'channels_first'):\\n x = tf.transpose(x, (0, 3, 1, 2))\\n if (floatx() == 'float64'):\\n x = tf.cast(x, 'float64')\\n return x\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _convert_to_naive_utc_time(time):\",\"targets\":\"\\\"\\\"\\\"Normalizes a datetime to a naive datetime in UTC.\\n time -- datetime to normalize. Assumed to be in UTC if not timezone\\n aware.\\n \\\"\\\"\\\"\\n if (time.tzinfo is not None):\\n offset = time.utcoffset()\\n offset = (offset if offset else datetime.timedelta())\\n return (time.replace(tzinfo=None) - offset)\\n else:\\n return time\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dump(data, stream=None, Dumper=Dumper, **kwds):\",\"targets\":\"\\\"\\\"\\\"Serialize a Python object into a YAML stream.\\n If stream is None, return the produced string instead.\\n \\\"\\\"\\\"\\n return dump_all([data], stream, Dumper=Dumper, **kwds)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _netstat_route_sunos():\",\"targets\":\"\\\"\\\"\\\"Return netstat routing information for SunOS\\n \\\"\\\"\\\"\\n ret = []\\n cmd = 'netstat -f inet -rn | tail +5'\\n out = __salt__['cmd.run'](cmd, python_shell=True)\\n for line in out.splitlines():\\n comps = line.split()\\n ret.append({'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': (comps[5] if (len(comps) >= 6) else '')})\\n cmd = 'netstat -f inet6 -rn | tail +5'\\n out = __salt__['cmd.run'](cmd, python_shell=True)\\n for line in out.splitlines():\\n comps = line.split()\\n ret.append({'addr_family': 'inet6', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': (comps[5] if (len(comps) >= 6) else '')})\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef delete(name, profile='splunk'):\\n\\n ''''Delete a splunk search\\n CLI Example:\\n splunk_search.delete \\\\'my search name\\\\''\\n '''\",\"targets\":\"client = _get_splunk(profile)\\n try:\\n client.saved_searches.delete(name)\\n return True\\n except KeyError:\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _parse_date_nate(dateString):\\n\\n ''''Parse a string according to the Nate 8-bit date format'\\n '''\",\"targets\":\"m = _korean_nate_date_re.match(dateString)\\n if (not m):\\n return\\n hour = int(m.group(5))\\n ampm = m.group(4)\\n if (ampm == _korean_pm):\\n hour += 12\\n hour = str(hour)\\n if (len(hour) == 1):\\n hour = ('0' + hour)\\n w3dtfdate = ('%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % {'year': m.group(1), 'month': m.group(2), 'day': m.group(3), 'hour': hour, 'minute': m.group(6), 'second': m.group(7), 'zonediff': '+09:00'})\\n return _parse_date_w3dtf(w3dtfdate)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef generate_presigned_url(self, ClientMethod, Params=None, ExpiresIn=3600, HttpMethod=None):\\n\\n ''''Generate a presigned url given a client, its method, and arguments\\n :type ClientMethod: string\\n :param ClientMethod: The client method to presign for\\n :type Params: dict\\n :param Params: The parameters normally passed to\\n ``ClientMethod``.\\n :type ExpiresIn: int\\n :param ExpiresIn: The number of seconds the presigned url is valid\\n for. By default it expires in an hour (3600 seconds)\\n :type HttpMethod: string\\n :param HttpMethod: The http method to use on the generated url. By\\n default, the http method is whatever is used in the method\\\\'s model.\\n :returns: The presigned url'\\n '''\",\"targets\":\"client_method = ClientMethod\\n params = Params\\n expires_in = ExpiresIn\\n http_method = HttpMethod\\n request_signer = self._request_signer\\n serializer = self._serializer\\n try:\\n operation_name = self._PY_TO_OP_NAME[client_method]\\n except KeyError:\\n raise UnknownClientMethodError(method_name=client_method)\\n operation_model = self.meta.service_model.operation_model(operation_name)\\n request_dict = serializer.serialize_to_request(params, operation_model)\\n if (http_method is not None):\\n request_dict['method'] = http_method\\n prepare_request_dict(request_dict, endpoint_url=self.meta.endpoint_url)\\n return request_signer.generate_presigned_url(request_dict=request_dict, expires_in=expires_in, operation_name=operation_name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _verify_options(options):\",\"targets\":\"\\\"\\\"\\\"Verify options and log warnings\\n Returns True if all options can be verified,\\n otherwise False\\n \\\"\\\"\\\"\\n bitwise_args = [('level', options['level']), ('facility', options['facility'])]\\n bitwise_args.extend([('option', x) for x in options['options']])\\n for (opt_name, opt) in bitwise_args:\\n if (not hasattr(syslog, opt)):\\n log.error('syslog has no attribute {0}'.format(opt))\\n return False\\n if (not isinstance(getattr(syslog, opt), int)):\\n log.error('{0} is not a valid syslog {1}'.format(opt, opt_name))\\n return False\\n if ('tag' in options):\\n if (not isinstance(options['tag'], six.string_types)):\\n log.error('tag must be a string')\\n return False\\n if (len(options['tag']) > 32):\\n log.error('tag size is limited to 32 characters')\\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 generate_new_element(items, prefix, numeric=False):\\n\\n ''''Creates a random string with prefix, that is not in \\\\'items\\\\' list.'\\n '''\",\"targets\":\"while True:\\n if numeric:\\n candidate = (prefix + generate_random_numeric(8))\\n else:\\n candidate = (prefix + generate_random_alphanumeric(8))\\n if (candidate not in items):\\n return candidate\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef __virtual__():\\n\\n ''''Only load this module if keystone\\n is installed on this minion.'\\n '''\",\"targets\":\"if HAS_KEYSTONE:\\n return 'keystone'\\n return (False, 'keystone execution module cannot be loaded: keystoneclient python library not available.')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n logger.info('Estimating phase slope index (PSI)')\\n (cohy, freqs_, times, n_epochs, n_tapers) = spectral_connectivity(data, method='cohy', indices=indices, sfreq=sfreq, mode=mode, fmin=fmin, fmax=fmax, fskip=0, faverage=False, tmin=tmin, tmax=tmax, mt_bandwidth=mt_bandwidth, mt_adaptive=mt_adaptive, mt_low_bias=mt_low_bias, cwt_frequencies=cwt_frequencies, cwt_n_cycles=cwt_n_cycles, block_size=block_size, n_jobs=n_jobs, verbose=verbose)\\n logger.info('Computing PSI from estimated Coherency')\\n if (fmin is None):\\n fmin = (- np.inf)\\n bands = list(zip(np.asarray((fmin,)).ravel(), np.asarray((fmax,)).ravel()))\\n n_bands = len(bands)\\n freq_dim = ((-2) if (mode == 'cwt_morlet') else (-1))\\n out_shape = list(cohy.shape)\\n out_shape[freq_dim] = n_bands\\n psi = np.zeros(out_shape, dtype=np.float)\\n acc_shape = copy.copy(out_shape)\\n acc_shape.pop(freq_dim)\\n acc = np.empty(acc_shape, dtype=np.complex128)\\n freqs = list()\\n idx_fi = ([slice(None)] * cohy.ndim)\\n idx_fj = ([slice(None)] * cohy.ndim)\\n for (band_idx, band) in enumerate(bands):\\n freq_idx = np.where(((freqs_ > band[0]) & (freqs_ < band[1])))[0]\\n freqs.append(freqs_[freq_idx])\\n acc.fill(0.0)\\n for (fi, fj) in zip(freq_idx, freq_idx[1:]):\\n idx_fi[freq_dim] = fi\\n idx_fj[freq_dim] = fj\\n acc += (np.conj(cohy[idx_fi]) * cohy[idx_fj])\\n idx_fi[freq_dim] = band_idx\\n psi[idx_fi] = np.imag(acc)\\n logger.info('[PSI Estimation Done]')\\n return (psi, freqs, times, n_epochs, n_tapers)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@verbose\\ndef phase_slope_index(data, indices=None, sfreq=(2 * np.pi), mode='multitaper', fmin=None, fmax=np.inf, tmin=None, tmax=None, mt_bandwidth=None, mt_adaptive=False, mt_low_bias=True, cwt_frequencies=None, cwt_n_cycles=7, block_size=1000, n_jobs=1, verbose=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef delete(uuid):\\n\\n ''''Deletes Memcache items and times them.\\n Args:\\n uuid: A unique identifier as part of the keynames of items.\\n Returns:\\n A tuple of two lists. A list of float times to delete\\n all items, and a list of errors. A zero value signifies\\n a failure.'\\n '''\",\"targets\":\"timings = []\\n errors = []\\n for index in range(0, constants.NUM_SAMPLES):\\n start = time.time()\\n try:\\n memcache.delete((uuid + str(index)))\\n total_time = (time.time() - start)\\n except Exception as exception:\\n logging.exception(exception)\\n errors.append(str(exception))\\n total_time = 0\\n timings.append((total_time * constants.SECONDS_TO_MILLI))\\n return (timings, errors)\",\"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_state_key = Location.from_deprecated_string(request.GET.get('module_id'))\\n csv = request.GET.get('csv')\\n students = models.StudentModule.objects.select_related('student').filter(module_state_key__exact=module_state_key, module_type__exact='sequential').values('student__username', 'student__profile__name').order_by('student__profile__name')\\n results = []\\n if (not csv):\\n for student in students[0:(MAX_SCREEN_LIST_LENGTH + 1)]:\\n results.append({'name': student['student__profile__name'], 'username': student['student__username']})\\n max_exceeded = False\\n if (len(results) > MAX_SCREEN_LIST_LENGTH):\\n del results[(-1)]\\n max_exceeded = True\\n response_payload = {'results': results, 'max_exceeded': max_exceeded}\\n return JsonResponse(response_payload)\\n else:\\n tooltip = request.GET.get('tooltip')\\n filename = sanitize_filename(' '.join(tooltip.split(' ')[3:]))\\n header = [_('Name'), _('Username')]\\n for student in students:\\n results.append([student['student__profile__name'], student['student__username']])\\n response = create_csv_response(filename, header, results)\\n return response\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_students_opened_subsection(request, csv=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef http2time(text):\\n\\n ''''Returns time in seconds since epoch of time represented by a string.\\n Return value is an integer.\\n None is returned if the format of str is unrecognized, the time is outside\\n the representable range, or the timezone string is not recognized. If the\\n string contains no timezone, UTC is assumed.\\n The timezone in the string may be numerical (like \\\"-0800\\\" or \\\"+0100\\\") or a\\n string timezone (like \\\"UTC\\\", \\\"GMT\\\", \\\"BST\\\" or \\\"EST\\\"). Currently, only the\\n timezone strings equivalent to UTC (zero offset) are known to the function.\\n The function loosely parses the following formats:\\n Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format\\n Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format\\n Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format\\n 09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday)\\n 08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday)\\n 08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday)\\n The parser ignores leading and trailing whitespace. The time may be\\n absent.\\n If the year is given with only 2 digits, the function will select the\\n century that makes the year closest to the current date.'\\n '''\",\"targets\":\"m = STRICT_DATE_RE.search(text)\\n if m:\\n g = m.groups()\\n mon = (MONTHS_LOWER.index(g[1].lower()) + 1)\\n tt = (int(g[2]), mon, int(g[0]), int(g[3]), int(g[4]), float(g[5]))\\n return _timegm(tt)\\n text = text.lstrip()\\n text = WEEKDAY_RE.sub('', text, 1)\\n (day, mon, yr, hr, min, sec, tz) = ([None] * 7)\\n m = LOOSE_HTTP_DATE_RE.search(text)\\n if (m is not None):\\n (day, mon, yr, hr, min, sec, tz) = m.groups()\\n else:\\n return None\\n return _str2time(day, mon, yr, hr, min, sec, tz)\",\"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 (namespace is None):\\n namespace = namespace_manager.get_namespace()\\n else:\\n namespace_manager.validate_namespace(namespace, datastore_errors.BadArgumentError)\\n return namespace\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ResolveNamespace(namespace):\",\"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 sip\\n from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui\\n QtCore.Signal = QtCore.pyqtSignal\\n QtCore.Slot = QtCore.pyqtSlot\\n QtGuiCompat = types.ModuleType('QtGuiCompat')\\n QtGuiCompat.__dict__.update(QtGui.__dict__)\\n QtGuiCompat.__dict__.update(QtWidgets.__dict__)\\n api = QT_API_PYQT5\\n return (QtCore, QtGuiCompat, QtSvg, api)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def import_pyqt5():\",\"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 (arg is None):\\n return []\\n elif ((not isinstance(arg, dict)) and hasattr(arg, '__iter__')):\\n return arg\\n else:\\n return [arg]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def arg_to_iter(arg):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n cmd = _nix_collect_garbage()\\n cmd.append('--delete-old')\\n out = _run(cmd)\\n return out['stdout'].splitlines()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def collect_garbage():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def found(url):\",\"targets\":\"\\\"\\\"\\\"A `302 Found` redirect.\\n \\\"\\\"\\\"\\n return redirect(url, '302 Found')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_rendition_or_not_found(image, specs):\",\"targets\":\"\\\"\\\"\\\"Tries to get \\/ create the rendition for the image or renders a not-found image if it does not exist.\\n :param image: AbstractImage\\n :param specs: str or Filter\\n :return: Rendition\\n \\\"\\\"\\\"\\n try:\\n return image.get_rendition(specs)\\n except SourceImageIOError:\\n Rendition = image.renditions.model\\n rendition = Rendition(image=image, width=0, height=0)\\n rendition.file.name = u'not-found'\\n return rendition\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def list_incidents(profile=None, api_key=None):\",\"targets\":\"\\\"\\\"\\\"List incidents belonging to this account\\n CLI Example:\\n salt myminion pagerduty.list_incidents my-pagerduty-account\\n \\\"\\\"\\\"\\n return salt.utils.pagerduty.list_items('incidents', 'id', __salt__['config.option'](profile), api_key, opts=__opts__)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef from_current_timezone(value):\\n\\n ''''When time zone support is enabled, convert naive datetimes\\n entered in the current time zone to aware datetimes.'\\n '''\",\"targets\":\"if (settings.USE_TZ and (value is not None) and timezone.is_naive(value)):\\n current_timezone = timezone.get_current_timezone()\\n try:\\n return timezone.make_aware(value, current_timezone)\\n except Exception:\\n raise ValidationError((_(u\\\"%(datetime)s couldn't be interpreted in time zone %(current_timezone)s; it may be ambiguous or it may not exist.\\\") % {u'datetime': value, u'current_timezone': current_timezone}))\\n return value\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (grad_x, grad_y, grad_z) = np.gradient(volume)\\n a = (actual_verts[:, 0, :] - actual_verts[:, 1, :])\\n b = (actual_verts[:, 0, :] - actual_verts[:, 2, :])\\n centroids = (actual_verts.sum(axis=1) \\/ 3.0).T\\n del actual_verts\\n grad_centroids_x = ndi.map_coordinates(grad_x, centroids)\\n grad_centroids_y = ndi.map_coordinates(grad_y, centroids)\\n grad_centroids_z = ndi.map_coordinates(grad_z, centroids)\\n grad_centroids = np.c_[(grad_centroids_x, grad_centroids_y, grad_centroids_z)]\\n grad_centroids = (grad_centroids \\/ (np.sum((grad_centroids ** 2), axis=1) ** 0.5)[:, np.newaxis])\\n crosses = np.cross(a, b)\\n crosses = (crosses \\/ (np.sum((crosses ** 2), axis=1) ** 0.5)[:, np.newaxis])\\n dotproducts = (grad_centroids * crosses).sum(axis=1)\\n if ('descent' in gradient_direction):\\n indices = (dotproducts < 0).nonzero()[0]\\n elif ('ascent' in gradient_direction):\\n indices = (dotproducts > 0).nonzero()[0]\\n else:\\n raise ValueError(('Incorrect input %s in `gradient_direction`, see docstring.' % gradient_direction))\\n faces_corrected = faces.copy()\\n faces_corrected[indices] = faces_corrected[indices, ::(-1)]\\n return faces_corrected\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _correct_mesh_orientation(volume, actual_verts, faces, spacing=(1.0, 1.0, 1.0), gradient_direction='descent'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@register.filter(is_safe=False)\\ndef length_is(value, arg):\",\"targets\":\"\\\"\\\"\\\"Returns a boolean of whether the value\\\\s length is the argument.\\n \\\"\\\"\\\"\\n try:\\n return (len(value) == int(arg))\\n except (ValueError, TypeError):\\n return u''\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_locales_from_config():\\n\\n ''''despite the name of this function it gets the locales defined by\\n the config AND also the locals available subject to the config.'\\n '''\",\"targets\":\"locales_offered = config.get('ckan.locales_offered', '').split()\\n filtered_out = config.get('ckan.locales_filtered_out', '').split()\\n locale_default = [config.get('ckan.locale_default', 'en')]\\n locale_order = config.get('ckan.locale_order', '').split()\\n known_locales = get_locales()\\n all_locales = (((set(known_locales) | set(locales_offered)) | set(locale_order)) | set(locale_default))\\n all_locales -= set(filtered_out)\\n return all_locales\",\"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 (locals is None):\\n locals = globals\\n with open(filename, 'rb') as fin:\\n source = fin.read()\\n code = compile(source, filename, 'exec')\\n exec code in globals, locals\\n\\n\\nWhat's a good function header?\",\"targets\":\"def execfile(filename, globals, locals=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def assert_true(expr, msg=None):\",\"targets\":\"\\\"\\\"\\\"Fail the test unless the expression is True.\\n \\\"\\\"\\\"\\n if (not expr):\\n _report_failure(msg)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _explode_list_args(args):\",\"targets\":\"\\\"\\\"\\\"Iterate through each attribute member of args and create a copy with\\n the IterateValues \\\\flattened\\\\ to only contain a single value\\n Ex.\\n { a1:\\\\x\\\\, a2:IterateValue([\\\\y\\\\, \\\\z\\\\]) } => [{ a1:\\\\x\\\\, a2:\\\\y\\\\),{ a1:\\\\x\\\\, a2:\\\\z\\\\}]\\n \\\"\\\"\\\"\\n list_args = {argname: argvalue for (argname, argvalue) in vars(args).items() if isinstance(argvalue, IterateValue)}\\n if (not list_args):\\n (yield args)\\n else:\\n values = list(zip(*list_args.values()))\\n for key in list_args:\\n delattr(args, key)\\n for value in values:\\n new_ns = argparse.Namespace(**vars(args))\\n for (key_index, key) in enumerate(list_args.keys()):\\n setattr(new_ns, key, value[key_index])\\n (yield new_ns)\",\"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 should_bypass_proxies(url):\\n return {}\\n else:\\n return getproxies()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_environ_proxies(url):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@handle_response_format\\n@treeio_login_required\\ndef ticket_set_status(request, ticket_id, status_id, response_format='html'):\",\"targets\":\"\\\"\\\"\\\"Ticket quick set: Status\\n \\\"\\\"\\\"\\n ticket = get_object_or_404(Ticket, pk=ticket_id)\\n if (not request.user.profile.has_permission(ticket, mode='w')):\\n return user_denied(request, message=\\\"You don't have access to this Ticket\\\")\\n status = get_object_or_404(TicketStatus, pk=status_id)\\n if (not request.user.profile.has_permission(status)):\\n return user_denied(request, message=\\\"You don't have access to this Ticket Status\\\")\\n if (not (ticket.status == status)):\\n ticket.status = status\\n ticket.save()\\n return ticket_view(request, ticket_id, 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 if (_db is None):\\n init()\\n return _db.guess_extension(type, strict)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def guess_extension(type, strict=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 g = np.zeros_like(prices)\\n g[1:] = ((prices[1:] - prices[:(-1)]) \\/ prices[:(-1)])\\n return g\\n\\n\\nWhat's a good function header?\",\"targets\":\"def daily_return(prices):\",\"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 (lno, line) in enumerate(lines):\\n if (len(line) > 81):\\n if ((line.lstrip()[0] not in '+|') and ('http:\\/\\/' not in line) and (not line.lstrip().startswith(('.. function', '.. method', '.. cfunction')))):\\n (yield ((lno + 1), 'line too long'))\\n\\n\\nWhat's a good function header?\",\"targets\":\"@checker('.rst', severity=0)\\ndef check_line_length(fn, lines):\",\"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(sequences) == 1):\\n return sequences[0]\\n sequences = [pair[1] for pair in sorted(((len(fi), fi) for fi in sequences))]\\n if (not sequences):\\n return None\\n for (i, comparison_ch) in enumerate(sequences[0]):\\n for fi in sequences[1:]:\\n ch = fi[i]\\n if (ch != comparison_ch):\\n return fi[:i]\\n return sequences[0]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def longestCommonPrefix(*sequences):\",\"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__(name)\\n return sys.modules[name]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _import_module(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n i = j = 0\\n missing = []\\n unexpected = []\\n while True:\\n try:\\n e = expected[i]\\n a = actual[j]\\n if (e < a):\\n missing.append(e)\\n i += 1\\n while (expected[i] == e):\\n i += 1\\n elif (e > a):\\n unexpected.append(a)\\n j += 1\\n while (actual[j] == a):\\n j += 1\\n else:\\n i += 1\\n try:\\n while (expected[i] == e):\\n i += 1\\n finally:\\n j += 1\\n while (actual[j] == a):\\n j += 1\\n except IndexError:\\n missing.extend(expected[i:])\\n unexpected.extend(actual[j:])\\n break\\n return (missing, unexpected)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def sorted_list_difference(expected, actual):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _clickthrough_rate(impressions, clicks):\",\"targets\":\"\\\"\\\"\\\"Return the click-through rate percentage.\\n \\\"\\\"\\\"\\n if impressions:\\n return ((float(clicks) \\/ impressions) * 100.0)\\n else:\\n return 0\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef is_import(node):\\n\\n ''''Returns true if the node is an import statement.'\\n '''\",\"targets\":\"return (node.type in (syms.import_name, syms.import_from))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef DoubleToStringAddress(number):\\n\\n ''''Converts a number (base 10) to an IP string.\\n For Windows\\n Sample Usage:\\n >>> DoubleToStringAddress(3232235985)\\n \\\\'192.168.1.209\\\\'\\n @type number: number\\n @param number: Number to be converted.\\n @rtype: String\\n @return: The IP string converted from the number (base 10).\\n @raise LabJackException:'\\n '''\",\"targets\":\"number = int(number)\\n address = ('%i.%i.%i.%i' % (((number >> (8 * 3)) & 255), ((number >> (8 * 2)) & 255), ((number >> 8) & 255), (number & 255)))\\n return address\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def float_compare(value1, value2, precision_digits=None, precision_rounding=None):\",\"targets\":\"\\\"\\\"\\\"Compare ``value1`` and ``value2`` after rounding them according to the\\n given precision. A value is considered lower\\/greater than another value\\n if their rounded value is different. This is not the same as having a\\n non-zero difference!\\n Precision must be given by ``precision_digits`` or ``precision_rounding``,\\n not both!\\n Example: 1.432 and 1.431 are equal at 2 digits precision,\\n so this method would return 0\\n However 0.006 and 0.002 are considered different (this method returns 1)\\n because they respectively round to 0.01 and 0.0, even though\\n 0.006-0.002 = 0.004 which would be considered zero at 2 digits precision.\\n Warning: ``float_is_zero(value1-value2)`` is not equivalent to\\n ``float_compare(value1,value2) == 0``, as the former will round after\\n computing the difference, while the latter will round before, giving\\n different results for e.g. 0.006 and 0.002 at 2 digits precision.\\n :param int precision_digits: number of fractional digits to round to.\\n :param float precision_rounding: decimal number representing the minimum\\n non-zero value at the desired precision (for example, 0.01 for a\\n 2-digit precision).\\n :param float value1: first value to compare\\n :param float value2: second value to compare\\n :return: (resp.) -1, 0 or 1, if ``value1`` is (resp.) lower than,\\n equal to, or greater than ``value2``, at the given precision.\\n \\\"\\\"\\\"\\n rounding_factor = _float_check_precision(precision_digits=precision_digits, precision_rounding=precision_rounding)\\n value1 = float_round(value1, precision_rounding=rounding_factor)\\n value2 = float_round(value2, precision_rounding=rounding_factor)\\n delta = (value1 - value2)\\n if float_is_zero(delta, precision_rounding=rounding_factor):\\n return 0\\n return ((-1) if (delta < 0.0) else 1)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_delete_url(comment):\\n\\n ''''Get the URL for the \\\"delete this comment\\\" view.'\\n '''\",\"targets\":\"if ((get_comment_app_name() != DEFAULT_COMMENTS_APP) and hasattr(get_comment_app(), 'get_delete_url')):\\n return get_comment_app().get_delete_url(comment)\\n else:\\n return urlresolvers.reverse('django.contrib.comments.views.moderation.delete', args=(comment.id,))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for _ in xrange(nbr_cases):\\n l = (np.random.randint(max_length) + 1)\\n inputs = [np.random.randint(nbr_symbols) for _ in xrange(l)]\\n (yield {'inputs': inputs, 'targets': list(reversed(inputs))})\\n\\n\\nWhat's a good function header?\",\"targets\":\"def reverse_generator(nbr_symbols, max_length, nbr_cases):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def extract_dependencies(reg, assignments):\",\"targets\":\"\\\"\\\"\\\"Return a list of all registers which directly\\n depend on the specified register.\\n Example:\\n >>> extract_dependencies(\\\\a\\\\, {\\\\a\\\\: 1})\\n >>> extract_dependencies(\\\\a\\\\, {\\\\a\\\\: \\\\b\\\\, \\\\b\\\\: 1})\\n >>> extract_dependencies(\\\\a\\\\, {\\\\a\\\\: 1, \\\\b\\\\: \\\\a\\\\})\\n [\\\\b\\\\]\\n >>> extract_dependencies(\\\\a\\\\, {\\\\a\\\\: 1, \\\\b\\\\: \\\\a\\\\, \\\\c\\\\: \\\\a\\\\})\\n [\\\\b\\\\, \\\\c\\\\]\\n \\\"\\\"\\\"\\n return sorted([k for (k, v) in assignments.items() if (v == reg)])\",\"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 _tidy_cmd, _tidy_exists\\n from commands import _options\\n require_tidy = _options.get('require_tidy')\\n if (not _tidy_exists):\\n if require_tidy:\\n raise TwillException('tidy does not exist and require_tidy is set')\\n return (None, None)\\n clean_html = None\\n if _tidy_exists:\\n try:\\n process = subprocess.Popen(_tidy_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, shell=False)\\n (stdout, stderr) = process.communicate(html)\\n clean_html = stdout\\n errors = stderr\\n except OSError:\\n _tidy_exists = False\\n errors = None\\n if (require_tidy and (clean_html is None)):\\n raise TwillException('tidy does not exist and require_tidy is set')\\n return (clean_html, errors)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def run_tidy(html):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _AddHasExtensionMethod(cls):\",\"targets\":\"\\\"\\\"\\\"Helper for _AddMessageMethods().\\n \\\"\\\"\\\"\\n def HasExtension(self, extension_handle):\\n _VerifyExtensionHandle(self, extension_handle)\\n if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED):\\n raise KeyError(('\\\"%s\\\" is repeated.' % extension_handle.full_name))\\n if (extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE):\\n value = self._fields.get(extension_handle)\\n return ((value is not None) and value._is_present_in_parent)\\n else:\\n return (extension_handle in self._fields)\\n cls.HasExtension = HasExtension\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef gce_connect(module, provider=None):\\n\\n ''''Return a GCP connection for Google Compute Engine.'\\n '''\",\"targets\":\"if (not HAS_LIBCLOUD_BASE):\\n module.fail_json(msg='libcloud must be installed to use this module')\\n provider = (provider or Provider.GCE)\\n return gcp_connect(module, provider, get_driver, USER_AGENT_PRODUCT, USER_AGENT_VERSION)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def floored_twelfth_of_a_year(date):\",\"targets\":\"\\\"\\\"\\\"This function converts a date to a month number by flooring\\n to the nearest 12th of a year.\\n \\\"\\\"\\\"\\n timetuple = date.timetuple()\\n year = timetuple.tm_year\\n day_of_year = timetuple.tm_yday\\n month0 = floor(((day_of_year \\/ ((isleap(year) and 366.0) or 365.0)) * 12))\\n return ((((year - start_year) * 12) + month0) - start_month_0_indexed)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _match_div_rewrite(expr, i):\\n\\n ''''helper for __trigsimp'\\n '''\",\"targets\":\"if (i == 0):\\n expr = _replace_mul_fpowxgpow(expr, sin, cos, _midn, tan, _idn)\\n elif (i == 1):\\n expr = _replace_mul_fpowxgpow(expr, tan, cos, _idn, sin, _idn)\\n elif (i == 2):\\n expr = _replace_mul_fpowxgpow(expr, cot, sin, _idn, cos, _idn)\\n elif (i == 3):\\n expr = _replace_mul_fpowxgpow(expr, tan, sin, _midn, cos, _midn)\\n elif (i == 4):\\n expr = _replace_mul_fpowxgpow(expr, cot, cos, _midn, sin, _midn)\\n elif (i == 5):\\n expr = _replace_mul_fpowxgpow(expr, cot, tan, _idn, _one, _idn)\\n elif (i == 8):\\n expr = _replace_mul_fpowxgpow(expr, sinh, cosh, _midn, tanh, _idn)\\n elif (i == 9):\\n expr = _replace_mul_fpowxgpow(expr, tanh, cosh, _idn, sinh, _idn)\\n elif (i == 10):\\n expr = _replace_mul_fpowxgpow(expr, coth, sinh, _idn, cosh, _idn)\\n elif (i == 11):\\n expr = _replace_mul_fpowxgpow(expr, tanh, sinh, _midn, cosh, _midn)\\n elif (i == 12):\\n expr = _replace_mul_fpowxgpow(expr, coth, cosh, _midn, sinh, _midn)\\n elif (i == 13):\\n expr = _replace_mul_fpowxgpow(expr, coth, tanh, _idn, _one, _idn)\\n else:\\n return None\\n return expr\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if is_installed('django.contrib.admin'):\\n admin_base = admin_reverse('index')\\n if path.startswith(admin_base):\\n match = ADMIN_PAGE_RE.search(path)\\n if match:\\n return Page.objects.filter(pk=match.group(1))\\n else:\\n return Page.objects.none()\\n if (not site):\\n site = Site.objects.get_current()\\n if draft:\\n pages = Page.objects.drafts().filter(site=site)\\n elif preview:\\n pages = Page.objects.public().filter(site=site)\\n else:\\n pages = Page.objects.public().published(site=site)\\n if (not path):\\n return pages.filter(is_home=True, site=site)[:1]\\n return pages.filter(title_set__path=path).distinct()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_page_queryset_from_path(path, preview=False, draft=False, site=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 hexval = ('%x' % ip.value)\\n if (len(hexval) < length):\\n hexval = (('0' * (length - len(hexval))) + hexval)\\n return hexval.upper()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def pretty_hex(ip, length=8):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_fqdn():\\n\\n ''''Get fully qualified domain name\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' network.get_fqdn'\\n '''\",\"targets\":\"return socket.getfqdn()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@frappe.whitelist()\\ndef get_student_guardians(student):\",\"targets\":\"\\\"\\\"\\\"Returns List of Guardians of a Student.\\n :param student: Student.\\n \\\"\\\"\\\"\\n guardians = frappe.get_list(u'Student Guardian', fields=[u'guardian'], filters={u'parent': student})\\n return guardians\",\"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_extras_install_from_pypi(script):\\n\\n ''''Test installing a package from PyPI using extras dependency Paste[openid].'\\n '''\",\"targets\":\"result = script.pip('install', 'Paste[openid]==1.7.5.1', expect_stderr=True)\\n initools_folder = (script.site_packages \\/ 'openid')\\n assert (initools_folder in result.files_created), result.files_created\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def attach_closed_milestones(queryset, as_field='closed_milestones_attr'):\",\"targets\":\"\\\"\\\"\\\"Attach a closed milestones counter to each object of the queryset.\\n :param queryset: A Django projects queryset object.\\n :param as_field: Attach the counter as an attribute with this name.\\n :return: Queryset object with the additional `as_field` field.\\n \\\"\\\"\\\"\\n model = queryset.model\\n sql = '\\\\n SELECT COUNT(milestones_milestone.id)\\\\n FROM milestones_milestone\\\\n WHERE milestones_milestone.project_id = {tbl}.id AND\\\\n milestones_milestone.closed = True\\\\n '\\n sql = sql.format(tbl=model._meta.db_table)\\n queryset = queryset.extra(select={as_field: sql})\\n return queryset\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def index(request, sitemaps):\",\"targets\":\"\\\"\\\"\\\"This view generates a sitemap index that uses the proper view\\n for resolving geographic section sitemap URLs.\\n \\\"\\\"\\\"\\n current_site = get_current_site(request)\\n sites = []\\n protocol = ((request.is_secure() and 'https') or 'http')\\n for (section, site) in sitemaps.items():\\n if callable(site):\\n pages = site().paginator.num_pages\\n else:\\n pages = site.paginator.num_pages\\n sitemap_url = urlresolvers.reverse('django.contrib.gis.sitemaps.views.sitemap', kwargs={'section': section})\\n sites.append(('%s:\\/\\/%s%s' % (protocol, current_site.domain, sitemap_url)))\\n if (pages > 1):\\n for page in range(2, (pages + 1)):\\n sites.append(('%s:\\/\\/%s%s?p=%s' % (protocol, current_site.domain, sitemap_url, page)))\\n xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites})\\n return HttpResponse(xml, content_type='application\\/xml')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def compile_info(record):\",\"targets\":\"\\\"\\\"\\\"Fill record with VM status information.\\n \\\"\\\"\\\"\\n return {'state': XENAPI_POWER_STATE[record['power_state']], 'max_mem': (long(record['memory_static_max']) >> 10), 'mem': (long(record['memory_dynamic_max']) >> 10), 'num_cpu': record['VCPUs_max'], 'cpu_time': 0}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@depends(HAS_PYVMOMI)\\n@ignores_kwargs('credstore')\\ndef list_vapps(host, username, password, protocol=None, port=None):\",\"targets\":\"\\\"\\\"\\\"Returns a list of vApps for the the specified host.\\n host\\n The location of the host.\\n username\\n The username used to login to the host, such as ``root``.\\n password\\n The password used to login to the host.\\n protocol\\n Optionally set to alternate protocol if the host is not using the default\\n protocol. Default protocol is ``https``.\\n port\\n Optionally set to alternate port if the host is not using the default\\n port. Default port is ``443``.\\n CLI Example:\\n .. code-block:: bash\\n # List vapps from all minions\\n salt \\\\*\\\\ vsphere.list_vapps 1.2.3.4 root bad-password\\n \\\"\\\"\\\"\\n service_instance = salt.utils.vmware.get_service_instance(host=host, username=username, password=password, protocol=protocol, port=port)\\n return salt.utils.vmware.list_vapps(service_instance)\",\"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 statsmodels.genmod.generalized_linear_model import GLM\\n from statsmodels.genmod.generalized_linear_model import families\\n from statsmodels.regression.linear_model import OLS\\n minz = min(zscores)\\n maxz = max(zscores)\\n bins = np.linspace(minz, maxz, nbins)\\n zhist = np.histogram(zscores, bins)[0]\\n zbins = ((bins[:(-1)] + bins[1:]) \\/ 2)\\n dmat = np.vander(zbins, (deg + 1))\\n md = OLS(np.log((1 + zhist)), dmat).fit()\\n md = GLM(zhist, dmat, family=families.Poisson()).fit(start_params=md.params)\\n dmat_full = np.vander(zscores, (deg + 1))\\n fz = (md.predict(dmat_full) \\/ (len(zscores) * (bins[1] - bins[0])))\\n if (null_pdf is None):\\n f0 = (np.exp(((-0.5) * (zscores ** 2))) \\/ np.sqrt((2 * np.pi)))\\n else:\\n f0 = null_pdf(zscores)\\n fdr = ((null_proportion * f0) \\/ fz)\\n fdr = np.clip(fdr, 0, 1)\\n return fdr\\n\\n\\nWhat's a good function header?\",\"targets\":\"def local_fdr(zscores, null_proportion=1.0, null_pdf=None, deg=7, nbins=30):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@verbose\\ndef _compute_forwards(rr, bem, coils_list, ccoils_list, infos, coil_types, n_jobs, verbose=None):\",\"targets\":\"\\\"\\\"\\\"Compute the MEG and EEG forward solutions.\\n This effectively combines compute_forward_meg and compute_forward_eeg\\n from MNE-C.\\n Parameters\\n rr : ndarray, shape (n_sources, 3)\\n 3D dipole in head coordinates\\n bem : dict\\n Boundary Element Model information for all surfaces\\n coils_list : list\\n List of MEG and\\/or EEG sensor information dicts\\n ccoils_list : list\\n Optional list of MEG compensation information\\n coil_types : list of str\\n Sensor types. May contain \\\\meg\\\\ and\\/or \\\\eeg\\\\\\n n_jobs: int\\n Number of jobs to run in parallel\\n infos : list, len(2)\\n infos[0] is MEG info, infos[1] is EEG info\\n Returns\\n Bs : list of ndarray\\n Each element contains ndarray, shape (3 * n_dipoles, n_sensors) where\\n n_sensors depends on which channel types are requested (MEG and\\/or EEG)\\n \\\"\\\"\\\"\\n fwd_data = dict(coils_list=coils_list, ccoils_list=ccoils_list, infos=infos, coil_types=coil_types)\\n _prep_field_computation(rr, bem, fwd_data, n_jobs)\\n Bs = _compute_forwards_meeg(rr, fwd_data, n_jobs)\\n return Bs\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n obj = results['obj'].clone()\\n if (obj.type == syms.arglist):\\n newarglist = obj.clone()\\n else:\\n newarglist = Node(syms.arglist, [obj.clone()])\\n after = results['after']\\n if after:\\n after = [n.clone() for n in after]\\n new = Node(syms.power, ((Attr(Name(names[0]), Name(names[1])) + [Node(syms.trailer, [results['lpar'].clone(), newarglist, results['rpar'].clone()])]) + after))\\n new.prefix = node.prefix\\n return new\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ImportAndCall(node, results, names):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getManipulatedGeometryOutput(elementNode, geometryOutput, prefix):\\n\\n ''''Get bottomed geometryOutput.'\\n '''\",\"targets\":\"derivation = BottomDerivation(elementNode, prefix)\\n copyShallow = elementNode.getCopyShallow()\\n solid.processElementNodeByGeometry(copyShallow, geometryOutput)\\n targetMatrix = matrix.getBranchMatrixSetElementNode(elementNode)\\n matrix.setElementNodeDictionaryMatrix(copyShallow, targetMatrix)\\n minimumZ = boolean_geometry.getMinimumZ(copyShallow.xmlObject)\\n copyShallow.parentNode.xmlObject.archivableObjects.remove(copyShallow.xmlObject)\\n lift = (derivation.altitude - minimumZ)\\n vertexes = matrix.getVertexes(geometryOutput)\\n for vertex in vertexes:\\n vertex.z += lift\\n return geometryOutput\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_currency_name(currency, locale=LC_NUMERIC):\",\"targets\":\"\\\"\\\"\\\"Return the name used by the locale for the specified currency.\\n >>> get_currency_name(\\\\USD\\\\, \\\\en_US\\\\)\\n u\\\\US Dollar\\\\\\n :param currency: the currency code\\n :param locale: the `Locale` object or locale identifier\\n :return: the currency symbol\\n :rtype: `unicode`\\n :since: version 0.9.4\\n \\\"\\\"\\\"\\n return Locale.parse(locale).currencies.get(currency, currency)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def listen_tcp(portrange, host, factory):\",\"targets\":\"\\\"\\\"\\\"Like reactor.listenTCP but tries different ports in a range.\\n \\\"\\\"\\\"\\n assert (len(portrange) <= 2), ('invalid portrange: %s' % portrange)\\n if (not hasattr(portrange, '__iter__')):\\n return reactor.listenTCP(portrange, factory, interface=host)\\n if (not portrange):\\n return reactor.listenTCP(0, factory, interface=host)\\n if (len(portrange) == 1):\\n return reactor.listenTCP(portrange[0], factory, interface=host)\\n for x in range(portrange[0], (portrange[1] + 1)):\\n try:\\n return reactor.listenTCP(x, factory, interface=host)\\n except error.CannotListenError:\\n if (x == portrange[1]):\\n raise\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@permission_required('users.add_userban')\\ndef revert_document(request, revision_id):\\n\\n ''''Revert document to a specific revision.'\\n '''\",\"targets\":\"revision = get_object_or_404(Revision.objects.select_related('document'), pk=revision_id)\\n comment = 'spam'\\n document = revision.document\\n old_revision_pk = revision.pk\\n try:\\n new_revision = document.revert(revision, request.user, comment)\\n if (new_revision.pk != old_revision_pk):\\n document.schedule_rendering('max-age=0')\\n except IntegrityError:\\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 _augknt(x, k):\\n\\n ''''Construct a knot vector appropriate for the order-k interpolation.'\\n '''\",\"targets\":\"return np.r_[(((x[0],) * k), x, ((x[(-1)],) * k))]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef channel_session_user(func):\\n\\n ''''Presents a message.user attribute obtained from a user ID in the channel\\n session, rather than in the http_session. Turns on channel session implicitly.'\\n '''\",\"targets\":\"@channel_session\\n @functools.wraps(func)\\n def inner(message, *args, **kwargs):\\n if (not hasattr(message, 'channel_session')):\\n raise ValueError('Did not see a channel session to get auth from')\\n if (message.channel_session is None):\\n from django.contrib.auth.models import AnonymousUser\\n message.user = AnonymousUser()\\n else:\\n fake_request = type('FakeRequest', (object,), {'session': message.channel_session})\\n message.user = auth.get_user(fake_request)\\n return func(message, *args, **kwargs)\\n return inner\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_strategy_name():\\n\\n ''''Return strategy module name.'\\n '''\",\"targets\":\"return 'store_type'\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def is_namedtuple(x):\",\"targets\":\"\\\"\\\"\\\"Check if object is an instance of namedtuple.\\n \\\"\\\"\\\"\\n t = type(x)\\n b = t.__bases__\\n if ((len(b) != 1) or (b[0] != tuple)):\\n return False\\n f = getattr(t, '_fields', None)\\n if (not isinstance(f, tuple)):\\n return False\\n return all(((type(n) == str) for n in f))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n permissions = permission_bound_field.field._queryset\\n content_type_ids = set(permissions.values_list(u'content_type_id', flat=True))\\n if (django.VERSION < (1, 11)):\\n checkboxes_by_id = {int(checkbox.choice_value): checkbox for checkbox in permission_bound_field}\\n else:\\n checkboxes_by_id = {int(checkbox.data[u'value']): checkbox for checkbox in permission_bound_field}\\n object_perms = []\\n other_perms = []\\n for content_type_id in content_type_ids:\\n content_perms = permissions.filter(content_type_id=content_type_id)\\n content_perms_dict = {}\\n for perm in content_perms:\\n checkbox = checkboxes_by_id[perm.id]\\n permission_action = perm.codename.split(u'_')[0]\\n if (permission_action in [u'add', u'change', u'delete']):\\n content_perms_dict[u'object'] = perm.content_type.name\\n content_perms_dict[permission_action] = checkbox\\n else:\\n other_perms.append((perm, checkbox))\\n if content_perms_dict:\\n object_perms.append(content_perms_dict)\\n return {u'object_perms': object_perms, u'other_perms': other_perms}\\n\\n\\nWhat's a good function header?\",\"targets\":\"@register.inclusion_tag(u'wagtailusers\\/groups\\/includes\\/formatted_permissions.html')\\ndef format_permissions(permission_bound_field):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_file(filename):\",\"targets\":\"\\\"\\\"\\\"Returns the path of a test file.\\n \\\"\\\"\\\"\\n return os.path.join(TEST_DIR, filename)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n mount_info = set()\\n for p in partition_list:\\n try:\\n uuid = utils.system_output(('blkid -p -s UUID -o value %s' % p.device))\\n except error.CmdError:\\n uuid = p.device\\n mount_info.add((uuid, p.get_mountpoint()))\\n return mount_info\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_mount_info(partition_list):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@conf.commands.register\\ndef sr1(x, filter=None, iface=None, nofilter=0, *args, **kargs):\",\"targets\":\"\\\"\\\"\\\"Send packets at layer 3 and return only the first answer\\n nofilter: put 1 to avoid use of bpf filters\\n retry: if positive, how many times to resend unanswered packets\\n if negative, how many times to retry when no more packets are answered\\n timeout: how much time to wait after the last packet has been sent\\n verbose: set verbosity level\\n multi: whether to accept multiple answers for the same stimulus\\n filter: provide a BPF filter\\n iface: listen answers only on the given interface\\n \\\"\\\"\\\"\\n if (not kargs.has_key('timeout')):\\n kargs['timeout'] = (-1)\\n s = conf.L3socket(filter=filter, nofilter=nofilter, iface=iface)\\n (a, b) = sndrcv(s, x, *args, **kargs)\\n s.close()\\n if (len(a) > 0):\\n return a[0][1]\\n else:\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def iter_all_children(obj, skipContainers=False):\",\"targets\":\"\\\"\\\"\\\"Returns an iterator over all children and nested children using\\n obj\\\\s get_children() method\\n if skipContainers is true, only childless objects are returned.\\n \\\"\\\"\\\"\\n if (hasattr(obj, 'get_children') and (len(obj.get_children()) > 0)):\\n for child in obj.get_children():\\n if (not skipContainers):\\n (yield child)\\n for grandchild in iter_all_children(child, skipContainers):\\n (yield grandchild)\\n else:\\n (yield obj)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_user_sites_queryset(user):\\n\\n ''''Returns queryset of all sites available for given user.\\n 1. For superuser always returns all sites.\\n 2. For global user returns all sites he haves in global page permissions\\n together with any sites he is assigned to over an page.\\n 3. For standard user returns just sites he is assigned to over pages.'\\n '''\",\"targets\":\"qs = Site.objects.all()\\n if ((not get_cms_setting('PERMISSION')) or user.is_superuser):\\n return qs\\n global_ids = GlobalPagePermission.objects.with_user(user).filter((Q(can_add=True) | Q(can_change=True))).values_list('id', flat=True)\\n query = Q()\\n if global_ids:\\n query = Q(globalpagepermission__id__in=global_ids)\\n if (not qs.filter(query).exists()):\\n return qs\\n query |= (Q((Q(djangocms_pages__pagepermission__user=user) | Q(djangocms_pages__pagepermission__group__user=user))) & Q((Q(djangocms_pages__pagepermission__can_add=True) | Q(djangocms_pages__pagepermission__can_change=True))))\\n return qs.filter(query).distinct()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef findTypeParent(element, tag):\\n\\n ''''Finds fist parent of element of the given type\\n @param object element: etree element\\n @param string the tag parent to search for\\n @return object element: the found parent or None when not found'\\n '''\",\"targets\":\"p = element\\n while True:\\n p = p.getparent()\\n if (p.tag == tag):\\n return p\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __virtual__():\",\"targets\":\"\\\"\\\"\\\"Only load if the docker execution module is available\\n \\\"\\\"\\\"\\n if ('docker.version' in __salt__):\\n return __virtualname__\\n return (False, __salt__.missing_fun_string('docker.version'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def charcount(s):\",\"targets\":\"\\\"\\\"\\\"Return number of characters in string, with ANSI color codes excluded.\\n \\\"\\\"\\\"\\n return len(ansirx.sub('', s))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def add_lazy_relation(cls, field, relation, operation):\",\"targets\":\"\\\"\\\"\\\"Adds a lookup on ``cls`` when a related field is defined using a string,\\n i.e.::\\n class MyModel(Model):\\n fk = ForeignKey(\\\"AnotherModel\\\")\\n This string can be:\\n * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. \\\"self\\\") to indicate a recursive\\n relation.\\n * The name of a model (i.e \\\"AnotherModel\\\") to indicate another model in\\n the same app.\\n * An app-label and model name (i.e. \\\"someapp.AnotherModel\\\") to indicate\\n another model in a different app.\\n If the other model hasn\\\\t yet been loaded -- almost a given if you\\\\re using\\n lazy relationships -- then the relation won\\\\t be set up until the\\n class_prepared signal fires at the end of model initialization.\\n operation is the work that must be performed once the relation can be resolved.\\n \\\"\\\"\\\"\\n if (relation == RECURSIVE_RELATIONSHIP_CONSTANT):\\n app_label = cls._meta.app_label\\n model_name = cls.__name__\\n else:\\n try:\\n (app_label, model_name) = relation.split('.')\\n except ValueError:\\n app_label = cls._meta.app_label\\n model_name = relation\\n except AttributeError:\\n app_label = relation._meta.app_label\\n model_name = relation._meta.object_name\\n model = get_model(app_label, model_name, False)\\n if model:\\n operation(field, model, cls)\\n else:\\n key = (app_label, model_name)\\n value = (cls, field, operation)\\n pending_lookups.setdefault(key, []).append(value)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for path in all_locale_paths():\\n if (gettext_module.find(u'django', path, [to_locale(lang_code)]) is not None):\\n return True\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_for_language(lang_code):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_enabled():\",\"targets\":\"\\\"\\\"\\\"Return a list of enabled services. Enabled is defined as a service that is\\n marked to Auto Start.\\n Returns:\\n list: A list of enabled services\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\*\\\\ service.get_enabled\\n \\\"\\\"\\\"\\n raw_services = _get_services()\\n services = set()\\n for service in raw_services:\\n if (info(service['ServiceName'])['StartType'] in ['Auto']):\\n services.add(service['ServiceName'])\\n return sorted(services)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n model = queryset.model\\n sql = '\\\\n SELECT json_agg(\\\\n row_to_json(custom_attributes_issuecustomattribute)\\\\n ORDER BY custom_attributes_issuecustomattribute.order\\\\n )\\\\n FROM custom_attributes_issuecustomattribute\\\\n WHERE custom_attributes_issuecustomattribute.project_id = {tbl}.id\\\\n '\\n sql = sql.format(tbl=model._meta.db_table)\\n queryset = queryset.extra(select={as_field: sql})\\n return queryset\\n\\n\\nWhat's a good function header?\",\"targets\":\"def attach_issue_custom_attributes(queryset, as_field='issue_custom_attributes_attr'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@bdd.when(bdd.parsers.parse('I wait until {path} is loaded'))\\ndef wait_until_loaded(quteproc, path):\",\"targets\":\"\\\"\\\"\\\"Wait until the given path is loaded (as per qutebrowser log).\\n \\\"\\\"\\\"\\n quteproc.wait_for_load_finished(path)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n content = json.loads(result_response.content)\\n assert_true(content['isSuccess'])\\n csv_link = ('\\/beeswax\\/download\\/%s\\/csv' % content['id'])\\n csv_resp = client.get(csv_link)\\n return ''.join(csv_resp.streaming_content)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_csv(client, result_response):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef changequery(**kw):\\n\\n ''''Imagine you\\\\'re at `\\/foo?a=1&b=2`. Then `changequery(a=3)` will return\\n `\\/foo?a=3&b=2` -- the same URL but with the arguments you requested\\n changed.'\\n '''\",\"targets\":\"query = input(_method='get')\\n for (k, v) in kw.iteritems():\\n if (v is None):\\n query.pop(k, None)\\n else:\\n query[k] = v\\n out = ctx.path\\n if query:\\n out += ('?' + urllib.urlencode(query))\\n return out\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_localzone():\\n\\n ''''Get the computers configured local timezone, if any.'\\n '''\",\"targets\":\"global _cache_tz\\n if (_cache_tz is None):\\n _cache_tz = _get_localzone()\\n return _cache_tz\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (backslash, dot) = ((u'\\\\\\\\', u'.') if isinstance(path, _unicode) else ('\\\\\\\\', '.'))\\n if path.startswith(('\\\\\\\\\\\\\\\\.\\\\\\\\', '\\\\\\\\\\\\\\\\?\\\\\\\\')):\\n return path\\n path = path.replace('\\/', '\\\\\\\\')\\n (prefix, path) = splitdrive(path)\\n if (prefix == ''):\\n while (path[:1] == '\\\\\\\\'):\\n prefix = (prefix + backslash)\\n path = path[1:]\\n elif path.startswith('\\\\\\\\'):\\n prefix = (prefix + backslash)\\n path = path.lstrip('\\\\\\\\')\\n comps = path.split('\\\\\\\\')\\n i = 0\\n while (i < len(comps)):\\n if (comps[i] in ('.', '')):\\n del comps[i]\\n elif (comps[i] == '..'):\\n if ((i > 0) and (comps[(i - 1)] != '..')):\\n del comps[(i - 1):(i + 1)]\\n i -= 1\\n elif ((i == 0) and prefix.endswith('\\\\\\\\')):\\n del comps[i]\\n else:\\n i += 1\\n else:\\n i += 1\\n if ((not prefix) and (not comps)):\\n comps.append(dot)\\n return (prefix + backslash.join(comps))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def normpath(path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n pass\\n\\n\\nWhat's a good function header?\",\"targets\":\"def simplify_jobs(joblist):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef logprob(predictions, labels):\\n\\n ''''Log-probability of the true labels in a predicted batch.'\\n '''\",\"targets\":\"predictions[(predictions < 1e-10)] = 1e-10\\n return (np.sum(np.multiply(labels, (- np.log(predictions)))) \\/ labels.shape[0])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def check_interaction(fn):\",\"targets\":\"\\\"\\\"\\\"Decorator to clean and prevent interaction when not available\\n \\\"\\\"\\\"\\n def check_fn(self, *args, **kwargs):\\n interact_lock.acquire()\\n try:\\n if self.filename:\\n self.clear_interaction()\\n return fn(self, *args, **kwargs)\\n finally:\\n interact_lock.release()\\n return check_fn\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def logistic_log_gradient_i(x_i, y_i, beta):\",\"targets\":\"\\\"\\\"\\\"the gradient of the log likelihood\\n corresponding to the i-th data point\\n \\\"\\\"\\\"\\n return [logistic_log_partial_ij(x_i, y_i, beta, j) for (j, _) in enumerate(beta)]\",\"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(s, basestring):\\n s = s.replace('\\\\\\\\n', '\\\\n')\\n s = s.replace('\\\\\\\\r', '\\\\r')\\n s = s.replace('\\\\\\\\\\\"', '\\\"')\\n return s\\n\\n\\nWhat's a good function header?\",\"targets\":\"def unescape(s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@register.inclusion_tag('inclusion.html')\\ndef inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Expected inclusion_unlimited_args_kwargs __doc__\\n \\\"\\\"\\\"\\n sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))\\n return {'result': ('inclusion_unlimited_args_kwargs - Expected result: %s \\/ %s' % (', '.join([six.text_type(arg) for arg in ([one, two] + list(args))]), ', '.join([('%s=%s' % (k, v)) for (k, v) in sorted_kwarg])))}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_buddy_info(chunk_sizes, nodes='all', zones='all'):\\n\\n ''''Get the fragement status of the host. It use the same method\\n to get the page size in buddyinfo.\\n 2^chunk_size * page_size\\n The chunk_sizes can be string make up by all orders that you want to check\\n splited with blank or a mathematical expression with \\\\'>\\\\', \\\\'<\\\\' or \\\\'=\\\\'.\\n For example:\\n The input of chunk_size could be: \\\"0 2 4\\\"\\n And the return will be: {\\\\'0\\\\': 3, \\\\'2\\\\': 286, \\\\'4\\\\': 687}\\n if you are using expression: \\\">=9\\\"\\n the return will be: {\\\\'9\\\\': 63, \\\\'10\\\\': 225}\\n :param chunk_size: The order number shows in buddyinfo. This is not\\n the real page size.\\n :type chunk_size: string\\n :param nodes: The numa node that you want to check. Default value is all\\n :type nodes: string\\n :param zones: The memory zone that you want to check. Default value is all\\n :type zones: string\\n :return: A dict using the chunk_size as the keys\\n :rtype: dict'\\n '''\",\"targets\":\"buddy_info = open('\\/proc\\/buddyinfo')\\n buddy_info_content = buddy_info.read()\\n buddy_info.close()\\n re_buddyinfo = 'Node\\\\\\\\s+'\\n if (nodes == 'all'):\\n re_buddyinfo += '(\\\\\\\\d+)'\\n else:\\n re_buddyinfo += ('(%s)' % '|'.join(nodes.split()))\\n if (not re.findall(re_buddyinfo, buddy_info_content)):\\n logging.warn(('Can not find Nodes %s' % nodes))\\n return None\\n re_buddyinfo += '.*?zone\\\\\\\\s+'\\n if (zones == 'all'):\\n re_buddyinfo += '(\\\\\\\\w+)'\\n else:\\n re_buddyinfo += ('(%s)' % '|'.join(zones.split()))\\n if (not re.findall(re_buddyinfo, buddy_info_content)):\\n logging.warn(('Can not find zones %s' % zones))\\n return None\\n re_buddyinfo += '\\\\\\\\s+([\\\\\\\\s\\\\\\\\d]+)'\\n buddy_list = re.findall(re_buddyinfo, buddy_info_content)\\n if (re.findall('[<>=]', chunk_sizes) and buddy_list):\\n size_list = range(len(buddy_list[(-1)][(-1)].strip().split()))\\n chunk_sizes = [str(_) for _ in size_list if eval(('%s %s' % (_, chunk_sizes)))]\\n chunk_sizes = ' '.join(chunk_sizes)\\n buddyinfo_dict = {}\\n for chunk_size in chunk_sizes.split():\\n buddyinfo_dict[chunk_size] = 0\\n for (_, _, chunk_info) in buddy_list:\\n chunk_info = chunk_info.strip().split()[int(chunk_size)]\\n buddyinfo_dict[chunk_size] += int(chunk_info)\\n return buddyinfo_dict\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (len(a) != len(b)):\\n return False\\n result = 0\\n for (x, y) in zip(a, b):\\n result |= (ord(x) ^ ord(y))\\n return (result == 0)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def compare_hashes(a, b):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def model(inputs):\\n 'Model function corresponding to a specific network architecture.'\\n outputs = {}\\n encoder_fn = _get_network(params.encoder_name)\\n with tf.variable_scope('encoder', reuse=reuse):\\n enc_outputs = encoder_fn(inputs['images_1'], params, is_training)\\n outputs['ids_1'] = enc_outputs['ids']\\n decoder_fn = _get_network(params.decoder_name)\\n with tf.variable_scope('decoder', reuse=reuse):\\n outputs['voxels_1'] = decoder_fn(outputs['ids_1'], params, is_training)\\n if run_projection:\\n projector_fn = _get_network(params.projector_name)\\n with tf.variable_scope('projector', reuse=reuse):\\n outputs['projs_1'] = projector_fn(outputs['voxels_1'], inputs['matrix_1'], params, is_training)\\n with tf.variable_scope('oracle', reuse=reuse):\\n outputs['masks_1'] = projector_fn(inputs['voxels'], inputs['matrix_1'], params, False)\\n for k in range(1, params.step_size):\\n with tf.variable_scope('projector', reuse=True):\\n outputs[('projs_%d' % (k + 1))] = projector_fn(outputs['voxels_1'], inputs[('matrix_%d' % (k + 1))], params, is_training)\\n with tf.variable_scope('oracle', reuse=True):\\n outputs[('masks_%d' % (k + 1))] = projector_fn(inputs['voxels'], inputs[('matrix_%d' % (k + 1))], params, False)\\n return outputs\\n return model\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get(params, is_training=False, reuse=False, run_projection=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 G = groebner(polys, gens, polys=True)\\n G = list(reversed(G))\\n domain = args.get('domain')\\n if (domain is not None):\\n for (i, g) in enumerate(G):\\n G[i] = g.set_domain(domain)\\n (f, G) = (G[0].ltrim((-1)), G[1:])\\n dom = f.get_domain()\\n zeros = f.ground_roots()\\n solutions = set([])\\n for zero in zeros:\\n solutions.add(((zero,), dom))\\n var_seq = reversed(gens[:(-1)])\\n vars_seq = postfixes(gens[1:])\\n for (var, vars) in zip(var_seq, vars_seq):\\n _solutions = set([])\\n for (values, dom) in solutions:\\n (H, mapping) = ([], list(zip(vars, values)))\\n for g in G:\\n _vars = ((var,) + vars)\\n if (g.has_only_gens(*_vars) and (g.degree(var) != 0)):\\n h = g.ltrim(var).eval(dict(mapping))\\n if (g.degree(var) == h.degree()):\\n H.append(h)\\n p = min(H, key=(lambda h: h.degree()))\\n zeros = p.ground_roots()\\n for zero in zeros:\\n if (not zero.is_Rational):\\n dom_zero = dom.algebraic_field(zero)\\n else:\\n dom_zero = dom\\n _solutions.add((((zero,) + values), dom_zero))\\n solutions = _solutions\\n solutions = list(solutions)\\n for (i, (solution, _)) in enumerate(solutions):\\n solutions[i] = solution\\n return sorted(solutions, key=default_sort_key)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def solve_triangulated(polys, *gens, **args):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n namespace_str = (namespace or '')\\n if kinds:\\n kind_str = ('all %s entities' % ', '.join(kinds))\\n else:\\n kind_str = ''\\n return (namespace_str, kind_str)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def GetPrintableStrs(namespace, kinds):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_certificate_template(course_key, mode):\",\"targets\":\"\\\"\\\"\\\"Retrieves the custom certificate template based on course_key and mode.\\n \\\"\\\"\\\"\\n (org_id, template) = (None, None)\\n course_organization = get_course_organizations(course_key)\\n if course_organization:\\n org_id = course_organization[0]['id']\\n if (org_id and mode):\\n template = CertificateTemplate.objects.filter(organization_id=org_id, course_key=course_key, mode=mode, is_active=True)\\n if ((not template) and org_id and mode):\\n template = CertificateTemplate.objects.filter(organization_id=org_id, course_key=CourseKeyField.Empty, mode=mode, is_active=True)\\n if ((not template) and org_id):\\n template = CertificateTemplate.objects.filter(organization_id=org_id, course_key=CourseKeyField.Empty, mode=None, is_active=True)\\n if ((not template) and mode):\\n template = CertificateTemplate.objects.filter(organization_id=None, course_key=CourseKeyField.Empty, mode=mode, is_active=True)\\n return (template[0].template if template else None)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef create_controller_spec(client_factory, key, adapter_type='lsiLogic'):\\n\\n ''''Builds a Config Spec for the LSI or Bus Logic Controller\\\\'s addition\\n which acts as the controller for the virtual hard disk to be attached\\n to the VM.'\\n '''\",\"targets\":\"virtual_device_config = client_factory.create('ns0:VirtualDeviceConfigSpec')\\n virtual_device_config.operation = 'add'\\n if (adapter_type == 'busLogic'):\\n virtual_controller = client_factory.create('ns0:VirtualBusLogicController')\\n else:\\n virtual_controller = client_factory.create('ns0:VirtualLsiLogicController')\\n virtual_controller.key = key\\n virtual_controller.busNumber = 0\\n virtual_controller.sharedBus = 'noSharing'\\n virtual_device_config.device = virtual_controller\\n return virtual_device_config\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef load_config(config_file=None, **kwargs):\\n\\n ''''Load the configuration for a given file object or name\\n The config_file can either be a file object, string or None. If it is None\\n the default `mkdocs.yml` filename will loaded.\\n Extra kwargs are passed to the configuration to replace any default values\\n unless they themselves are None.'\\n '''\",\"targets\":\"options = kwargs.copy()\\n for (key, value) in options.copy().items():\\n if (value is None):\\n options.pop(key)\\n config_file = _open_config_file(config_file)\\n options[u'config_file_path'] = getattr(config_file, u'name', u'')\\n from mkdocs import config\\n cfg = Config(schema=config.DEFAULT_SCHEMA)\\n cfg.load_file(config_file)\\n cfg.load_dict(options)\\n (errors, warnings) = cfg.validate()\\n for (config_name, warning) in warnings:\\n log.warning(u\\\"Config value: '%s'. Warning: %s\\\", config_name, warning)\\n for (config_name, error) in errors:\\n log.error(u\\\"Config value: '%s'. Error: %s\\\", config_name, error)\\n for (key, value) in cfg.items():\\n log.debug(u\\\"Config value: '%s' = %r\\\", key, value)\\n if (len(errors) > 0):\\n raise exceptions.ConfigurationError(u'Aborted with {0} Configuration Errors!'.format(len(errors)))\\n elif (cfg[u'strict'] and (len(warnings) > 0)):\\n raise exceptions.ConfigurationError(u\\\"Aborted with {0} Configuration Warnings in 'strict' mode!\\\".format(len(warnings)))\\n return cfg\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def factorized(A):\",\"targets\":\"\\\"\\\"\\\"Return a function for solving a sparse linear system, with A pre-factorized.\\n Parameters\\n A : (N, N) array_like\\n Input.\\n Returns\\n solve : callable\\n To solve the linear system of equations given in `A`, the `solve`\\n callable should be passed an ndarray of shape (N,).\\n Examples\\n >>> from scipy.sparse.linalg import factorized\\n >>> A = np.array([[ 3. , 2. , -1. ],\\n ... [ 2. , -2. , 4. ],\\n ... [-1. , 0.5, -1. ]])\\n >>> solve = factorized(A) # Makes LU decomposition.\\n >>> rhs1 = np.array([1, -2, 0])\\n >>> solve(rhs1) # Uses the LU factors.\\n array([ 1., -2., -2.])\\n \\\"\\\"\\\"\\n if useUmfpack:\\n if noScikit:\\n raise RuntimeError('Scikits.umfpack not installed.')\\n if (not isspmatrix_csc(A)):\\n A = csc_matrix(A)\\n warn('splu requires CSC matrix format', SparseEfficiencyWarning)\\n A = A.asfptype()\\n if (A.dtype.char not in 'dD'):\\n raise ValueError('convert matrix data to double, please, using .astype(), or set linsolve.useUmfpack = False')\\n umf = umfpack.UmfpackContext(_get_umf_family(A))\\n umf.numeric(A)\\n def solve(b):\\n return umf.solve(umfpack.UMFPACK_A, A, b, autoTranspose=True)\\n return solve\\n else:\\n return splu(A).solve\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef assert_is_quantized_sequence(note_sequence):\\n\\n ''''Confirms that the given NoteSequence proto has been quantized.\\n Args:\\n note_sequence: A music_pb2.NoteSequence proto.\\n Raises:\\n QuantizationStatusException: If the sequence is not quantized.'\\n '''\",\"targets\":\"if (not is_quantized_sequence(note_sequence)):\\n raise QuantizationStatusException(('NoteSequence %s is not quantized.' % note_sequence.id))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_signed_purchase_params(cart, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Return the parameters to send to the current payment processor.\\n Args:\\n cart (Order): The order model representing items in the user\\\\s cart.\\n Keyword Args:\\n Can be used to provide additional information to concrete implementations.\\n Returns:\\n dict\\n \\\"\\\"\\\"\\n return PROCESSOR_MODULE.get_signed_purchase_params(cart, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def boto_supports_param_in_spot_request(ec2, param):\",\"targets\":\"\\\"\\\"\\\"Check if Boto library has a in its request_spot_instances() method. For example, the placement_group parameter wasn\\\\t added until 2.3.0.\\n ec2: authenticated ec2 connection object\\n Returns:\\n True if boto library has the named param as an argument on the request_spot_instances method, else False\\n \\\"\\\"\\\"\\n method = getattr(ec2, 'request_spot_instances')\\n return (param in get_function_code(method).co_varnames)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef decrypt_password(encrypted_password, key=None):\\n\\n ''''Decrypt an encrypted password encoded in Base64.\\n This will decrypt a Base64-encoded encrypted password (from\\n :py:func:`encrypt_password`) into a usable password string.\\n Args:\\n encrypted_password (bytes):\\n The Base64-encoded encrypted password to decrypt.\\n key (bytes, optional):\\n The optional custom encryption key to use. This must match the key\\n used for encryption. If not supplied, the default encryption key\\n (from :py:func:`get_default_aes_encryption_key)` will be used.\\n Returns:\\n bytes:\\n The resulting password.\\n Raises:\\n ValueError:\\n The encryption key was not in the right format.'\\n '''\",\"targets\":\"return aes_decrypt(base64.b64decode(encrypted_password), key=key)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@with_setup(prepare_stdout)\\ndef test_output_level_1_fail():\\n\\n ''''Output with verbosity 2 must show only the scenario names, followed by \\\"... FAILED\\\" in case of fail'\\n '''\",\"targets\":\"runner = Runner(feature_name('failed_table'), verbosity=1)\\n runner.run()\\n assert_stdout_lines_with_traceback(('F\\\\n\\\\n\\\\nTraceback (most recent call last):\\\\n File \\\"%(lettuce_core_file)s\\\", line %(call_line)d, in __call__\\\\n ret = self.function(self.step, *args, **kw)\\\\n File \\\"%(step_file)s\\\", line 25, in tof\\\\n assert False\\\\nAssertionError\\\\n\\\\n1 feature (0 passed)\\\\n1 scenario (0 passed)\\\\n5 steps (1 failed, 2 skipped, 1 undefined, 1 passed)\\\\n\\\\nList of failed scenarios:\\\\n Scenario: See it fail # tests\\/functional\\/output_features\\/failed_table\\/failed_table.feature:2\\\\n\\\\n' % {'lettuce_core_file': lettuce_path('core.py'), 'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')), 'call_line': call_line}))\",\"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 = 'systemctl enable systemd-nspawn@{0}'.format(name)\\n if (__salt__['cmd.retcode'](cmd, python_shell=False) != 0):\\n __context__['retcode'] = salt.defaults.exitcodes.EX_UNAVAILABLE\\n return False\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"@_ensure_exists\\ndef enable(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _CopySortExpressionToProtocolBuffer(sort_expression, pb):\",\"targets\":\"\\\"\\\"\\\"Copies a SortExpression to a search_service_pb.SortSpec protocol buffer.\\n \\\"\\\"\\\"\\n pb.set_sort_expression(sort_expression.expression.encode('utf-8'))\\n if (sort_expression.direction == SortExpression.ASCENDING):\\n pb.set_sort_descending(False)\\n if (sort_expression.default_value is not None):\\n if isinstance(sort_expression.default_value, basestring):\\n pb.set_default_value_text(sort_expression.default_value.encode('utf-8'))\\n elif (isinstance(sort_expression.default_value, datetime.datetime) or isinstance(sort_expression.default_value, datetime.date)):\\n pb.set_default_value_text(str(search_util.EpochTime(sort_expression.default_value)))\\n else:\\n pb.set_default_value_numeric(sort_expression.default_value)\\n return pb\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n Loader.add_constructor(tag, constructor)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def add_constructor(tag, constructor, Loader=Loader):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@before.each_scenario\\ndef configure_screenshots(scenario):\",\"targets\":\"\\\"\\\"\\\"Before each scenario, turn off automatic screenshots.\\n Args: str, scenario. Name of current scenario.\\n \\\"\\\"\\\"\\n world.auto_capture_screenshots = False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def gen_with_app(*args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Decorate a test generator to pass a TestApp as the first argument to the\\n test generator when it\\\\s executed.\\n \\\"\\\"\\\"\\n def generator(func):\\n @wraps(func)\\n def deco(*args2, **kwargs2):\\n app = TestApp(*args, **kwargs)\\n for item in func(app, *args2, **kwargs2):\\n (yield item)\\n app.cleanup()\\n return deco\\n return generator\",\"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 (hToken == None):\\n TOKEN_ADJUST_PRIVILEGES = 32\\n TOKEN_QUERY = 8\\n hToken = HANDLE(INVALID_HANDLE_VALUE)\\n hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, windll.kernel32.GetCurrentProcessId())\\n windll.advapi32.OpenProcessToken(hProcess, (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), byref(hToken))\\n e = GetLastError()\\n if (e != 0):\\n raise WinError(e)\\n windll.kernel32.CloseHandle(hProcess)\\n privilege_id = LUID()\\n windll.advapi32.LookupPrivilegeValueA(None, privilegeStr, byref(privilege_id))\\n e = GetLastError()\\n if (e != 0):\\n raise WinError(e)\\n SE_PRIVILEGE_ENABLED = 2\\n laa = LUID_AND_ATTRIBUTES(privilege_id, SE_PRIVILEGE_ENABLED)\\n tp = TOKEN_PRIVILEGES(1, laa)\\n windll.advapi32.AdjustTokenPrivileges(hToken, False, byref(tp), sizeof(tp), None, None)\\n e = GetLastError()\\n if (e != 0):\\n raise WinError(e)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def EnablePrivilege(privilegeStr, hToken=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _scipy_univariate_kde(data, bw, gridsize, cut, clip):\",\"targets\":\"\\\"\\\"\\\"Compute a univariate kernel density estimate using scipy.\\n \\\"\\\"\\\"\\n try:\\n kde = stats.gaussian_kde(data, bw_method=bw)\\n except TypeError:\\n kde = stats.gaussian_kde(data)\\n if (bw != 'scott'):\\n msg = 'Ignoring bandwidth choice, please upgrade scipy to use a different bandwidth.'\\n warnings.warn(msg, UserWarning)\\n if isinstance(bw, string_types):\\n bw = ('scotts' if (bw == 'scott') else bw)\\n bw = (getattr(kde, ('%s_factor' % bw))() * np.std(data))\\n grid = _kde_support(data, bw, gridsize, cut, clip)\\n y = kde(grid)\\n return (grid, y)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def find_xpath_with_wait(context, id_str, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Tries to find an element with given XPATH with an explicit timeout.\\n context: a behave context\\n id_str: A string with the XPATH (no leading #)\\n kwargs: can optionally pass \\\"wait_time\\\", which will be the max wait time in\\n seconds. Default is defined by behave_helpers.py\\n Returns the element if found or raises TimeoutException\\n \\\"\\\"\\\"\\n return _find_elem_with_wait(context, (By.XPATH, id_str), **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 assert ((path or url_name) and (not (path and url_name))), 'Must have path or url_name parameter, but not both'\\n if (not cache):\\n cache = get_web_cache()\\n request = HttpRequest()\\n request.path = (path or reverse(url_name))\\n request.session = {settings.LANGUAGE_COOKIE_NAME: translation.get_language()}\\n cache_key = django_get_cache_key(request, cache=get_web_cache())\\n if ((not cache_key) and (not failure_ok)):\\n pass\\n return cache_key\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_cache_key(path=None, url_name=None, cache=None, failure_ok=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _find_image_files(data_dir, labels_file):\",\"targets\":\"\\\"\\\"\\\"Build a list of all images files and labels in the data set.\\n Args:\\n data_dir: string, path to the root directory of images.\\n Assumes that the image data set resides in JPEG files located in\\n the following directory structure.\\n data_dir\\/dog\\/another-image.JPEG\\n data_dir\\/dog\\/my-image.jpg\\n where \\\\dog\\\\ is the label associated with these images.\\n labels_file: string, path to the labels file.\\n The list of valid labels are held in this file. Assumes that the file\\n contains entries as such:\\n dog\\n cat\\n flower\\n where each line corresponds to a label. We map each label contained in\\n the file to an integer starting with the integer 0 corresponding to the\\n label contained in the first line.\\n Returns:\\n filenames: list of strings; each string is a path to an image file.\\n texts: list of strings; each string is the class, e.g. \\\\dog\\\\\\n labels: list of integer; each integer identifies the ground truth.\\n \\\"\\\"\\\"\\n print(('Determining list of input files and labels from %s.' % data_dir))\\n unique_labels = [l.strip() for l in tf.gfile.FastGFile(labels_file, 'r').readlines()]\\n labels = []\\n filenames = []\\n texts = []\\n label_index = 1\\n for text in unique_labels:\\n jpeg_file_path = ('%s\\/%s\\/*' % (data_dir, text))\\n matching_files = tf.gfile.Glob(jpeg_file_path)\\n labels.extend(([label_index] * len(matching_files)))\\n texts.extend(([text] * 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(labels))))\\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 texts = [texts[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(unique_labels), data_dir)))\\n return (filenames, texts, labels)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not hasattr(instance, 'cache_instance')):\\n return\\n sender.cache_instance(instance)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def update_cached_instance(sender, instance, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_all():\\n\\n ''''Return all installed services.\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' service.get_all'\\n '''\",\"targets\":\"ret = []\\n service = _cmd()\\n for svc in __salt__['cmd.run']('{0} ls all'.format(service)).splitlines():\\n ret.append(svc)\\n return sorted(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 add_devices([KNXSensor(hass, KNXConfig(config))])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def setup_platform(hass, config, add_devices, discovery_info=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_comment_app():\\n\\n ''''Get the comment app (i.e. \\\"django.contrib.comments\\\") as defined in the settings'\\n '''\",\"targets\":\"comments_app = get_comment_app_name()\\n if (comments_app not in settings.INSTALLED_APPS):\\n raise ImproperlyConfigured(('The COMMENTS_APP (%r) must be in INSTALLED_APPS' % settings.COMMENTS_APP))\\n try:\\n package = import_module(comments_app)\\n except ImportError:\\n raise ImproperlyConfigured('The COMMENTS_APP setting refers to a non-existing package.')\\n return package\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def broadcast_to(array, shape, subok=False):\",\"targets\":\"\\\"\\\"\\\"Broadcast an array to a new shape.\\n Parameters\\n array : array_like\\n The array to broadcast.\\n shape : tuple\\n The shape of the desired array.\\n subok : bool, optional\\n If True, then sub-classes will be passed-through, otherwise\\n the returned array will be forced to be a base-class array (default).\\n Returns\\n broadcast : array\\n A readonly view on the original array with the given shape. It is\\n typically not contiguous. Furthermore, more than one element of a\\n broadcasted array may refer to a single memory location.\\n Raises\\n ValueError\\n If the array is not compatible with the new shape according to NumPy\\\\s\\n broadcasting rules.\\n Notes\\n .. versionadded:: 1.10.0\\n Examples\\n >>> x = np.array([1, 2, 3])\\n >>> np.broadcast_to(x, (3, 3))\\n array([[1, 2, 3],\\n [1, 2, 3],\\n [1, 2, 3]])\\n \\\"\\\"\\\"\\n return _broadcast_to(array, shape, subok=subok, readonly=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def GetTensorOpName(x):\",\"targets\":\"\\\"\\\"\\\"Get the name of the op that created a tensor.\\n Useful for naming related tensors, as \\\\:\\\\ in name field of op is not permitted\\n Args:\\n x: the input tensor.\\n Returns:\\n the name of the op.\\n \\\"\\\"\\\"\\n t = x.name.rsplit(':', 1)\\n if (len(t) == 1):\\n return x.name\\n else:\\n return t[0]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n comps = []\\n ances = ancestry(path)\\n for anc in ances:\\n comp = os.path.basename(anc)\\n if comp:\\n comps.append(comp)\\n else:\\n comps.append(anc)\\n last = os.path.basename(path)\\n if last:\\n comps.append(last)\\n return comps\\n\\n\\nWhat's a good function header?\",\"targets\":\"def components(path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def f_threshold_mway_rm(n_subjects, factor_levels, effects='A*B', pvalue=0.05):\",\"targets\":\"\\\"\\\"\\\"Compute f-value thesholds for a two-way ANOVA.\\n Parameters\\n n_subjects : int\\n The number of subjects to be analyzed.\\n factor_levels : list-like\\n The number of levels per factor.\\n effects : str\\n A string denoting the effect to be returned. The following\\n mapping is currently supported:\\n * ``\\\\A\\\\``: main effect of A\\n * ``\\\\B\\\\``: main effect of B\\n * ``\\\\A:B\\\\``: interaction effect\\n * ``\\\\A+B\\\\``: both main effects\\n * ``\\\\A*B\\\\``: all three effects\\n pvalue : float\\n The p-value to be thresholded.\\n Returns\\n f_threshold : list | float\\n list of f-values for each effect if the number of effects\\n requested > 2, else float.\\n See Also\\n f_oneway\\n f_mway_rm\\n Notes\\n .. versionadded:: 0.10\\n \\\"\\\"\\\"\\n from scipy.stats import f\\n (effect_picks, _) = _map_effects(len(factor_levels), effects)\\n f_threshold = []\\n for (_, df1, df2) in _iter_contrasts(n_subjects, factor_levels, effect_picks):\\n f_threshold.append(f(df1, df2).isf(pvalue))\\n return (f_threshold if (len(f_threshold) > 1) else f_threshold[0])\",\"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 ((getpwnam is None) or (name is None)):\\n return None\\n try:\\n result = getpwnam(name)\\n except KeyError:\\n result = None\\n if (result is not None):\\n return result[2]\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_uid(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if isinstance(source, str):\\n source = xmlreader.InputSource(source)\\n elif hasattr(source, 'read'):\\n f = source\\n source = xmlreader.InputSource()\\n source.setByteStream(f)\\n if hasattr(f, 'name'):\\n source.setSystemId(f.name)\\n if (source.getByteStream() is None):\\n sysid = source.getSystemId()\\n basehead = os.path.dirname(os.path.normpath(base))\\n sysidfilename = os.path.join(basehead, sysid)\\n if os.path.isfile(sysidfilename):\\n source.setSystemId(sysidfilename)\\n f = open(sysidfilename, 'rb')\\n else:\\n source.setSystemId(urllib.parse.urljoin(base, sysid))\\n f = urllib.request.urlopen(source.getSystemId())\\n source.setByteStream(f)\\n return source\\n\\n\\nWhat's a good function header?\",\"targets\":\"def prepare_input_source(source, base=''):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _make_chunk_iter(stream, limit, buffer_size):\",\"targets\":\"\\\"\\\"\\\"Helper for the line and chunk iter functions.\\n \\\"\\\"\\\"\\n if isinstance(stream, (bytes, bytearray, text_type)):\\n raise TypeError('Passed a string or byte object instead of true iterator or stream.')\\n if (not hasattr(stream, 'read')):\\n for item in stream:\\n if item:\\n (yield item)\\n return\\n if ((not isinstance(stream, LimitedStream)) and (limit is not None)):\\n stream = LimitedStream(stream, limit)\\n _read = stream.read\\n while 1:\\n item = _read(buffer_size)\\n if (not item):\\n break\\n (yield item)\",\"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 in s):\\n return ('', s)\\n colon = 0\\n for i in range(len(s)):\\n if (s[i] == ':'):\\n colon = (i + 1)\\n (path, file) = (s[:(colon - 1)], s[colon:])\\n if (path and (not (':' in path))):\\n path = (path + ':')\\n return (path, file)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def split(s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef face_encodings(face_image, known_face_locations=None, num_jitters=1):\\n\\n ''''Given an image, return the 128-dimension face encoding for each face in the image.\\n :param face_image: The image that contains one or more faces\\n :param known_face_locations: Optional - the bounding boxes of each face if you already know them.\\n :param num_jitters: How many times to re-sample the face when calculating encoding. Higher is more accurate, but slower (i.e. 100 is 100x slower)\\n :return: A list of 128-dimentional face encodings (one for each face in the image)'\\n '''\",\"targets\":\"raw_landmarks = _raw_face_landmarks(face_image, known_face_locations)\\n return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@command(usage='echo arguments')\\ndef echo(args):\",\"targets\":\"\\\"\\\"\\\"lx echo ...\\n \\\"\\\"\\\"\\n print ' '.join(expand_command_line(args))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef import_vul_csv_part1():\\n\\n ''''Controller to manage the first phase of the import of vulnerability\\n indicators from CSV'\\n '''\",\"targets\":\"from gluon.serializers import json as jsons\\n try:\\n file = request.post_vars.file.file\\n except:\\n response.headers['Content-Type'] = 'application\\/json'\\n return jsons({'Error': s3_unicode(T('File missing'))})\\n authorised = auth.s3_has_permission('create', 'vulnerability_data')\\n if (not authorised):\\n response.headers['Content-Type'] = 'application\\/json'\\n return jsons({'Error': s3_unicode(T('You are not permitted to upload files'))})\\n output = s3_rest_controller('vulnerability', 'data', csv_stylesheet='data.xsl')\\n if ('Error' in output):\\n response.headers['Content-Type'] = 'application\\/json'\\n return jsons({'Error': s3_unicode(output['Error'])})\\n upload_id = output[0]\\n item_ids = output[1]\\n data = output[2]\\n from lxml import etree\\n loc_labels = {}\\n ele_dict = {}\\n for value in data:\\n if value['s3_import_item.error']:\\n response.headers['Content-Type'] = 'application\\/json'\\n return jsons({'Error': value['s3_import_item.error']})\\n ele = value['s3_import_item.element']\\n ele = s3xml.xml_decode(ele)\\n try:\\n element = etree.fromstring(ele)\\n except:\\n return T('No valid data in the file')\\n data_dict = {}\\n data = element.findall('data')\\n for item in data:\\n f = item.get('field', None)\\n v = item.get('value', None)\\n data_dict[f] = v\\n references = element.findall('reference')\\n for reference in references:\\n f = reference.get('field', None)\\n if (f == 'source_id'):\\n source_tuid = reference.get('tuid', None)\\n try:\\n loc_parts = source_tuid.split('\\/\\/')[1].split('\\/')\\n data_dict['location'] = loc_parts[(-1)]\\n level = loc_parts[0]\\n country_code = loc_parts[1]\\n if (country_code not in loc_labels):\\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 for fn in [filename, (filename + '.exe')]:\\n try:\\n if (installsubdir is None):\\n path = _where(fn)\\n else:\\n path = _where(fn, dirs=[os.path.join(os.environ[env], installsubdir)])\\n except IOError:\\n path = filename\\n else:\\n break\\n return path\\n\\n\\nWhat's a good function header?\",\"targets\":\"def win_find_exe(filename, installsubdir=None, env='ProgramFiles'):\",\"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 (pwhash.count('$') < 2):\\n return False\\n (hashval, method, salt) = pwhash.split('$', 2)\\n return (hash_password(password, method, salt, pepper) == hashval)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_password_hash(password, pwhash, pepper=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@handle_response_format\\n@treeio_login_required\\n@_process_mass_form\\ndef index_in_progress(request, response_format='html'):\",\"targets\":\"\\\"\\\"\\\"A page with a list of tasks in progress\\n \\\"\\\"\\\"\\n query = Q(parent__isnull=True)\\n if request.GET:\\n query = ((query & Q(status__hidden=False)) & _get_filter_query(request.GET))\\n else:\\n query = (query & Q(status__hidden=False))\\n tasks = Object.filter_by_request(request, Task.objects.filter(query))\\n milestones = Object.filter_by_request(request, Milestone.objects.filter(status__hidden=False))\\n filters = FilterForm(request.user.profile, 'status', request.GET)\\n time_slots = Object.filter_by_request(request, TaskTimeSlot.objects.filter(time_from__isnull=False, time_to__isnull=True))\\n context = _get_default_context(request)\\n context.update({'milestones': milestones, 'tasks': tasks, 'filters': filters, 'time_slots': time_slots})\\n return render_to_response('projects\\/index_in_progress', 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\":\"def acc_check(expected, got, rel_err=2e-15, abs_err=5e-323):\",\"targets\":\"\\\"\\\"\\\"Determine whether non-NaN floats a and b are equal to within a\\n (small) rounding error. The default values for rel_err and\\n abs_err are chosen to be suitable for platforms where a float is\\n represented by an IEEE 754 double. They allow an error of between\\n 9 and 19 ulps.\\n \\\"\\\"\\\"\\n if (math.isinf(expected) and (got == expected)):\\n return None\\n error = (got - expected)\\n permitted_error = max(abs_err, (rel_err * abs(expected)))\\n if (abs(error) < permitted_error):\\n return None\\n return 'error = {}; permitted error = {}'.format(error, permitted_error)\",\"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 = optparse.OptionParser(usage=usage)\\n parser.add_option('--gdb-executable', dest='gdb', default='gdb', help='gdb executable to use [default: gdb]')\\n parser.add_option('--verbose', '-v', dest='verbosity', action='count', default=0, help='Verbose mode. Multiple -v options increase the verbosity')\\n (options, args) = parser.parse_args()\\n if (path_to_debug_info is None):\\n if (len(args) > 1):\\n path_to_debug_info = args[0]\\n else:\\n path_to_debug_info = os.curdir\\n if (gdb_argv is None):\\n gdb_argv = args[1:]\\n if (path_to_debug_info == '--'):\\n no_import = True\\n logging_level = logging.WARN\\n if (options.verbosity == 1):\\n logging_level = logging.INFO\\n if (options.verbosity >= 2):\\n logging_level = logging.DEBUG\\n logging.basicConfig(level=logging_level)\\n logger.info('verbosity = %r', options.verbosity)\\n logger.debug('options = %r; args = %r', options, args)\\n logger.debug('Done parsing command-line options. path_to_debug_info = %r, gdb_argv = %r', path_to_debug_info, gdb_argv)\\n tempfilename = make_command_file(path_to_debug_info, no_import=no_import)\\n logger.info('Launching %s with command file: %s and gdb_argv: %s', options.gdb, tempfilename, gdb_argv)\\n with open(tempfilename) as tempfile:\\n logger.debug('Command file (%s) contains: \\\"\\\"\\\"\\\\n%s\\\"\\\"\\\"', tempfilename, tempfile.read())\\n logger.info('Spawning %s...', options.gdb)\\n p = subprocess.Popen(([options.gdb, '-command', tempfilename] + gdb_argv))\\n logger.info('Spawned %s (pid %d)', options.gdb, p.pid)\\n while True:\\n try:\\n logger.debug('Waiting for gdb (pid %d) to exit...', p.pid)\\n ret = p.wait()\\n logger.debug('Wait for gdb (pid %d) to exit is done. Returned: %r', p.pid, ret)\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def main(path_to_debug_info=None, gdb_argv=None, no_import=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef MainCGI(method, path, unused_headers, parameters, outfile):\\n\\n ''''CGI for all OAuth handlers.\\n Args:\\n method: HTTP method\\n path: Path of the request\\n unused_headers: Instance of mimetools.Message with headers from the request.\\n parameters: Dictionary of parameters from the request.\\n outfile: File-like object to which all output data should be written.'\\n '''\",\"targets\":\"if ((method != 'GET') and (method != 'POST')):\\n outfile.write('Status: 400\\\\r\\\\n')\\n return\\n if (path == _GET_REQUEST_TOKEN_URL):\\n OAuthGetRequestTokenCGI(outfile)\\n elif (path == _AUTHORIZE_TOKEN_URL):\\n OAuthAuthorizeTokenCGI(method, parameters, outfile)\\n elif (path == _GET_ACCESS_TOKEN_URL):\\n OAuthGetAccessTokenCGI(outfile)\\n else:\\n outfile.write('Status: 404 Unknown OAuth handler\\\\r\\\\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 dim = 1\\n batch_size = 3\\n n_batches = 10\\n m = (n_batches * batch_size)\\n dataset = ArangeDataset(m)\\n model = SoftmaxModel(dim)\\n monitor = Monitor.get_monitor(model)\\n learning_rate = 0.001\\n data_specs = (model.get_input_space(), model.get_input_source())\\n cost = DummyCost()\\n termination_criterion = EpochCounter(1)\\n monitor_rate = 3\\n em = EpochMonitor(model=model, tick_rate=None, monitor_rate=monitor_rate)\\n algorithm = SGD(learning_rate, cost, batch_size=batch_size, train_iteration_mode='sequential', monitoring_dataset=dataset, termination_criterion=termination_criterion, update_callbacks=[em], set_batch_size=False)\\n algorithm.setup(dataset=dataset, model=model)\\n algorithm.train(dataset)\\n for (key, val) in monitor.channels.items():\\n assert (len(val.val_record) == (n_batches \\/\\/ monitor_rate))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_epoch_monitor():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _beta_loss_to_float(beta_loss):\",\"targets\":\"\\\"\\\"\\\"Convert string beta_loss to float\\n \\\"\\\"\\\"\\n allowed_beta_loss = {'frobenius': 2, 'kullback-leibler': 1, 'itakura-saito': 0}\\n if (isinstance(beta_loss, str) and (beta_loss in allowed_beta_loss)):\\n beta_loss = allowed_beta_loss[beta_loss]\\n if (not isinstance(beta_loss, numbers.Number)):\\n raise ValueError(('Invalid beta_loss parameter: got %r instead of one of %r, or a float.' % (beta_loss, allowed_beta_loss.keys())))\\n return beta_loss\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@register.simple_tag(takes_context=True)\\ndef admin_widget(context, widget):\",\"targets\":\"\\\"\\\"\\\"Render a widget with the given information.\\n The widget will be created and returned as HTML. Any states in the\\n database will be loaded into the rendered widget.\\n \\\"\\\"\\\"\\n request = context.get(u'request')\\n siteconfig = SiteConfiguration.objects.get(site=Site.objects.get_current())\\n widget_states = siteconfig.get(u'widget_settings')\\n if widget_states:\\n widget.collapsed = (widget_states.get(widget.name, u'0') != u'0')\\n else:\\n widget.collapsed = False\\n return widget.render(request)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@cli.command()\\n@click.argument('result_pickle_file_path', type=click.Path(exists=True), required=True)\\n@click.option('--show\\/--hide', 'show', default=True)\\n@click.option('--plot-save', 'plot_save_file', default=None, type=click.Path(), help='save plot result to file')\\ndef plot(result_pickle_file_path, show, plot_save_file):\",\"targets\":\"\\\"\\\"\\\"[sys_analyser] draw result DataFrame\\n \\\"\\\"\\\"\\n import pandas as pd\\n from .plot import plot_result\\n result_dict = pd.read_pickle(result_pickle_file_path)\\n plot_result(result_dict, show, plot_save_file)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dict_to_sequence(d):\",\"targets\":\"\\\"\\\"\\\"Returns an internal sequence dictionary update.\\n \\\"\\\"\\\"\\n if hasattr(d, 'items'):\\n d = d.items()\\n return d\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n query_parts = []\\n sort_parts = []\\n subquery_parts = []\\n for part in (parts + [u',']):\\n if part.endswith(u','):\\n last_subquery_part = part[:(-1)]\\n if last_subquery_part:\\n subquery_parts.append(last_subquery_part)\\n query_parts.append(query_from_strings(query.AndQuery, model_cls, prefixes, subquery_parts))\\n del subquery_parts[:]\\n elif (part.endswith((u'+', u'-')) and (u':' not in part) and (len(part) > 1)):\\n sort_parts.append(part)\\n else:\\n subquery_parts.append(part)\\n q = (query.OrQuery(query_parts) if (len(query_parts) > 1) else query_parts[0])\\n s = sort_from_strings(model_cls, sort_parts)\\n return (q, s)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_sorted_query(model_cls, parts, prefixes={}):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n packer = Packer()\\n HOSTNAME = 'test'\\n SPOOF = 0\\n packer.pack_int(128)\\n packer.pack_string(HOSTNAME)\\n packer.pack_string(NAME)\\n packer.pack_int(SPOOF)\\n packer.pack_string(TYPE)\\n packer.pack_string(NAME)\\n packer.pack_string(UNITS)\\n packer.pack_int(slope_str2int[SLOPE])\\n packer.pack_uint(int(TMAX))\\n packer.pack_uint(int(DMAX))\\n if (GROUP == ''):\\n packer.pack_int(0)\\n else:\\n packer.pack_int(1)\\n packer.pack_string('GROUP')\\n packer.pack_string(GROUP)\\n data = Packer()\\n data.pack_int((128 + 5))\\n data.pack_string(HOSTNAME)\\n data.pack_string(NAME)\\n data.pack_int(SPOOF)\\n data.pack_string('%s')\\n data.pack_string(str(VAL))\\n return (packer.get_buffer(), data.get_buffer())\\n\\n\\nWhat's a good function header?\",\"targets\":\"def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP):\",\"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 callable(leftkey)):\\n leftkey = getter(leftkey)\\n if (not callable(rightkey)):\\n rightkey = getter(rightkey)\\n d = groupby(leftkey, leftseq)\\n seen_keys = set()\\n left_default_is_no_default = (left_default == no_default)\\n for item in rightseq:\\n key = rightkey(item)\\n seen_keys.add(key)\\n try:\\n left_matches = d[key]\\n for match in left_matches:\\n (yield (match, item))\\n except KeyError:\\n if (not left_default_is_no_default):\\n (yield (left_default, item))\\n if (right_default != no_default):\\n for (key, matches) in d.items():\\n if (key not in seen_keys):\\n for match in matches:\\n (yield (match, right_default))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def join(leftkey, leftseq, rightkey, rightseq, left_default=no_default, right_default=no_default):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n class MyServer(wsgi_server, ):\\n def error(self, req):\\n w = req.stdout.write\\n internalerror()\\n w((('Status: ' + ctx.status) + '\\\\r\\\\n'))\\n for (h, v) in ctx.headers:\\n w((((h + ': ') + v) + '\\\\r\\\\n'))\\n w(('\\\\r\\\\n' + ctx.output))\\n return MyServer\\n\\n\\nWhat's a good function header?\",\"targets\":\"def makeserver(wsgi_server):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@verbose\\ndef _read_raw_egi_mff(input_fname, montage=None, eog=None, misc=None, include=None, exclude=None, preload=False, channel_naming='E%d', verbose=None):\\n\\n ''''Read EGI mff binary as raw object.\\n .. note:: This function attempts to create a synthetic trigger channel.\\n See notes below.\\n Parameters\\n input_fname : str\\n Path to the raw file.\\n montage : str | None | instance of montage\\n Path or instance of montage containing electrode positions.\\n If None, sensor locations are (0,0,0). See the documentation of\\n :func:`mne.channels.read_montage` for more information.\\n eog : list or tuple\\n Names of channels or list of indices that should be designated\\n EOG channels. Default is None.\\n misc : list or tuple\\n Names of channels or list of indices that should be designated\\n MISC channels. Default is None.\\n include : None | list\\n The event channels to be ignored when creating the synthetic\\n trigger. Defaults to None.\\n Note. Overrides `exclude` parameter.\\n exclude : None | list\\n The event channels to be ignored when creating the synthetic\\n trigger. Defaults to None. If None, channels that have more than\\n one event and the ``sync`` and ``TREV`` channels will be\\n ignored.\\n preload : bool or str (default False)\\n Preload data into memory for data manipulation and faster indexing.\\n If True, the data will be preloaded into memory (fast, requires\\n large amount of memory). If preload is a string, preload is the\\n file name of a memory-mapped file which is used to store the data\\n on the hard drive (slower, requires less memory).\\n channel_naming : str\\n Channel naming convention for the data channels. Defaults to \\\\'E%d\\\\'\\n (resulting in channel names \\\\'E1\\\\', \\\\'E2\\\\', \\\\'E3\\\\'...). The effective default\\n prior to 0.14.0 was \\\\'EEG %03d\\\\'.\\n verbose : bool, str, int, or None\\n If not None, override default verbose level (see mne.verbose).\\n Returns\\n raw : Instance of RawMff\\n A Raw object containing EGI mff data.\\n Notes\\n The trigger channel names are based on the arbitrary user dependent event\\n codes used. However this function will attempt to generate a synthetic\\n trigger...'''\",\"targets\":\"return RawMff(input_fname, montage, eog, misc, include, exclude, preload, channel_naming, verbose)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef datetime2epoch(dt):\\n\\n ''''Convert a non-naive datetime object to a UNIX epoch timestamp'\\n '''\",\"targets\":\"if (dt is not None):\\n return calendar.timegm(dt.utctimetuple())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (X, Y) = check_pairwise_arrays(X, Y)\\n X_normalized = normalize(X, copy=True)\\n if (X is Y):\\n Y_normalized = X_normalized\\n else:\\n Y_normalized = normalize(Y, copy=True)\\n K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output)\\n return K\\n\\n\\nWhat's a good function header?\",\"targets\":\"def cosine_similarity(X, Y=None, dense_output=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 if (value is None):\\n return None\\n if isinstance(value, bool):\\n return value\\n elif isinstance(value, str):\\n if (value == 'no'):\\n return False\\n elif (value == 'yes'):\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def to_bool(value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _HandleCommonSuffix(first_handler, second_handler, common_suffix):\\n\\n ''''Strips matching suffix from handlers and intersects the substrings.'\\n '''\",\"targets\":\"stripped_first_handler = SimpleHandler(first_handler.pattern[:(- len(common_suffix))], first_handler.properties)\\n stripped_second_handler = SimpleHandler(second_handler.pattern[:(- len(common_suffix))], second_handler.properties)\\n stripped_handlers = _IntersectTwoHandlers(stripped_first_handler, stripped_second_handler)\\n handlers = set()\\n for stripped_handler in stripped_handlers:\\n handlers.add(SimpleHandler((stripped_handler.pattern + common_suffix), stripped_handler.properties))\\n return handlers\",\"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 (not os.path.exists(outpath)), outpath\\n if c_code:\\n if (not which('gcc')):\\n raise ValueError('gcc is not installed')\\n if (c_code is None):\\n c_code = textwrap.dedent('\\\\n #include \\\\n int main() {\\\\n pause();\\\\n return 1;\\\\n }\\\\n ')\\n with tempfile.NamedTemporaryFile(suffix='.c', delete=False, mode='wt') as f:\\n f.write(c_code)\\n try:\\n subprocess.check_call(['gcc', f.name, '-o', outpath])\\n finally:\\n safe_rmpath(f.name)\\n else:\\n shutil.copyfile(sys.executable, outpath)\\n if POSIX:\\n st = os.stat(outpath)\\n os.chmod(outpath, (st.st_mode | stat.S_IEXEC))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def create_exe(outpath, c_code=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 assertHasMessage(case, logger, ZFS_ERROR, {'status': 1, 'zfs_command': 'nonsense garbage made up no such command', 'output': '[Errno 2] No such file or directory'})\\n case.assertEqual(len(LoggedMessage.ofType(logger.messages, ZFS_ERROR)), 1)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def no_such_executable_logged(case, logger):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def cpu_count_logical():\",\"targets\":\"\\\"\\\"\\\"Return the number of logical CPUs in the system.\\n \\\"\\\"\\\"\\n try:\\n return os.sysconf('SC_NPROCESSORS_ONLN')\\n except ValueError:\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def list_nodes_full(conn=None, call=None):\",\"targets\":\"\\\"\\\"\\\"Return a list of the VMs that are on the provider, with all fields\\n \\\"\\\"\\\"\\n if (call == 'action'):\\n raise SaltCloudSystemExit('The list_nodes_full function must be called with -f or --function.')\\n if (not conn):\\n conn = get_conn()\\n ret = {}\\n datacenter_id = get_datacenter_id()\\n nodes = conn.list_servers(datacenter_id=datacenter_id, depth=3)\\n for item in nodes['items']:\\n node = {'id': item['id']}\\n node.update(item['properties'])\\n node['public_ips'] = []\\n node['private_ips'] = []\\n if (item['entities']['nics']['items'] > 0):\\n for nic in item['entities']['nics']['items']:\\n ip_address = nic['properties']['ips'][0]\\n if salt.utils.cloud.is_public_ip(ip_address):\\n node['public_ips'].append(ip_address)\\n else:\\n node['private_ips'].append(ip_address)\\n ret[node['name']] = node\\n __utils__['cloud.cache_node_list'](ret, __active_provider_name__.split(':')[0], __opts__)\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@verbose\\ndef infomax(data, weights=None, l_rate=None, block=None, w_change=1e-12, anneal_deg=60.0, anneal_step=0.9, extended=True, n_subgauss=1, kurt_size=6000, ext_blocks=1, max_iter=200, random_state=None, blowup=10000.0, blowup_fac=0.5, n_small_angle=20, use_bias=True, verbose=None):\",\"targets\":\"\\\"\\\"\\\"Run (extended) Infomax ICA decomposition on raw data.\\n Parameters\\n data : np.ndarray, shape (n_samples, n_features)\\n The whitened data to unmix.\\n weights : np.ndarray, shape (n_features, n_features)\\n The initialized unmixing matrix.\\n Defaults to None, which means the identity matrix is used.\\n l_rate : float\\n This quantity indicates the relative size of the change in weights.\\n Defaults to ``0.01 \\/ log(n_features ** 2)``.\\n .. note:: Smaller learning rates will slow down the ICA procedure.\\n block : int\\n The block size of randomly chosen data segments.\\n Defaults to floor(sqrt(n_times \\/ 3.)).\\n w_change : float\\n The change at which to stop iteration. Defaults to 1e-12.\\n anneal_deg : float\\n The angle (in degrees) at which the learning rate will be reduced.\\n Defaults to 60.0.\\n anneal_step : float\\n The factor by which the learning rate will be reduced once\\n ``anneal_deg`` is exceeded: ``l_rate *= anneal_step.``\\n Defaults to 0.9.\\n extended : bool\\n Whether to use the extended Infomax algorithm or not.\\n Defaults to True.\\n n_subgauss : int\\n The number of subgaussian components. Only considered for extended\\n Infomax. Defaults to 1.\\n kurt_size : int\\n The window size for kurtosis estimation. Only considered for extended\\n Infomax. Defaults to 6000.\\n ext_blocks : int\\n Only considered for extended Infomax. If positive, denotes the number\\n of blocks after which to recompute the kurtosis, which is used to\\n estimate the signs of the sources. In this case, the number of\\n sub-gaussian sources is automatically determined.\\n If negative, the number of sub-gaussian sources to be used is fixed\\n and equal to n_subgauss. In this case, the kurtosis is not estimated.\\n Defaults to 1.\\n max_iter : int\\n The maximum number of iterations. Defaults to 200.\\n random_state : int | np.random.RandomState\\n If random_state is an int, use random_state to seed the random number\\n generator. If random_state is already a...\\\"\\\"\\\"\\n from scipy.stats import kurtosis\\n rng = check_random_state(random_state)\\n max_weight = 100000000.0\\n restart_fac = 0.9\\n min_l_rate = 1e-10\\n degconst = (180.0 \\/ np.pi)\\n extmomentum = 0.5\\n signsbias = 0.02\\n signcount_threshold = 25\\n signcount_step = 2\\n (n_samples, n_features) = data.shape\\n n_features_square = (n_features ** 2)\\n if (l_rate is None):\\n l_rate = (0.01 \\/ math.log((n_features ** 2.0)))\\n if (block is None):\\n block = int(math.floor(math.sqrt((n_samples \\/ 3.0))))\\n logger.info((('computing%sInfomax ICA' % ' Extended ') if extended else ' '))\\n nblock = (n_samples \\/\\/ block)\\n lastt = (((nblock - 1) * block) + 1)\\n if (weights is None):\\n weights = np.identity(n_features, dtype=np.float64)\\n else:\\n weights = weights.T\\n BI = (block * np.identity(n_features, dtype=np.float64))\\n bias = np.zeros((n_features, 1), dtype=np.float64)\\n onesrow = np.ones((1, block), dtype=np.float64)\\n startweights = weights.copy()\\n oldweights = startweights.copy()\\n step = 0\\n count_small_angle = 0\\n wts_blowup = False\\n blockno = 0\\n signcount = 0\\n initial_ext_blocks = ext_blocks\\n if extended:\\n signs = np.ones(n_features)\\n for k in range(n_subgauss):\\n signs[k] = (-1)\\n kurt_size = min(kurt_size, n_samples)\\n old_kurt = np.zeros(n_features, dtype=np.float64)\\n oldsigns = np.zeros(n_features)\\n (olddelta, oldchange) = (1.0, 0.0)\\n while (step < max_iter):\\n permute = random_permutation(n_samples, rng)\\n for t in range(0, lastt, block):\\n u = np.dot(data[permute[t:(t + block)], :], weights)\\n u += np.dot(bias, onesrow).T\\n if extended:\\n y = np.tanh(u)\\n weights += (l_rate * np.dot(weights, ((BI - (signs[None, :] * np.dot(u.T, y))) - np.dot(u.T, u))))\\n if use_bias:\\n bias += (l_rate * np.reshape((np.sum(y, axis=0, dtype=np.float64) * (-2.0)), (n_features, 1)))\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef configure_inline_support(shell, backend):\\n\\n ''''Configure an IPython shell object for matplotlib use.\\n Parameters\\n shell : InteractiveShell instance\\n backend : matplotlib backend'\\n '''\",\"targets\":\"try:\\n from ipykernel.pylab.backend_inline import InlineBackend\\n except ImportError:\\n return\\n import matplotlib\\n cfg = InlineBackend.instance(parent=shell)\\n cfg.shell = shell\\n if (cfg not in shell.configurables):\\n shell.configurables.append(cfg)\\n if (backend == backends['inline']):\\n from ipykernel.pylab.backend_inline import flush_figures\\n shell.events.register('post_execute', flush_figures)\\n shell._saved_rcParams = {}\\n for k in cfg.rc:\\n shell._saved_rcParams[k] = matplotlib.rcParams[k]\\n matplotlib.rcParams.update(cfg.rc)\\n new_backend_name = 'inline'\\n else:\\n from ipykernel.pylab.backend_inline import flush_figures\\n try:\\n shell.events.unregister('post_execute', flush_figures)\\n except ValueError:\\n pass\\n if hasattr(shell, '_saved_rcParams'):\\n matplotlib.rcParams.update(shell._saved_rcParams)\\n del shell._saved_rcParams\\n new_backend_name = 'other'\\n cur_backend = getattr(configure_inline_support, 'current_backend', 'unset')\\n if (new_backend_name != cur_backend):\\n select_figure_formats(shell, cfg.figure_formats, **cfg.print_figure_kwargs)\\n configure_inline_support.current_backend = new_backend_name\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _generateScalar(filename='simple.csv', numSequences=2, elementsPerSeq=1, numRepeats=10, stepSize=0.1, resets=False):\\n\\n ''''Generate a simple dataset. This contains a bunch of non-overlapping\\n sequences of scalar values.\\n Parameters:\\n filename: name of the file to produce, including extension. It will\\n be created in a \\\\'datasets\\\\' sub-directory within the\\n directory containing this script.\\n numSequences: how many sequences to generate\\n elementsPerSeq: length of each sequence\\n numRepeats: how many times to repeat each sequence in the output\\n stepSize: how far apart each scalar is\\n resets: if True, turn on reset at start of each sequence'\\n '''\",\"targets\":\"scriptDir = os.path.dirname(__file__)\\n pathname = os.path.join(scriptDir, 'datasets', filename)\\n print ('Creating %s...' % pathname)\\n fields = [('reset', 'int', 'R'), ('category', 'int', 'C'), ('field1', 'float', '')]\\n outFile = FileRecordStream(pathname, write=True, fields=fields)\\n sequences = []\\n for i in range(numSequences):\\n seq = [x for x in range((i * elementsPerSeq), ((i + 1) * elementsPerSeq))]\\n sequences.append(seq)\\n seqIdxs = []\\n for i in range(numRepeats):\\n seqIdxs += range(numSequences)\\n random.shuffle(seqIdxs)\\n for seqIdx in seqIdxs:\\n reset = int(resets)\\n seq = sequences[seqIdx]\\n for x in seq:\\n outFile.appendRecord([reset, str(seqIdx), (x * stepSize)])\\n reset = 0\\n outFile.close()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _get_tab_registry(win_id, tab_id):\",\"targets\":\"\\\"\\\"\\\"Get the registry of a tab.\\n \\\"\\\"\\\"\\n if (tab_id is None):\\n raise ValueError('Got tab_id None (win_id {})'.format(win_id))\\n if ((tab_id == 'current') and (win_id is None)):\\n app = get('app')\\n window = app.activeWindow()\\n if ((window is None) or (not hasattr(window, 'win_id'))):\\n raise RegistryUnavailableError('tab')\\n win_id = window.win_id\\n elif (win_id is not None):\\n window = window_registry[win_id]\\n else:\\n raise TypeError('window is None with scope tab!')\\n if (tab_id == 'current'):\\n tabbed_browser = get('tabbed-browser', scope='window', window=win_id)\\n tab = tabbed_browser.currentWidget()\\n if (tab is None):\\n raise RegistryUnavailableError('window')\\n tab_id = tab.tab_id\\n tab_registry = get('tab-registry', scope='window', window=win_id)\\n try:\\n return tab_registry[tab_id].registry\\n except AttributeError:\\n raise RegistryUnavailableError('tab')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_prop_filter_spec(client_factory, obj_spec, prop_spec):\\n\\n ''''Builds the Property Filter Spec Object.'\\n '''\",\"targets\":\"prop_filter_spec = client_factory.create('ns0:PropertyFilterSpec')\\n prop_filter_spec.propSet = prop_spec\\n prop_filter_spec.objectSet = obj_spec\\n return prop_filter_spec\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def main():\",\"targets\":\"\\\"\\\"\\\"main entry point for module execution\\n \\\"\\\"\\\"\\n argument_spec = dict(commands=dict(type='list', required=True), wait_for=dict(type='list', aliases=['waitfor']), match=dict(default='all', choices=['all', 'any']), retries=dict(default=10, type='int'), interval=dict(default=1, type='int'))\\n argument_spec.update(dellos9_argument_spec)\\n module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)\\n result = {'changed': False}\\n warnings = list()\\n check_args(module, warnings)\\n commands = parse_commands(module, warnings)\\n result['warnings'] = warnings\\n wait_for = (module.params['wait_for'] or list())\\n conditionals = [Conditional(c) for c in wait_for]\\n retries = module.params['retries']\\n interval = module.params['interval']\\n match = module.params['match']\\n while (retries > 0):\\n responses = run_commands(module, commands)\\n for item in list(conditionals):\\n if item(responses):\\n if (match == 'any'):\\n conditionals = list()\\n break\\n conditionals.remove(item)\\n if (not conditionals):\\n break\\n time.sleep(interval)\\n retries -= 1\\n if conditionals:\\n failed_conditions = [item.raw for item in conditionals]\\n msg = 'One or more conditional statements have not be satisfied'\\n module.fail_json(msg=msg, failed_conditions=failed_conditions)\\n result = {'changed': False, 'stdout': responses, 'stdout_lines': list(to_lines(responses))}\\n module.exit_json(**result)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def compute_hash(localfn):\",\"targets\":\"\\\"\\\"\\\"Computes the MD5 hash for a file.\\n The hash for a data file is used for looking up data files in a unique\\n fashion. This is of particular use for tests; a test may require a\\n particular version of a particular file, in which case it can be accessed\\n via hash to get the appropriate version.\\n Typically, if you wish to write a test that requires a particular data\\n file, you will want to submit that file to the astropy data servers, and\\n use\\n e.g. ``get_pkg_data_filename(\\\\hash\\/34c33b3eb0d56eb9462003af249eff28\\\\)``,\\n but with the hash for your file in place of the hash in the example.\\n Parameters\\n localfn : str\\n The path to the file for which the hash should be generated.\\n Returns\\n md5hash : str\\n The hex digest of the MD5 hash for the contents of the ``localfn``\\n file.\\n \\\"\\\"\\\"\\n with open(localfn, u'rb') as f:\\n h = hashlib.md5()\\n block = f.read(conf.compute_hash_block_size)\\n while block:\\n h.update(block)\\n block = f.read(conf.compute_hash_block_size)\\n return h.hexdigest()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def clear_coefficients(expr, rhs=S.Zero):\",\"targets\":\"\\\"\\\"\\\"Return `p, r` where `p` is the expression obtained when Rational\\n additive and multiplicative coefficients of `expr` have been stripped\\n away in a naive fashion (i.e. without simplification). The operations\\n needed to remove the coefficients will be applied to `rhs` and returned\\n as `r`.\\n Examples\\n >>> from sympy.simplify.simplify import clear_coefficients\\n >>> from sympy.abc import x, y\\n >>> from sympy import Dummy\\n >>> expr = 4*y*(6*x + 3)\\n >>> clear_coefficients(expr - 2)\\n (y*(2*x + 1), 1\\/6)\\n When solving 2 or more expressions like `expr = a`,\\n `expr = b`, etc..., it is advantageous to provide a Dummy symbol\\n for `rhs` and simply replace it with `a`, `b`, etc... in `r`.\\n >>> rhs = Dummy(\\\\rhs\\\\)\\n >>> clear_coefficients(expr, rhs)\\n (y*(2*x + 1), _rhs\\/12)\\n >>> _[1].subs(rhs, 2)\\n 1\\/6\\n \\\"\\\"\\\"\\n was = None\\n free = expr.free_symbols\\n if expr.is_Rational:\\n return (S.Zero, (rhs - expr))\\n while (expr and (was != expr)):\\n was = expr\\n (m, expr) = (expr.as_content_primitive() if free else factor_terms(expr).as_coeff_Mul(rational=True))\\n rhs \\/= m\\n (c, expr) = expr.as_coeff_Add(rational=True)\\n rhs -= c\\n expr = signsimp(expr, evaluate=False)\\n if _coeff_isneg(expr):\\n expr = (- expr)\\n rhs = (- rhs)\\n return (expr, rhs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef javascript_prompt(url, js_msg, default, abort_on):\\n\\n ''''Display a javascript prompt.'\\n '''\",\"targets\":\"log.js.debug('prompt: {}'.format(js_msg))\\n if config.get('ui', 'modal-js-dialog'):\\n raise CallSuper\\n if config.get('content', 'ignore-javascript-prompt'):\\n return (False, '')\\n msg = '{}<\\/b> asks:{}'.format(html.escape(url.toDisplayString()), html.escape(js_msg))\\n answer = message.ask('Javascript prompt', msg, mode=usertypes.PromptMode.text, default=default, abort_on=abort_on)\\n if (answer is None):\\n return (False, '')\\n else:\\n return (True, answer)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def layer_norm_compute_python(x, epsilon, scale, bias):\",\"targets\":\"\\\"\\\"\\\"Layer norm raw computation.\\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)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getNewDerivation(elementNode, prefix, sideLength):\\n\\n ''''Get new derivation.'\\n '''\",\"targets\":\"return BevelDerivation(elementNode, prefix, sideLength)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _parse_text_rule(rule):\",\"targets\":\"\\\"\\\"\\\"Translates a policy written in the policy language into a tree of\\n Check objects.\\n \\\"\\\"\\\"\\n if (not rule):\\n return TrueCheck()\\n state = ParseState()\\n for (tok, value) in _parse_tokenize(rule):\\n state.shift(tok, value)\\n try:\\n return state.result\\n except ValueError:\\n LOG.exception((_('Failed to understand rule %(rule)r') % locals()))\\n return FalseCheck()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_pygments_extensions():\\n\\n ''''Return all file type extensions supported by Pygments'\\n '''\",\"targets\":\"import pygments.lexers as lexers\\n extensions = []\\n for lx in lexers.get_all_lexers():\\n lexer_exts = lx[2]\\n if lexer_exts:\\n other_exts = [le for le in lexer_exts if (not le.startswith('*'))]\\n lexer_exts = [le[1:] for le in lexer_exts if le.startswith('*')]\\n lexer_exts = [le for le in lexer_exts if (not le.endswith('_*'))]\\n extensions = ((extensions + list(lexer_exts)) + list(other_exts))\\n return sorted(list(set(extensions)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_base_network(input_dim):\",\"targets\":\"\\\"\\\"\\\"Base network to be shared (eq. to feature extraction).\\n \\\"\\\"\\\"\\n seq = Sequential()\\n seq.add(Dense(128, input_shape=(input_dim,), activation='relu'))\\n seq.add(Dropout(0.1))\\n seq.add(Dense(128, activation='relu'))\\n seq.add(Dropout(0.1))\\n seq.add(Dense(128, activation='relu'))\\n return seq\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if _is_pair(key):\\n key = key[1]\\n if (not isinstance(key, basestring)):\\n raise TypeError(('Key must be a string instance, received %r' % key))\\n if (not isinstance(key_prefix, basestring)):\\n raise TypeError(('key_prefix must be a string instance, received %r' % key_prefix))\\n server_key = (key_prefix + key)\\n if isinstance(server_key, unicode):\\n server_key = server_key.encode('utf-8')\\n if (len(server_key) > MAX_KEY_SIZE):\\n server_key = hashlib.sha1(server_key).hexdigest()\\n if (server_to_user_dict is not None):\\n assert isinstance(server_to_user_dict, dict)\\n server_to_user_dict[server_key] = key\\n return server_key\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _key_string(key, key_prefix='', server_to_user_dict=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def deleteFile():\",\"targets\":\"\\\"\\\"\\\"\\n \\\"\\\"\\\"\\n if ((GPSTRACKER_THREAD != None) and (GPSTRACKER_THREAD.isFollowing() == False)):\\n try:\\n os.remove(GPSTRACKER_THREAD.filename)\\n except OSError:\\n return False\\n return True\\n else:\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef add_section(data, label, icon, items):\\n\\n ''''Adds a section to the module data.'\\n '''\",\"targets\":\"if (not items):\\n return\\n data.append({u'label': label, u'icon': icon, u'items': items})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n d = (x - y)\\n return np.sqrt(np.dot(d, d))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def dist(x, y):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def lookupFor(typeCode):\",\"targets\":\"\\\"\\\"\\\"Return field definition class for the given type code.\\n ``typeCode`` must be a single character. That type should be\\n previously registered.\\n Use `registerField` to register new field class.\\n Return:\\n Return value is a subclass of the `DbfFieldDef`.\\n \\\"\\\"\\\"\\n return _fieldsRegistry[typeCode]\",\"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 backend in get_backends():\\n try:\\n user = backend.authenticate(**credentials)\\n except TypeError:\\n continue\\n if (user is None):\\n continue\\n user.backend = ('%s.%s' % (backend.__module__, backend.__class__.__name__))\\n return user\\n\\n\\nWhat's a good function header?\",\"targets\":\"def authenticate(**credentials):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@app.route('\\/add_message', methods=['POST'])\\ndef add_message():\\n\\n ''''Registers a new message for the user.'\\n '''\",\"targets\":\"if ('user_id' not in session):\\n abort(401)\\n if request.form['text']:\\n db = get_db()\\n db.execute('insert into message (author_id, text, pub_date)\\\\n values (?, ?, ?)', (session['user_id'], request.form['text'], int(time.time())))\\n db.commit()\\n flash('Your message was recorded')\\n return redirect(url_for('timeline'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef Int2AP(num):\\n\\n ''''string = Int2AP(num)\\n Return \\\\'num\\\\' converted to a string using characters from the set \\\\'A\\\\'..\\\\'P\\\\''\\n '''\",\"targets\":\"(val, a2p) = ([], 'ABCDEFGHIJKLMNOP')\\n num = int(abs(num))\\n while num:\\n (num, mod) = divmod(num, 16)\\n val.insert(0, a2p[mod])\\n return ''.join(val)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n allparts = []\\n while True:\\n parts = os.path.split(path)\\n if (parts[0] == path):\\n allparts.insert(0, parts[0])\\n break\\n elif (parts[1] == path):\\n allparts.insert(0, parts[1])\\n break\\n else:\\n path = parts[0]\\n allparts.insert(0, parts[1])\\n return allparts\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _splitall(path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _SetWsdlType(ns, wsdlName, typ):\",\"targets\":\"\\\"\\\"\\\"Set a WSDL type with wsdl namespace and wsdl name.\\n Returns added type \\/ existing type if (ns, wsdlName) already in the map\\n Note: Must be holding the _lazyLock, or in main init path\\n \\\"\\\"\\\"\\n return _wsdlTypeMap.setdefault((ns, wsdlName), typ)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef load_args_and_kwargs(func, args, data=None, ignore_invalid=False):\\n\\n ''''Detect the args and kwargs that need to be passed to a function call, and\\n check them against what was passed.'\\n '''\",\"targets\":\"argspec = salt.utils.args.get_function_argspec(func)\\n _args = []\\n _kwargs = {}\\n invalid_kwargs = []\\n for arg in args:\\n if (isinstance(arg, dict) and (arg.pop(u'__kwarg__', False) is True)):\\n for (key, val) in six.iteritems(arg):\\n if (argspec.keywords or (key in argspec.args)):\\n _kwargs[key] = val\\n else:\\n invalid_kwargs.append(u'{0}={1}'.format(key, val))\\n continue\\n else:\\n string_kwarg = salt.utils.args.parse_input([arg], condition=False)[1]\\n if string_kwarg:\\n if (argspec.keywords or (next(six.iterkeys(string_kwarg)) in argspec.args)):\\n _kwargs.update(string_kwarg)\\n else:\\n for (key, val) in six.iteritems(string_kwarg):\\n invalid_kwargs.append(u'{0}={1}'.format(key, val))\\n else:\\n _args.append(arg)\\n if (invalid_kwargs and (not ignore_invalid)):\\n salt.utils.args.invalid_kwargs(invalid_kwargs)\\n if (argspec.keywords and isinstance(data, dict)):\\n for (key, val) in six.iteritems(data):\\n _kwargs[u'__pub_{0}'.format(key)] = val\\n return (_args, _kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@contextlib.contextmanager\\ndef unset_organization():\\n\\n ''''Temporarily unset QApplication.organizationName().\\n This is primarily needed in config.py.'\\n '''\",\"targets\":\"qapp = QApplication.instance()\\n orgname = qapp.organizationName()\\n qapp.setOrganizationName(None)\\n try:\\n (yield)\\n finally:\\n qapp.setOrganizationName(orgname)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef bugs_to_json_response(data, bunch_of_bugs, callback_function_name=''):\\n\\n ''''The search results page accesses this view via jQuery\\\\'s getJSON method,\\n and loads its results into the DOM.'\\n '''\",\"targets\":\"obj_serializer = serializers.get_serializer('python')()\\n bugs = obj_serializer.serialize(bunch_of_bugs)\\n for bug in bugs:\\n project = Project.objects.get(pk=int(bug['fields']['project']))\\n bug['fields']['project'] = project.display_name\\n data_list = [{'bugs': bugs}]\\n json_as_string = json.dumps(data_list, default=encode_datetime)\\n json_string_with_callback = (((callback_function_name + '(') + json_as_string) + ')')\\n return HttpResponse(json_string_with_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 platform = '-'.join((x.strip() for x in filter(len, args)))\\n platform = platform.replace(' ', '_')\\n platform = platform.replace('\\/', '-')\\n platform = platform.replace('\\\\\\\\', '-')\\n platform = platform.replace(':', '-')\\n platform = platform.replace(';', '-')\\n platform = platform.replace('\\\"', '-')\\n platform = platform.replace('(', '-')\\n platform = platform.replace(')', '-')\\n platform = platform.replace('unknown', '')\\n while 1:\\n cleaned = platform.replace('--', '-')\\n if (cleaned == platform):\\n break\\n platform = cleaned\\n while (platform[(-1)] == '-'):\\n platform = platform[:(-1)]\\n return platform\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _platform(*args):\",\"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 (line_min is None):\\n line_min = math.floor(((int(_get_window_columns()) \\/ 2) - 15))\\n if (long_phrase is None):\\n return long_phrase\\n line_min = int(line_min)\\n nl_loc = []\\n skip = False\\n index = 0\\n if (len(long_phrase) > line_min):\\n for _ in range(int(math.floor((len(long_phrase) \\/ line_min)))):\\n previous = index\\n index += line_min\\n if skip:\\n index += 1\\n skip = False\\n while ((index < len(long_phrase)) and (not long_phrase[index].isspace()) and (index < ((tolerance + previous) + line_min))):\\n index += 1\\n if (index < len(long_phrase)):\\n if long_phrase[index].isspace():\\n index += 1\\n skip = True\\n nl_loc.append(index)\\n counter = 0\\n for loc in nl_loc:\\n long_phrase = ((long_phrase[:(loc + counter)] + '\\\\n') + long_phrase[(loc + counter):])\\n counter += 1\\n return (long_phrase + '\\\\n')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def add_new_lines(long_phrase, line_min=None, tolerance=TOLERANCE):\",\"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 (value is None):\\n collectd.warning(('marathon plugin: Value not found for %s' % name))\\n return\\n log_verbose(('Sending value[%s]: %s=%s' % (type, name, value)))\\n val = collectd.Values(plugin='marathon')\\n val.type = type\\n val.type_instance = name\\n val.values = [value]\\n val.dispatch()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def dispatch_stat(type, name, value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef align_block(raw, multiple=4, pad='\\\\x00'):\\n\\n ''''Return raw with enough pad bytes append to ensure its length is a multiple\\n of 4.'\\n '''\",\"targets\":\"extra = (len(raw) % multiple)\\n if (extra == 0):\\n return raw\\n return (raw + (pad * (multiple - extra)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef enable_2fa():\\n\\n ''''Enable Two factor in system settings.'\\n '''\",\"targets\":\"system_settings = frappe.get_doc(u'System Settings')\\n system_settings.enable_two_factor_auth = 1\\n system_settings.two_factor_method = u'OTP App'\\n system_settings.save(ignore_permissions=True)\\n frappe.db.commit()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if hasattr(sys, u'getwindowsversion'):\\n raise NotImplementedError()\\n else:\\n from distutils.ccompiler import new_compiler\\n compiler = new_compiler().compiler\\n cflags = os.environ.get(u'CFLAGS', str(u'-O3'))\\n subprocess.check_call(((compiler + shlex.split(cflags)) + [u'client\\/powerline.c', u'-o', u'scripts\\/powerline']))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def compile_client():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef gradient_terms(binomial_power=0):\\n\\n ''''Returns a list of all the possible\\n monomials between 0 and y**binomial_power\\n Parameters\\n binomial_power : Power upto which terms are generated.\\n Examples\\n >>> from sympy.abc import x, y\\n >>> from sympy.integrals.intpoly import gradient_terms\\n >>> gradient_terms(2)\\n [[1, 0, 0, None], [y, 0, 1, None], [y**2, 0, 2, None], [x, 1, 0, None], [x*y, 1, 1, None], [x**2, 2, 0, None]]'\\n '''\",\"targets\":\"terms = []\\n for x_count in range(0, (binomial_power + 1)):\\n for y_count in range(0, ((binomial_power - x_count) + 1)):\\n terms.append([((x ** x_count) * (y ** y_count)), x_count, y_count, None])\\n return terms\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def evennia_version():\",\"targets\":\"\\\"\\\"\\\"Get the Evennia version info from the main package.\\n \\\"\\\"\\\"\\n version = 'Unknown'\\n try:\\n version = evennia.__version__\\n except ImportError:\\n pass\\n try:\\n rev = check_output('git rev-parse --short HEAD', shell=True, cwd=EVENNIA_ROOT, stderr=STDOUT).strip()\\n version = ('%s (rev %s)' % (version, rev))\\n except (IOError, CalledProcessError):\\n pass\\n return version\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n Loader.add_constructor(tag, constructor)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def add_constructor(tag, constructor, Loader=Loader):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def is_enabled(name):\",\"targets\":\"\\\"\\\"\\\"List a Job only if its enabled\\n .. versionadded:: 2015.5.3\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\*\\\\ schedule.is_enabled name=job_name\\n \\\"\\\"\\\"\\n current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False)\\n if (name in current_schedule):\\n return current_schedule[name]\\n else:\\n return {}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def get_position(current_str):\\n return (len(fields_str) - len(current_str))\\n def parse_field_identifier(fields_str):\\n first_char = True\\n negated = False\\n ident = u''\\n while fields_str:\\n char = fields_str[0]\\n if (char in [u'(', u')', u',']):\\n if (not ident):\\n raise FieldsParameterParseError((u\\\"unexpected char '%s' at position %d\\\" % (char, get_position(fields_str))))\\n if ((ident in [u'*', u'_']) and (char == u'(')):\\n raise FieldsParameterParseError((u\\\"unexpected char '%s' at position %d\\\" % (char, get_position(fields_str))))\\n return (ident, negated, fields_str)\\n elif (char == u'-'):\\n if (not first_char):\\n raise FieldsParameterParseError((u\\\"unexpected char '%s' at position %d\\\" % (char, get_position(fields_str))))\\n negated = True\\n elif (char in [u'*', u'_']):\\n if (ident and (char == u'*')):\\n raise FieldsParameterParseError((u\\\"unexpected char '%s' at position %d\\\" % (char, get_position(fields_str))))\\n ident += char\\n elif (char.isalnum() or (char == u'_')):\\n if (ident == u'*'):\\n raise FieldsParameterParseError((u\\\"unexpected char '%s' at position %d\\\" % (char, get_position(fields_str))))\\n ident += char\\n elif char.isspace():\\n raise FieldsParameterParseError((u'unexpected whitespace at position %d' % get_position(fields_str)))\\n else:\\n raise FieldsParameterParseError((u\\\"unexpected char '%s' at position %d\\\" % (char, get_position(fields_str))))\\n first_char = False\\n fields_str = fields_str[1:]\\n return (ident, negated, fields_str)\\n def parse_fields(fields_str, expect_close_bracket=False):\\n first_ident = None\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def parse_fields_parameter(fields_str):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _exception_traceback(exc_info):\\n\\n ''''Return a string containing a traceback message for the given\\n exc_info tuple (as returned by sys.exc_info()).'\\n '''\",\"targets\":\"excout = StringIO()\\n (exc_type, exc_val, exc_tb) = exc_info\\n traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)\\n return excout.getvalue()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def conv(x, y, mode=2):\",\"targets\":\"\\\"\\\"\\\"convolve x with y\\n \\\"\\\"\\\"\\n warnings.warn(\\\"Use numpy.convolve(x, y, mode='full')\\\", DeprecationWarning)\\n return np.convolve(x, y, mode)\",\"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 jid):\\n raise InvalidJidError()\\n request = xmpp_service_pb.BulkPresenceRequest()\\n response = xmpp_service_pb.BulkPresenceResponse()\\n if isinstance(jid, basestring):\\n single_jid = True\\n jidlist = [jid]\\n else:\\n single_jid = False\\n get_show = True\\n jidlist = jid\\n for given_jid in jidlist:\\n request.add_jid(_to_str(given_jid))\\n if from_jid:\\n request.set_from_jid(_to_str(from_jid))\\n try:\\n apiproxy_stub_map.MakeSyncCall('xmpp', 'BulkGetPresence', request, response)\\n except apiproxy_errors.ApplicationError as e:\\n if (e.application_error == xmpp_service_pb.XmppServiceError.INVALID_JID):\\n raise InvalidJidError()\\n elif (e.application_error == xmpp_service_pb.XmppServiceError.NONDEFAULT_MODULE):\\n raise NondefaultModuleError()\\n else:\\n raise Error()\\n def HandleSubresponse(subresponse):\\n if get_show:\\n if subresponse.has_presence():\\n presence = subresponse.presence()\\n show = _PRESENCE_SHOW_MAPPING.get(presence, None)\\n else:\\n show = None\\n return (bool(subresponse.is_available()), show, subresponse.valid())\\n else:\\n return (bool(subresponse.is_available()), subresponse.valid())\\n results = [HandleSubresponse(s) for s in response.presence_response_list()]\\n if (not any((t[(-1)] for t in results))):\\n raise InvalidJidError()\\n if single_jid:\\n if get_show:\\n return results[0][:(-1)]\\n else:\\n return results[0][0]\\n else:\\n return results\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_presence(jid, from_jid=None, get_show=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def copy_plural_forms(msgs, locale, domain, verbosity, stdout=sys.stdout):\",\"targets\":\"\\\"\\\"\\\"Copies plural forms header contents from a Django catalog of locale to\\n the msgs string, inserting it at the right place. msgs should be the\\n contents of a newly created .po file.\\n \\\"\\\"\\\"\\n django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__)))\\n if (domain == 'djangojs'):\\n domains = ('djangojs', 'django')\\n else:\\n domains = ('django',)\\n for domain in domains:\\n django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', ('%s.po' % domain))\\n if os.path.exists(django_po):\\n with open(django_po, 'rU') as fp:\\n m = plural_forms_re.search(fp.read())\\n if m:\\n if (verbosity > 1):\\n stdout.write(('copying plural forms: %s\\\\n' % m.group('value')))\\n lines = []\\n seen = False\\n for line in msgs.split('\\\\n'):\\n if ((not line) and (not seen)):\\n line = ('%s\\\\n' % m.group('value'))\\n seen = True\\n lines.append(line)\\n msgs = '\\\\n'.join(lines)\\n break\\n return msgs\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n n = x1.shape[1]\\n if (x2.shape[1] != n):\\n raise ValueError(\\\"Number of points don't match.\\\")\\n X = [triangulate_point(x1[:, i], x2[:, i], P1, P2) for i in range(n)]\\n return array(X).T\\n\\n\\nWhat's a good function header?\",\"targets\":\"def triangulate(x1, x2, P1, P2):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _timestamp(pathname):\",\"targets\":\"\\\"\\\"\\\"Return the file modification time as a Long.\\n \\\"\\\"\\\"\\n try:\\n s = _os_stat(pathname)\\n except OSError:\\n return None\\n return long(s.st_mtime)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@functools.lru_cache(maxsize=None)\\ndef no_style():\",\"targets\":\"\\\"\\\"\\\"Return a Style object with no color scheme.\\n \\\"\\\"\\\"\\n return make_style('nocolor')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n A = _asarray_square(A)\\n if np.iscomplexobj(A):\\n return (0.5 * (expm((1j * A)) + expm(((-1j) * A))))\\n else:\\n return expm((1j * A)).real\\n\\n\\nWhat's a good function header?\",\"targets\":\"def cosm(A):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (':' not in s):\\n return simple_import(s)\\n (module_name, expr) = s.split(':', 1)\\n module = import_module(module_name)\\n obj = eval(expr, module.__dict__)\\n return obj\\n\\n\\nWhat's a good function header?\",\"targets\":\"def eval_import(s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def include_config(include, orig_path, verbose, exit_on_config_errors=False):\",\"targets\":\"\\\"\\\"\\\"Parses extra configuration file(s) specified in an include list in the\\n main config file.\\n \\\"\\\"\\\"\\n if (not include):\\n return {}\\n if (orig_path is None):\\n return {}\\n if isinstance(include, six.string_types):\\n include = [include]\\n configuration = {}\\n for path in include:\\n path = os.path.expanduser(path)\\n if (not os.path.isabs(path)):\\n path = os.path.join(os.path.dirname(orig_path), path)\\n if (len(glob.glob(path)) == 0):\\n if verbose:\\n log.warning('Warning parsing configuration file: \\\"include\\\" path\\/glob \\\\'{0}\\\\' matches no files'.format(path))\\n for fn_ in sorted(glob.glob(path)):\\n log.debug(\\\"Including configuration from '{0}'\\\".format(fn_))\\n try:\\n opts = _read_conf_file(fn_)\\n except salt.exceptions.SaltConfigurationError as error:\\n log.error(error)\\n if exit_on_config_errors:\\n sys.exit(salt.defaults.exitcodes.EX_GENERIC)\\n else:\\n opts = {}\\n schedule = opts.get('schedule', {})\\n if (schedule and ('schedule' in configuration)):\\n configuration['schedule'].update(schedule)\\n include = opts.get('include', [])\\n if include:\\n opts.update(include_config(include, fn_, verbose))\\n salt.utils.dictupdate.update(configuration, opts, True, True)\\n return configuration\",\"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 WIN:\\n key = ((roaming and 'APPDATA') or 'LOCALAPPDATA')\\n folder = os.environ.get(key)\\n if (folder is None):\\n folder = os.path.expanduser('~')\\n return os.path.join(folder, app_name)\\n if force_posix:\\n return os.path.join(os.path.expanduser(('~\\/.' + _posixify(app_name))))\\n if (sys.platform == 'darwin'):\\n return os.path.join(os.path.expanduser('~\\/Library\\/Application Support'), app_name)\\n return os.path.join(os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~\\/.config')), _posixify(app_name))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_app_dir(app_name, roaming=True, force_posix=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 context = RequestContext(request, processors=[csrf])\\n template = Template('{% csrf_token %}')\\n return HttpResponse(template.render(context))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def token_view(request):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n a = np.asarray(a)\\n if (a.size == 0):\\n return a\\n if (axis is None):\\n a = a.ravel()\\n axis = 0\\n nobs = a.shape[axis]\\n lowercut = int((proportiontocut * nobs))\\n uppercut = (nobs - lowercut)\\n if (lowercut >= uppercut):\\n raise ValueError('Proportion too big.')\\n atmp = np.partition(a, (lowercut, (uppercut - 1)), axis)\\n sl = ([slice(None)] * atmp.ndim)\\n sl[axis] = slice(lowercut, uppercut)\\n return atmp[sl]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def trimboth(a, proportiontocut, axis=0):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def assert_header_parsing(headers):\",\"targets\":\"\\\"\\\"\\\"Asserts whether all headers have been successfully parsed.\\n Extracts encountered errors from the result of parsing headers.\\n Only works on Python 3.\\n :param headers: Headers to verify.\\n :type headers: `httplib.HTTPMessage`.\\n :raises urllib3.exceptions.HeaderParsingError:\\n If parsing errors are found.\\n \\\"\\\"\\\"\\n if (not isinstance(headers, httplib.HTTPMessage)):\\n raise TypeError('expected httplib.Message, got {0}.'.format(type(headers)))\\n defects = getattr(headers, 'defects', None)\\n get_payload = getattr(headers, 'get_payload', None)\\n unparsed_data = None\\n if get_payload:\\n unparsed_data = get_payload()\\n if (defects or unparsed_data):\\n raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@LocalContext\\ndef asm(shellcode, vma=0, extract=True, shared=False):\\n\\n ''''asm(code, vma = 0, extract = True, shared = False, ...) -> str\\n Runs :func:`cpp` over a given shellcode and then assembles it into bytes.\\n To see which architectures or operating systems are supported,\\n look in :mod:`pwnlib.contex`.\\n Assembling shellcode requires that the GNU assembler is installed\\n for the target architecture.\\n See :doc:`Installing Binutils <\\/install\\/binutils>` for more information.\\n Arguments:\\n shellcode(str): Assembler code to assemble.\\n vma(int): Virtual memory address of the beginning of assembly\\n extract(bool): Extract the raw assembly bytes from the assembled\\n file. If :const:`False`, returns the path to an ELF file\\n with the assembly embedded.\\n shared(bool): Create a shared object.\\n kwargs(dict): Any attributes on :data:`.context` can be set, e.g.set\\n ``arch=\\\\'arm\\\\'``.\\n Examples:\\n >>> asm(\\\"mov eax, SYS_select\\\", arch = \\\\'i386\\\\', os = \\\\'freebsd\\\\')\\n \\\\'\\\\xb8]\\\\x00\\\\x00\\\\x00\\\\'\\n >>> asm(\\\"mov eax, SYS_select\\\", arch = \\\\'amd64\\\\', os = \\\\'linux\\\\')\\n \\\\'\\\\xb8\\\\x17\\\\x00\\\\x00\\\\x00\\\\'\\n >>> asm(\\\"mov rax, SYS_select\\\", arch = \\\\'amd64\\\\', os = \\\\'linux\\\\')\\n \\\\'H\\\\xc7\\\\xc0\\\\x17\\\\x00\\\\x00\\\\x00\\\\'\\n >>> asm(\\\"mov r0, #SYS_select\\\", arch = \\\\'arm\\\\', os = \\\\'linux\\\\', bits=32)\\n \\\\'R\\\\x00\\\\xa0\\\\xe3\\\\''\\n '''\",\"targets\":\"result = ''\\n assembler = _assembler()\\n linker = _linker()\\n objcopy = (_objcopy() + ['-j', '.shellcode', '-Obinary'])\\n code = ''\\n code += _arch_header()\\n code += cpp(shellcode)\\n log.debug(('Assembling\\\\n%s' % code))\\n tmpdir = tempfile.mkdtemp(prefix='pwn-asm-')\\n step1 = path.join(tmpdir, 'step1')\\n step2 = path.join(tmpdir, 'step2')\\n step3 = path.join(tmpdir, 'step3')\\n step4 = path.join(tmpdir, 'step4')\\n try:\\n with open(step1, 'w') as fd:\\n fd.write(code)\\n _run((assembler + ['-o', step2, step1]))\\n if (not vma):\\n shutil.copy(step2, step3)\\n if (vma or (not extract)):\\n ldflags = ['-z', 'execstack', '-o', step3, step2]\\n if vma:\\n ldflags += [('--section-start=.shellcode=%#x' % vma), ('--entry=%#x' % vma)]\\n elif shared:\\n ldflags += ['-shared', '-init=_start']\\n ldflags += ['-z', 'max-page-size=4096', '-z', 'common-page-size=4096']\\n _run((linker + ldflags))\\n elif (file(step2, 'rb').read(4) == '\\\\x7fELF'):\\n relocs = subprocess.check_output([which_binutils('readelf'), '-r', step2]).strip()\\n if (extract and (len(relocs.split('\\\\n')) > 1)):\\n log.error(('Shellcode contains relocations:\\\\n%s' % relocs))\\n else:\\n shutil.copy(step2, step3)\\n if (not extract):\\n return step3\\n _run((objcopy + [step3, step4]))\\n with open(step4) as fd:\\n result = fd.read()\\n except Exception:\\n lines = '\\\\n'.join((('%4i: %s' % ((i + 1), line)) for (i, line) in enumerate(code.splitlines())))\\n log.exception(('An error occurred while assembling:\\\\n%s' % lines))\\n else:\\n atexit.register((lambda : shutil.rmtree(tmpdir)))\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@bdd.when(bdd.parsers.parse('I set up a fake editor returning \\\"{text}\\\"'))\\ndef set_up_editor(quteproc, httpbin, tmpdir, text):\",\"targets\":\"\\\"\\\"\\\"Set up general->editor to a small python script inserting a text.\\n \\\"\\\"\\\"\\n script = (tmpdir \\/ 'script.py')\\n script.write(textwrap.dedent(\\\"\\\\n import sys\\\\n\\\\n with open(sys.argv[1], 'w', encoding='utf-8') as f:\\\\n f.write({text!r})\\\\n \\\".format(text=text)))\\n editor = '\\\"{}\\\" \\\"{}\\\" {{}}'.format(sys.executable, script)\\n quteproc.set_setting('general', 'editor', editor)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@app.route('\\/announce.php')\\ndef announce():\",\"targets\":\"\\\"\\\"\\\"\\/announce.php?info_hash=&peer_id=&ip=&port=&uploaded=&downloaded=&left=&numwant=&key=&compact=1\\n \\\"\\\"\\\"\\n ip = request.args.get('ip')\\n port = request.args.get('port')\\n if ((not ip) or (not port)):\\n return abort(404)\\n address = (ip, int(port))\\n binhash = urlparse.parse_qs(request.query_string)['info_hash'][0]\\n country = geoip.country_code_by_addr(ip)\\n if (country not in ('CN', 'TW', 'JP', 'HK', 'KR')):\\n return abort(404)\\n rpc.announce(binhash.encode('hex'), address)\\n return bencode({'peers': '', 'interval': 86400})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _getModelCheckpointDir(experimentDir, checkpointLabel):\\n\\n ''''Creates directory for serialization of the model\\n checkpointLabel:\\n Checkpoint label (string)\\n Returns:\\n absolute path to the serialization directory'\\n '''\",\"targets\":\"checkpointDir = os.path.join(getCheckpointParentDir(experimentDir), (checkpointLabel + g_defaultCheckpointExtension))\\n checkpointDir = os.path.abspath(checkpointDir)\\n return checkpointDir\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _native_set_to_python_list(typ, payload, c):\\n\\n ''''Create a Python list from a native set\\\\'s items.'\\n '''\",\"targets\":\"nitems = payload.used\\n listobj = c.pyapi.list_new(nitems)\\n ok = cgutils.is_not_null(c.builder, listobj)\\n with c.builder.if_then(ok, likely=True):\\n index = cgutils.alloca_once_value(c.builder, ir.Constant(nitems.type, 0))\\n with payload._iterate() as loop:\\n i = c.builder.load(index)\\n item = loop.entry.key\\n itemobj = c.box(typ.dtype, item)\\n c.pyapi.list_setitem(listobj, i, itemobj)\\n i = c.builder.add(i, ir.Constant(i.type, 1))\\n c.builder.store(i, index)\\n return (ok, listobj)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def fib(n):\",\"targets\":\"\\\"\\\"\\\"return nth term of Fibonacci sequence\\n \\\"\\\"\\\"\\n (a, b) = (0, 1)\\n i = 0\\n while (i < n):\\n (a, b) = (b, (a + b))\\n i += 1\\n return b\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef makeRGBA(*args, **kwds):\\n\\n ''''Equivalent to makeARGB(..., useRGBA=True)'\\n '''\",\"targets\":\"kwds['useRGBA'] = True\\n return makeARGB(*args, **kwds)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef OptionName(widget):\\n\\n ''''Returns the qualified path name for the widget. Normally used to set\\n default options for subwidgets. See tixwidgets.py'\\n '''\",\"targets\":\"return widget.tk.call('tixOptionName', widget._w)\",\"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 (func(None, 'x', 'y') == \\\"x: ['x'], y: ['y'], ls: x, w: xyz, label: None\\\")\\n assert (func(None, x='x', y='y') == \\\"x: ['x'], y: ['y'], ls: x, w: xyz, label: None\\\")\\n assert (func(None, 'x', 'y', label='') == \\\"x: ['x'], y: ['y'], ls: x, w: xyz, label: \\\")\\n assert (func(None, 'x', 'y', label='text') == \\\"x: ['x'], y: ['y'], ls: x, w: xyz, label: text\\\")\\n assert (func(None, x='x', y='y', label='') == \\\"x: ['x'], y: ['y'], ls: x, w: xyz, label: \\\")\\n assert (func(None, x='x', y='y', label='text') == \\\"x: ['x'], y: ['y'], ls: x, w: xyz, label: text\\\")\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)\\ndef test_function_call_without_data(func):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_host(url):\\n\\n ''''Deprecated. Use :func:`.parse_url` instead.'\\n '''\",\"targets\":\"p = parse_url(url)\\n return ((p.scheme or 'http'), p.hostname, p.port)\",\"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 difflib import ndiff\\n explanation = []\\n if isinstance(left, py.builtin.bytes):\\n left = u(repr(left)[1:(-1)]).replace('\\\\\\\\n', '\\\\n')\\n if isinstance(right, py.builtin.bytes):\\n right = u(repr(right)[1:(-1)]).replace('\\\\\\\\n', '\\\\n')\\n if (not verbose):\\n i = 0\\n for i in range(min(len(left), len(right))):\\n if (left[i] != right[i]):\\n break\\n if (i > 42):\\n i -= 10\\n explanation = [(u('Skipping %s identical leading characters in diff, use -v to show') % i)]\\n left = left[i:]\\n right = right[i:]\\n if (len(left) == len(right)):\\n for i in range(len(left)):\\n if (left[(- i)] != right[(- i)]):\\n break\\n if (i > 42):\\n i -= 10\\n explanation += [(u('Skipping %s identical trailing characters in diff, use -v to show') % i)]\\n left = left[:(- i)]\\n right = right[:(- i)]\\n keepends = True\\n explanation += [line.strip('\\\\n') for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))]\\n return explanation\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _diff_text(left, right, verbose=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n loader = Loader(stream)\\n while loader.check_event():\\n (yield loader.get_event())\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse(stream, Loader=Loader):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def make_style(opts=(), **kwargs):\",\"targets\":\"\\\"\\\"\\\"Returns a function with default parameters for colorize()\\n Example:\\n bold_red = make_style(opts=(\\\\bold\\\\,), fg=\\\\red\\\\)\\n print bold_red(\\\\hello\\\\)\\n KEYWORD = make_style(fg=\\\\yellow\\\\)\\n COMMENT = make_style(fg=\\\\blue\\\\, opts=(\\\\bold\\\\,))\\n \\\"\\\"\\\"\\n return (lambda text: colorize(text, opts, **kwargs))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef load(stream, Loader=Loader):\\n\\n ''''Parse the first YAML document in a stream\\n and produce the corresponding Python object.'\\n '''\",\"targets\":\"loader = Loader(stream)\\n if loader.check_data():\\n return loader.get_data()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n fsvers = '\\/proc\\/fs\\/lustre\\/version'\\n logging.debug((' opening file ' + fsvers))\\n try:\\n fobj = open(fsvers)\\n except IOError:\\n logging.debug(('ERROR opening file ' + fsvers))\\n exit()\\n vals = []\\n for line in fobj:\\n item = re.split('\\\\\\\\s+', line.rstrip())\\n vals.append(item)\\n for n in range(len(vals)):\\n if ('lustre:' in vals[n]):\\n vers_string = vals[n][1]\\n fir = vers_string.find('.')\\n sec = vers_string.find('.', (fir + 1))\\n lus_version = ((vers_string[0:fir] + '.') + vers_string[(fir + 1):sec])\\n logging.debug((' lus_version: ' + str(lus_version)))\\n return float(lus_version)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_lus_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 hist._private = True\\n config_stub.data = CONFIG_PRIVATE\\n hist.append('new item')\\n assert (hist.history == HISTORY)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_append_private_mode(hist, config_stub):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_all_ips():\",\"targets\":\"\\\"\\\"\\\"Get the IPs for all deployment nodes.\\n Returns:\\n A list of node IPs.\\n \\\"\\\"\\\"\\n nodes = file_io.read(constants.ALL_IPS_LOC)\\n nodes = nodes.split('\\\\n')\\n return filter(None, nodes)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _process_os_dirs(starting_dir, template_linters, options, summary_results, out):\\n\\n ''''For each linter, lints all the directories in the starting directory.\\n Arguments:\\n starting_dir: The initial directory to begin the walk.\\n template_linters: A list of linting objects.\\n options: A list of the options.\\n summary_results: A SummaryResults with a summary of the violations.\\n out: output file'\\n '''\",\"targets\":\"for (root, dirs, files) in os.walk(starting_dir):\\n if is_skip_dir(SKIP_DIRS, root):\\n del dirs\\n continue\\n dirs.sort(key=(lambda s: s.lower()))\\n _process_os_dir(root, files, template_linters, options, summary_results, out)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def main():\",\"targets\":\"\\\"\\\"\\\"Simple command-line program for creating host and VM folders in a\\n datacenter.\\n \\\"\\\"\\\"\\n args = GetArgs()\\n if args.password:\\n password = args.password\\n else:\\n password = getpass.getpass(prompt=('Enter password for host %s and user %s: ' % (args.host, args.user)))\\n si = SmartConnect(host=args.host, user=args.user, pwd=password, port=int(args.port))\\n if (not si):\\n print('Could not connect to the specified host using specified username and password')\\n return (-1)\\n atexit.register(Disconnect, si)\\n content = si.RetrieveContent()\\n dc = get_obj(content, [vim.Datacenter], args.datacenter)\\n if get_obj(content, [vim.Folder], args.folder):\\n print((\\\"Folder '%s' already exists\\\" % args.folder))\\n return 0\\n create_folder(content, dc.hostFolder, args.folder)\\n print((\\\"Successfully created the host folder '%s'\\\" % args.folder))\\n create_folder(content, dc.vmFolder, args.folder)\\n print((\\\"Successfully created the VM folder '%s'\\\" % args.folder))\\n return 0\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _get_uid(name):\",\"targets\":\"\\\"\\\"\\\"Returns an uid, given a user name.\\n \\\"\\\"\\\"\\n if ((getpwnam is None) or (name is None)):\\n return None\\n try:\\n result = getpwnam(name)\\n except KeyError:\\n result = None\\n if (result is not None):\\n return result[2]\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def load_param(prefix, epoch, convert=False, ctx=None, process=False):\",\"targets\":\"\\\"\\\"\\\"wrapper for load checkpoint\\n :param prefix: Prefix of model name.\\n :param epoch: Epoch number of model we would like to load.\\n :param convert: reference model should be converted to GPU NDArray first\\n :param ctx: if convert then ctx must be designated.\\n :param process: model should drop any test\\n :return: (arg_params, aux_params)\\n \\\"\\\"\\\"\\n (arg_params, aux_params) = load_checkpoint(prefix, epoch)\\n if convert:\\n if (ctx is None):\\n ctx = mx.cpu()\\n arg_params = convert_context(arg_params, ctx)\\n aux_params = convert_context(aux_params, ctx)\\n if process:\\n tests = [k for k in arg_params.keys() if ('_test' in k)]\\n for test in tests:\\n arg_params[test.replace('_test', '')] = arg_params.pop(test)\\n return (arg_params, aux_params)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not misc.is_string_secure(watch)):\\n logging.error('Watch string [{0}] is a possible security violation'.format(watch))\\n return False\\n logging.info('Reloading monit.')\\n if (not run_with_retry([MONIT, 'reload'])):\\n return False\\n logging.info('Starting watch {0}'.format(watch))\\n if is_group:\\n run_with_retry([MONIT, 'monitor', '-g', watch])\\n return run_with_retry([MONIT, 'start', '-g', watch])\\n else:\\n run_with_retry([MONIT, 'monitor', watch])\\n return run_with_retry([MONIT, 'start', watch])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def start(watch, is_group=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 if isinstance(jira_keys, unicode):\\n jira_keys = [jira_keys]\\n annotation = _FlakyAnnotation(jira_keys=pset(jira_keys), max_runs=max_runs, min_passes=min_passes)\\n def wrapper(test_method):\\n existing_flaky = getattr(test_method, _FLAKY_ATTRIBUTE, None)\\n if (existing_flaky is None):\\n note = annotation\\n else:\\n note = _combine_flaky_annotation(annotation, existing_flaky)\\n setattr(test_method, _FLAKY_ATTRIBUTE, note)\\n return test_method\\n return wrapper\\n\\n\\nWhat's a good function header?\",\"targets\":\"def flaky(jira_keys, max_runs=3, min_passes=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 derivation = HeightmapDerivation(elementNode)\\n heightGrid = derivation.heightGrid\\n if (derivation.fileName != ''):\\n heightGrid = getHeightGrid(archive.getAbsoluteFolderPath(elementNode.getOwnerDocument().fileName, derivation.fileName))\\n return getGeometryOutputByHeightGrid(derivation, elementNode, heightGrid)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def getGeometryOutput(elementNode):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_profile_when_user_created(instance, created, raw, *args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Post-save hook for Users. raw is populated from kwargs.\\n See Django docs on Signals:\\n https:\\/\\/docs.djangoproject.com\\/en\\/dev\\/ref\\/signals\\/#post-save\\n \\\"\\\"\\\"\\n if (created and (not raw)):\\n (person, p_created) = Person.objects.get_or_create(user=instance)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def kl_divergence(q, p):\",\"targets\":\"\\\"\\\"\\\".. todo::\\n WRITEME\\n \\\"\\\"\\\"\\n assert isinstance(q, DiagonalMND)\\n assert isinstance(p, DiagonalMND)\\n assert (q.nvis == p.nvis)\\n k = q.nvis\\n beta_q = q.beta\\n beta_p = p.beta\\n beta_q_inv = (1.0 \\/ beta_q)\\n trace_term = T.dot(beta_q_inv, beta_p)\\n assert (trace_term.ndim == 0)\\n mu_p = p.mu\\n mu_q = q.mu\\n quad_term = T.dot(beta_p, T.sqr((mu_p - mu_q)))\\n assert (quad_term.ndim == 0)\\n log_term = (T.sum(T.log(beta_q)) - T.sum(T.log(beta_p)))\\n assert (log_term.ndim == 0)\\n inside_parens = (((trace_term + quad_term) + log_term) - k)\\n assert (inside_parens.ndim == 0)\\n rval = (0.5 * inside_parens)\\n return rval\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dijkstra_shortest_path(graph, id1, id2, heuristic=None, directed=False):\",\"targets\":\"\\\"\\\"\\\"Dijkstra algorithm for finding the shortest path between two nodes.\\n Returns a list of node id\\\\s, starting with id1 and ending with id2.\\n Raises an IndexError between nodes on unconnected graphs.\\n \\\"\\\"\\\"\\n def flatten(list):\\n while (len(list) > 0):\\n (yield list[0])\\n list = list[1]\\n G = adjacency(graph, directed=directed, heuristic=heuristic)\\n q = [(0, id1, ())]\\n visited = set()\\n while True:\\n (cost1, n1, path) = heappop(q)\\n if (n1 not in visited):\\n visited.add(n1)\\n if (n1 == id2):\\n return (list(flatten(path))[::(-1)] + [n1])\\n path = (n1, path)\\n for (n2, cost2) in G[n1].items():\\n if (n2 not in visited):\\n heappush(q, ((cost1 + cost2), n2, path))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (call != 'function'):\\n raise SaltCloudSystemExit('The create_datastore_cluster function must be called with -f or --function.')\\n datastore_cluster_name = (kwargs.get('name') if (kwargs and ('name' in kwargs)) else None)\\n datacenter_name = (kwargs.get('datacenter') if (kwargs and ('datacenter' in kwargs)) else None)\\n if (not datastore_cluster_name):\\n raise SaltCloudSystemExit('You must specify name of the new datastore cluster to be created.')\\n if ((len(datastore_cluster_name) >= 80) or (len(datastore_cluster_name) <= 0)):\\n raise SaltCloudSystemExit('The datastore cluster name must be a non empty string of less than 80 characters.')\\n if (not datacenter_name):\\n raise SaltCloudSystemExit('You must specify name of the datacenter where the datastore cluster should be created.')\\n si = _get_si()\\n datastore_cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.StoragePod, datastore_cluster_name)\\n if datastore_cluster_ref:\\n return {datastore_cluster_name: 'datastore cluster already exists'}\\n datacenter_ref = salt.utils.vmware.get_mor_by_property(si, vim.Datacenter, datacenter_name)\\n if (not datacenter_ref):\\n raise SaltCloudSystemExit('The specified datacenter does not exist.')\\n try:\\n datacenter_ref.datastoreFolder.CreateStoragePod(name=datastore_cluster_name)\\n except Exception as exc:\\n log.error('Error creating datastore cluster {0}: {1}'.format(datastore_cluster_name, exc), exc_info_on_loglevel=logging.DEBUG)\\n return False\\n return {datastore_cluster_name: 'created'}\\n\\n\\nWhat's a good function header?\",\"targets\":\"def create_datastore_cluster(kwargs=None, call=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@requires_pandas\\ndef test_to_data_frame():\",\"targets\":\"\\\"\\\"\\\"Test edf Raw Pandas exporter.\\n \\\"\\\"\\\"\\n for path in [edf_path, bdf_path]:\\n raw = read_raw_edf(path, stim_channel=None, preload=True)\\n (_, times) = raw[0, :10]\\n df = raw.to_data_frame()\\n assert_true((df.columns == raw.ch_names).all())\\n assert_array_equal(np.round((times * 1000.0)), df.index.values[:10])\\n df = raw.to_data_frame(index=None, scalings={'eeg': 10000000000000.0})\\n assert_true(('time' in df.index.names))\\n assert_array_equal(df.values[:, 0], (raw._data[0] * 10000000000000.0))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_cms_block_link(block, page):\\n\\n ''''Returns a link to block_index for editing the course in cms,\\n assuming that the block is actually cms-backed.'\\n '''\",\"targets\":\"return u'\\/\\/{}\\/{}\\/{}'.format(settings.CMS_BASE, page, block.location)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def KAMA(ds, count, timeperiod=(- (2 ** 31))):\",\"targets\":\"\\\"\\\"\\\"Kaufman Adaptive Moving Average\\n \\\"\\\"\\\"\\n return call_talib_with_ds(ds, count, talib.KAMA, timeperiod)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _scryptBlockMix(blocks, len_blocks):\",\"targets\":\"\\\"\\\"\\\"Hash function for ROMix.\\n \\\"\\\"\\\"\\n x = blocks[(-1)]\\n core = _raw_salsa20_lib.Salsa20_8_core\\n result = [create_string_buffer(64) for _ in range(len(blocks))]\\n for i in xrange(len(blocks)):\\n core(x, blocks[i], result[i])\\n x = result[i]\\n return [result[(i + j)] for j in xrange(2) for i in xrange(0, len_blocks, 2)]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@get('\\/scan\\/\\/log\\/\\/')\\ndef scan_log_limited(taskid, start, end):\\n\\n ''''Retrieve a subset of log messages'\\n '''\",\"targets\":\"json_log_messages = list()\\n if (taskid not in DataStore.tasks):\\n logger.warning(('[%s] Invalid task ID provided to scan_log_limited()' % taskid))\\n return jsonize({'success': False, 'message': 'Invalid task ID'})\\n if ((not start.isdigit()) or (not end.isdigit()) or (end < start)):\\n logger.warning(('[%s] Invalid start or end value provided to scan_log_limited()' % taskid))\\n return jsonize({'success': False, 'message': 'Invalid start or end value, must be digits'})\\n start = max(1, int(start))\\n end = max(1, int(end))\\n for (time_, level, message) in DataStore.current_db.execute('SELECT time, level, message FROM logs WHERE taskid = ? AND id >= ? AND id <= ? ORDER BY id ASC', (taskid, start, end)):\\n json_log_messages.append({'time': time_, 'level': level, 'message': message})\\n logger.debug(('[%s] Retrieved scan log messages subset' % taskid))\\n return jsonize({'success': True, 'log': json_log_messages})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n lines = text.splitlines(1)\\n _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)\\n return ''.join(lines)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _dedent(text, tabsize=8, skip_first_line=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_model(model_identifier):\\n\\n ''''Helper to look up a model from an \\\"app_label.module_name\\\" string.'\\n '''\",\"targets\":\"try:\\n Model = models.get_model(*model_identifier.split('.'))\\n except TypeError:\\n Model = None\\n if (Model is None):\\n raise base.DeserializationError((u\\\"Invalid model identifier: '%s'\\\" % model_identifier))\\n return Model\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (len(sys.argv) > 1):\\n writeOutput(' '.join(sys.argv[1:]))\\n else:\\n settings.startMainLoopFromConstructor(getNewRepository())\\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\":\"def _cast_params_from(params, context, schemas):\",\"targets\":\"\\\"\\\"\\\"Pick a list of parameters from context and cast each of them according to the schemas provided\\n \\\"\\\"\\\"\\n result = {}\\n for name in params:\\n param_schema = {}\\n for schema in schemas:\\n if (name in schema):\\n param_schema = schema[name]\\n result[name] = _cast(context[name], param_schema)\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def check_bool(result, func, cargs):\",\"targets\":\"\\\"\\\"\\\"Returns the boolean evaluation of the value.\\n \\\"\\\"\\\"\\n if bool(result):\\n return True\\n else:\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (value.node.manufacturer_id.strip() and value.node.product_id.strip() and value.node.product_type.strip()):\\n manufacturer_id = int(value.node.manufacturer_id, 16)\\n product_type = int(value.node.product_type, 16)\\n product_id = int(value.node.product_id, 16)\\n result = DEVICE_MAPPINGS_MTII.get((manufacturer_id, product_type, product_id, value.index))\\n if result:\\n return result\\n result = DEVICE_MAPPINGS_MTI_INSTANCE.get((manufacturer_id, product_type, product_id, value.instance))\\n if result:\\n return result\\n return DEVICE_MAPPINGS_MT.get((manufacturer_id, product_type))\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_device_mapping(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 global Image\\n if (Image is None):\\n raise RuntimeError(\\\"You are trying to use PIL-dependent functionality but don't have PIL installed.\\\")\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ensure_Image():\",\"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 config.PLAYER.get) or (not util.has_exefile(config.PLAYER.get))):\\n g.message = ('Player not configured! Enter %sset player %s to set a player' % (c.g, c.w))\\n return\\n if config.NOTIFIER.get:\\n subprocess.Popen((shlex.split(config.NOTIFIER.get) + [song.title]))\\n while (song.ytid in g.preloading):\\n screen.writestatus('fetching item..')\\n time.sleep(0.1)\\n try:\\n streams.get(song, force=failcount, callback=screen.writestatus)\\n except (IOError, URLError, HTTPError, socket.timeout) as e:\\n util.dbg('--ioerror in _playsong call to streams.get %s', str(e))\\n if ('Youtube says' in str(e)):\\n g.message = (util.F('cant get track') % ((song.title + ' ') + str(e)))\\n return\\n elif (failcount < g.max_retries):\\n util.dbg('--ioerror - trying next stream')\\n failcount += 1\\n return _playsong(song, failcount=failcount, override=override, softrepeat=softrepeat)\\n elif ('pafy' in str(e)):\\n g.message = ((str(e) + ' - ') + song.ytid)\\n return\\n except ValueError:\\n g.message = util.F('track unresolved')\\n util.dbg('----valueerror in _playsong call to streams.get')\\n return\\n try:\\n video = ((config.SHOW_VIDEO.get and (override != 'audio')) or (override in ('fullscreen', 'window', 'forcevid')))\\n m4a = ('mplayer' not in config.PLAYER.get)\\n cached = g.streams[song.ytid]\\n stream = streams.select(cached, q=failcount, audio=(not video), m4a_ok=m4a)\\n if (((not stream) or failcount) and (not video)):\\n util.dbg(((c.r + 'no audio or mplayer m4a, using video stream') + c.w))\\n override = 'a-v'\\n video = True\\n stream = streams.select(cached, q=failcount, audio=False, maxres=1600)\\n if (not stream):\\n raise IOError('No streams ...\\n\\nWhat's a good function header?\",\"targets\":\"def _playsong(song, failcount=0, override=False, softrepeat=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef compress(body, compress_level):\\n\\n ''''Compress \\\\'body\\\\' at the given compress_level.'\\n '''\",\"targets\":\"import zlib\\n (yield ntob('\\\\x1f\\\\x8b'))\\n (yield ntob('\\\\x08'))\\n (yield ntob('\\\\x00'))\\n (yield struct.pack(' \\\"sain\\\" -> \\\"shin\\\" -> \\\"shine\\\". These operations could have\\n been done in other orders, but at least three steps are needed.\\n Allows specifying the cost of substitution edits (e.g., \\\"a\\\" -> \\\"b\\\"),\\n because sometimes it makes sense to assign greater penalties to substitutions.\\n This also optionally allows transposition edits (e.g., \\\"ab\\\" -> \\\"ba\\\"),\\n though this is disabled by default.\\n :param s1, s2: The strings to be analysed\\n :param transpositions: Whether to allow transposition edits\\n :type s1: str\\n :type s2: str\\n :type substitution_cost: int\\n :type transpositions: bool\\n :rtype int'\\n '''\",\"targets\":\"len1 = len(s1)\\n len2 = len(s2)\\n lev = _edit_dist_init((len1 + 1), (len2 + 1))\\n for i in range(len1):\\n for j in range(len2):\\n _edit_dist_step(lev, (i + 1), (j + 1), s1, s2, substitution_cost=substitution_cost, transpositions=transpositions)\\n return lev[len1][len2]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def main():\",\"targets\":\"\\\"\\\"\\\"Upgrades the hardware version of a Virtual Machine.\\n \\\"\\\"\\\"\\n args = get_args()\\n service_instance = connect_vsphere(args.user, args.password, args.host, int(args.port), args.use_ssl)\\n content = service_instance.RetrieveContent()\\n virtual_machine = get_vm(content, args.name)\\n if (not virtual_machine):\\n print(('Could not find VM %s' % args.name))\\n else:\\n print(('Upgrading VM %s' % args.name))\\n if (args.version is not None):\\n print(('New version will be %s' % args.version))\\n version = 'vmx-{:02d}'.format(args.version)\\n else:\\n version = None\\n try:\\n task.WaitForTask(task=virtual_machine.UpgradeVM_Task(version), si=service_instance)\\n except vim.fault.AlreadyUpgraded:\\n print('VM is already upgraded')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef jacobian(sess, x, grads, target, X, nb_features, nb_classes, feed=None):\\n\\n ''''TensorFlow implementation of the foward derivative \\/ Jacobian\\n :param x: the input placeholder\\n :param grads: the list of TF gradients returned by jacobian_graph()\\n :param target: the target misclassification class\\n :param X: numpy array with sample input\\n :param nb_features: the number of features in the input\\n :return: matrix of forward derivatives flattened into vectors'\\n '''\",\"targets\":\"feed_dict = {x: X}\\n if (feed is not None):\\n feed_dict.update(feed)\\n jacobian_val = np.zeros((nb_classes, nb_features), dtype=np.float32)\\n for (class_ind, grad) in enumerate(grads):\\n run_grad = sess.run(grad, feed_dict)\\n jacobian_val[class_ind] = np.reshape(run_grad, (1, nb_features))\\n other_classes = utils.other_classes(nb_classes, target)\\n grad_others = np.sum(jacobian_val[other_classes, :], axis=0)\\n return (jacobian_val[target], grad_others)\",\"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 is_import_stmt(node):\\n return ((node.type == syms.simple_stmt) and node.children and is_import(node.children[0]))\\n root = find_root(node)\\n if does_tree_import(package, name, root):\\n return\\n insert_pos = offset = 0\\n for (idx, node) in enumerate(root.children):\\n if (not is_import_stmt(node)):\\n continue\\n for (offset, node2) in enumerate(root.children[idx:]):\\n if (not is_import_stmt(node2)):\\n break\\n insert_pos = (idx + offset)\\n break\\n if (insert_pos == 0):\\n for (idx, node) in enumerate(root.children):\\n if ((node.type == syms.simple_stmt) and node.children and (node.children[0].type == token.STRING)):\\n insert_pos = (idx + 1)\\n break\\n if (package is None):\\n import_ = Node(syms.import_name, [Leaf(token.NAME, u'import'), Leaf(token.NAME, name, prefix=u' ')])\\n else:\\n import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u' ')])\\n children = [import_, Newline()]\\n root.insert_child(insert_pos, Node(syms.simple_stmt, children))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def touch_import(package, name, 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 kwargs = salt.utils.args.clean_kwargs(**kwargs)\\n failhard = kwargs.pop('failhard', True)\\n if kwargs:\\n salt.utils.args.invalid_kwargs(kwargs)\\n ret = dict()\\n for (pkg_name, pkg_nfo) in __salt__['lowpkg.info'](failhard=failhard, *names).items():\\n t_nfo = dict()\\n for (key, value) in pkg_nfo.items():\\n if (key == 'package'):\\n t_nfo['name'] = value\\n elif (key == 'origin'):\\n t_nfo['vendor'] = value\\n elif (key == 'section'):\\n t_nfo['group'] = value\\n elif (key == 'maintainer'):\\n t_nfo['packager'] = value\\n elif (key == 'homepage'):\\n t_nfo['url'] = value\\n else:\\n t_nfo[key] = value\\n ret[pkg_name] = t_nfo\\n return ret\\n\\n\\nWhat's a good function header?\",\"targets\":\"def info_installed(*names, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __validate__(config):\",\"targets\":\"\\\"\\\"\\\"Validate the beacon configuration\\n \\\"\\\"\\\"\\n if (not isinstance(config, dict)):\\n return (False, 'Configuration for wtmp beacon must be a dictionary.')\\n return (True, 'Valid beacon configuration')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@jinja_filter('base64_decode')\\ndef base64_b64decode(instr):\",\"targets\":\"\\\"\\\"\\\"Decode a base64-encoded string using the \\\"modern\\\" Python interface.\\n \\\"\\\"\\\"\\n if six.PY3:\\n b = salt.utils.stringutils.to_bytes(instr)\\n data = base64.b64decode(b)\\n try:\\n return salt.utils.stringutils.to_str(data)\\n except UnicodeDecodeError:\\n return data\\n return base64.b64decode(instr)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef from_html_one(html_code, **kwargs):\\n\\n ''''Generates a PrettyTables from a string of HTML code which contains only a\\n single '\\n '''\",\"targets\":\"tables = from_html(html_code, **kwargs)\\n try:\\n assert (len(tables) == 1)\\n except AssertionError:\\n raise Exception('More than one
in provided HTML code! Use from_html instead.')\\n return tables[0]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@snippet\\ndef dataset_create(client, to_delete):\\n\\n ''''Create a dataset.'\\n '''\",\"targets\":\"DATASET_NAME = ('dataset_create_%d' % (_millis(),))\\n dataset = client.dataset(DATASET_NAME)\\n dataset.create()\\n to_delete.append(dataset)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef dictsort(value, arg):\\n\\n ''''Takes a list of dicts, returns that list sorted by the property given in\\n the argument.'\\n '''\",\"targets\":\"return sorted(value, key=Variable(arg).resolve)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def connect_dynamodb(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):\",\"targets\":\"\\\"\\\"\\\":type aws_access_key_id: string\\n :param aws_access_key_id: Your AWS Access Key ID\\n :type aws_secret_access_key: string\\n :param aws_secret_access_key: Your AWS Secret Access Key\\n :rtype: :class:`boto.dynamodb.layer2.Layer2`\\n :return: A connection to the Layer2 interface for DynamoDB.\\n \\\"\\\"\\\"\\n from boto.dynamodb.layer2 import Layer2\\n return Layer2(aws_access_key_id, aws_secret_access_key, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_featured_activity_references():\\n\\n ''''Gets a list of ActivityReference domain models.\\n Returns:\\n A list of all ActivityReference domain objects that are\\n currently featured.'\\n '''\",\"targets\":\"featured_model_instance = activity_models.ActivityReferencesModel.get_or_create(activity_models.ACTIVITY_REFERENCE_LIST_FEATURED)\\n return [activity_domain.ActivityReference(reference['type'], reference['id']) for reference in featured_model_instance.activity_references]\",\"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 planner\\n planner = Planner()\\n scale = Variable('scale', 10)\\n offset = Variable('offset', 1000)\\n (src, dest) = (None, None)\\n dests = OrderedCollection()\\n for i in range(n):\\n src = Variable(('src%s' % i), i)\\n dst = Variable(('dst%s' % i), i)\\n dests.append(dst)\\n StayConstraint(src, Strength.NORMAL)\\n ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED)\\n change(src, 17)\\n if (dst.value != 1170):\\n print('Projection 1 failed')\\n change(dst, 1050)\\n if (src.value != 5):\\n print('Projection 2 failed')\\n change(scale, 5)\\n for i in range((n - 1)):\\n if (dests[i].value != ((i * 5) + 1000)):\\n print('Projection 3 failed')\\n change(offset, 2000)\\n for i in range((n - 1)):\\n if (dests[i].value != ((i * 5) + 2000)):\\n print('Projection 4 failed')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def projection_test(n):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _list_certs(certificate_store=u'My'):\",\"targets\":\"\\\"\\\"\\\"List details of available certificates in the LocalMachine certificate\\n store.\\n Args:\\n certificate_store (str): The name of the certificate store on the local\\n machine.\\n Returns:\\n dict: A dictionary of certificates found in the store\\n \\\"\\\"\\\"\\n ret = dict()\\n blacklist_keys = [u'DnsNameList', u'Thumbprint']\\n ps_cmd = [u'Get-ChildItem', u'-Path', u\\\"'Cert:\\\\\\\\LocalMachine\\\\\\\\{0}'\\\".format(certificate_store), u'|', u'Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version']\\n cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)\\n try:\\n items = json.loads(cmd_ret[u'stdout'], strict=False)\\n except ValueError:\\n raise CommandExecutionError(u'Unable to parse return data as Json.')\\n for item in items:\\n cert_info = dict()\\n for key in item:\\n if (key not in blacklist_keys):\\n cert_info[key.lower()] = item[key]\\n cert_info[u'dnsnames'] = [name[u'Unicode'] for name in item[u'DnsNameList']]\\n ret[item[u'Thumbprint']] = cert_info\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _normalize(op1, op2, prec=0):\",\"targets\":\"\\\"\\\"\\\"Normalizes op1, op2 to have the same exp and length of coefficient.\\n Done during addition.\\n \\\"\\\"\\\"\\n if (op1.exp < op2.exp):\\n tmp = op2\\n other = op1\\n else:\\n tmp = op1\\n other = op2\\n tmp_len = len(str(tmp.int))\\n other_len = len(str(other.int))\\n exp = (tmp.exp + min((-1), ((tmp_len - prec) - 2)))\\n if (((other_len + other.exp) - 1) < exp):\\n other.int = 1\\n other.exp = exp\\n tmp.int *= (10 ** (tmp.exp - other.exp))\\n tmp.exp = other.exp\\n return (op1, op2)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef inspect_path(prefix):\\n\\n ''''Inspects the prefix of an installation to search for common layouts. Issues\\n a request to modify the environment accordingly when an item is found.\\n Args:\\n prefix: prefix of the installation\\n Returns:\\n instance of EnvironmentModifications containing the requested\\n modifications'\\n '''\",\"targets\":\"env = EnvironmentModifications()\\n prefix_inspections = _module_config.get('prefix_inspections', {})\\n for (relative_path, variables) in prefix_inspections.items():\\n expected = join_path(prefix, relative_path)\\n if os.path.isdir(expected):\\n for variable in variables:\\n env.prepend_path(variable, expected)\\n return env\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def alert_recipient():\",\"targets\":\"\\\"\\\"\\\"RESTful CRUD controller for options.s3json lookups\\n - needed for adding recipients\\n \\\"\\\"\\\"\\n s3.prep = (lambda r: ((r.method == 'options') and (r.representation == 's3json')))\\n return s3_rest_controller()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef main():\\n\\n ''''Display the export dialog.'\\n '''\",\"targets\":\"if (len(sys.argv) > 1):\\n writeOutput(' '.join(sys.argv[1:]))\\n else:\\n settings.startMainLoopFromConstructor(getNewRepository())\",\"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 attr in _INDEXER_NAMES:\\n try:\\n delattr(df, attr)\\n except AttributeError:\\n pass\\n\\n\\nWhat's a good function header?\",\"targets\":\"def clear_dataframe_indexer_caches(df):\",\"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 ((dtype == '2I') and (byteorder == '<'))\\n values = fh.read_array(' a'\\n '''\",\"targets\":\"if isinstance(node.op, T.CAReduce):\\n (summed,) = node.inputs\\n if (summed.type == node.outputs[0].type):\\n return [summed]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getcolumns(stream):\\n\\n ''''Function that return the colums of a SELECT query'\\n '''\",\"targets\":\"pipe = Pipeline()\\n pipe.append(ColumnsSelect())\\n return pipe(stream)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n parser = argparse.ArgumentParser(description='Faster R-CNN demo')\\n parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int)\\n parser.add_argument('--cpu', dest='cpu_mode', help='Use CPU mode (overrides --gpu)', action='store_true')\\n parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]', choices=NETS.keys(), default='vgg16')\\n args = parser.parse_args()\\n return args\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_args():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n lastLoopLength = len(loop)\\n while (lastLoopLength > 3):\\n removeIntersection(loop)\\n if (len(loop) == lastLoopLength):\\n return loop\\n lastLoopLength = len(loop)\\n return loop\\n\\n\\nWhat's a good function header?\",\"targets\":\"def getWithoutIntersections(loop):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef colorx(clip, factor):\\n\\n ''''multiplies the clip\\\\'s colors by the given factor, can be used\\n to decrease or increase the clip\\\\'s brightness (is that the\\n reight word ?)'\\n '''\",\"targets\":\"return clip.fl_image((lambda pic: np.minimum(255, (factor * pic)).astype('uint8')))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef lru_cache(maxsize=100):\\n\\n ''''Least-recently-used cache decorator.\\n Arguments to the cached function must be hashable.\\n Cache performance statistics stored in f.hits and f.misses.\\n Clear the cache with f.clear().\\n http:\\/\\/en.wikipedia.org\\/wiki\\/Cache_algorithms#Least_Recently_Used'\\n '''\",\"targets\":\"maxqueue = (maxsize * 10)\\n def decorating_function(user_function, len=len, iter=iter, tuple=tuple, sorted=sorted, KeyError=KeyError):\\n cache = {}\\n queue = collections.deque()\\n refcount = Counter()\\n sentinel = object()\\n kwd_mark = object()\\n (queue_append, queue_popleft) = (queue.append, queue.popleft)\\n (queue_appendleft, queue_pop) = (queue.appendleft, queue.pop)\\n @functools.wraps(user_function)\\n def wrapper(*args, **kwds):\\n key = args\\n if kwds:\\n key += ((kwd_mark,) + tuple(sorted(kwds.items())))\\n queue_append(key)\\n refcount[key] += 1\\n try:\\n result = cache[key]\\n wrapper.hits += 1\\n except KeyError:\\n result = user_function(*args, **kwds)\\n cache[key] = result\\n wrapper.misses += 1\\n if (len(cache) > maxsize):\\n key = queue_popleft()\\n refcount[key] -= 1\\n while refcount[key]:\\n key = queue_popleft()\\n refcount[key] -= 1\\n del cache[key], refcount[key]\\n if (len(queue) > maxqueue):\\n refcount.clear()\\n queue_appendleft(sentinel)\\n for key in ifilterfalse(refcount.__contains__, iter(queue_pop, sentinel)):\\n queue_appendleft(key)\\n refcount[key] = 1\\n return result\\n def clear():\\n cache.clear()\\n queue.clear()\\n refcount.clear()\\n wrapper.hits = wrapper.misses = 0\\n wrapper.hits = wrapper.misses = 0\\n wrapper.clear = clear\\n return wrapper\\n return decorating_function\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _build_localename(localetuple):\",\"targets\":\"\\\"\\\"\\\"Builds a locale code from the given tuple (language code,\\n encoding).\\n No aliasing or normalizing takes place.\\n \\\"\\\"\\\"\\n (language, encoding) = localetuple\\n if (language is None):\\n language = 'C'\\n if (encoding is None):\\n return language\\n else:\\n return ((language + '.') + encoding)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n @gen.engine\\n def _ProcessOneFile(contents, day_stats):\\n 'Iterate over the contents of a processed file: one entry per line. Increment stats for specific entries.'\\n buf = cStringIO.StringIO(contents)\\n buf.seek(0)\\n ui_events = Counter()\\n while True:\\n line = buf.readline()\\n if (not line):\\n break\\n parsed = json.loads(line)\\n if (not parsed):\\n continue\\n if ('version' not in parsed):\\n continue\\n payload = parsed['payload']\\n if ('name' in payload):\\n if ((payload['name'] == '\\/assets\\/scan') and (payload['type'] == 'full')):\\n day_stats.AddScan(parsed['version'], payload['num_scanned'], payload['elapsed'])\\n elif payload['name'].startswith('\\/ui\\/'):\\n ui_events[payload['name']] += 1\\n if ui_events:\\n ui_events['\\/ui\\/anything'] += 1\\n day_stats.AddEvents(ui_events)\\n buf.close()\\n today = util.NowUTCToISO8601()\\n files_by_day = defaultdict(list)\\n for filename in filenames:\\n (_, day, user) = filename.split('\\/')\\n if (options.options.compute_today or (today != day)):\\n files_by_day[day].append(filename)\\n stats_by_day = {}\\n for day in sorted(files_by_day.keys()):\\n files = files_by_day[day]\\n day_stats = DayStats(day)\\n for f in files:\\n contents = ''\\n try:\\n contents = (yield gen.Task(merged_store.Get, f))\\n except Exception as e:\\n logging.error(('Error fetching file %s: %r' % (f, e)))\\n continue\\n _ProcessOneFile(contents, day_stats)\\n if (len(day_stats._long_scan_speeds) == 0):\\n continue\\n dd = DotDict()\\n for p in [1, 5, 10, 25, 50, 75, 90, 95, 99]:\\n dd[('user_analytics.scans_gt1s_speed_percentile.%.2d' % p)] =...\\n\\nWhat's a good function header?\",\"targets\":\"@gen.engine\\ndef ProcessFiles(merged_store, filenames, callback):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef is_aware(value):\\n\\n ''''Determines if a given datetime.datetime is aware.\\n The logic is described in Python\\\\'s docs:\\n http:\\/\\/docs.python.org\\/library\\/datetime.html#datetime.tzinfo'\\n '''\",\"targets\":\"return ((value.tzinfo is not None) and (value.tzinfo.utcoffset(value) is not None))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def all_pairs_matching_predicate(values, pred):\",\"targets\":\"\\\"\\\"\\\"Return an iterator of all pairs, (v0, v1) from values such that\\n `pred(v0, v1) == True`\\n Parameters\\n values : iterable\\n pred : function\\n Returns\\n pairs_iterator : generator\\n Generator yielding pairs matching `pred`.\\n Examples\\n >>> from zipline.testing import all_pairs_matching_predicate\\n >>> from operator import eq, lt\\n >>> list(all_pairs_matching_predicate(range(5), eq))\\n [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\\n >>> list(all_pairs_matching_predicate(\\\"abcd\\\", lt))\\n [(\\\\a\\\\, \\\\b\\\\), (\\\\a\\\\, \\\\c\\\\), (\\\\a\\\\, \\\\d\\\\), (\\\\b\\\\, \\\\c\\\\), (\\\\b\\\\, \\\\d\\\\), (\\\\c\\\\, \\\\d\\\\)]\\n \\\"\\\"\\\"\\n return filter((lambda pair: pred(*pair)), product(values, repeat=2))\",\"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 distutils.sysconfig import parse_makefile, expand_makefile_vars, _variable_rx\\n from distutils.text_file import TextFile\\n from distutils.util import split_quoted\\n vars = parse_makefile(filename)\\n file = TextFile(filename, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1)\\n try:\\n extensions = []\\n while True:\\n line = file.readline()\\n if (line is None):\\n break\\n if _variable_rx.match(line):\\n continue\\n if (line[0] == line[(-1)] == '*'):\\n file.warn((\\\"'%s' lines not handled yet\\\" % line))\\n continue\\n line = expand_makefile_vars(line, vars)\\n words = split_quoted(line)\\n module = words[0]\\n ext = Extension(module, [])\\n append_next_word = None\\n for word in words[1:]:\\n if (append_next_word is not None):\\n append_next_word.append(word)\\n append_next_word = None\\n continue\\n suffix = os.path.splitext(word)[1]\\n switch = word[0:2]\\n value = word[2:]\\n if (suffix in ('.c', '.cc', '.cpp', '.cxx', '.c++', '.m', '.mm')):\\n ext.sources.append(word)\\n elif (switch == '-I'):\\n ext.include_dirs.append(value)\\n elif (switch == '-D'):\\n equals = value.find('=')\\n if (equals == (-1)):\\n ext.define_macros.append((value, None))\\n else:\\n ext.define_macros.append((value[0:equals], value[(equals + 2):]))\\n elif (switch == '-U'):\\n ext.undef_macros.append(value)\\n elif (switch == '-C'):\\n ext.extra_compile_args.append(word)\\n elif (switch == '-l'):\\n ext.libraries.append(value)\\n elif (switch == '-L'):\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def read_setup_file(filename):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef chisquare_effectsize(probs0, probs1, correction=None, cohen=True, axis=0):\\n\\n ''''effect size for a chisquare goodness-of-fit test\\n Parameters\\n probs0 : array_like\\n probabilities or cell frequencies under the Null hypothesis\\n probs1 : array_like\\n probabilities or cell frequencies under the Alternative hypothesis\\n probs0 and probs1 need to have the same length in the ``axis`` dimension.\\n and broadcast in the other dimensions\\n Both probs0 and probs1 are normalized to add to one (in the ``axis``\\n dimension).\\n correction : None or tuple\\n If None, then the effect size is the chisquare statistic divide by\\n the number of observations.\\n If the correction is a tuple (nobs, df), then the effectsize is\\n corrected to have less bias and a smaller variance. However, the\\n correction can make the effectsize negative. In that case, the\\n effectsize is set to zero.\\n Pederson and Johnson (1990) as referenced in McLaren et all. (1994)\\n cohen : bool\\n If True, then the square root is returned as in the definition of the\\n effect size by Cohen (1977), If False, then the original effect size\\n is returned.\\n axis : int\\n If the probability arrays broadcast to more than 1 dimension, then\\n this is the axis over which the sums are taken.\\n Returns\\n effectsize : float\\n effect size of chisquare test'\\n '''\",\"targets\":\"probs0 = np.asarray(probs0, float)\\n probs1 = np.asarray(probs1, float)\\n probs0 = (probs0 \\/ probs0.sum(axis))\\n probs1 = (probs1 \\/ probs1.sum(axis))\\n d2 = (((probs1 - probs0) ** 2) \\/ probs0).sum(axis)\\n if (correction is not None):\\n (nobs, df) = correction\\n diff = ((probs1 - probs0) \\/ probs0).sum(axis)\\n d2 = np.maximum(((((d2 * nobs) - diff) - df) \\/ (nobs - 1.0)), 0)\\n if cohen:\\n return np.sqrt(d2)\\n else:\\n return d2\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef CAN_ASSIGN_OWNER(article, user):\\n\\n ''''Is user allowed to change group of article to one of its own groups?'\\n '''\",\"targets\":\"return _is_staff_for_article(article, user)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _list_new_metadata(repository_path):\\n\\n ''''List the filenames of new and changed repository metadata files.\\n :param FilePath repository_path: Location of repository to list repository\\n metadata from.\\n :param set existing_metadata: Filenames of existing metadata files.'\\n '''\",\"targets\":\"return {'\\/'.join(path.segmentsFrom(repository_path)) for path in repository_path.child('repodata').walk()}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n exclude_string = '--exclude=deps\\/* --exclude=tests\\/* --exclude=site_tests\\/*'\\n prof_dir = os.path.join(client_dir, 'profilers')\\n for f in os.listdir(prof_dir):\\n if os.path.isdir(os.path.join(prof_dir, f)):\\n exclude_string += (' --exclude=profilers\\/%s' % f)\\n return exclude_string\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_exclude_string(client_dir):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_users_with_perms(obj, attach_perms=False, with_superusers=False, with_group_users=True):\",\"targets\":\"\\\"\\\"\\\"Returns queryset of all ``User`` objects with *any* object permissions for\\n the given ``obj``.\\n :param obj: persisted Django\\\\s ``Model`` instance\\n :param attach_perms: Default: ``False``. If set to ``True`` result would be\\n dictionary of ``User`` instances with permissions\\\\ codenames list as\\n values. This would fetch users eagerly!\\n :param with_superusers: Default: ``False``. If set to ``True`` result would\\n contain all superusers.\\n :param with_group_users: Default: ``True``. If set to ``False`` result would\\n **not** contain those users who have only group permissions for given\\n ``obj``.\\n Example::\\n >>> from django.contrib.flatpages.models import FlatPage\\n >>> from django.contrib.auth.models import User\\n >>> from guardian.shortcuts import assign_perm, get_users_with_perms\\n >>> page = FlatPage.objects.create(title=\\\\Some page\\\\, path=\\\\\\/some\\/page\\/\\\\)\\n >>> joe = User.objects.create_user(\\\\joe\\\\, \\\\joe@example.com\\\\, \\\\joesecret\\\\)\\n >>> assign_perm(\\\\change_flatpage\\\\, joe, page)\\n >>> get_users_with_perms(page)\\n []\\n >>> get_users_with_perms(page, attach_perms=True)\\n {: [u\\\\change_flatpage\\\\]}\\n \\\"\\\"\\\"\\n ctype = get_content_type(obj)\\n if (not attach_perms):\\n user_model = get_user_obj_perms_model(obj)\\n related_name = user_model.user.field.related_query_name()\\n if user_model.objects.is_generic():\\n user_filters = {(u'%s__content_type' % related_name): ctype, (u'%s__object_pk' % related_name): obj.pk}\\n else:\\n user_filters = {(u'%s__content_object' % related_name): obj}\\n qset = Q(**user_filters)\\n if with_group_users:\\n group_model = get_group_obj_perms_model(obj)\\n group_rel_name = group_model.group.field.related_query_name()\\n if group_model.objects.is_generic():\\n group_filters = {(u'groups__%s__content_type' % group_rel_name): ctype, (u'groups__%s__object_pk' % group_rel_name): obj.pk}\\n else:\\n group_filters = {(u'groups__%s__content_object' % group_rel_name): obj}\\n qset = (qset | Q(**group_filters))\\n if with_superusers:\\n qset = (qset | Q(is_superuser=True))\\n return get_user_model().objects.filter(qset).distinct()\\n else:\\n users = {}\\n for user in get_users_with_perms(obj, with_group_users=with_group_users, with_superusers=with_superusers):\\n if (with_group_users or with_superusers):\\n users[user] = sorted(get_perms(user, obj))\\n else:\\n users[user] = sorted(get_user_perms(user, obj))\\n return users\",\"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 decode_record(record):\\n 'Serialized Example to dict of .'\\n example_serialized = record\\n item_decoders = data_items_to_decoders\\n if (item_decoders is None):\\n item_decoders = {field: tf.contrib.slim.tfexample_decoder.Tensor(field) for field in data_fields_to_features}\\n decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder(data_fields_to_features, item_decoders)\\n decode_items = data_items_to_decode\\n if (decode_items is None):\\n decode_items = list(item_decoders)\\n decoded = decoder.decode(example_serialized, items=decode_items)\\n return dict(zip(decode_items, decoded))\\n with tf.name_scope('examples_in'):\\n data_files = tf.contrib.slim.parallel_reader.get_data_files(data_sources)\\n num_readers = min((4 if training else 1), len(data_files))\\n (_, example_serialized) = tf.contrib.slim.parallel_reader.parallel_read(data_sources, tf.TFRecordReader, num_epochs=(None if training else 1), shuffle=training, capacity=(2 * capacity), min_after_dequeue=capacity, num_readers=num_readers)\\n return decode_record(example_serialized)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def examples_reader(data_sources, data_fields_to_features, training, capacity=32, data_items_to_decoders=None, data_items_to_decode=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 media):\\n return\\n if isinstance(media, basestring):\\n media = [media]\\n request = cherrypy.serving.request\\n ranges = request.headers.elements('Accept')\\n if (not ranges):\\n if debug:\\n cherrypy.log('No Accept header elements', 'TOOLS.ACCEPT')\\n return media[0]\\n else:\\n for element in ranges:\\n if (element.qvalue > 0):\\n if (element.value == '*\\/*'):\\n if debug:\\n cherrypy.log('Match due to *\\/*', 'TOOLS.ACCEPT')\\n return media[0]\\n elif element.value.endswith('\\/*'):\\n mtype = element.value[:(-1)]\\n for m in media:\\n if m.startswith(mtype):\\n if debug:\\n cherrypy.log(('Match due to %s' % element.value), 'TOOLS.ACCEPT')\\n return m\\n elif (element.value in media):\\n if debug:\\n cherrypy.log(('Match due to %s' % element.value), 'TOOLS.ACCEPT')\\n return element.value\\n ah = request.headers.get('Accept')\\n if (ah is None):\\n msg = 'Your client did not send an Accept header.'\\n else:\\n msg = ('Your client sent this Accept header: %s.' % ah)\\n msg += (' But this resource only emits these media types: %s.' % ', '.join(media))\\n raise cherrypy.HTTPError(406, msg)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def accept(media=None, debug=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef TR10i(rv):\\n\\n ''''Sum of products to function of sum.\\n Examples\\n >>> from sympy.simplify.fu import TR10i\\n >>> from sympy import cos, sin, pi, Add, Mul, sqrt, Symbol\\n >>> from sympy.abc import x, y\\n >>> TR10i(cos(1)*cos(3) + sin(1)*sin(3))\\n cos(2)\\n >>> TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3))\\n cos(3) + sin(4)\\n >>> TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x)\\n 2*sqrt(2)*x*sin(x + pi\\/6)'\\n '''\",\"targets\":\"global _ROOT2, _ROOT3, _invROOT3\\n if (_ROOT2 is None):\\n _roots()\\n def f(rv):\\n if (not rv.is_Add):\\n return rv\\n def do(rv, first=True):\\n if (not rv.is_Add):\\n return rv\\n args = list(ordered(rv.args))\\n if (len(args) != 2):\\n hit = False\\n for i in range(len(args)):\\n ai = args[i]\\n if (ai is None):\\n continue\\n for j in range((i + 1), len(args)):\\n aj = args[j]\\n if (aj is None):\\n continue\\n was = (ai + aj)\\n new = do(was)\\n if (new != was):\\n args[i] = new\\n args[j] = None\\n hit = True\\n break\\n if hit:\\n rv = Add(*[_f for _f in args if _f])\\n if rv.is_Add:\\n rv = do(rv)\\n return rv\\n split = trig_split(two=True, *args)\\n if (not split):\\n return rv\\n (gcd, n1, n2, a, b, same) = split\\n if same:\\n gcd = (n1 * gcd)\\n if (n1 == n2):\\n return (gcd * cos((a - b)))\\n return (gcd * cos((a + b)))\\n else:\\n gcd = (n1 * gcd)\\n if (n1 == n2):\\n return (gcd * sin((a + b)))\\n return (gcd * sin((b - a)))\\n rv = process_common_addends(rv, do, (lambda x: tuple(ordered(x.free_symbols))))\\n while rv.is_Add:\\n byrad = defaultdict(list)\\n for a in rv.args:\\n hit = 0\\n if a.is_Mul:\\n for ai in a.args:\\n if (ai.is_Pow and (ai.exp is S.Half) and ai.base.is_Integer):\\n byrad[ai].append(a)\\n hit...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef connect(uri=None, session_args={}, engine_args={}, engine_prefix=''):\\n\\n ''''Connects to the requested URI. Returns a session object.\\n With the URI omitted, attempts to connect to a default SQLite database\\n contained within the package directory.\\n Calling this function also binds the metadata object to the created engine.'\\n '''\",\"targets\":\"if (uri is None):\\n uri = engine_args.get((engine_prefix + 'url'), None)\\n if (uri is None):\\n uri = get_default_db_uri()\\n if uri.startswith('mysql:'):\\n if ('charset' not in uri):\\n uri += '?charset=utf8'\\n for table in metadata.tables.values():\\n table.kwargs['mysql_engine'] = 'InnoDB'\\n table.kwargs['mysql_charset'] = 'utf8'\\n elif uri.startswith(('oracle:', 'oracle+cx_oracle:')):\\n if ('auto_setinputsizes' not in uri):\\n uri += '?auto_setinputsizes=FALSE'\\n engine_args[(engine_prefix + 'url')] = uri\\n engine = engine_from_config(engine_args, prefix=engine_prefix)\\n engine.connect()\\n metadata.bind = engine\\n all_session_args = dict(autoflush=True, autocommit=False, bind=engine)\\n all_session_args.update(session_args)\\n sm = orm.sessionmaker(class_=MultilangSession, default_language_id=ENGLISH_ID, **all_session_args)\\n session = MultilangScopedSession(sm)\\n return session\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef in6_getifaddr():\\n\\n ''''Returns all IPv6 addresses found on the computer'\\n '''\",\"targets\":\"if is_new_release():\\n ret = []\\n ps = sp.Popen([conf.prog.powershell, 'Get-NetRoute', '-AddressFamily IPV6', '|', 'select ifIndex, DestinationPrefix'], stdout=sp.PIPE, universal_newlines=True)\\n (stdout, stdin) = ps.communicate()\\n netstat_line = '\\\\\\\\s+'.join(['(\\\\\\\\d+)', ''.join(['([A-z|0-9|:]+)', '(\\\\\\\\\\/\\\\\\\\d+)'])])\\n pattern = re.compile(netstat_line)\\n for l in stdout.split('\\\\n'):\\n match = re.search(pattern, l)\\n if match:\\n try:\\n if_index = match.group(1)\\n iface = dev_from_index(if_index)\\n except:\\n continue\\n scope = scapy.utils6.in6_getscope(match.group(2))\\n ret.append((match.group(2), scope, iface))\\n continue\\n return ret\\n else:\\n ret = []\\n for line in exec_query(['Get-WmiObject', 'Win32_NetworkAdapterConfiguration'], ['InterfaceIndex', 'IPAddress']):\\n try:\\n iface = dev_from_index(line[0])\\n except:\\n continue\\n _l_addresses = line[1]\\n _inline = []\\n if _l_addresses:\\n _inline = _l_addresses[1:(-1)].split(',')\\n for _address in _inline:\\n _a = _address.strip()\\n if ('.' not in _a):\\n scope = scapy.utils6.in6_getscope(_a)\\n ret.append((_a, scope, iface))\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _get_filtered_exp_playlist_summaries(exploration_summaries, exploration_ids):\",\"targets\":\"\\\"\\\"\\\"Returns a list of summaries of the explorations in the learner playlist\\n and the ids of explorations that are no longer present.\\n Args:\\n exploration_summaries: list(ExplorationSummary). The list of exploration\\n summary domain objects to be filtered.\\n exploration_ids: list(str). The ids of the explorations corresponding to\\n the exploration summary domain objects.\\n Returns:\\n tuple. A 2-tuple whose elements are as follows:\\n - list(ExplorationSummary). Filtered list of ExplorationSummary domain\\n objects of the explorations in the learner playlist.\\n - list(str). The ids of the explorations that are no longer present.\\n \\\"\\\"\\\"\\n nonexistent_playlist_exp_ids = []\\n filtered_exp_playlist_summaries = []\\n for (index, exploration_summary) in enumerate(exploration_summaries):\\n if (exploration_summary is None):\\n nonexistent_playlist_exp_ids.append(exploration_ids[index])\\n else:\\n filtered_exp_playlist_summaries.append(exploration_summary)\\n return (filtered_exp_playlist_summaries, nonexistent_playlist_exp_ids)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n nps = [surf['np'] for surf in surfs]\\n np_tot = sum(nps)\\n coeff = np.zeros((np_tot, np_tot))\\n offsets = np.cumsum(np.concatenate(([0], nps)))\\n for (si_1, surf1) in enumerate(surfs):\\n rr_ord = np.arange(nps[si_1])\\n for (si_2, surf2) in enumerate(surfs):\\n logger.info((' %s (%d) -> %s (%d) ...' % (_bem_explain_surface(surf1['id']), nps[si_1], _bem_explain_surface(surf2['id']), nps[si_2])))\\n tri_rr = surf2['rr'][surf2['tris']]\\n tri_nn = surf2['tri_nn']\\n tri_area = surf2['tri_area']\\n submat = coeff[offsets[si_1]:offsets[(si_1 + 1)], offsets[si_2]:offsets[(si_2 + 1)]]\\n for k in range(surf2['ntri']):\\n tri = surf2['tris'][k]\\n if (si_1 == si_2):\\n skip_idx = (((rr_ord == tri[0]) | (rr_ord == tri[1])) | (rr_ord == tri[2]))\\n else:\\n skip_idx = list()\\n coeffs = _lin_pot_coeff(surf1['rr'], tri_rr[k], tri_nn[k], tri_area[k])\\n coeffs[skip_idx] = 0.0\\n submat[:, tri] -= coeffs\\n if (si_1 == si_2):\\n _correct_auto_elements(surf1, submat)\\n return coeff\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _fwd_bem_lin_pot_coeff(surfs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n promo = get_object_or_404(SupporterPromo, pk=promo_id)\\n count = cache.get(promo.cache_key(type=CLICKS, hash=hash), None)\\n if (count is None):\\n log.warning('Old or nonexistent hash tried on Click.')\\n elif (count == 0):\\n promo.incr(CLICKS)\\n cache.incr(promo.cache_key(type=CLICKS, hash=hash))\\n project_slug = cache.get(promo.cache_key(type='project', hash=hash), None)\\n if project_slug:\\n project = Project.objects.get(slug=project_slug)\\n promo.incr(CLICKS, project=project)\\n else:\\n agent = request.META.get('HTTP_USER_AGENT', 'Unknown')\\n log.warning('Duplicate click logged. {count} total clicks tried. User Agent: [{agent}]'.format(count=count, agent=agent))\\n cache.incr(promo.cache_key(type=CLICKS, hash=hash))\\n raise Http404('Invalid click. This has been logged.')\\n return redirect(promo.link)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def click_proxy(request, promo_id, hash):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def fromstr(string, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Given a string value, returns a GEOSGeometry object.\\n \\\"\\\"\\\"\\n return GEOSGeometry(string, **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 authstr = ('Basic ' + to_native_string(b64encode(('%s:%s' % (username, password)).encode('latin1')).strip()))\\n return authstr\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _basic_auth_str(username, password):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def check_children(options):\",\"targets\":\"\\\"\\\"\\\"When a child process hasn\\\\t received a datapoint in a while,\\n assume it\\\\s died in some fashion and restart it.\\n \\\"\\\"\\\"\\n for col in all_living_collectors():\\n now = int(time.time())\\n if ((col.interval == 0) and (col.last_datapoint < (now - options.allowed_inactivity_time))):\\n LOG.warning('Terminating collector %s after %d seconds of inactivity', col.name, (now - col.last_datapoint))\\n col.shutdown()\\n if (not options.remove_inactive_collectors):\\n register_collector(Collector(col.name, col.interval, col.filename, col.mtime, col.lastspawn))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def is_installable_dir(path):\",\"targets\":\"\\\"\\\"\\\"Return True if `path` is a directory containing a setup.py file.\\n \\\"\\\"\\\"\\n if (not os.path.isdir(path)):\\n return False\\n setup_py = os.path.join(path, 'setup.py')\\n if os.path.isfile(setup_py):\\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 import MySQLdb\\n if (m in MySQLdb.NUMBER):\\n return u'Currency'\\n elif (m in MySQLdb.DATE):\\n return u'Date'\\n else:\\n return u'Data'\\n\\n\\nWhat's a good function header?\",\"targets\":\"def guess_type(m):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def decode(input, output):\",\"targets\":\"\\\"\\\"\\\"Decode a file.\\n \\\"\\\"\\\"\\n while True:\\n line = input.readline()\\n if (not line):\\n break\\n s = binascii.a2b_base64(line)\\n output.write(s)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef ci_skip(registry, xml_parent, data):\\n\\n ''''yaml: ci-skip\\n Skip making a build for certain push.\\n Just add [ci skip] into your commit\\\\'s message to let Jenkins know,\\n that you do not want to perform build for the next push.\\n Requires the Jenkins :jenkins-wiki:`Ci Skip Plugin `.\\n Example:\\n .. literalinclude:: \\/..\\/..\\/tests\\/wrappers\\/fixtures\\/ci-skip001.yaml'\\n '''\",\"targets\":\"rpobj = XML.SubElement(xml_parent, 'ruby-proxy-object')\\n robj = XML.SubElement(rpobj, 'ruby-object', attrib={'pluginid': 'ci-skip', 'ruby-class': 'Jenkins::Tasks::BuildWrapperProxy'})\\n pluginid = XML.SubElement(robj, 'pluginid', {'pluginid': 'ci-skip', 'ruby-class': 'String'})\\n pluginid.text = 'ci-skip'\\n obj = XML.SubElement(robj, 'object', {'ruby-class': 'CiSkipWrapper', 'pluginid': 'ci-skip'})\\n XML.SubElement(obj, 'ci__skip', {'pluginid': 'ci-skip', 'ruby-class': 'NilClass'})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef addPillarFromConvexLoopsGridTop(faces, indexedGridTop, indexedLoops):\\n\\n ''''Add pillar from convex loops and grid top.'\\n '''\",\"targets\":\"addFacesByLoopReversed(faces, indexedLoops[0])\\n addFacesByConvexLoops(faces, indexedLoops)\\n addFacesByGrid(faces, indexedGridTop)\",\"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 (hsl_to_rgb(6120, 100, 50) == (255, 0, 0))\\n assert (hsl_to_rgb((-9660), 100, 50) == (255, 255, 0))\\n assert (hsl_to_rgb(99840, 100, 50) == (0, 255, 0))\\n assert (hsl_to_rgb((-900), 100, 50) == (0, 255, 255))\\n assert (hsl_to_rgb((-104880), 100, 50) == (0, 0, 255))\\n assert (hsl_to_rgb(2820, 100, 50) == (255, 0, 255))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_hsl_to_rgb_part_3():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef __virtual__():\\n\\n ''''Only work on OpenBSD'\\n '''\",\"targets\":\"if ((__grains__['os'] == 'OpenBSD') and os.path.exists('\\/etc\\/rc.d\\/rc.subr')):\\n krel = list(list(map(int, __grains__['kernelrelease'].split('.'))))\\n if ((krel[0] > 5) or ((krel[0] == 5) and (krel[1] > 0))):\\n if (not os.path.exists('\\/usr\\/sbin\\/rcctl')):\\n return __virtualname__\\n return (False, 'The openbsdservice execution module cannot be loaded: only available on OpenBSD systems.')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_dasharray(obj):\\n\\n ''''Get an SVG dash array for the given matplotlib linestyle\\n Parameters\\n obj : matplotlib object\\n The matplotlib line or path object, which must have a get_linestyle()\\n method which returns a valid matplotlib line code\\n Returns\\n dasharray : string\\n The HTML\\/SVG dasharray code associated with the object.'\\n '''\",\"targets\":\"if (obj.__dict__.get('_dashSeq') is not None):\\n return ','.join(map(str, obj._dashSeq))\\n else:\\n ls = obj.get_linestyle()\\n dasharray = LINESTYLES.get(ls, 'not found')\\n if (dasharray == 'not found'):\\n warnings.warn(\\\"line style '{0}' not understood: defaulting to solid line.\\\".format(ls))\\n dasharray = LINESTYLES['solid']\\n return dasharray\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n ch_2nd = metric_to_Christoffel_2nd(expr)\\n coord_sys = expr.atoms(CoordSystem).pop()\\n indices = list(range(coord_sys.dim))\\n deriv_ch = [[[[d(ch_2nd[(i, j, k)]) for d in coord_sys.base_vectors()] for k in indices] for j in indices] for i in indices]\\n riemann_a = [[[[(deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu]) for nu in indices] for mu in indices] for sig in indices] for rho in indices]\\n riemann_b = [[[[Add(*[((ch_2nd[(rho, l, mu)] * ch_2nd[(l, sig, nu)]) - (ch_2nd[(rho, l, nu)] * ch_2nd[(l, sig, mu)])) for l in indices]) for nu in indices] for mu in indices] for sig in indices] for rho in indices]\\n riemann = [[[[(riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu]) for nu in indices] for mu in indices] for sig in indices] for rho in indices]\\n return ImmutableDenseNDimArray(riemann)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def metric_to_Riemann_components(expr):\",\"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 is_entrance_exams_enabled():\\n graders = [grader for grader in graders if (grader.get('type') != u'Entrance Exam')]\\n return graders\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _filter_entrance_exam_grader(graders):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef garden():\\n\\n ''''RESTful CRUD controller'\\n '''\",\"targets\":\"def postp(r, output):\\n if (r.interactive and (r.component_name == 'tenure')):\\n s3_action_buttons(r)\\n s3.actions += [dict(label=s3base.s3_str(T('Certificate')), _class='action-btn', url=URL(f='tenure', args=['[id]', 'certificate']))]\\n return output\\n s3.postp = postp\\n return s3_rest_controller(rheader=s3db.stdm_rheader)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not os.path.exists(filename)):\\n filename = salt.utils.path.which(filename)\\n if (ret is None):\\n ret = []\\n out = __salt__['cmd.run'](('ldd', filename), python_shell=False)\\n for line in out.splitlines():\\n if (not line.strip()):\\n continue\\n dep_path = ''\\n if ('=>' in line):\\n comps = line.split(' => ')\\n dep_comps = comps[1].strip().split()\\n if os.path.exists(dep_comps[0]):\\n dep_path = dep_comps[0]\\n else:\\n dep_comps = line.strip().split()\\n if os.path.exists(dep_comps[0]):\\n dep_path = dep_comps[0]\\n if dep_path:\\n if (dep_path not in ret):\\n ret.append(dep_path)\\n new_deps = ldd_deps(dep_path, ret)\\n for dep in new_deps:\\n if (dep not in ret):\\n ret.append(dep)\\n return ret\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ldd_deps(filename, ret=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def annotate(head, list):\",\"targets\":\"\\\"\\\"\\\"Add \\\\\\/\\\\ suffixes to directories.\\n \\\"\\\"\\\"\\n for i in range(len(list)):\\n if os.path.isdir(os.path.join(head, list[i])):\\n list[i] = (list[i] + '\\/')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _write_file_routes(iface, data, folder, pattern):\",\"targets\":\"\\\"\\\"\\\"Writes a file to disk\\n \\\"\\\"\\\"\\n iface = iface.replace('.', '_')\\n filename = os.path.join(folder, pattern.format(iface))\\n if (not os.path.exists(folder)):\\n msg = '{0} cannot be written. {1} does not exist'\\n msg = msg.format(filename, folder)\\n log.error(msg)\\n raise AttributeError(msg)\\n with salt.utils.files.flopen(filename, 'w') as fout:\\n fout.write(data)\\n __salt__['file.set_mode'](filename, '0755')\\n return filename\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_unbound_method(func, cls):\",\"targets\":\"\\\"\\\"\\\"Create an unbounded method from a function and a class.\\n Notes\\n See https:\\/\\/bitbucket.org\\/gutworth\\/six\\/pull-request\\/64.\\n \\\"\\\"\\\"\\n if six.PY2:\\n return MethodType(func, None, cls)\\n if six.PY3:\\n return func\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@jinja_test('equalto')\\ndef test_equalto(value, other):\",\"targets\":\"\\\"\\\"\\\"Returns true if two values are equal.\\n \\\"\\\"\\\"\\n return (value == other)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef encode_multipart(boundary, data):\\n\\n ''''Encodes multipart POST data from a dictionary of form values.\\n The key will be used as the form data name; the value will be transmitted\\n as content. If the value is a file, the contents of the file will be sent\\n as an application\\/octet-stream; otherwise, str(value) will be sent.'\\n '''\",\"targets\":\"lines = []\\n to_str = (lambda s: smart_str(s, settings.DEFAULT_CHARSET))\\n is_file = (lambda thing: (hasattr(thing, 'read') and callable(thing.read)))\\n for (key, value) in data.items():\\n if is_file(value):\\n lines.extend(encode_file(boundary, key, value))\\n elif ((not isinstance(value, basestring)) and is_iterable(value)):\\n for item in value:\\n if is_file(item):\\n lines.extend(encode_file(boundary, key, item))\\n else:\\n lines.extend([('--' + boundary), ('Content-Disposition: form-data; name=\\\"%s\\\"' % to_str(key)), '', to_str(item)])\\n else:\\n lines.extend([('--' + boundary), ('Content-Disposition: form-data; name=\\\"%s\\\"' % to_str(key)), '', to_str(value)])\\n lines.extend([(('--' + boundary) + '--'), ''])\\n return '\\\\r\\\\n'.join(lines)\",\"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 get_compare_type(xml_tag, compare_type):\\n valid_compare_types = ['PLAIN', 'ANT', 'REG_EXP']\\n if (compare_type not in valid_compare_types):\\n raise InvalidAttributeError(xml_tag, compare_type, valid_compare_types)\\n return compare_type\\n gerrit_handle_legacy_configuration(data)\\n projects = data.get('projects', [])\\n gtrig = XML.SubElement(xml_parent, 'com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritTrigger')\\n XML.SubElement(gtrig, 'spec')\\n gprojects = XML.SubElement(gtrig, 'gerritProjects')\\n for project in projects:\\n gproj = XML.SubElement(gprojects, 'com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.GerritProject')\\n XML.SubElement(gproj, 'compareType').text = get_compare_type('project-compare-type', project.get('project-compare-type', 'PLAIN'))\\n XML.SubElement(gproj, 'pattern').text = project['project-pattern']\\n branches = XML.SubElement(gproj, 'branches')\\n project_branches = project.get('branches', [])\\n if (('branch-compare-type' in project) and ('branch-pattern' in project)):\\n warning = 'branch-compare-type and branch-pattern at project level are deprecated and support will be removed in a later version of Jenkins Job Builder; '\\n if project_branches:\\n warning += 'discarding values and using values from branches section'\\n else:\\n warning += 'please use branches section instead'\\n logger.warning(warning)\\n if (not project_branches):\\n project_branches = [{'branch-compare-type': project.get('branch-compare-type', 'PLAIN'), 'branch-pattern': project['branch-pattern']}]\\n for branch in project_branches:\\n gbranch = XML.SubElement(branches, 'com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.Branch')\\n XML.SubElement(gbranch, 'compareType').text =...\\n\\nWhat's a good function header?\",\"targets\":\"def gerrit(registry, xml_parent, data):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _diff(state_data, resource_object):\",\"targets\":\"\\\"\\\"\\\"helper method to compare salt state info with the PagerDuty API json structure,\\n and determine if we need to update.\\n returns the dict to pass to the PD API to perform the update, or empty dict if no update.\\n \\\"\\\"\\\"\\n state_data['id'] = resource_object['schedule']['id']\\n objects_differ = None\\n for (k, v) in state_data['schedule'].items():\\n if (k == 'schedule_layers'):\\n continue\\n if (v != resource_object['schedule'][k]):\\n objects_differ = '{0} {1} {2}'.format(k, v, resource_object['schedule'][k])\\n break\\n if (not objects_differ):\\n for layer in state_data['schedule']['schedule_layers']:\\n resource_layer = None\\n for resource_layer in resource_object['schedule']['schedule_layers']:\\n found = False\\n if (layer['name'] == resource_layer['name']):\\n found = True\\n break\\n if (not found):\\n objects_differ = 'layer {0} missing'.format(layer['name'])\\n break\\n layer['id'] = resource_layer['id']\\n for (k, v) in layer.items():\\n if (k == 'users'):\\n continue\\n if (k == 'start'):\\n continue\\n if (v != resource_layer[k]):\\n objects_differ = 'layer {0} key {1} {2} != {3}'.format(layer['name'], k, v, resource_layer[k])\\n break\\n if objects_differ:\\n break\\n if (len(layer['users']) != len(resource_layer['users'])):\\n objects_differ = 'num users in layer {0} {1} != {2}'.format(layer['name'], len(layer['users']), len(resource_layer['users']))\\n break\\n for user1 in layer['users']:\\n found = False\\n user2 = None\\n for user2 in resource_layer['users']:\\n if (user1['member_order'] == (user2['member_order'] - 1)):\\n found = True\\n break\\n if (not found):\\n objects_differ = 'layer {0} no one with member_order {1}'.format(layer['name'],...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def format_timedelta(datetime_or_timedelta, granularity='second', threshold=0.85):\",\"targets\":\"\\\"\\\"\\\"See :meth:`I18n.format_timedelta`.\\n \\\"\\\"\\\"\\n return get_i18n().format_timedelta(datetime_or_timedelta, granularity, threshold)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@pytest.fixture\\ndef api_client_inject_project_id():\",\"targets\":\"\\\"\\\"\\\"Patches all googleapiclient requests to replace \\\\YOUR_PROJECT_ID\\\\ with\\n the project ID.\\n \\\"\\\"\\\"\\n import googleapiclient.http\\n old_execute = googleapiclient.http.HttpRequest.execute\\n def new_execute(self, http=None, num_retries=0):\\n self.uri = self.uri.replace('YOUR_PROJECT_ID', PROJECT)\\n return old_execute(self, http=http, num_retries=num_retries)\\n with mock.patch('googleapiclient.http.HttpRequest.execute', new=new_execute):\\n (yield)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@contextlib.contextmanager\\ndef remove_path_on_error(path):\",\"targets\":\"\\\"\\\"\\\"Protect code that wants to operate on PATH atomically.\\n Any exception will cause PATH to be removed.\\n \\\"\\\"\\\"\\n try:\\n (yield)\\n except Exception:\\n with excutils.save_and_reraise_exception():\\n delete_if_exists(path)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n QtWebKitWidgets = pytest.importorskip('PyQt5.QtWebKitWidgets')\\n view = QtWebKitWidgets.QWebView()\\n qtbot.add_widget(view)\\n view.page().deleteLater()\\n view.setPage(webpage)\\n view.resize(640, 480)\\n return view\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.fixture\\ndef webview(qtbot, webpage):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def diff_info_plot(frame, time):\",\"targets\":\"\\\"\\\"\\\"Useful for plotting a frame with multiple times. *Not* used in the testing\\n suite per se, but extremely useful for interactive plotting of results from\\n tests in this module.\\n \\\"\\\"\\\"\\n from matplotlib import pyplot as plt\\n (fig, ((ax1, ax2), (ax3, ax4))) = plt.subplots(2, 2, figsize=(20, 12))\\n ax1.plot_date(time.plot_date, frame.data.differentials[u's'].d_xyz.to((u.km \\/ u.s)).T, fmt=u'-')\\n ax1.legend([u'x', u'y', u'z'])\\n ax2.plot_date(time.plot_date, (np.sum((frame.data.differentials[u's'].d_xyz.to((u.km \\/ u.s)) ** 2), axis=0) ** 0.5), fmt=u'-')\\n ax2.set_title(u'total')\\n sd = frame.data.differentials[u's'].represent_as(SphericalDifferential, frame.data)\\n ax3.plot_date(time.plot_date, sd.d_distance.to((u.km \\/ u.s)), fmt=u'-')\\n ax3.set_title(u'radial')\\n ax4.plot_date(time.plot_date, sd.d_lat.to((u.marcsec \\/ u.yr)), fmt=u'-', label=u'lat')\\n ax4.plot_date(time.plot_date, sd.d_lon.to((u.marcsec \\/ u.yr)), fmt=u'-', label=u'lon')\\n return fig\",\"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_include_exclude_names(parallel, read_basic):\\n\\n ''''Make sure that include_names is applied before exclude_names if both are specified.'\\n '''\",\"targets\":\"text = '\\\\nA B C D E F G H\\\\n1 2 3 4 5 6 7 8\\\\n9 10 11 12 13 14 15 16\\\\n'\\n table = read_basic(text, include_names=['A', 'B', 'D', 'F', 'H'], exclude_names=['B', 'F'], parallel=parallel)\\n expected = Table([[1, 9], [4, 12], [8, 16]], names=('A', 'D', 'H'))\\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 if (__grains__['kernel'] == 'AIX'):\\n return __virtualname__\\n return (False, 'The aix_group execution module failed to load: only available on AIX systems.')\\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 _minimize_powell(func, x0, args=(), callback=None, xtol=0.0001, ftol=0.0001, maxiter=None, maxfev=None, disp=False, direc=None, return_all=False, **unknown_options):\\n\\n ''''Minimization of scalar function of one or more variables using the\\n modified Powell algorithm.\\n Options\\n disp : bool\\n Set to True to print convergence messages.\\n xtol : float\\n Relative error in solution `xopt` acceptable for convergence.\\n ftol : float\\n Relative error in ``fun(xopt)`` acceptable for convergence.\\n maxiter, maxfev : int\\n Maximum allowed number of iterations and function evaluations.\\n Will default to ``N*1000``, where ``N`` is the number of\\n variables, if neither `maxiter` or `maxfev` is set. If both\\n `maxiter` and `maxfev` are set, minimization will stop at the\\n first reached.\\n direc : ndarray\\n Initial set of direction vectors for the Powell method.'\\n '''\",\"targets\":\"_check_unknown_options(unknown_options)\\n maxfun = maxfev\\n retall = return_all\\n (fcalls, func) = wrap_function(func, args)\\n x = asarray(x0).flatten()\\n if retall:\\n allvecs = [x]\\n N = len(x)\\n if ((maxiter is None) and (maxfun is None)):\\n maxiter = (N * 1000)\\n maxfun = (N * 1000)\\n elif (maxiter is None):\\n if (maxfun == np.inf):\\n maxiter = (N * 1000)\\n else:\\n maxiter = np.inf\\n elif (maxfun is None):\\n if (maxiter == np.inf):\\n maxfun = (N * 1000)\\n else:\\n maxfun = np.inf\\n if (direc is None):\\n direc = eye(N, dtype=float)\\n else:\\n direc = asarray(direc, dtype=float)\\n fval = squeeze(func(x))\\n x1 = x.copy()\\n iter = 0\\n ilist = list(range(N))\\n while True:\\n fx = fval\\n bigind = 0\\n delta = 0.0\\n for i in ilist:\\n direc1 = direc[i]\\n fx2 = fval\\n (fval, x, direc1) = _linesearch_powell(func, x, direc1, tol=(xtol * 100))\\n if ((fx2 - fval) > delta):\\n delta = (fx2 - fval)\\n bigind = i\\n iter += 1\\n if (callback is not None):\\n callback(x)\\n if retall:\\n allvecs.append(x)\\n bnd = ((ftol * (numpy.abs(fx) + numpy.abs(fval))) + 1e-20)\\n if ((2.0 * (fx - fval)) <= bnd):\\n break\\n if (fcalls[0] >= maxfun):\\n break\\n if (iter >= maxiter):\\n break\\n direc1 = (x - x1)\\n x2 = ((2 * x) - x1)\\n x1 = x.copy()\\n fx2 = squeeze(func(x2))\\n if (fx > fx2):\\n t = (2.0 * ((fx + fx2) - (2.0 * fval)))\\n temp = ((fx - fval) - delta)\\n t *= (temp * temp)\\n temp = (fx - fx2)\\n t -= ((delta * temp) * temp)\\n if (t < 0.0):\\n (fval, x, direc1) = _linesearch_powell(func, x, direc1, tol=(xtol * 100))\\n direc[bigind] = direc[(-1)]\\n direc[(-1)] = direc1\\n warnflag = 0\\n if (fcalls[0] >=...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@LocalContext\\ndef flat(*args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"flat(*args, preprocessor = None, word_size = None, endianness = None, sign = None)\\n Flattens the arguments into a string.\\n This function takes an arbitrary number of arbitrarily nested lists and\\n tuples. It will then find every string and number inside those and flatten\\n them out. Strings are inserted directly while numbers are packed using the\\n :func:`pack` function.\\n The three kwargs `word_size`, `endianness` and `sign` will default to using\\n values in :mod:`pwnlib.context` if not specified as an argument.\\n Arguments:\\n args: Values to flatten\\n preprocessor (function): Gets called on every element to optionally\\n transform the element before flattening. If :const:`None` is\\n returned, then the original value is uded.\\n word_size (int): Word size of the converted integer.\\n endianness (str): Endianness of the converted integer (\\\"little\\\"\\/\\\"big\\\").\\n sign (str): Signedness of the converted integer (False\\/True)\\n Examples:\\n >>> flat(1, \\\"test\\\", [[[\\\"AB\\\"]*2]*3], endianness = \\\\little\\\\, word_size = 16, sign = False)\\n \\\\\\\\x01\\\\x00testABABABABABAB\\\\\\n >>> flat([1, [2, 3]], preprocessor = lambda x: str(x+1))\\n \\\\234\\\\\\n \\\"\\\"\\\"\\n preprocessor = kwargs.pop('preprocessor', (lambda x: None))\\n word_size = kwargs.pop('word_size', None)\\n if (kwargs != {}):\\n raise TypeError(('flat() does not support argument %r' % kwargs.popitem()[0]))\\n return _flat(args, preprocessor, make_packer(word_size))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def allocation():\",\"targets\":\"\\\"\\\"\\\"REST controller for budget_allocation\\n @status: experimental, not for production use\\n \\\"\\\"\\\"\\n return s3_rest_controller()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n nzo_ids = []\\n if (catdir is None):\\n catdir = cat\\n try:\\n f = open(path, 'rb')\\n b1 = f.read(1)\\n b2 = f.read(1)\\n f.close()\\n if ((b1 == '\\\\x1f') and (b2 == '\\\\x8b')):\\n name = filename.replace('.nzb.gz', '.nzb')\\n f = gzip.GzipFile(path, 'rb')\\n elif ((b1 == 'B') and (b2 == 'Z')):\\n name = filename.replace('.nzb.bz2', '.nzb')\\n f = bz2.BZ2File(path, 'rb')\\n else:\\n name = filename\\n f = open(path, 'rb')\\n data = f.read()\\n f.close()\\n except:\\n logging.warning(T('Cannot read %s'), misc.clip_path(path))\\n logging.info('Traceback: ', exc_info=True)\\n return ((-2), nzo_ids)\\n if name:\\n (name, cat) = name_to_cat(name, catdir)\\n if (not nzbname):\\n nzbname = os.path.split(name)[1]\\n try:\\n nzo = nzbstuff.NzbObject(name, pp, script, data, cat=cat, priority=priority, nzbname=nzbname, nzo_info=nzo_info, url=url, reuse=reuse, dup_check=dup_check)\\n if (not nzo.password):\\n nzo.password = password\\n except TypeError:\\n if nzo_id:\\n sabnzbd.nzbqueue.NzbQueue.do.remove(nzo_id, add_to_history=False)\\n nzo = None\\n except ValueError:\\n return ((-1), nzo_ids)\\n except:\\n if ((data.find('= 0) and (data.find('<\\/nzb') < 0)):\\n return ((-2), nzo_ids)\\n else:\\n return ((-1), nzo_ids)\\n if nzo:\\n if nzo_id:\\n sabnzbd.nzbqueue.NzbQueue.do.remove(nzo_id, add_to_history=False)\\n nzo.nzo_id = nzo_id\\n nzo_ids.append(sabnzbd.nzbqueue.NzbQueue.do.add(nzo, quiet=reuse))\\n nzo.update_rating()\\n try:\\n if (not keep):\\n os.remove(path)\\n except:\\n logging.error(T('Error removing %s'), misc.clip_path(path))\\n logging.info('Traceback: ', exc_info=True)\\n return (1, nzo_ids)\\n return (0, nzo_ids)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ProcessSingleFile(filename, path, pp=None, script=None, cat=None, catdir=None, keep=False, priority=None, nzbname=None, reuse=False, nzo_info=None, dup_check=True, url='', password=None, nzo_id=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 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\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _build_shadow_vm_config_spec(session, name, size_kb, disk_type, ds_name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n cache.delete_many([instance_key(model, x) for x in instance_or_pk])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def delete_instance(model, *instance_or_pk):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_A(host, resolver=None, use_dnspython=True):\\n\\n ''''Lookup DNS A records for a given host.\\n If ``resolver`` is not provided, or is ``None``, then resolution will\\n be performed using the built-in :mod:`socket` module.\\n :param host: The hostname to resolve for A record IPv4 addresses.\\n :param resolver: Optional DNS resolver object to use for the query.\\n :param use_dnspython: Optionally control if dnspython is used to make\\n the DNS queries instead of the built-in DNS\\n library.\\n :type host: string\\n :type resolver: :class:`dns.resolver.Resolver` or ``None``\\n :type use_dnspython: bool\\n :return: A list of IPv4 literals.'\\n '''\",\"targets\":\"log.debug(('DNS: Querying %s for A records.' % host))\\n if ((resolver is None) or (not use_dnspython)):\\n try:\\n recs = socket.getaddrinfo(host, None, socket.AF_INET, socket.SOCK_STREAM)\\n return [rec[4][0] for rec in recs]\\n except socket.gaierror:\\n log.debug(('DNS: Error retreiving A address info for %s.' % host))\\n return []\\n try:\\n recs = resolver.query(host, dns.rdatatype.A)\\n return [rec.to_text() for rec in recs]\\n except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):\\n log.debug(('DNS: No A records for %s' % host))\\n return []\\n except dns.exception.Timeout:\\n log.debug(('DNS: A record resolution timed out for %s' % host))\\n return []\\n except dns.exception.DNSException as e:\\n log.debug(('DNS: Error querying A records for %s' % host))\\n log.exception(e)\\n return []\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _retcode_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, template=None, umask=None, output_loglevel='quiet', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Helper for running commands quietly for minion startup.\\n Returns same as retcode\\n \\\"\\\"\\\"\\n return retcode(cmd, cwd=cwd, stdin=stdin, runas=runas, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_timezone_name():\",\"targets\":\"\\\"\\\"\\\"This returns a cross-platform compatible timezone name suitable for\\n embedding into cache-keys. Its inclusion into cache-keys enables, but does\\n not guarantee by itself, that dates are display correctly for the client\\\\s\\n timezone. In order to complete this the project should use middleware or\\n some other mechanism to affect\\\\s Django\\\\s get_current_timezone_name().\\n \\\"\\\"\\\"\\n tz_name = force_text(get_current_timezone_name(), errors='ignore')\\n return tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def copytodir(src, dstdir):\",\"targets\":\"\\\"\\\"\\\"Copy a file or a directory to an existing directory.\\n \\\"\\\"\\\"\\n dst = pathjoin(dstdir, os.path.basename(src))\\n copy(src, dst)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef is_safe_url(url, host=None):\\n\\n ''''Return ``True`` if the url is a safe redirection (i.e. it doesn\\\\'t point to\\n a different host).\\n Always returns ``False`` on an empty url.'\\n '''\",\"targets\":\"if (not url):\\n return False\\n netloc = urlparse.urlparse(url)[1]\\n return ((not netloc) or (netloc == host))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef GammaInverse(name, a, b):\\n\\n ''''Create a continuous random variable with an inverse Gamma distribution.\\n The density of the inverse Gamma distribution is given by\\n .. math::\\n f(x) := \\\\frac{\\\\beta^\\\\alpha}{\\\\Gamma(\\\\alpha)} x^{-\\\\alpha - 1}\\n \\\\exp\\\\left(\\\\frac{-\\\\beta}{x}\\\\right)\\n with :math:`x > 0`.\\n Parameters\\n a : Real number, `a > 0` a shape\\n b : Real number, `b > 0` a scale\\n Returns\\n A RandomSymbol.\\n Examples\\n >>> from sympy.stats import GammaInverse, density, cdf, E, variance\\n >>> from sympy import Symbol, pprint\\n >>> a = Symbol(\\\"a\\\", positive=True)\\n >>> b = Symbol(\\\"b\\\", positive=True)\\n >>> z = Symbol(\\\"z\\\")\\n >>> X = GammaInverse(\\\"x\\\", a, b)\\n >>> D = density(X)(z)\\n >>> pprint(D, use_unicode=False)\\n -b\\n a -a - 1 z\\n b *z *e\\n gamma(a)\\n References\\n .. [1] http:\\/\\/en.wikipedia.org\\/wiki\\/Inverse-gamma_distribution'\\n '''\",\"targets\":\"return rv(name, GammaInverseDistribution, (a, b))\",\"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(s, str) and (HAS_UTF8.search(s) is not None)):\\n s = s.decode('utf-8')\\n def replace(match):\\n s = match.group(0)\\n try:\\n return ESCAPE_DCT[s]\\n except KeyError:\\n n = ord(s)\\n if (n < 65536):\\n return '\\\\\\\\u{0:04x}'.format(n)\\n else:\\n n -= 65536\\n s1 = (55296 | ((n >> 10) & 1023))\\n s2 = (56320 | (n & 1023))\\n return '\\\\\\\\u{0:04x}\\\\\\\\u{1:04x}'.format(s1, s2)\\n return (('\\\"' + str(ESCAPE_ASCII.sub(replace, s))) + '\\\"')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def py_encode_basestring_ascii(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 parser = argparse.ArgumentParser()\\n rules = shlex.split(rule)\\n rules.pop(0)\\n parser.add_argument('--utc', dest='utc', action='store_true')\\n parser.add_argument('--nontp', dest='nontp', action='store_true')\\n parser.add_argument('--ntpservers', dest='ntpservers', action='store')\\n parser.add_argument('--isUtc', dest='isutc', action='store_true')\\n parser.add_argument('timezone')\\n args = clean_args(vars(parser.parse_args(rules)))\\n parser = None\\n return args\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_timezone(rule):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef dump_follow_restriction(followRes):\\n\\n ''''Dumps the given dictionary to a file using the json format'\\n '''\",\"targets\":\"with open('.\\/logs\\/followRestriction.json', 'w') as followResFile:\\n json.dump(followRes, followResFile)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def command_sanity_shellcheck(args, targets):\",\"targets\":\"\\\"\\\"\\\":type args: SanityConfig\\n :type targets: SanityTargets\\n :rtype: SanityResult\\n \\\"\\\"\\\"\\n test = 'shellcheck'\\n with open('test\\/sanity\\/shellcheck\\/skip.txt', 'r') as skip_fd:\\n skip_paths = set(skip_fd.read().splitlines())\\n with open('test\\/sanity\\/shellcheck\\/exclude.txt', 'r') as exclude_fd:\\n exclude = set(exclude_fd.read().splitlines())\\n paths = sorted((i.path for i in targets.include if ((os.path.splitext(i.path)[1] == '.sh') and (i.path not in skip_paths))))\\n if (not paths):\\n return SanitySkipped(test)\\n cmd = (['shellcheck', '-e', ','.join(sorted(exclude)), '--format', 'checkstyle'] + paths)\\n try:\\n (stdout, stderr) = run_command(args, cmd, capture=True)\\n status = 0\\n except SubprocessError as ex:\\n stdout = ex.stdout\\n stderr = ex.stderr\\n status = ex.status\\n if (stderr or (status > 1)):\\n raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)\\n if args.explain:\\n return SanitySkipped(test)\\n root = fromstring(stdout)\\n results = []\\n for item in root:\\n for entry in item:\\n results.append(SanityMessage(message=entry.attrib['message'], path=item.attrib['name'], line=int(entry.attrib['line']), column=int(entry.attrib['column']), level=entry.attrib['severity'], code=entry.attrib['source'].replace('ShellCheck.', '')))\\n if results:\\n return SanityFailure(test, messages=results)\\n return SanitySuccess(test)\",\"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 set_ in sort_as_subsets(tuples, allitems, deterministic_order):\\n for s in set_:\\n (yield s)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def sort(tuples, allitems, deterministic_order=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 (type, value, context, children) = raw_node\\n if (children or (type in grammar.number2symbol)):\\n if (len(children) == 1):\\n return children[0]\\n return Node(type, children, context=context)\\n else:\\n return Leaf(type, value, context=context)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def convert(grammar, raw_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 if (not os.path.isdir(cachedir)):\\n os.mkdir(cachedir)\\n cachefile = os.path.join(cachedir, 'annots.pkl')\\n with open(imagesetfile, 'r') as f:\\n lines = f.readlines()\\n imagenames = [x.strip() for x in lines]\\n if (not os.path.isfile(cachefile)):\\n recs = {}\\n for (i, imagename) in enumerate(imagenames):\\n recs[imagename] = parse_rec(annopath.format(imagename))\\n if ((i % 100) == 0):\\n print 'Reading annotation for {:d}\\/{:d}'.format((i + 1), len(imagenames))\\n print 'Saving cached annotations to {:s}'.format(cachefile)\\n with open(cachefile, 'w') as f:\\n cPickle.dump(recs, f)\\n else:\\n with open(cachefile, 'r') as f:\\n recs = cPickle.load(f)\\n class_recs = {}\\n npos = 0\\n for imagename in imagenames:\\n R = [obj for obj in recs[imagename] if (obj['name'] == classname)]\\n bbox = np.array([x['bbox'] for x in R])\\n difficult = np.array([x['difficult'] for x in R]).astype(np.bool)\\n det = ([False] * len(R))\\n npos = (npos + sum((~ difficult)))\\n class_recs[imagename] = {'bbox': bbox, 'difficult': difficult, 'det': det}\\n detfile = detpath.format(classname)\\n with open(detfile, 'r') as f:\\n lines = f.readlines()\\n if (any(lines) == 1):\\n splitlines = [x.strip().split(' ') for x in lines]\\n image_ids = [x[0] for x in splitlines]\\n confidence = np.array([float(x[1]) for x in splitlines])\\n BB = np.array([[float(z) for z in x[2:]] for x in splitlines])\\n sorted_ind = np.argsort((- confidence))\\n sorted_scores = np.sort((- confidence))\\n BB = BB[sorted_ind, :]\\n image_ids = [image_ids[x] for x in sorted_ind]\\n nd = len(image_ids)\\n tp = np.zeros(nd)\\n fp = np.zeros(nd)\\n for d in range(nd):\\n R = class_recs[image_ids[d]]\\n bb = BB[d, :].astype(float)\\n ovmax = (- np.inf)\\n BBGT = R['bbox'].astype(float)\\n if...\\n\\nWhat's a good function header?\",\"targets\":\"def voc_eval(detpath, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=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 (__opts__.get('keep_jobs', False) and (int(__opts__.get('keep_jobs', 0)) > 0)):\\n try:\\n with _get_serv() as cur:\\n sql = 'select date_sub(now(), interval {0} hour) as stamp;'.format(__opts__['keep_jobs'])\\n cur.execute(sql)\\n rows = cur.fetchall()\\n stamp = rows[0][0]\\n if __opts__.get('archive_jobs', False):\\n _archive_jobs(stamp)\\n else:\\n _purge_jobs(stamp)\\n except MySQLdb.Error as e:\\n log.error('Mysql returner was unable to get timestamp for purge\\/archive of jobs')\\n log.error(str(e))\\n raise salt.exceptions.Salt(str(e))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def clean_old_jobs():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef bokeh_issue(name, rawtext, text, lineno, inliner, options=None, content=None):\\n\\n ''''Link to a Bokeh Github issue.\\n Returns 2 part tuple containing list of nodes to insert into the\\n document and a list of system messages. Both are allowed to be\\n empty.'\\n '''\",\"targets\":\"app = inliner.document.settings.env.app\\n try:\\n issue_num = int(text)\\n if (issue_num <= 0):\\n raise ValueError\\n except ValueError:\\n msg = inliner.reporter.error(('Github issue number must be a number greater than or equal to 1; \\\"%s\\\" is invalid.' % text), line=lineno)\\n prb = inliner.problematic(rawtext, rawtext, msg)\\n return ([prb], [msg])\\n node = _make_gh_link_node(app, rawtext, 'issue', '#', 'issues', str(issue_num), options)\\n return ([node], [])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.simple_tag(takes_context=True)\\ndef no_params_with_context(context):\\n\\n ''''Expected no_params_with_context __doc__'\\n '''\",\"targets\":\"return ('no_params_with_context - Expected result (context value: %s)' % context['value'])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _check_input_names(symbol, names, typename, throw):\\n\\n ''''Check that all input names are in symbol\\\\'s arguments.'\\n '''\",\"targets\":\"args = symbol.list_arguments()\\n for name in names:\\n if (name in args):\\n continue\\n candidates = [arg for arg in args if ((not arg.endswith('_weight')) and (not arg.endswith('_bias')) and (not arg.endswith('_gamma')) and (not arg.endswith('_beta')))]\\n msg = (\\\"\\\\x1b[91mYou created Module with Module(..., %s_names=%s) but input with name '%s' is not found in symbol.list_arguments(). Did you mean one of:\\\\n DCTB %s\\\\x1b[0m\\\" % (typename, str(names), name, '\\\\n DCTB '.join(candidates)))\\n if throw:\\n raise ValueError(msg)\\n else:\\n warnings.warn(msg)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef clipped_relu(x, z=20.0):\\n\\n ''''Clipped Rectifier Unit function.\\n For a clipping value :math:`z(>0)`, it computes\\n .. math::`ClippedReLU(x, z) = \\\\min(\\\\max(0, x), z)`.\\n Args:\\n x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or :class:`cupy.ndarray`):\\n Input variable. A :math:`(s_1, s_2, ..., s_n)`-shaped float array.\\n z (float): Clipping value. (default = 20.0)\\n Returns:\\n ~chainer.Variable: Output variable. A\\n :math:`(s_1, s_2, ..., s_n)`-shaped float array.\\n .. admonition:: Example\\n >>> x = np.random.uniform(-100, 100, (10, 20)).astype(\\\\'f\\\\')\\n >>> z = 10.0\\n >>> np.any(x < 0)\\n True\\n >>> np.any(x > z)\\n True\\n >>> y = F.clipped_relu(x, z=z)\\n >>> np.any(y.data < 0)\\n False\\n >>> np.any(y.data > z)\\n False'\\n '''\",\"targets\":\"return ClippedReLU(z)(x)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (sys.getwindowsversion().major < 6):\\n raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')\\n paths_seen = set((path,))\\n cur_depth = 0\\n while is_link(path):\\n path = readlink(path)\\n if (path in paths_seen):\\n raise CommandExecutionError('The given path is involved in a symlink loop.')\\n paths_seen.add(path)\\n cur_depth += 1\\n if (cur_depth > max_depth):\\n raise CommandExecutionError('Too many levels of symbolic links.')\\n return path\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _resolve_symlink(path, max_depth=64):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n check_slug_candidate(slug_candidate, shutdown_slug)\\n force_shutdown()\\n return ''\\n\\n\\nWhat's a good function header?\",\"targets\":\"@app.route('\\/\\/shutdown')\\ndef shutdown(slug_candidate):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _EndRecData64(fpin, offset, endrec):\",\"targets\":\"\\\"\\\"\\\"Read the ZIP64 end-of-archive records and use that to update endrec\\n \\\"\\\"\\\"\\n try:\\n fpin.seek((offset - sizeEndCentDir64Locator), 2)\\n except IOError:\\n return endrec\\n data = fpin.read(sizeEndCentDir64Locator)\\n (sig, diskno, reloff, disks) = struct.unpack(structEndArchive64Locator, data)\\n if (sig != stringEndArchive64Locator):\\n return endrec\\n if ((diskno != 0) or (disks != 1)):\\n raise BadZipfile('zipfiles that span multiple disks are not supported')\\n fpin.seek(((offset - sizeEndCentDir64Locator) - sizeEndCentDir64), 2)\\n data = fpin.read(sizeEndCentDir64)\\n (sig, sz, create_version, read_version, disk_num, disk_dir, dircount, dircount2, dirsize, diroffset) = struct.unpack(structEndArchive64, data)\\n if (sig != stringEndArchive64):\\n return endrec\\n endrec[_ECD_SIGNATURE] = sig\\n endrec[_ECD_DISK_NUMBER] = disk_num\\n endrec[_ECD_DISK_START] = disk_dir\\n endrec[_ECD_ENTRIES_THIS_DISK] = dircount\\n endrec[_ECD_ENTRIES_TOTAL] = dircount2\\n endrec[_ECD_SIZE] = dirsize\\n endrec[_ECD_OFFSET] = diroffset\\n return endrec\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@pytest.hookimpl(tryfirst=True, hookwrapper=True)\\ndef pytest_runtest_makereport(item, call):\",\"targets\":\"\\\"\\\"\\\"Make test information available in fixtures.\\n See http:\\/\\/pytest.org\\/latest\\/example\\/simple.html#making-test-result-information-available-in-fixtures\\n \\\"\\\"\\\"\\n outcome = (yield)\\n rep = outcome.get_result()\\n setattr(item, ('rep_' + rep.when), rep)\",\"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 ..attributes import Attribute\\n @six.add_metaclass(OrderedDescriptorContainer)\\n class TestAttributes(object, ):\\n attr_none = Attribute()\\n attr_2 = Attribute(default=2)\\n attr_3_attr2 = Attribute(default=3, secondary_attribute=u'attr_2')\\n attr_none_attr2 = Attribute(default=None, secondary_attribute=u'attr_2')\\n attr_none_nonexist = Attribute(default=None, secondary_attribute=u'nonexist')\\n t = TestAttributes()\\n assert (t.attr_none is None)\\n assert (t.attr_2 == 2)\\n assert (t.attr_3_attr2 == 3)\\n assert (t.attr_none_attr2 == t.attr_2)\\n assert (t.attr_none_nonexist is None)\\n t._attr_none = 10\\n assert (t.attr_none == 10)\\n t._attr_2 = 20\\n assert (t.attr_2 == 20)\\n assert (t.attr_3_attr2 == 3)\\n assert (t.attr_none_attr2 == t.attr_2)\\n t._attr_none_attr2 = 40\\n assert (t.attr_none_attr2 == 40)\\n with pytest.raises(AttributeError) as err:\\n t.attr_none = 5\\n assert (u'Cannot set frame attribute' in str(err))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_frame_attribute_descriptor():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n pats = []\\n if (not dn):\\n return False\\n parts = dn.split('.')\\n leftmost = parts[0]\\n remainder = parts[1:]\\n wildcards = leftmost.count('*')\\n if (wildcards > max_wildcards):\\n raise CertificateError(('too many wildcards in certificate DNS name: ' + repr(dn)))\\n if (not wildcards):\\n return (dn.lower() == hostname.lower())\\n if (leftmost == '*'):\\n pats.append('[^.]+')\\n elif (leftmost.startswith('xn--') or hostname.startswith('xn--')):\\n pats.append(re.escape(leftmost))\\n else:\\n pats.append(re.escape(leftmost).replace('\\\\\\\\*', '[^.]*'))\\n for frag in remainder:\\n pats.append(re.escape(frag))\\n pat = re.compile((('\\\\\\\\A' + '\\\\\\\\.'.join(pats)) + '\\\\\\\\Z'), re.IGNORECASE)\\n return pat.match(hostname)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _dnsname_match(dn, hostname, max_wildcards=1):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def DEFINE_flag(flag, flag_values=FLAGS):\",\"targets\":\"\\\"\\\"\\\"Registers a \\\\Flag\\\\ object with a \\\\FlagValues\\\\ object.\\n By default, the global FLAGS \\\\FlagValue\\\\ object is used.\\n Typical users will use one of the more specialized DEFINE_xxx\\n functions, such as DEFINE_string or DEFINE_integer. But developers\\n who need to create Flag objects themselves should use this function\\n to register their flags.\\n \\\"\\\"\\\"\\n fv = flag_values\\n fv[flag.name] = flag\\n if isinstance(flag_values, FlagValues):\\n (module, module_name) = _GetCallingModuleObjectAndName()\\n flag_values._RegisterFlagByModule(module_name, flag)\\n flag_values._RegisterFlagByModuleId(id(module), flag)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (len(p) == 4):\\n p[0] = (p[1] + [p[3]])\\n else:\\n p[0] = [p[1]]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def p_arglist(p):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def format_user_presence_state(state, now, include_user_id=True):\",\"targets\":\"\\\"\\\"\\\"Convert UserPresenceState to a format that can be sent down to clients\\n and to other servers.\\n The \\\"user_id\\\" is optional so that this function can be used to format presence\\n updates for client \\/sync responses and for federation \\/send requests.\\n \\\"\\\"\\\"\\n content = {'presence': state.state}\\n if include_user_id:\\n content['user_id'] = state.user_id\\n if state.last_active_ts:\\n content['last_active_ago'] = (now - state.last_active_ts)\\n if (state.status_msg and (state.state != PresenceState.OFFLINE)):\\n content['status_msg'] = state.status_msg\\n if (state.state == PresenceState.ONLINE):\\n content['currently_active'] = state.currently_active\\n return content\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_interface_type(interface):\\n\\n ''''Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF...'\\n '''\",\"targets\":\"if (interface is None):\\n return None\\n iftype = None\\n if interface.upper().startswith('GE'):\\n iftype = 'ge'\\n elif interface.upper().startswith('10GE'):\\n iftype = '10ge'\\n elif interface.upper().startswith('25GE'):\\n iftype = '25ge'\\n elif interface.upper().startswith('4X10GE'):\\n iftype = '4x10ge'\\n elif interface.upper().startswith('40GE'):\\n iftype = '40ge'\\n elif interface.upper().startswith('100GE'):\\n iftype = '100ge'\\n elif interface.upper().startswith('VLANIF'):\\n iftype = 'vlanif'\\n elif interface.upper().startswith('LOOPBACK'):\\n iftype = 'loopback'\\n elif interface.upper().startswith('METH'):\\n iftype = 'meth'\\n elif interface.upper().startswith('ETH-TRUNK'):\\n iftype = 'eth-trunk'\\n elif interface.upper().startswith('VBDIF'):\\n iftype = 'vbdif'\\n elif interface.upper().startswith('NVE'):\\n iftype = 'nve'\\n elif interface.upper().startswith('TUNNEL'):\\n iftype = 'tunnel'\\n elif interface.upper().startswith('ETHERNET'):\\n iftype = 'ethernet'\\n elif interface.upper().startswith('FCOE-PORT'):\\n iftype = 'fcoe-port'\\n elif interface.upper().startswith('FABRIC-PORT'):\\n iftype = 'fabric-port'\\n elif interface.upper().startswith('STACK-PORT'):\\n iftype = 'stack-Port'\\n elif interface.upper().startswith('NULL'):\\n iftype = 'null'\\n else:\\n return None\\n return iftype.lower()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def createTestSocket(test, addressFamily, socketType):\",\"targets\":\"\\\"\\\"\\\"Create a socket for the duration of the given test.\\n @param test: the test to add cleanup to.\\n @param addressFamily: an C{AF_*} constant\\n @param socketType: a C{SOCK_*} constant.\\n @return: a socket object.\\n \\\"\\\"\\\"\\n skt = socket.socket(addressFamily, socketType)\\n test.addCleanup(skt.close)\\n return skt\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef Value(typecode_or_type, *args, **kwds):\\n\\n ''''Returns a synchronized shared object'\\n '''\",\"targets\":\"from multiprocessing.sharedctypes import Value\\n return Value(typecode_or_type, *args, **kwds)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef contains_inf(arr, node=None, var=None):\\n\\n ''''Test whether a numpy.ndarray contains any `np.inf` values.\\n Parameters\\n arr : np.ndarray or output of any Theano op\\n node : None or an Apply instance.\\n If the output of a Theano op, the node associated to it.\\n var : The Theano symbolic variable.\\n Returns\\n contains_inf : bool\\n `True` if the array contains any `np.inf` values, `False` otherwise.\\n Notes\\n Tests for the presence of `np.inf`\\\\'s by determining whether the\\n values returned by `np.nanmin(arr)` and `np.nanmax(arr)` are finite.\\n This approach is more memory efficient than the obvious alternative,\\n calling `np.any(np.isinf(ndarray))`, which requires the construction of a\\n boolean array with the same shape as the input array.'\\n '''\",\"targets\":\"if (not _is_numeric_value(arr, var)):\\n return False\\n elif (getattr(arr, 'dtype', '') in T.discrete_dtypes):\\n return False\\n elif (pygpu_available and isinstance(arr, GpuArray)):\\n return (np.isinf(f_gpua_min(arr.reshape(arr.size))) or np.isinf(f_gpua_max(arr.reshape(arr.size))))\\n return (np.isinf(np.nanmax(arr)) or np.isinf(np.nanmin(arr)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (ssh_conn, scp_transfer) = scp_fixture\\n ssh_conn.disconnect()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_disconnect(scp_fixture):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n dataset_id = manifestation.dataset.dataset_id\\n node_state = node_state.transform(['manifestations', dataset_id], discard)\\n node_state = node_state.transform(['paths', dataset_id], discard)\\n node_state = node_state.transform(['devices', UUID(dataset_id)], discard)\\n return node_state\\n\\n\\nWhat's a good function header?\",\"targets\":\"def delete_manifestation(node_state, manifestation):\",\"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 (fn is None):\\n def decorator(fn):\\n return profile(fn, skip=skip, filename=filename, immediate=immediate, dirs=dirs, sort=sort, entries=entries, profiler=profiler)\\n return decorator\\n if isinstance(profiler, str):\\n profiler = [profiler]\\n for p in profiler:\\n if (p in AVAILABLE_PROFILERS):\\n profiler_class = AVAILABLE_PROFILERS[p]\\n break\\n else:\\n raise ValueError(('only these profilers are available: %s' % ', '.join(AVAILABLE_PROFILERS)))\\n fp = profiler_class(fn, skip=skip, filename=filename, immediate=immediate, dirs=dirs, sort=sort, entries=entries)\\n def new_fn(*args, **kw):\\n return fp(*args, **kw)\\n new_fn.__doc__ = fn.__doc__\\n new_fn.__name__ = fn.__name__\\n new_fn.__dict__ = fn.__dict__\\n new_fn.__module__ = fn.__module__\\n return new_fn\\n\\n\\nWhat's a good function header?\",\"targets\":\"def profile(fn=None, skip=0, filename=None, immediate=False, dirs=False, sort=None, entries=40, profiler=('cProfile', 'profile', 'hotshot')):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _local_tasks():\",\"targets\":\"\\\"\\\"\\\"(Create and) return the threadlocal set of indexing tasks.\\n \\\"\\\"\\\"\\n if (getattr(_local, 'tasks', None) is None):\\n _local.tasks = set()\\n return _local.tasks\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def enabled(name, **kwargs):\",\"targets\":\"\\\"\\\"\\\".. versionadded:: 2014.7.0\\n Return True if the named service is enabled, false otherwise\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\*\\\\ service.enabled \\n \\\"\\\"\\\"\\n return (name in get_enabled())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def mail_managers(subject, message, fail_silently=False, connection=None, html_message=None):\",\"targets\":\"\\\"\\\"\\\"Send a message to the managers, as defined by the MANAGERS setting.\\n \\\"\\\"\\\"\\n if (not settings.MANAGERS):\\n return\\n mail = EmailMultiAlternatives(('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)), message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], connection=connection)\\n if html_message:\\n mail.attach_alternative(html_message, 'text\\/html')\\n mail.send(fail_silently=fail_silently)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (scheme, host, port) = get_host(url)\\n if (scheme == 'https'):\\n return HTTPSConnectionPool(host, port=port, **kw)\\n else:\\n return HTTPConnectionPool(host, port=port, **kw)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def connection_from_url(url, **kw):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def is_ipv6(addr):\",\"targets\":\"\\\"\\\"\\\"Checks if a given address is an IPv6 address.\\n \\\"\\\"\\\"\\n try:\\n socket.inet_pton(socket.AF_INET6, addr)\\n return True\\n except socket.error:\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@verbose\\ndef make_eeg_average_ref_proj(info, activate=True, verbose=None):\",\"targets\":\"\\\"\\\"\\\"Create an EEG average reference SSP projection vector.\\n Parameters\\n info : dict\\n Measurement info.\\n activate : bool\\n If True projections are activated.\\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 eeg_proj: instance of Projection\\n The SSP\\/PCA projector.\\n \\\"\\\"\\\"\\n if info.get('custom_ref_applied', False):\\n raise RuntimeError('A custom reference has been applied to the data earlier. Please use the mne.io.set_eeg_reference function to move from one EEG reference to another.')\\n logger.info('Adding average EEG reference projection.')\\n eeg_sel = pick_types(info, meg=False, eeg=True, ref_meg=False, exclude='bads')\\n ch_names = info['ch_names']\\n eeg_names = [ch_names[k] for k in eeg_sel]\\n n_eeg = len(eeg_sel)\\n if (n_eeg == 0):\\n raise ValueError('Cannot create EEG average reference projector (no EEG data found)')\\n vec = np.ones((1, n_eeg))\\n vec \\/= n_eeg\\n explained_var = None\\n eeg_proj_data = dict(col_names=eeg_names, row_names=None, data=vec, nrow=1, ncol=n_eeg)\\n eeg_proj = Projection(active=activate, data=eeg_proj_data, desc='Average EEG reference', kind=FIFF.FIFFV_MNE_PROJ_ITEM_EEG_AVREF, explained_var=explained_var)\\n return eeg_proj\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _preprocess(method, headers, url):\",\"targets\":\"\\\"\\\"\\\"Unify input.\\n Example:\\n _preprocess(\\\\POST\\\\, {\\\\Content-Type\\\\: \\\\Foo\\\\}, http:\\/\\/gs.com\\/b\\/f?foo=bar)\\n -> \\\\POST\\\\, {\\\\content-type\\\\: \\\\Foo\\\\}, \\\\\\/b\\/f\\\\, {\\\\foo\\\\:\\\\bar\\\\}\\n Args:\\n method: HTTP method used by the request.\\n headers: HTTP request headers in a dict.\\n url: HTTP request url.\\n Returns:\\n method: method in all upper case.\\n headers: headers with keys in all lower case.\\n filename: a google storage filename of form \\/bucket\\/filename or\\n a bucket path of form \\/bucket\\n param_dict: a dict of query parameters.\\n \\\"\\\"\\\"\\n (_, _, filename, query, _) = urlparse.urlsplit(url)\\n param_dict = urlparse.parse_qs(query, True)\\n for k in param_dict:\\n param_dict[k] = urllib.unquote(param_dict[k][0])\\n headers = dict(((k.lower(), v) for (k, v) in headers.iteritems()))\\n return (method, headers, filename, param_dict)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def iter_modules(path=None, prefix=''):\",\"targets\":\"\\\"\\\"\\\"Yields (module_loader, name, ispkg) for all submodules on path,\\n or, if path is None, all top-level modules on sys.path.\\n \\\\path\\\\ should be either None or a list of paths to look for\\n modules in.\\n \\\\prefix\\\\ is a string to output on the front of every module name\\n on output.\\n \\\"\\\"\\\"\\n if (path is None):\\n importers = iter_importers()\\n else:\\n importers = map(get_importer, path)\\n yielded = {}\\n for i in importers:\\n for (name, ispkg) in iter_importer_modules(i, prefix):\\n if (name not in yielded):\\n yielded[name] = 1\\n (yield (i, name, ispkg))\\n return\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if is_categorical_dtype(dtype):\\n dtype = CategoricalDtype()\\n elif is_datetime64tz_dtype(dtype):\\n dtype = DatetimeTZDtype(dtype)\\n elif is_period_dtype(dtype):\\n dtype = PeriodDtype(dtype)\\n elif is_interval_dtype(dtype):\\n dtype = IntervalDtype(dtype)\\n else:\\n dtype = np.dtype(dtype)\\n return dtype\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _coerce_to_dtype(dtype):\",\"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 (fs_class == u'default'):\\n fs_class = _default_fs_class(fstruct)\\n return _remove_variables(copy.deepcopy(fstruct), fs_class, set())\\n\\n\\nWhat's a good function header?\",\"targets\":\"def remove_variables(fstruct, fs_class=u'default'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def init_request_processor(conf_file, app_section, *args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Loads common settings from conf\\n Sets the logger\\n Loads the request processor\\n :param conf_file: Path to paste.deploy style configuration file\\n :param app_section: App name from conf file to load config from\\n :returns: the loaded application entry point\\n :raises ConfigFileError: Exception is raised for config file error\\n \\\"\\\"\\\"\\n try:\\n conf = appconfig(('config:%s' % conf_file), name=app_section)\\n except Exception as e:\\n raise ConfigFileError(('Error trying to load config %s: %s' % (conf_file, e)))\\n validate_configuration()\\n log_name = conf.get('log_name', app_section)\\n if ('logger' in kwargs):\\n logger = kwargs.pop('logger')\\n else:\\n logger = get_logger(conf, log_name, log_to_console=kwargs.pop('verbose', False), log_route='wsgi')\\n if config_true_value(conf.get('disable_fallocate', 'no')):\\n disable_fallocate()\\n monkey_patch_mimetools()\\n app = loadapp(('config:%s' % conf_file), global_conf={'log_name': log_name})\\n return (app, conf, logger, log_name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef image_gallery(registry, xml_parent, data):\\n\\n ''''yaml: image-gallery\\n Produce an image gallery using Javascript library. Requires the Jenkins\\n :jenkins-wiki:`Image Gallery Plugin`.\\n :arg str gallery-type:\\n :gallery-type values:\\n * **archived-images-gallery** (default)\\n * **in-folder-comparative-gallery**\\n * **multiple-folder-comparative-gallery**\\n :arg str title: gallery title (optional)\\n :arg int image-width: width of the image (optional)\\n :arg bool unstable-if-no-artifacts: mark build as unstable\\n if no archived artifacts were found (default false)\\n :arg str includes: include pattern (valid for archived-images-gallery\\n gallery)\\n :arg str base-root-folder: base root dir (valid for comparative gallery)\\n :arg int image-inner-width: width of the image displayed in the inner\\n gallery popup (valid for comparative gallery, optional)\\n Example:\\n .. literalinclude:: \\/..\\/..\\/tests\\/publishers\\/fixtures\\/image-gallery001.yaml'\\n '''\",\"targets\":\"def include_comparative_elements(gallery_parent_elem, gallery):\\n XML.SubElement(gallery_parent_elem, 'baseRootFolder').text = str(gallery.get('base-root-folder', ''))\\n image_inner_width = gallery.get('image-inner-width', '')\\n if image_inner_width:\\n XML.SubElement(gallery_parent_elem, 'imageInnerWidth').text = str(image_inner_width)\\n package_prefix = 'org.jenkinsci.plugins.imagegallery.'\\n builder = XML.SubElement(xml_parent, (package_prefix + 'ImageGalleryRecorder'))\\n image_galleries = XML.SubElement(builder, 'imageGalleries')\\n galleries = {'archived-images-gallery': (package_prefix + 'imagegallery.ArchivedImagesGallery'), 'in-folder-comparative-gallery': (package_prefix + 'comparative.InFolderComparativeArchivedImagesGallery'), 'multiple-folder-comparative-gallery': (package_prefix + 'comparative.MultipleFolderComparativeArchivedImagesGallery')}\\n for gallery_def in data:\\n gallery_type = gallery_def.get('gallery-type', 'archived-images-gallery')\\n if (gallery_type not in galleries):\\n raise InvalidAttributeError('gallery-type', gallery_type, galleries.keys())\\n gallery_config = XML.SubElement(image_galleries, galleries[gallery_type])\\n XML.SubElement(gallery_config, 'title').text = str(gallery_def.get('title', ''))\\n image_width = str(gallery_def.get('image-width', ''))\\n if image_width:\\n XML.SubElement(gallery_config, 'imageWidth').text = str(image_width)\\n XML.SubElement(gallery_config, 'markBuildAsUnstableIfNoArchivesFound').text = str(gallery_def.get('unstable-if-no-artifacts', False))\\n if (gallery_type == 'archived-images-gallery'):\\n XML.SubElement(gallery_config, 'includes').text = str(gallery_def.get('includes', ''))\\n if (gallery_type == 'in-folder-comparative-gallery'):\\n include_comparative_elements(gallery_config, gallery_def)\\n if (gallery_type == 'multiple-folder-comparative-gallery'):\\n include_comparative_elements(gallery_config,...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef make_style(opts=(), **kwargs):\\n\\n ''''Returns a function with default parameters for colorize()\\n Example:\\n bold_red = make_style(opts=(\\\\'bold\\\\',), fg=\\\\'red\\\\')\\n print bold_red(\\\\'hello\\\\')\\n KEYWORD = make_style(fg=\\\\'yellow\\\\')\\n COMMENT = make_style(fg=\\\\'blue\\\\', opts=(\\\\'bold\\\\',))'\\n '''\",\"targets\":\"return (lambda text: colorize(text, opts, **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 parser = OptionParser()\\n parser.add_option('--platform', dest='platform', help=\\\"Platform ('os' grain)\\\")\\n parser.add_option('--log-level', dest='log_level', default='warning', help='Control verbosity of logging. Default: %default')\\n path_group = OptionGroup(parser, 'File\\/Directory Options')\\n path_group.add_option('--source-dir', default='\\/testing', help='Source directory. Must be a git checkout. (default: %default)')\\n path_group.add_option('--build-dir', default='\\/tmp\\/salt-buildpackage', help='Build root, will be removed if it exists prior to running script. (default: %default)')\\n path_group.add_option('--artifact-dir', default='\\/tmp\\/salt-packages', help='Location where build artifacts should be placed for Jenkins to retrieve them (default: %default)')\\n parser.add_option_group(path_group)\\n rpm_group = OptionGroup(parser, 'RPM-specific File\\/Directory Options')\\n rpm_group.add_option('--spec', dest='spec_file', default='\\/tmp\\/salt.spec', help='Spec file to use as a template to build RPM. (default: %default)')\\n parser.add_option_group(rpm_group)\\n opts = parser.parse_args()[0]\\n for group in (path_group, rpm_group):\\n for path_opt in [opt.dest for opt in group.option_list]:\\n path = getattr(opts, path_opt)\\n if (not os.path.isabs(path)):\\n path = os.path.expanduser(path)\\n if (not os.path.isabs(path)):\\n path = os.path.realpath(path)\\n setattr(opts, path_opt, path)\\n problems = []\\n if (not opts.platform):\\n problems.append(\\\"Platform ('os' grain) required\\\")\\n if (not os.path.isdir(opts.source_dir)):\\n problems.append('Source directory {0} not found'.format(opts.source_dir))\\n try:\\n shutil.rmtree(opts.build_dir)\\n except OSError as exc:\\n if (exc.errno not in (errno.ENOENT,...\\n\\nWhat's a good function header?\",\"targets\":\"def _init():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@api_versions.wraps('2.17')\\n@utils.arg('server', metavar='', help=_('Name or ID of server.'))\\ndef do_trigger_crash_dump(cs, args):\",\"targets\":\"\\\"\\\"\\\"Trigger crash dump in an instance.\\n \\\"\\\"\\\"\\n server = _find_server(cs, args.server)\\n server.trigger_crash_dump()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n ipython_cmd = [sys.executable, '-m', 'IPython']\\n if as_string:\\n ipython_cmd = ' '.join(ipython_cmd)\\n return ipython_cmd\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_ipython_cmd(as_string=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _bdecode(s):\\n\\n ''''Decodes a base64 string.\\n This function is equivalent to base64.decodestring and it\\\\'s retained only\\n for backward compatibility. It used to remove the last \\\\n of the decoded\\n string, if it had any (see issue 7143).'\\n '''\",\"targets\":\"if (not s):\\n return s\\n return base64.decodestring(s)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def change_log_dir(log_dir, web_log):\",\"targets\":\"\\\"\\\"\\\"Change logging directory for application and webserver\\n :param log_dir: Path to new logging directory\\n :param web_log: Enable\\/disable web logging\\n :return: True on success, False on failure\\n \\\"\\\"\\\"\\n abs_log_dir = ek(os.path.normpath, ek(os.path.join, sickbeard.DATA_DIR, log_dir))\\n sickbeard.WEB_LOG = checkbox_to_value(web_log)\\n if (ek(os.path.normpath, sickbeard.LOG_DIR) != abs_log_dir):\\n if (not helpers.makeDir(abs_log_dir)):\\n return False\\n sickbeard.ACTUAL_LOG_DIR = ek(os.path.normpath, log_dir)\\n sickbeard.LOG_DIR = abs_log_dir\\n logger.init_logging()\\n logger.log((u'Initialized new log file in ' + sickbeard.LOG_DIR))\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (source is None):\\n if (target is None):\\n if (weight is None):\\n paths = nx.all_pairs_shortest_path_length(G)\\n else:\\n paths = nx.all_pairs_dijkstra_path_length(G, weight=weight)\\n else:\\n with nx.utils.reversed(G):\\n if (weight is None):\\n path_length = nx.single_source_shortest_path_length\\n paths = list(path_length(G, target))\\n else:\\n path_length = nx.single_source_dijkstra_path_length\\n paths = path_length(G, target, weight=weight)\\n else:\\n if (source not in G):\\n raise nx.NodeNotFound('Source {} not in G'.format(source))\\n if (target is None):\\n if (weight is None):\\n paths = nx.single_source_shortest_path_length(G, source)\\n else:\\n paths = nx.single_source_dijkstra_path_length(G, source, weight=weight)\\n elif (weight is None):\\n p = nx.bidirectional_shortest_path(G, source, target)\\n paths = (len(p) - 1)\\n else:\\n paths = nx.dijkstra_path_length(G, source, target, weight)\\n return paths\\n\\n\\nWhat's a good function header?\",\"targets\":\"def shortest_path_length(G, source=None, target=None, weight=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _type(self, new_type=None, async=False):\\n\\n ''''Returns the type if `new_type` is not provided, else casts this object to\\n the specified type.\\n If this is already of the correct type, no copy is performed and the\\n original object is returned.\\n Args:\\n new_type (type or string): The desired type\\n async (bool): If True, and the source is in pinned memory and\\n destination is on the GPU or vice versa, the copy is\\n performed asynchronously with respect to the host.\\n Otherwise, the argument has no effect.'\\n '''\",\"targets\":\"if (new_type is None):\\n return ((self.__module__ + '.') + self.__class__.__name__)\\n if isinstance(new_type, str):\\n new_type = _import_dotted_name(new_type)\\n if (new_type == type(self)):\\n return self\\n if self.is_sparse:\\n if (not new_type.is_sparse):\\n raise RuntimeError('Cannot cast sparse tensor to dense tensor')\\n new_type_name = ((new_type.__module__ + '.') + new_type.__name__)\\n new_values_type_name = new_type_name.replace('.sparse', '')\\n new_values = self._values().type(new_values_type_name, async)\\n return new_type(self._indices(), new_values, self.size())\\n if new_type.is_sparse:\\n raise RuntimeError('Cannot cast dense tensor to sparse tensor')\\n return new_type(self.size()).copy_(self, async)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@with_setup(prepare_stdout)\\ndef test_output_with_failful_outline_colorless():\",\"targets\":\"\\\"\\\"\\\"With colorless output, an unsuccessful outline scenario should print beautifully.\\n \\\"\\\"\\\"\\n runner = Runner(feature_name('fail_outline'), verbosity=3, no_color=True)\\n runner.run()\\n assert_stdout_lines_with_traceback((u'\\\\nFeature: Failful Scenario Outline # tests\\/functional\\/output_features\\/fail_outline\\/fail_outline.feature:1\\\\n As lettuce author # tests\\/functional\\/output_features\\/fail_outline\\/fail_outline.feature:2\\\\n In order to finish the first release # tests\\/functional\\/output_features\\/fail_outline\\/fail_outline.feature:3\\\\n I want to make scenario outlines work \\\\u2665 # tests\\/functional\\/output_features\\/fail_outline\\/fail_outline.feature:4\\\\n\\\\n Scenario Outline: fill a web form # tests\\/functional\\/output_features\\/fail_outline\\/fail_outline.feature:6\\\\n Given I open browser at \\\"http:\\/\\/www.my-website.com\\/\\\" # tests\\/functional\\/output_features\\/fail_outline\\/fail_outline_steps.py:21\\\\n And click on \\\"sign-up\\\" # tests\\/functional\\/output_features\\/fail_outline\\/fail_outline_steps.py:25\\\\n When I fill the field \\\"username\\\" with \\\"\\\" # tests\\/functional\\/output_features\\/fail_outline\\/fail_outline_steps.py:29\\\\n And I fill the ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _write_data(writer, data):\",\"targets\":\"\\\"\\\"\\\"Writes datachars to writer.\\n \\\"\\\"\\\"\\n if data:\\n data = data.replace('&', '&').replace('<', '<').replace('\\\"', '"').replace('>', '>')\\n writer.write(data)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getprime(nbits, poolsize):\",\"targets\":\"\\\"\\\"\\\"Returns a prime number that can be stored in \\\\nbits\\\\ bits.\\n Works in multiple threads at the same time.\\n >>> p = getprime(128, 3)\\n >>> rsa.prime.is_prime(p-1)\\n False\\n >>> rsa.prime.is_prime(p)\\n True\\n >>> rsa.prime.is_prime(p+1)\\n False\\n >>> from rsa import common\\n >>> common.bit_size(p) == 128\\n True\\n \\\"\\\"\\\"\\n (pipe_recv, pipe_send) = mp.Pipe(duplex=False)\\n try:\\n procs = [mp.Process(target=_find_prime, args=(nbits, pipe_send)) for _ in range(poolsize)]\\n for p in procs:\\n p.start()\\n result = pipe_recv.recv()\\n finally:\\n pipe_recv.close()\\n pipe_send.close()\\n for p in procs:\\n p.terminate()\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def download_libxslt(dest_dir, version=None):\",\"targets\":\"\\\"\\\"\\\"Downloads libxslt, returning the filename where the library was downloaded\\n \\\"\\\"\\\"\\n version_re = re.compile('^LATEST_LIBXSLT_IS_(.*)$')\\n filename = 'libxslt-%s.tar.gz'\\n return download_library(dest_dir, LIBXML2_LOCATION, 'libxslt', version_re, filename, version=version)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None):\",\"targets\":\"\\\"\\\"\\\"Returns a process pool object\\n \\\"\\\"\\\"\\n from multiprocessing.pool import Pool\\n return Pool(processes, initializer, initargs, maxtasksperchild)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def clear_placeholder_cache(placeholder, lang, site_id):\",\"targets\":\"\\\"\\\"\\\"Invalidates all existing cache entries for (placeholder x lang x site_id).\\n We don\\\\t need to re-store the vary_on_list, because the cache is now\\n effectively empty.\\n \\\"\\\"\\\"\\n version = int((time.time() * 1000000))\\n _set_placeholder_cache_version(placeholder, lang, site_id, version, [])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef list_policy_versions(policyName, region=None, key=None, keyid=None, profile=None):\\n\\n ''''List the versions available for the given policy.\\n CLI Example:\\n .. code-block:: bash\\n salt myminion boto_iot.list_policy_versions mypolicy\\n Example Return:\\n .. code-block:: yaml\\n policyVersions:'\\n '''\",\"targets\":\"try:\\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\\n vers = []\\n for ret in salt.utils.boto3.paged_call(conn.list_policy_versions, marker_flag='nextMarker', marker_arg='marker', policyName=policyName):\\n vers.extend(ret['policyVersions'])\\n if (not bool(vers)):\\n log.warning('No versions found')\\n return {'policyVersions': vers}\\n except ClientError as e:\\n return {'error': salt.utils.boto3.get_error(e)}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n finfo = getfileinfo(inp)\\n ofp = BinHex(finfo, out)\\n ifp = open(inp, 'rb')\\n while 1:\\n d = ifp.read(128000)\\n if (not d):\\n break\\n ofp.write(d)\\n ofp.close_data()\\n ifp.close()\\n ifp = openrsrc(inp, 'rb')\\n while 1:\\n d = ifp.read(128000)\\n if (not d):\\n break\\n ofp.write_rsrc(d)\\n ofp.close()\\n ifp.close()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def binhex(inp, out):\",\"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 Cheetah.Template import Template\\n return str(Template(tmplstr, searchList=[context]))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def render_cheetah_tmpl(tmplstr, context, tmplpath=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef html(einfo, context=5):\\n\\n ''''Return a nice HTML document describing a given traceback.'\\n '''\",\"targets\":\"(etype, evalue, etb) = einfo\\n if isinstance(etype, type):\\n etype = etype.__name__\\n pyver = ((('Python ' + sys.version.split()[0]) + ': ') + sys.executable)\\n date = time.ctime(time.time())\\n head = (('' + pydoc.html.heading(('%s<\\/big><\\/big>' % strong(pydoc.html.escape(str(etype)))), '#ffffff', '#6622aa', ((pyver + '
') + date))) + '\\\\n

A problem occurred in a Python script. Here is the sequence of\\\\nfunction calls leading up to the error, in the order they occurred.<\\/p>')\\n indent = (('' + small((' ' * 5))) + ' <\\/tt>')\\n frames = []\\n records = inspect.getinnerframes(etb, context)\\n for (frame, file, lnum, func, lines, index) in records:\\n if file:\\n file = os.path.abspath(file)\\n link = ('%s<\\/a>' % (file, pydoc.html.escape(file)))\\n else:\\n file = link = '?'\\n (args, varargs, varkw, locals) = inspect.getargvalues(frame)\\n call = ''\\n if (func != '?'):\\n call = (('in ' + strong(func)) + inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=(lambda value: ('=' + pydoc.html.repr(value)))))\\n highlight = {}\\n def reader(lnum=[lnum]):\\n highlight[lnum[0]] = 1\\n try:\\n return linecache.getline(file, lnum[0])\\n finally:\\n lnum[0] += 1\\n vars = scanvars(reader, frame, locals)\\n rows = [('

%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"