Muennighoff/xP3x-sample huggingface dataset:
inputs: Complete the below
def createsuperuser(username=None, email=None, password=None):

    ''''Helper function for creating a superuser from the command line. All
    arguments are optional and will be prompted-for if invalid or not given.'
    '''
targets: try:
        import pwd
    except ImportError:
        default_username = ''
    else:
        default_username = pwd.getpwuid(os.getuid())[0].replace('    ', '').lower()
    if default_username:
        try:
            User.objects.get(username=default_username)
        except User.DoesNotExist:
            pass
        else:
            default_username = ''
    try:
        while 1:
            if (not username):
                input_msg = 'Username'
                if default_username:
                    input_msg += ('    (Leave    blank    to    use    %r)' % default_username)
                username = raw_input((input_msg + ':    '))
            if (default_username and (username == '')):
                username = default_username
            if (not username.isalnum()):
                sys.stderr.write('Error:    That    username    is    invalid.    Use    only    letters,    digits    and    underscores.\n')
                username = None
                continue
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                break
            else:
                sys.stderr.write('Error:    That    username    is    already    taken.\n')
                username = None
        while 1:
            if (not email):
                email = raw_input('E-mail    address:    ')
            try:
                validators.isValidEmail(email, None)
            except validators.ValidationError:
                sys.stderr.write('Error:    That    e-mail    address    is    invalid.\n')
                email = None
            else:
                break
        while 1:
            if (not password):
                password = getpass.getpass()
                password2 = getpass.getpass('Password    (again):    ')
                if (password != password2):
                    sys.stderr.write("Error:    Your    passwords    didn't    match.\n")
                    password = None
                    continue
            if...
inputs: Complete the below
def digestAuth(realm, algorithm=MD5, nonce=None, qop=AUTH):

    ''''Challenges the client for a Digest authentication.'
    '''
targets: global SUPPORTED_ALGORITHM, DIGEST_AUTH_ENCODERS, SUPPORTED_QOP
    assert (algorithm in SUPPORTED_ALGORITHM)
    assert (qop in SUPPORTED_QOP)
    if (nonce is None):
        nonce = calculateNonce(realm, algorithm)
    return ('Digest    realm="%s",    nonce="%s",    algorithm="%s",    qop="%s"' % (realm, nonce, algorithm, qop))
inputs: I wrote the below code

    if ('x' in dictionary):
        valueComplex = complex(euclidean.getFloatFromValue(dictionary['x']), valueComplex.imag)
    if ('y' in dictionary):
        valueComplex = complex(valueComplex.real, euclidean.getFloatFromValue(dictionary['y']))
    return valueComplex


What's a good function header?
targets: def getComplexByDictionary(dictionary, valueComplex):
inputs: I wrote the below code

    i2h = mx.sym.FullyConnected(data=indata, weight=param.i2h_weight, bias=param.i2h_bias, num_hidden=(num_hidden * 4), name=('t%d_l%d_i2h' % (seqidx, layeridx)))
    h2h = mx.sym.FullyConnected(data=prev_state.h, weight=param.h2h_weight, bias=param.h2h_bias, num_hidden=(num_hidden * 4), name=('t%d_l%d_h2h' % (seqidx, layeridx)))
    gates = (i2h + h2h)
    slice_gates = mx.sym.SliceChannel(gates, num_outputs=4, name=('t%d_l%d_slice' % (seqidx, layeridx)))
    in_gate = mx.sym.Activation(slice_gates[0], act_type='sigmoid')
    in_transform = mx.sym.Activation(slice_gates[1], act_type='tanh')
    forget_gate = mx.sym.Activation(slice_gates[2], act_type='sigmoid')
    out_gate = mx.sym.Activation(slice_gates[3], act_type='sigmoid')
    next_c = ((forget_gate * prev_state.c) + (in_gate * in_transform))
    next_h = (out_gate * mx.sym.Activation(next_c, act_type='tanh'))
    return LSTMState(c=next_c, h=next_h)


What's a good function header?
targets: def lstm(num_hidden, indata, prev_state, param, seqidx, layeridx):
inputs: @raises(ValueError)
def test_bootstrap_arglength():
targets: """Test that different length args raise ValueError.
    """
    algo.bootstrap(np.arange(5), np.arange(10))
inputs: I wrote the below code

    imagepath = album.artpath
    if (not imagepath):
        log.info(u'No    album    art    present    for    {0}', album)
        return
    if (not os.path.isfile(syspath(imagepath))):
        log.info(u'Album    art    not    found    at    {0}    for    {1}', displayable_path(imagepath), album)
        return
    if maxwidth:
        imagepath = resize_image(log, imagepath, maxwidth)
    log.info(u'Embedding    album    art    into    {0}', album)
    for item in album.items():
        embed_item(log, item, imagepath, maxwidth, None, compare_threshold, ifempty, as_album=True)


What's a good function header?
targets: def embed_album(log, album, maxwidth=None, quiet=False, compare_threshold=0, ifempty=False):
inputs: def epoch2num(e):
targets: """Convert an epoch or sequence of epochs to the new date format,
    that is days since 0001.
    """
    spd = (24.0 * 3600.0)
    return (719163 + (np.asarray(e) / spd))
inputs: Complete the below
def have_qstring():

    ''''p3/qt5 get rid of QString wrapper as py3 has native unicode str type'
    '''
targets: return (not ((sys.version_info.major >= 3) or QT_VERSION_STR.startswith('5.')))
inputs: I wrote the below code

    actual = [x[0] for x in data_shapes]
    if (sorted(data_names) != sorted(actual)):
        msg = ("Data    provided    by    %s_shapes    don't    match    names    specified    by    %s_names    (%s    vs.    %s)" % (name, name, str(data_shapes), str(data_names)))
        if throw:
            raise ValueError(msg)
        else:
            warnings.warn(msg)


What's a good function header?
targets: def _check_names_match(data_names, data_shapes, name, throw):
inputs: def _capabilities():
targets: """Return connection capabilities
    It\s a huge klutz to parse right,
    so hide func for now and pass on the XML instead
    """
    conn = __get_conn()
    caps = conn.getCapabilities()
    caps = minidom.parseString(caps)
    return caps
inputs: Complete the below
def foldr(fn, elems, initializer=None, name=None):

    ''''Reduce elems using fn to combine them from right to left.
    # Arguments
    fn: Callable that will be called upon each element in elems and an
    accumulator, for instance `lambda acc, x: acc + x`
    elems: tensor
    initializer: The first value used (`elems[-1]` in case of None)
    name: A string name for the foldr node in the graph
    # Returns
    Tensor with same type and shape as `initializer`.'
    '''
targets: return tf.foldr(fn, elems, initializer=initializer, name=name)
inputs: Complete the below
def _get_importer(path_name):

    ''''Python version of PyImport_GetImporter C API function'
    '''
targets: cache = sys.path_importer_cache
    try:
        importer = cache[path_name]
    except KeyError:
        cache[path_name] = None
        for hook in sys.path_hooks:
            try:
                importer = hook(path_name)
                break
            except ImportError:
                pass
        else:
            try:
                importer = imp.NullImporter(path_name)
            except ImportError:
                return None
        cache[path_name] = importer
    return importer
inputs: def get_attachments(xml):
targets: """returns a dictionary of posts that have attachments with a list
    of the attachment_urls
    """
    items = get_items(xml)
    names = {}
    attachments = []
    for item in items:
        kind = item.find(u'post_type').string
        filename = item.find(u'post_name').string
        post_id = item.find(u'post_id').string
        if (kind == u'attachment'):
            attachments.append((item.find(u'post_parent').string, item.find(u'attachment_url').string))
        else:
            filename = get_filename(filename, post_id)
            names[post_id] = filename
    attachedposts = {}
    for (parent, url) in attachments:
        try:
            parent_name = names[parent]
        except KeyError:
            parent_name = None
        try:
            attachedposts[parent_name].append(url)
        except KeyError:
            attachedposts[parent_name] = []
            attachedposts[parent_name].append(url)
    return attachedposts
inputs: I wrote the below code

    class _FakeUser(ndb.Model, ):
        _use_memcache = False
        _use_cache = False
        user = ndb.UserProperty(required=True)
    try:
        fake_user = users.User(email)
    except users.UserNotFoundError:
        logging.error(('The    email    address    %s    does    not    correspond    to    a    valid    user_id' % email))
        return None
    key = _FakeUser(id=email, user=fake_user).put()
    obj = _FakeUser.get_by_id(key.id())
    user_id = obj.user.user_id()
    if user_id:
        return unicode(user_id)
    else:
        return None


What's a good function header?
targets: def get_user_id_from_email(email):
inputs: Complete the below
def itervalues(d):

    ''''Return an iterator over the values of a dictionary.'
    '''
targets: return iter(getattr(d, _itervalues)())
inputs: Complete the below
def integration_reduction(facets, index, a, b, expr, dims, degree):

    ''''Helper method for main_integrate. Returns the value of the input
    expression evaluated over the polytope facet referenced by a given index.
    Parameters
    facets : List of facets of the polytope.
    index : Index referencing the facet to integrate the expression over.
    a : Hyperplane parameter denoting direction.
    b : Hyperplane parameter denoting distance.
    expr : The expression to integrate over the facet.
    dims : List of symbols denoting axes.
    degree : Degree of the homogeneous polynomial.
    >>> from sympy.abc import x, y
    >>> from sympy.integrals.intpoly import integration_reduction,    hyperplane_parameters
    >>> from sympy.geometry.point import Point
    >>> from sympy.geometry.polygon import Polygon
    >>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
    >>> facets = triangle.sides
    >>> a, b = hyperplane_parameters(triangle)[0]
    >>> integration_reduction(facets, 0, a, b, 1, (x, y), 0)
    5'
    '''
targets: if (expr == S.Zero):
        return expr
    (a, b) = ((S(a[0]), S(a[1])), S(b))
    value = S.Zero
    x0 = facets[index].points[0]
    m = len(facets)
    gens = (x, y)
    inner_product = ((diff(expr, gens[0]) * x0[0]) + (diff(expr, gens[1]) * x0[1]))
    if (inner_product != 0):
        value += integration_reduction(facets, index, a, b, inner_product, dims, (degree - 1))
    value += left_integral(m, index, facets, x0, expr, gens)
    return (value / ((len(dims) + degree) - 1))
inputs: def dict_from_cookiejar(cj):
targets: """Returns a key/value dictionary from a CookieJar.
    :param cj: CookieJar object to extract cookies from.
    """
    cookie_dict = {}
    for cookie in cj:
        cookie_dict[cookie.name] = cookie.value
    return cookie_dict
inputs: def _environment_sanity_check(environment):
targets: """Perform a sanity check on the environment.
    """
    assert issubclass(environment.undefined, Undefined), 'undefined    must    be    a    subclass    of    undefined    because    filters    depend    on    it.'
    assert (environment.block_start_string != environment.variable_start_string != environment.comment_start_string), 'block,    variable    and    comment    start    strings    must    be    different'
    assert (environment.newline_sequence in ('\r', '\r\n', '\n')), 'newline_sequence    set    to    unknown    line    ending    string.'
    return environment
inputs: def dummyModelParams(perm):
targets: """This function can be used for Hypersearch algorithm development. When
    present, we don\t actually run the CLA model in the OPF, but instead run
    a dummy model. This function returns the dummy model params that will be
    used. See the OPFDummyModelRunner class source code (in
    nupic.swarming.ModelRunner) for a description of the schema for
    the dummy model params.
    """
    errScore = 500
    if (not (perm['modelParams']['sensorParams']['encoders']['A'] is None)):
        errScore -= 50
    if (not (perm['modelParams']['sensorParams']['encoders']['B'] is None)):
        errScore -= 40
    if (not (perm['modelParams']['sensorParams']['encoders']['C'] is None)):
        errScore -= 30
    if (not (perm['modelParams']['sensorParams']['encoders']['D'] is None)):
        errScore -= 20
    if (not (perm['modelParams']['sensorParams']['encoders']['E'] is None)):
        errScore -= 15
    if (not (perm['modelParams']['sensorParams']['encoders']['F'] is None)):
        errScore -= 10
    if (not (perm['modelParams']['sensorParams']['encoders']['G'] is None)):
        errScore -= 5
    delay = 0
    encoderCount = 0
    for key in perm.keys():
        if (('encoder' in key) and (not (perm[key] is None))):
            encoderCount += 1
    delay = ((encoderCount * encoderCount) * 0.1)
    dummyModelParams = dict(metricValue=errScore, metricFunctions=None, delay=delay)
    return dummyModelParams
inputs: Complete the below
def file_upload_echo(request):

    ''''Simple view to echo back info about uploaded files for tests.'
    '''
targets: r = {k: f.name for (k, f) in request.FILES.items()}
    return JsonResponse(r)
inputs: I wrote the below code

    if hasattr(target, 'im_self'):
        if (target.im_self is not None):
            assert hasattr(target, 'im_func'), ("safeRef    target    %r    has    im_self,    but    no    im_func,    don't    know    how    to    create    reference" % (target,))
            reference = get_bound_method_weakref(target=target, onDelete=onDelete)
            return reference
    if callable(onDelete):
        return weakref.ref(target, onDelete)
    else:
        return weakref.ref(target)


What's a good function header?
targets: def safeRef(target, onDelete=None):
inputs: Complete the below
def _mini_batch_convergence(model, iteration_idx, n_iter, tol, n_samples, centers_squared_diff, batch_inertia, context, verbose=0):

    ''''Helper function to encapsulate the early stopping logic'
    '''
targets: batch_inertia /= model.batch_size
    centers_squared_diff /= model.batch_size
    ewa_diff = context.get('ewa_diff')
    ewa_inertia = context.get('ewa_inertia')
    if (ewa_diff is None):
        ewa_diff = centers_squared_diff
        ewa_inertia = batch_inertia
    else:
        alpha = ((float(model.batch_size) * 2.0) / (n_samples + 1))
        alpha = (1.0 if (alpha > 1.0) else alpha)
        ewa_diff = ((ewa_diff * (1 - alpha)) + (centers_squared_diff * alpha))
        ewa_inertia = ((ewa_inertia * (1 - alpha)) + (batch_inertia * alpha))
    if verbose:
        progress_msg = ('Minibatch    iteration    %d/%d:    mean    batch    inertia:    %f,    ewa    inertia:    %f    ' % ((iteration_idx + 1), n_iter, batch_inertia, ewa_inertia))
        print progress_msg
    if ((tol > 0.0) and (ewa_diff <= tol)):
        if verbose:
            print ('Converged    (small    centers    change)    at    iteration    %d/%d' % ((iteration_idx + 1), n_iter))
        return True
    ewa_inertia_min = context.get('ewa_inertia_min')
    no_improvement = context.get('no_improvement', 0)
    if ((ewa_inertia_min is None) or (ewa_inertia < ewa_inertia_min)):
        no_improvement = 0
        ewa_inertia_min = ewa_inertia
    else:
        no_improvement += 1
    if ((model.max_no_improvement is not None) and (no_improvement >= model.max_no_improvement)):
        if verbose:
            print ('Converged    (lack    of    improvement    in    inertia)    at    iteration    %d/%d' % ((iteration_idx + 1), n_iter))
        return True
    context['ewa_diff'] = ewa_diff
    context['ewa_inertia'] = ewa_inertia
    context['ewa_inertia_min'] = ewa_inertia_min
    context['no_improvement'] = no_improvement
    return False
inputs: I wrote the below code

    if node.ownerDocument.isSameNode(newOwnerDocument):
        operation = xml.dom.UserDataHandler.NODE_CLONED
    else:
        operation = xml.dom.UserDataHandler.NODE_IMPORTED
    if (node.nodeType == Node.ELEMENT_NODE):
        clone = newOwnerDocument.createElementNS(node.namespaceURI, node.nodeName)
        for attr in node.attributes.values():
            clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
            a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
            a.specified = attr.specified
        if deep:
            for child in node.childNodes:
                c = _clone_node(child, deep, newOwnerDocument)
                clone.appendChild(c)
    elif (node.nodeType == Node.DOCUMENT_FRAGMENT_NODE):
        clone = newOwnerDocument.createDocumentFragment()
        if deep:
            for child in node.childNodes:
                c = _clone_node(child, deep, newOwnerDocument)
                clone.appendChild(c)
    elif (node.nodeType == Node.TEXT_NODE):
        clone = newOwnerDocument.createTextNode(node.data)
    elif (node.nodeType == Node.CDATA_SECTION_NODE):
        clone = newOwnerDocument.createCDATASection(node.data)
    elif (node.nodeType == Node.PROCESSING_INSTRUCTION_NODE):
        clone = newOwnerDocument.createProcessingInstruction(node.target, node.data)
    elif (node.nodeType == Node.COMMENT_NODE):
        clone = newOwnerDocument.createComment(node.data)
    elif (node.nodeType == Node.ATTRIBUTE_NODE):
        clone = newOwnerDocument.createAttributeNS(node.namespaceURI, node.nodeName)
        clone.specified = True
        clone.value = node.value
    elif (node.nodeType == Node.DOCUMENT_TYPE_NODE):
        assert (node.ownerDocument is not newOwnerDocument)
        operation = xml.dom.UserDataHandler.NODE_IMPORTED
        clone = newOwnerDocument.implementation.createDocumentType(node.name, node.publicId, node.systemId)
        clone.ownerDocument = newOwnerDocument
        if deep:
            clone.entities._seq = []
           ...

What's a good function header?
targets: def _clone_node(node, deep, newOwnerDocument):
inputs: def getRadioPluginsAddPluginFrame(directoryPath, importantFileNames, names, repository):
targets: """Get the radio plugins and add the plugin frame.
    """
    repository.pluginFrame = PluginFrame()
    radioPlugins = []
    for name in names:
        radioPlugin = RadioPlugin().getFromRadio((name in importantFileNames), repository.pluginFrame.latentStringVar, name, repository, (name == importantFileNames[0]))
        radioPlugin.updateFunction = repository.pluginFrame.update
        radioPlugins.append(radioPlugin)
    defaultRadioButton = getSelectedRadioPlugin((importantFileNames + [radioPlugins[0].name]), radioPlugins)
    repository.pluginFrame.getFromPath(defaultRadioButton, directoryPath, repository)
    return radioPlugins
inputs: I wrote the below code

    a = use_app()
    if (a.backend_name.lower() == 'pyglet'):
        return
    if (a.backend_name.lower() == 'osmesa'):
        return
    configs = [dict(samples=4), dict(stencil_size=8), dict(samples=4, stencil_size=8)]
    if (a.backend_name.lower() != 'glfw'):
        configs.append(dict(double_buffer=False, samples=4))
        configs.append(dict(double_buffer=False))
    else:
        assert_raises(RuntimeError, Canvas, app=a, config=dict(double_buffer=False))
    if ((a.backend_name.lower() == 'sdl2') and (os.getenv('TRAVIS') == 'true')):
        raise SkipTest('Travis    SDL    cannot    set    context')
    for config in configs:
        n_items = len(config)
        with Canvas(config=config):
            if ('true' in (os.getenv('TRAVIS', ''), os.getenv('APPVEYOR', '').lower())):
                props = config
            else:
                props = get_gl_configuration()
            assert_equal(len(config), n_items)
            for (key, val) in config.items():
                if (key == 'samples'):
                    iswx = (a.backend_name.lower() == 'wx')
                    if (not (sys.platform.startswith('win') or iswx)):
                        assert_equal(val, props[key], key)
    assert_raises(TypeError, Canvas, config='foo')
    assert_raises(KeyError, Canvas, config=dict(foo=True))
    assert_raises(TypeError, Canvas, config=dict(double_buffer='foo'))


What's a good function header?
targets: @requires_application()
def test_context_properties():
inputs: I wrote the below code

    host = urlparse(url)[1]
    if (not host):
        return None
    return host


What's a good function header?
targets: def host_for_url(url):
inputs: def get_all_uncheck_express():
targets: """
    """
    express_info = Express.query.filter((Express.ischeck != 3)).all()
    return express_info
inputs: I wrote the below code

    kwds = dict(root_id=lpar_uuid, suffix_type='quick', suffix_parm=qprop)
    if (not log_errors):
        helpers = adapter.helpers
        try:
            helpers.remove(pvm_log.log_helper)
        except ValueError:
            pass
        kwds['helpers'] = helpers
    try:
        resp = adapter.read(pvm_lpar.LPAR.schema_type, **kwds)
    except pvm_exc.HttpError as e:
        with excutils.save_and_reraise_exception(logger=LOG) as sare:
            if (e.response and (e.response.status == 404)):
                sare.reraise = False
                raise exc.InstanceNotFound(instance_id=lpar_uuid)
    return jsonutils.loads(resp.body)


What's a good function header?
targets: def get_vm_qp(adapter, lpar_uuid, qprop=None, log_errors=True):
inputs: Complete the below
def _lock_file(f, dotlock=True):

    ''''Lock file f using lockf and dot locking.'
    '''
targets: dotlock_done = False
    try:
        if fcntl:
            try:
                fcntl.lockf(f, (fcntl.LOCK_EX | fcntl.LOCK_NB))
            except IOError as e:
                if (e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS)):
                    raise ExternalClashError(('lockf:    lock    unavailable:    %s' % f.name))
                else:
                    raise
        if dotlock:
            try:
                pre_lock = _create_temporary((f.name + '.lock'))
                pre_lock.close()
            except IOError as e:
                if (e.errno in (errno.EACCES, errno.EROFS)):
                    return
                else:
                    raise
            try:
                if hasattr(os, 'link'):
                    os.link(pre_lock.name, (f.name + '.lock'))
                    dotlock_done = True
                    os.unlink(pre_lock.name)
                else:
                    os.rename(pre_lock.name, (f.name + '.lock'))
                    dotlock_done = True
            except OSError as e:
                if ((e.errno == errno.EEXIST) or ((os.name == 'os2') and (e.errno == errno.EACCES))):
                    os.remove(pre_lock.name)
                    raise ExternalClashError(('dot    lock    unavailable:    %s' % f.name))
                else:
                    raise
    except:
        if fcntl:
            fcntl.lockf(f, fcntl.LOCK_UN)
        if dotlock_done:
            os.remove((f.name + '.lock'))
        raise
inputs: I wrote the below code

    if (f is not None):
        return os.path.normpath(os.path.relpath(f, path))
    else:
        return None


What's a good function header?
targets: def relative_normpath(f, path):
inputs: def __virtual__():
targets: """Only load if boto is available.
    """
    if ('boto3_elasticache.cache_cluster_exists' in __salt__):
        return 'boto3_elasticache'
    else:
        return False
inputs: I wrote the below code

    newly_determined = []
    col = list(col)
    if (all((isinstance(x, (Float, Integer)) for x in col)) and any((isinstance(x, Float) for x in col))):
        col_abs = [abs(x) for x in col]
        max_value = max(col_abs)
        if iszerofunc(max_value):
            if (max_value != 0):
                newly_determined = [(i, 0) for (i, x) in enumerate(col) if (x != 0)]
            return (None, None, False, newly_determined)
        index = col_abs.index(max_value)
        return (index, col[index], False, newly_determined)
    possible_zeros = []
    for (i, x) in enumerate(col):
        is_zero = iszerofunc(x)
        if (is_zero == False):
            return (i, x, False, newly_determined)
        possible_zeros.append(is_zero)
    if all(possible_zeros):
        return (None, None, False, newly_determined)
    for (i, x) in enumerate(col):
        if (possible_zeros[i] is not None):
            continue
        simped = simpfunc(x)
        is_zero = iszerofunc(simped)
        if ((is_zero == True) or (is_zero == False)):
            newly_determined.append((i, simped))
        if (is_zero == False):
            return (i, simped, False, newly_determined)
        possible_zeros[i] = is_zero
    if all(possible_zeros):
        return (None, None, False, newly_determined)
    for (i, x) in enumerate(col):
        if (possible_zeros[i] is not None):
            continue
        if x.equals(S.Zero):
            possible_zeros[i] = True
            newly_determined.append((i, S.Zero))
    if all(possible_zeros):
        return (None, None, False, newly_determined)
    i = possible_zeros.index(None)
    return (i, col[i], True, newly_determined)


What's a good function header?
targets: def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify):
inputs: def get(schema=None, key=None, user=None, **kwargs):
targets: """Get key in a particular GNOME schema
    CLI Example:
    .. code-block:: bash
    salt \*\ gnome.get user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled
    """
    _gsession = _GSettings(user=user, schema=schema, key=key)
    return _gsession._get()
inputs: I wrote the below code

    net = Mininet(autoStaticArp=True)
    net.addController('c0')
    h1 = net.addHost('h1')
    h2 = net.addHost('h2')
    s1 = net.addSwitch('s1')
    link1 = net.addLink(h1, s1, cls=TCLink)
    net.addLink(h2, s1)
    net.start()
    net.pingAll()
    info('\n***    Configuring    one    intf    with    bandwidth    of    5    Mb\n')
    link1.intf1.config(bw=5)
    info('\n***    Running    iperf    to    test\n')
    net.iperf()
    info('\n***    Configuring    one    intf    with    loss    of    50%\n')
    link1.intf1.config(loss=50)
    info('\n')
    net.iperf((h1, h2), l4Type='UDP')
    info('\n***    Configuring    one    intf    with    delay    of    15ms\n')
    link1.intf1.config(delay='15ms')
    info('\n***    Run    a    ping    to    confirm    delay\n')
    net.pingPairFull()
    info('\n***    Done    testing\n')
    net.stop()


What's a good function header?
targets: def intfOptions():
inputs: def log_file(msg, filename='game.log'):
targets: """Arbitrary file logger using threads.
    Args:
    msg (str): String to append to logfile.
    filename (str, optional): Defaults to \game.log\. All logs
    will appear in the logs directory and log entries will start
    on new lines following datetime info.
    """
    def callback(filehandle, msg):
        'Writing    to    file    and    flushing    result'
        msg = ('\n%s    [-]    %s' % (timeformat(), msg.strip()))
        filehandle.write(msg)
        filehandle.flush()
    def errback(failure):
        'Catching    errors    to    normal    log'
        log_trace()
    filehandle = _open_log_file(filename)
    if filehandle:
        deferToThread(callback, filehandle, msg).addErrback(errback)
inputs: I wrote the below code

    global _sum_operands
    _sum_operands = []
    os.chdir(str(tmpdir))
    wf = pe.Workflow(name=u'test')
    inputspec = pe.Node(IdentityInterface(fields=[u'n']), name=u'inputspec')
    inputspec.iterables = [(u'n', [3, 1, 2, 1, 3])]
    pre_join1 = pe.Node(IncrementInterface(), name=u'pre_join1')
    wf.connect(inputspec, u'n', pre_join1, u'input1')
    join = pe.JoinNode(SumInterface(), joinsource=u'inputspec', joinfield=u'input1', unique=True, name=u'join')
    wf.connect(pre_join1, u'output1', join, u'input1')
    wf.run()
    assert (_sum_operands[0] == [4, 2, 3]), (u'The    unique    join    output    value    is    incorrect:    %s.' % _sum_operands[0])


What's a good function header?
targets: def test_unique_join_node(tmpdir):
inputs: def init(mpstate):
targets: """initialise module
    """
    return FollowTestModule(mpstate)
inputs: def arg_to_softmax(prob):
targets: """Oh no! Someone has passed you the probability output,
    "prob", of a softmax function, and you want the unnormalized
    log probability--the argument to the softmax.
    Verify that prob really is the output of a softmax. Raise a
    TypeError if it is not.
    If it is, return the argument to the softmax.
    """
    if (not isinstance(prob, Variable)):
        raise TypeError()
    if (prob.owner is None):
        raise TypeError()
    owner = prob.owner
    if (not isinstance(owner.op, T.nnet.Softmax)):
        raise TypeError()
    (rval,) = owner.inputs
    return rval
inputs: def _inFilesystemNamespace(path):
targets: """Determine whether the given unix socket path is in a filesystem namespace.
    While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and
    above support PF_UNIX sockets in an "abstract namespace" that does not
    correspond to any path. This function returns C{True} if the given socket
    path is stored in the filesystem and C{False} if the path is in this
    abstract namespace.
    """
    return (path[:1] != '\x00')
inputs: Complete the below
def is_str(s):

    ''''@brief      Determines if string.
    @param      s     String
    @return     True if string, False otherwise.'
    '''
targets: return isinstance(s, basestring)
inputs: Complete the below
def get_alarm(name, region=None, key=None, keyid=None, profile=None):

    ''''Get alarm details. Also can be used to check to see if an alarm exists.
    CLI example::
    salt myminion boto_cloudwatch.get_alarm myalarm region=us-east-1'
    '''
targets: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    alarms = conn.describe_alarms(alarm_names=[name])
    if (len(alarms) == 0):
        return None
    if (len(alarms) > 1):
        log.error("multiple    alarms    matched    name    '{0}'".format(name))
    return _metric_alarm_to_dict(alarms[0])
inputs: I wrote the below code

    (global_dict, local_dict) = get_twill_glocals()
    d = global_dict.copy()
    d.update(local_dict)
    print d.get(str(which))


What's a good function header?
targets: def showvar(which):
inputs: def intColor(index, hues=9, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255):
targets: """Creates a QColor from a single index. Useful for stepping through a predefined list of colors.
    The argument *index* determines which color from the set will be returned. All other arguments determine what the set of predefined colors will be
    Colors are chosen by cycling across hues while varying the value (brightness).
    By default, this selects from a list of 9 hues.
    """
    hues = int(hues)
    values = int(values)
    ind = (int(index) % (hues * values))
    indh = (ind % hues)
    indv = (ind // hues)
    if (values > 1):
        v = (minValue + (indv * ((maxValue - minValue) / (values - 1))))
    else:
        v = maxValue
    h = (minHue + ((indh * (maxHue - minHue)) / hues))
    c = QtGui.QColor()
    c.setHsv(h, sat, v)
    c.setAlpha(alpha)
    return c
inputs: def _generateExtraMetricSpecs(options):
targets: """Generates the non-default metrics specified by the expGenerator params
    """
    global _metricSpecSchema
    results = []
    for metric in options['metrics']:
        for propertyName in _metricSpecSchema['properties'].keys():
            _getPropertyValue(_metricSpecSchema, propertyName, metric)
        (specString, label) = _generateMetricSpecString(field=metric['field'], metric=metric['metric'], params=metric['params'], inferenceElement=metric['inferenceElement'], returnLabel=True)
        if metric['logged']:
            options['loggedMetrics'].append(label)
        results.append(specString)
    return results
inputs: I wrote the below code

    index = p.ring.gens.index(x)
    n = 1
    for k in p:
        power = k[index]
        if isinstance(power, Rational):
            (num, den) = power.as_numer_denom()
            n = ((n * den) // igcd(n, den))
        elif (power != int(power)):
            (num, den) = (power.numerator, power.denominator)
            n = ((n * den) // igcd(n, den))
    if (n != 1):
        p1 = pow_xin(p, index, n)
        r = f(p1, q, x, (prec * n))
        n1 = QQ(1, n)
        r = pow_xin(r, index, n1)
    else:
        r = f(p, q, x, prec)
    return r


What's a good function header?
targets: def rs_puiseux2(f, p, q, x, prec):
inputs: def list_groups(api):
targets: """This function prints a list of all host groups. This function requires
    one argument, the FreeIPA/IPA API object.
    """
    inventory = {}
    hostvars = {}
    meta = {}
    result = api.Command.hostgroup_find()['result']
    for hostgroup in result:
        members = []
        if ('member_host' in hostgroup):
            members = [host for host in hostgroup['member_host']]
        if ('memberindirect_host' in hostgroup):
            members += (host for host in hostgroup['memberindirect_host'])
        inventory[hostgroup['cn'][0]] = {'hosts': [host for host in members]}
        for member in members:
            hostvars[member] = {}
    inventory['_meta'] = {'hostvars': hostvars}
    inv_string = json.dumps(inventory, indent=1, sort_keys=True)
    print inv_string
    return None
inputs: I wrote the below code

    if (host_platform == 'darwin'):
        sysroot = macosx_sdk_root()
    for dir in std_dirs:
        f = os.path.join(dir, filename)
        if ((host_platform == 'darwin') and is_macosx_sdk_path(dir)):
            f = os.path.join(sysroot, dir[1:], filename)
        if os.path.exists(f):
            return []
    for dir in paths:
        f = os.path.join(dir, filename)
        if ((host_platform == 'darwin') and is_macosx_sdk_path(dir)):
            f = os.path.join(sysroot, dir[1:], filename)
        if os.path.exists(f):
            return [dir]
    return None


What's a good function header?
targets: def find_file(filename, std_dirs, paths):
inputs: def load_command_class(app_name, name):
targets: """Given a command name and an application name, returns the Command
    class instance. All errors raised by the import process
    (ImportError, AttributeError) are allowed to propagate.
    """
    module = import_module(('%s.management.commands.%s' % (app_name, name)))
    return module.Command()
inputs: def cxMessyOnePoint(ind1, ind2):
targets: """Executes a one point crossover on :term:`sequence` individual.
    The crossover will in most cases change the individuals size. The two
    individuals are modified in place.
    :param ind1: The first individual participating in the crossover.
    :param ind2: The second individual participating in the crossover.
    :returns: A tuple of two individuals.
    This function uses the :func:`~random.randint` function from the python base
    :mod:`random` module.
    """
    cxpoint1 = random.randint(0, len(ind1))
    cxpoint2 = random.randint(0, len(ind2))
    (ind1[cxpoint1:], ind2[cxpoint2:]) = (ind2[cxpoint2:], ind1[cxpoint1:])
    return (ind1, ind2)
inputs: Complete the below
def has_comments_in_diffsets_excluding(review, diffset_pair):

    ''''Returns whether the specified review has "other comments".
    This is used to notify users that their review has comments on diff
    revisions other than the one that they happen to be looking at at any given
    moment.'
    '''
targets: if (not review):
        return False
    (current_diffset, interdiff) = diffset_pair
    q = DiffSet.objects.filter(files__comments__review=review)
    q = q.filter(files__comments__interfilediff__isnull=True).distinct()
    if (not interdiff):
        q = q.exclude(pk=current_diffset.id)
    if (q.count() > 0):
        return True
    q = DiffSet.objects.filter(files__comments__review=review)
    q = q.filter(files__comments__interfilediff__isnull=False)
    if interdiff:
        q = q.exclude(pk=current_diffset.id, files__comments__interfilediff__diffset=interdiff)
    return (q.count() > 0)
inputs: @receiver(SignalHandler.course_published)
def _listen_for_course_publish(sender, course_key, **kwargs):
targets: """Catches the signal that a course has been published in Studio and
    sets the verification deadline date to a default.
    """
    course = modulestore().get_course(course_key)
    if course:
        try:
            deadline = VerificationDeadline.objects.get(course_key=course_key)
            if ((not deadline.deadline_is_explicit) and (deadline.deadline != course.end)):
                VerificationDeadline.set_deadline(course_key, course.end)
        except ObjectDoesNotExist:
            VerificationDeadline.set_deadline(course_key, course.end)
inputs: def cloudfiles(module, container, src, dest, method, typ, meta, clear_meta, structure, expires):
targets: """Dispatch from here to work with metadata or file objects
    """
    cf = pyrax.cloudfiles
    if (cf is None):
        module.fail_json(msg='Failed    to    instantiate    client.    This    typically    indicates    an    invalid    region    or    an    incorrectly    capitalized    region    name.')
    if (typ == 'file'):
        if (method == 'put'):
            upload(module, cf, container, src, dest, meta, expires)
        elif (method == 'get'):
            download(module, cf, container, src, dest, structure)
        elif (method == 'delete'):
            delete(module, cf, container, src, dest)
    else:
        if (method == 'get'):
            get_meta(module, cf, container, src, dest)
        if (method == 'put'):
            put_meta(module, cf, container, src, dest, meta, clear_meta)
        if (method == 'delete'):
            delete_meta(module, cf, container, src, dest, meta)
inputs: def filter_by_version(test_class, version_dict, current_version):
targets: """Remove test methods that do not work with the current lib version.
    """
    find_required_version = version_dict.get
    def dummy_test_method(self):
        pass
    for name in dir(test_class):
        expected_version = find_required_version(name, (0, 0, 0))
        if (expected_version > current_version):
            setattr(test_class, name, dummy_test_method)
inputs: def batch_tasks(registry, xml_parent, data):
targets: """yaml: batch-tasks
    Batch tasks can be tasks for events like releases, integration, archiving,
    etc. In this way, anyone in the project team can execute them in a way that
    leaves a record.
    A batch task consists of a shell script and a name. When you execute
    a build, the shell script gets run on the workspace, just like a build.
    Batch tasks and builds "lock" the workspace, so when one of those
    activities is in progress, all the others will block in the queue.
    Requires the Jenkins :jenkins-wiki:`Batch Task Plugin <Batch+Task+Plugin>`.
    :arg list batch-tasks: Batch tasks.
    :Tasks:
    * **name** (`str`) Task name.
    * **script** (`str`) Task script.
    Example:
    .. literalinclude:: /../../tests/properties/fixtures/batch-task.yaml
    :language: yaml
    """
    pdef = XML.SubElement(xml_parent, 'hudson.plugins.batch__task.BatchTaskProperty')
    tasks = XML.SubElement(pdef, 'tasks')
    for task in data:
        batch_task = XML.SubElement(tasks, 'hudson.plugins.batch__task.BatchTask')
        mapping = [('name', 'name', None), ('script', 'script', None)]
        helpers.convert_mapping_to_xml(batch_task, task, mapping, fail_required=True)
inputs: @XFAIL
def test_mul2():
targets: """When this fails, remove things labelled "2-arg hack"
    1) remove special handling in the fallback of subs that
    was added in the same commit as this test
    2) remove the special handling in Mul.flatten
    """
    assert (2 * (x + 1)).is_Mul
inputs: Complete the below
def dup_pquo(f, g, K):

    ''''Polynomial exact pseudo-quotient in ``K[X]``.
    Examples
    >>> from sympy.polys import ring, ZZ
    >>> R, x = ring("x", ZZ)
    >>> R.dup_pquo(x**2 - 1, 2*x - 2)
    2*x + 2
    >>> R.dup_pquo(x**2 + 1, 2*x - 4)
    2*x + 4'
    '''
targets: return dup_pdiv(f, g, K)[0]
inputs: Complete the below
def map_references(value, field, actual_course_key):

    ''''Map the references in value to actual_course_key and return value'
    '''
targets: if (not value):
        return value
    if isinstance(field, Reference):
        return value.map_into_course(actual_course_key)
    if isinstance(field, ReferenceList):
        return [sub.map_into_course(actual_course_key) for sub in value]
    if isinstance(field, ReferenceValueDict):
        return {key: ele.map_into_course(actual_course_key) for (key, ele) in value.iteritems()}
    return value
inputs: I wrote the below code

    opened_files = []
    try:
        if (in_file == '-'):
            in_file = sys.stdin
        elif isinstance(in_file, basestring):
            if (name is None):
                name = os.path.basename(in_file)
            if (mode is None):
                try:
                    mode = os.stat(in_file).st_mode
                except AttributeError:
                    pass
            in_file = open(in_file, 'rb')
            opened_files.append(in_file)
        if (out_file == '-'):
            out_file = sys.stdout
        elif isinstance(out_file, basestring):
            out_file = open(out_file, 'wb')
            opened_files.append(out_file)
        if (name is None):
            name = '-'
        if (mode is None):
            mode = 438
        out_file.write(('begin    %o    %s\n' % ((mode & 511), name)))
        data = in_file.read(45)
        while (len(data) > 0):
            out_file.write(binascii.b2a_uu(data))
            data = in_file.read(45)
        out_file.write('    \nend\n')
    finally:
        for f in opened_files:
            f.close()


What's a good function header?
targets: def encode(in_file, out_file, name=None, mode=None):
inputs: Complete the below
def _bootstrap_debian(name, **kwargs):

    ''''Bootstrap a Debian Linux container'
    '''
targets: version = kwargs.get('version', False)
    if (not version):
        if (__grains__['os'].lower() == 'debian'):
            version = __grains__['osrelease']
        else:
            version = 'stable'
    release_blacklist = ['hamm', 'slink', 'potato', 'woody', 'sarge', 'etch', 'lenny', 'squeeze', 'wheezy']
    if (version in release_blacklist):
        raise CommandExecutionError('Unsupported    Debian    version    "{0}".    Only    "stable"    or    "jessie"    and    newer    are    supported'.format(version))
    dst = _make_container_root(name)
    cmd = 'debootstrap    --arch=amd64    {0}    {1}'.format(version, dst)
    ret = __salt__['cmd.run_all'](cmd, python_shell=False)
    if (ret['retcode'] != 0):
        _build_failed(dst, name)
    return ret
inputs: def app(environ, start_response):
targets: """Application which cooperatively pauses 20 seconds (needed to surpass normal timeouts) before responding
    """
    status = '200    OK'
    response_headers = [('Content-type', 'text/plain'), ('Transfer-Encoding', 'chunked')]
    sys.stdout.write('request    received')
    sys.stdout.flush()
    start_response(status, response_headers)
    return TestIter()
inputs: Complete the below
def initRepeat(container, func, n):

    ''''Call the function *container* with a generator function corresponding
    to the calling *n* times the function *func*.
    :param container: The type to put in the data from func.
    :param func: The function that will be called n times to fill the
    container.
    :param n: The number of times to repeat func.
    :returns: An instance of the container filled with data from func.
    This helper function can can be used in conjunction with a Toolbox
    to register a generator of filled containers, as individuals or
    population.
    >>> initRepeat(list, random.random, 2) # doctest: +ELLIPSIS,
    ...                                    # doctest: +NORMALIZE_WHITESPACE
    [0.4761..., 0.6302...]
    See the :ref:`list-of-floats` and :ref:`population` tutorials for more examples.'
    '''
targets: return container((func() for _ in xrange(n)))
inputs: def UpdateWithDict(tablename, props, prere):
targets: """
    """
    sql = forEachUpdateProps(tablename, props, prere)
    conn = dbpool.connection()
    cursor = conn.cursor()
    count = 0
    try:
        count = cursor.execute(sql)
        conn.commit()
    except Exception as e:
        log.err(e)
        log.err(sql)
    cursor.close()
    conn.close()
    if (count >= 1):
        return True
    return False
inputs: Complete the below
def _get_journal():

    ''''Return the active running journal object'
    '''
targets: if ('systemd.journald' in __context__):
        return __context__['systemd.journald']
    __context__['systemd.journald'] = systemd.journal.Reader()
    __context__['systemd.journald'].seek_tail()
    __context__['systemd.journald'].get_previous()
    return __context__['systemd.journald']
inputs: Complete the below
def all_methods(obj):

    ''''Return a list of names of methods of `obj`'
    '''
targets: temp = []
    for name in dir(obj):
        func = getattr(obj, name)
        if hasattr(func, '__call__'):
            temp.append(name)
    return temp
inputs: def TranslateXmlToYamlForDevAppServer(app_engine_web_xml, web_xml, war_root):
targets: """Does parsed-XML to YAML-string translation.
    This method is used in the Dev App Server context, where files are served
    directly from the input war directory, unlike the appcfg case where they are
    copied or linked into a parallel hierarchy.  This means that there is no
    __static__ directory containing exactly the files that are supposed to be
    served statically.
    Args:
    app_engine_web_xml: parsed AppEngineWebXml object corresponding to the
    contents of app-engine.web.xml.
    web_xml: parsed WebXml object corresponding to the contents of web.xml.
    war_root: the path to the root directory of the war hierarchy
    Returns:
    The full text of the app.yaml generated from the xml files.
    Raises:
    AppEngineConfigException: raised in processing stage for illegal XML.
    """
    translator = AppYamlTranslatorForDevAppServer(app_engine_web_xml, web_xml, war_root)
    return translator.GetYaml()
inputs: def format_filesize(size):
targets: """Formats the file size into a human readable format.
    """
    for suffix in ('bytes', 'KB', 'MB', 'GB', 'TB'):
        if (size < 1024.0):
            if (suffix in ('GB', 'TB')):
                return '{0:3.2f}    {1}'.format(size, suffix)
            else:
                return '{0:3.1f}    {1}'.format(size, suffix)
        size /= 1024.0
inputs: def ackley(individual):
targets: """Ackley test objective function.
    .. list-table::
    :widths: 10 50
    :stub-columns: 1
    * - Type
    - minimization
    * - Range
    - :math:`x_i \in [-15, 30]`
    * - Global optima
    - :math:`x_i = 0, \forall i \in \lbrace 1 \ldots N\rbrace`, :math:`f(\mathbf{x}) = 0`
    * - Function
    - :math:`f(\mathbf{x}) = 20 - 20\exp\left(-0.2\sqrt{\frac{1}{N}             \sum_{i=1}^N x_i^2} \right) + e - \exp\left(\frac{1}{N}\sum_{i=1}^N \cos(2\pi x_i) \right)`
    .. plot:: code/benchmarks/ackley.py
    :width: 67 %
    """
    N = len(individual)
    return ((((20 - (20 * exp(((-0.2) * sqrt(((1.0 / N) * sum(((x ** 2) for x in individual)))))))) + e) - exp(((1.0 / N) * sum((cos(((2 * pi) * x)) for x in individual))))),)
inputs: Complete the below
def check_pool(lb, name):

    ''''Check to see if a pool exists
    CLI Examples:
    .. code-block:: bash
    salt-run f5.check_pool load_balancer pool_name'
    '''
targets: if __opts__['load_balancers'].get(lb, None):
        (username, password) = list(__opts__['load_balancers'][lb].values())
    else:
        raise Exception('Unable    to    find    `{0}`    load    balancer'.format(lb))
    F5 = F5Mgmt(lb, username, password)
    return F5.check_pool(name)
inputs: I wrote the below code

    def customized(*args, **kwargs):
        'Customized    constructor'
        kwargs = kwargs.copy()
        kwargs.update(params)
        return cls(*args, **kwargs)
    customized.__name__ = ('custom(%s,%s)' % (cls, params))
    return customized


What's a good function header?
targets: def custom(cls, **params):