Muennighoff/xP3x-sample huggingface dataset:
inputs: Complete the below
def linked_data(prefix, ignore_channels=False):

    ''''Return a dictionary of the linked packages in prefix.'
    '''
targets: pd = PrefixData(prefix)
    return {Dist(prefix_record): prefix_record for prefix_record in itervalues(pd._prefix_records)}
inputs: def generate_nonce(length=8):
targets: """Generate pseudorandom number.
    """
    return ''.join([str(random.randint(0, 9)) for i in range(length)])
inputs: Complete the below
def gaussian_conj(s_in, z_r_in, f):

    ''''Conjugation relation for gaussian beams.
    Parameters
    s_in : the distance to optical element from the waist
    z_r_in : the rayleigh range of the incident beam
    f : the focal length of the optical element
    Returns
    a tuple containing (s_out, z_r_out, m)
    s_out : the distance between the new waist and the optical element
    z_r_out : the rayleigh range of the emergent beam
    m : the ration between the new and the old waists
    Examples
    >>> from sympy.physics.optics import gaussian_conj
    >>> from sympy import symbols
    >>> s_in, z_r_in, f = symbols(\'s_in z_r_in f\')
    >>> gaussian_conj(s_in, z_r_in, f)[0]
    1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
    >>> gaussian_conj(s_in, z_r_in, f)[1]
    z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
    >>> gaussian_conj(s_in, z_r_in, f)[2]
    1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)'
    '''
targets: (s_in, z_r_in, f) = map(sympify, (s_in, z_r_in, f))
    s_out = (1 / (((-1) / (s_in + ((z_r_in ** 2) / (s_in - f)))) + (1 / f)))
    m = (1 / sqrt(((1 - ((s_in / f) ** 2)) + ((z_r_in / f) ** 2))))
    z_r_out = (z_r_in / ((1 - ((s_in / f) ** 2)) + ((z_r_in / f) ** 2)))
    return (s_out, z_r_out, m)
inputs: Complete the below
def _zpkbilinear(z, p, k, fs):

    ''''Return a digital filter from an analog one using a bilinear transform.
    Transform a set of poles and zeros from the analog s-plane to the digital
    z-plane using Tustin\'s method, which substitutes ``(z-1) / (z+1)`` for
    ``s``, maintaining the shape of the frequency response.
    Parameters
    z : array_like
    Zeros of the analog IIR filter transfer function.
    p : array_like
    Poles of the analog IIR filter transfer function.
    k : float
    System gain of the analog IIR filter transfer function.
    fs : float
    Sample rate, as ordinary frequency (e.g. hertz). No prewarping is
    done in this function.
    Returns
    z : ndarray
    Zeros of the transformed digital filter transfer function.
    p : ndarray
    Poles of the transformed digital filter transfer function.
    k : float
    System gain of the transformed digital filter.'
    '''
targets: z = atleast_1d(z)
    p = atleast_1d(p)
    degree = _relative_degree(z, p)
    fs2 = (2.0 * fs)
    z_z = ((fs2 + z) / (fs2 - z))
    p_z = ((fs2 + p) / (fs2 - p))
    z_z = append(z_z, (- ones(degree)))
    k_z = (k * real((prod((fs2 - z)) / prod((fs2 - p)))))
    return (z_z, p_z, k_z)
inputs: I wrote the below code

    (splt, coll, props) = generate_EventCollection_plot()
    coll.switch_orientation()
    coll.switch_orientation()
    new_positions = coll.get_positions()
    assert_equal(props[u'orientation'], coll.get_orientation())
    assert_equal(True, coll.is_horizontal())
    np.testing.assert_array_equal(props[u'positions'], new_positions)
    check_segments(coll, new_positions, props[u'linelength'], props[u'lineoffset'], props[u'orientation'])
    splt.set_title(u'EventCollection:    switch_orientation    2x')


What's a good function header?
targets: @image_comparison(baseline_images=[u'EventCollection_plot__switch_orientation__2x'])
def test__EventCollection__switch_orientation_2x():
inputs: I wrote the below code

    outputs = fgraph.outputs
    assert isinstance(outputs, (tuple, list, deque))
    parent_counts = {}
    node_to_children = {}
    visitable = deque()
    for var in fgraph.variables:
        owner = var.owner
        if owner:
            node_to_children.setdefault(owner, []).append(var)
            parent_counts[var] = 1
        else:
            visitable.append(var)
            parent_counts[var] = 0
    for a_n in fgraph.apply_nodes:
        parents = list(a_n.inputs)
        parents.extend(orderings.get(a_n, []))
        if parents:
            for parent in parents:
                node_to_children.setdefault(parent, []).append(a_n)
            parent_counts[a_n] = len(parents)
        else:
            visitable.append(a_n)
            parent_counts[a_n] = 0
    visited = 0
    while visitable:
        node = visitable.popleft()
        visited += 1
        for client in node_to_children.get(node, []):
            parent_counts[client] -= 1
            if (not parent_counts[client]):
                visitable.append(client)
    return (visited != len(parent_counts))


What's a good function header?
targets: def _contains_cycle(fgraph, orderings):
inputs: Complete the below
def _get_proc_create_time(proc):

    ''''Returns the create_time of a Process instance.
    It\'s backward compatible with < 2.0 versions of psutil.'
    '''
targets: try:
        return (proc.create_time() if PSUTIL2 else proc.create_time)
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        return None
inputs: def get_distribution(dist):
targets: """Return a current distribution object for a Requirement or string
    """
    if isinstance(dist, basestring):
        dist = Requirement.parse(dist)
    if isinstance(dist, Requirement):
        dist = get_provider(dist)
    if (not isinstance(dist, Distribution)):
        raise TypeError('Expected    string,    Requirement,    or    Distribution', dist)
    return dist
inputs: I wrote the below code

    paths = (os.environ.get('PATH', os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS)
    oc_binary = 'oc'
    try:
        which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
        if (which_result is not None):
            oc_binary = which_result
    except AttributeError:
        for path in paths:
            if os.path.exists(os.path.join(path, oc_binary)):
                oc_binary = os.path.join(path, oc_binary)
                break
    return oc_binary


What's a good function header?
targets: def locate_oc_binary():
inputs: def addsitedir(sitedir, known_paths=None):
targets: """Add \sitedir\ argument to sys.path if missing and handle .pth files in
    \sitedir\
    """
    if (known_paths is None):
        known_paths = _init_pathinfo()
        reset = 1
    else:
        reset = 0
    (sitedir, sitedircase) = makepath(sitedir)
    if (sitedircase not in known_paths):
        sys.path.append(sitedir)
    try:
        names = os.listdir(sitedir)
    except os.error:
        return
    dotpth = (os.extsep + 'pth')
    names = [name for name in names if name.endswith(dotpth)]
    for name in sorted(names):
        addpackage(sitedir, name, known_paths)
    if reset:
        known_paths = None
    return known_paths
inputs: I wrote the below code

    if (not host):
        raise ValueError("Host    values    of    ''    or    None    are    not    allowed.")
    if (timeout is None):
        timeout = free_port_timeout
    for trial in range(50):
        try:
            check_port(host, port, timeout=timeout)
        except IOError:
            time.sleep(timeout)
        else:
            return
    raise IOError(('Port    %r    not    free    on    %r' % (port, host)))


What's a good function header?
targets: def wait_for_free_port(host, port, timeout=None):
inputs: I wrote the below code

    body = BytesIO()
    if (boundary is None):
        boundary = choose_boundary()
    for (fieldname, value) in iter_fields(fields):
        body.write(b(('--%s\r\n' % boundary)))
        if isinstance(value, tuple):
            (filename, data) = value
            writer(body).write(('Content-Disposition:    form-data;    name="%s";    filename="%s"\r\n' % (fieldname, filename)))
            body.write(b(('Content-Type:    %s\r\n\r\n' % get_content_type(filename))))
        else:
            data = value
            writer(body).write(('Content-Disposition:    form-data;    name="%s"\r\n' % fieldname))
            body.write('Content-Type:    text/plain\r\n\r\n')
        if isinstance(data, int):
            data = str(data)
        if isinstance(data, six.text_type):
            writer(body).write(data)
        else:
            body.write(data)
        body.write('\r\n')
    body.write(b(('--%s--\r\n' % boundary)))
    content_type = b(('multipart/form-data;    boundary=%s' % boundary))
    return (body.getvalue(), content_type)


What's a good function header?
targets: def encode_multipart_formdata(fields, boundary=None):
inputs: Complete the below
def MX(domain, resolve=False, nameserver=None):

    ''''Return a list of lists for the MX of ``domain``.
    If the \'resolve\' argument is True, resolve IPs for the servers.
    It\'s limited to one IP, because although in practice it\'s very rarely a
    round robin, it is an acceptable configuration and pulling just one IP lets
    the data be similar to the non-resolved version. If you think an MX has
    multiple IPs, don\'t use the resolver here, resolve them in a separate step.
    CLI Example:
    .. code-block:: bash
    salt ns1 dnsutil.MX google.com'
    '''
targets: if _has_dig():
        return __salt__['dig.MX'](domain, resolve, nameserver)
    return 'This    function    requires    dig,    which    is    not    currently    available'
inputs: def _exists_in_path(cmd, environ):
targets: """Based on a code snippet from
    http://orip.org/2009/08/python-checking-if-executable-exists-in.html
    """
    if (u'PATH' in environ):
        input_environ = environ.get(u'PATH')
    else:
        input_environ = os.environ.get(u'PATH', u'')
    extensions = os.environ.get(u'PATHEXT', u'').split(os.pathsep)
    for directory in input_environ.split(os.pathsep):
        base = os.path.join(directory, cmd)
        options = ([base] + [(base + ext) for ext in extensions])
        for filename in options:
            if os.path.exists(filename):
                return (True, filename)
    return (False, None)
inputs: @utils.arg('monitor', metavar='<monitor>', help='ID    of    the    monitor    to    backup.')
@utils.arg('--container', metavar='<container>', help='Optional    Backup    container    name.    (Default=None)', default=None)
@utils.arg('--display-name', metavar='<display-name>', help='Optional    backup    name.    (Default=None)', default=None)
@utils.arg('--display-description', metavar='<display-description>', help='Optional    backup    description.    (Default=None)', default=None)
@utils.service_type('monitor')
def do_backup_create(cs, args):
targets: """Creates a backup.
    """
    cs.backups.create(args.monitor, args.container, args.display_name, args.display_description)
inputs: def _negotiate_value(r):
targets: """Extracts the gssapi authentication token from the appropriate header
    """
    authreq = r.headers.get('www-authenticate', None)
    if authreq:
        rx = re.compile('(?:.*,)*\\s*Negotiate\\s*([^,]*),?', re.I)
        mo = rx.search(authreq)
        if mo:
            return mo.group(1)
    return None
inputs: def debug_script(src, pm=False, globs=None):
targets: """Debug a test script.  `src` is the script, as a string.
    """
    import pdb
    srcfilename = tempfile.mktemp('.py', 'doctestdebug')
    f = open(srcfilename, 'w')
    f.write(src)
    f.close()
    try:
        if globs:
            globs = globs.copy()
        else:
            globs = {}
        if pm:
            try:
                execfile(srcfilename, globs, globs)
            except:
                print sys.exc_info()[1]
                pdb.post_mortem(sys.exc_info()[2])
        else:
            pdb.run(('execfile(%r)' % srcfilename), globs, globs)
    finally:
        os.remove(srcfilename)
inputs: def k_random_intersection_graph(n, m, k):
targets: """Return a intersection graph with randomly chosen attribute sets for
    each node that are of equal size (k).
    Parameters
    n : int
    The number of nodes in the first bipartite set (nodes)
    m : int
    The number of nodes in the second bipartite set (attributes)
    k : float
    Size of attribute set to assign to each node.
    seed : int, optional
    Seed for random number generator (default=None).
    See Also
    gnp_random_graph, uniform_random_intersection_graph
    References
    .. [1] Godehardt, E., and Jaworski, J.
    Two models of random intersection graphs and their applications.
    Electronic Notes in Discrete Mathematics 10 (2001), 129--132.
    """
    G = nx.empty_graph((n + m))
    mset = range(n, (n + m))
    for v in range(n):
        targets = random.sample(mset, k)
        G.add_edges_from(zip(([v] * len(targets)), targets))
    return nx.projected_graph(G, range(n))
inputs: def coerce_indexer_dtype(indexer, categories):
targets: """coerce the indexer input array to the smallest dtype possible
    """
    l = len(categories)
    if (l < _int8_max):
        return _ensure_int8(indexer)
    elif (l < _int16_max):
        return _ensure_int16(indexer)
    elif (l < _int32_max):
        return _ensure_int32(indexer)
    return _ensure_int64(indexer)
inputs: I wrote the below code

    cmd = ['shutdown', '-i', state, '-g', '0', '-y']
    ret = __salt__['cmd.run'](cmd, python_shell=False)
    return ret


What's a good function header?
targets: def init(state):
inputs: def do_with(parser, token):
targets: """Adds a value to the context (inside of this block) for caching and easy
    access.
    For example::
    {% with person.some_sql_method as total %}
    {{ total }} object{{ total|pluralize }}
    {% endwith %}
    """
    bits = list(token.split_contents())
    if ((len(bits) != 4) or (bits[2] != 'as')):
        raise TemplateSyntaxError(("%r    expected    format    is    'value    as    name'" % bits[0]))
    var = parser.compile_filter(bits[1])
    name = bits[3]
    nodelist = parser.parse(('endwith',))
    parser.delete_first_token()
    return WithNode(var, name, nodelist)
inputs: def _setup_constants(alphabet=NAMESPACE_CHARACTERS, max_length=MAX_NAMESPACE_LENGTH):
targets: """Calculate derived constant values. Only useful for testing.
    """
    global NAMESPACE_CHARACTERS
    global MAX_NAMESPACE_LENGTH
    global MAX_NAMESPACE
    global _LEX_DISTANCE
    NAMESPACE_CHARACTERS = alphabet
    MAX_NAMESPACE_LENGTH = max_length
    MAX_NAMESPACE = (NAMESPACE_CHARACTERS[(-1)] * MAX_NAMESPACE_LENGTH)
    _LEX_DISTANCE = [1]
    for i in range(1, MAX_NAMESPACE_LENGTH):
        _LEX_DISTANCE.append(((_LEX_DISTANCE[(i - 1)] * len(NAMESPACE_CHARACTERS)) + 1))
    del i
inputs: def check_api_key(key):
targets: """Validate an API key by calling an API endpoint with no quota cost
    """
    url = 'https://www.googleapis.com/youtube/v3/i18nLanguages'
    query = {'part': 'snippet', 'fields': 'items/id', 'key': key}
    try:
        urlopen(((url + '?') + urlencode(query))).read()
        message = (("The    key,    '" + key) + "'    will    now    be    used    for    API    requests.")
        pafy.set_api_key(Config.API_KEY.get)
        return dict(valid=True, message=message)
    except HTTPError:
        message = (("Invalid    key    or    quota    exceeded,    '" + key) + "'")
        return dict(valid=False, message=message)
inputs: def get_vmdk_adapter_type(adapter_type):
targets: """Return the adapter type to be used in vmdk descriptor.
    Adapter type in vmdk descriptor is same for LSI-SAS, LSILogic & ParaVirtual
    because Virtual Disk Manager API does not recognize the newer controller
    types.
    """
    if (adapter_type in [constants.ADAPTER_TYPE_LSILOGICSAS, constants.ADAPTER_TYPE_PARAVIRTUAL]):
        vmdk_adapter_type = constants.DEFAULT_ADAPTER_TYPE
    else:
        vmdk_adapter_type = adapter_type
    return vmdk_adapter_type
inputs: Complete the below
def getDeprecated(self, decorators):

    ''''With a list of decorators, and the object it is running on, set the
    C{_deprecated_info} flag if any of the decorators are a Twisted deprecation
    decorator.'
    '''
targets: for a in decorators:
        if isinstance(a, ast.CallFunc):
            decorator = a.asList()
            if isinstance(decorator[0], ast.Getattr):
                getAttr = decorator[0].asList()
                name = getAttr[0].name
                fn = ((self.expandName(name) + '.') + getAttr[1])
            else:
                fn = self.expandName(decorator[0].name)
            if (fn == 'twisted.python.deprecate.deprecated'):
                try:
                    self._deprecated_info = deprecatedToUsefulText(self.name, decorator)
                except AttributeError:
                    pass
inputs: Complete the below
def libvlc_media_library_new(p_instance):

    ''''Create an new Media Library object.
    @param p_instance: the libvlc instance.
    @return: a new object or NULL on error.'
    '''
targets: f = (_Cfunctions.get('libvlc_media_library_new', None) or _Cfunction('libvlc_media_library_new', ((1,),), class_result(MediaLibrary), ctypes.c_void_p, Instance))
    return f(p_instance)
inputs: def foobar_triangle(side_A, side_B, side_C):
targets: """This returns perimeter of a triangle.
    :param side_A:
    length of side_A
    :param side_B:
    length of side_B
    :param side_C:
    length of side_C
    :return: returns perimeter
    """
    return ((side_A + side_B) + side_C)
    triple_quote_string_literal_test = '\nThis    is    a    triple    quoted    string    and    is    not    a    valid    docstring.\n'
inputs: Complete the below
def _get_variables_to_train():

    ''''Returns a list of variables to train.
    Returns:
    A list of variables to train by the optimizer.'
    '''
targets: if (FLAGS.trainable_scopes is None):
        return tf.trainable_variables()
    else:
        scopes = [scope.strip() for scope in FLAGS.trainable_scopes.split(',')]
    variables_to_train = []
    for scope in scopes:
        variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)
        variables_to_train.extend(variables)
    return variables_to_train
inputs: I wrote the below code

    edges = _make_edges_3d(n_x, n_y, n_z)
    if (dtype is None):
        if (img is None):
            dtype = np.int
        else:
            dtype = img.dtype
    if (img is not None):
        img = np.atleast_3d(img)
        weights = _compute_gradient_3d(edges, img)
        if (mask is not None):
            (edges, weights) = _mask_edges_weights(mask, edges, weights)
            diag = img.squeeze()[mask]
        else:
            diag = img.ravel()
        n_voxels = diag.size
    else:
        if (mask is not None):
            mask = mask.astype(dtype=np.bool, copy=False)
            mask = np.asarray(mask, dtype=np.bool)
            edges = _mask_edges_weights(mask, edges)
            n_voxels = np.sum(mask)
        else:
            n_voxels = ((n_x * n_y) * n_z)
        weights = np.ones(edges.shape[1], dtype=dtype)
        diag = np.ones(n_voxels, dtype=dtype)
    diag_idx = np.arange(n_voxels)
    i_idx = np.hstack((edges[0], edges[1]))
    j_idx = np.hstack((edges[1], edges[0]))
    graph = sparse.coo_matrix((np.hstack((weights, weights, diag)), (np.hstack((i_idx, diag_idx)), np.hstack((j_idx, diag_idx)))), (n_voxels, n_voxels), dtype=dtype)
    if (return_as is np.ndarray):
        return graph.toarray()
    return return_as(graph)


What's a good function header?
targets: def _to_graph(n_x, n_y, n_z, mask=None, img=None, return_as=sparse.coo_matrix, dtype=None):
inputs: def GetMountpoints():
targets: """List all the filesystems mounted on the system.
    """
    devices = {}
    for filesys in GetFileSystems():
        devices[filesys.f_mntonname] = (filesys.f_mntfromname, filesys.f_fstypename)
    return devices
inputs: Complete the below
def getmacbyip(ip, chainCC=0):

    ''''Return MAC address corresponding to a given IP address'
    '''
targets: if isinstance(ip, Net):
        ip = iter(ip).next()
    tmp = map(ord, inet_aton(ip))
    if ((tmp[0] & 240) == 224):
        return ('01:00:5e:%.2x:%.2x:%.2x' % ((tmp[1] & 127), tmp[2], tmp[3]))
    (iff, a, gw) = conf.route.route(ip)
    if ((iff == LOOPBACK_NAME) or (ip == conf.route.get_if_bcast(iff))):
        return 'ff:ff:ff:ff:ff:ff'
    ifip = str(pcapdnet.dnet.intf().get(iff)['addr'])
    if (gw != ifip.split('/')[0]):
        ip = gw
    mac = conf.netcache.arp_cache.get(ip)
    if mac:
        return mac
    res = srp1((Ether(dst=ETHER_BROADCAST) / ARP(op='who-has', pdst=ip)), type=ETH_P_ARP, iface=iff, timeout=2, verbose=0, chainCC=chainCC, nofilter=1)
    if (res is not None):
        mac = res.payload.hwsrc
        conf.netcache.arp_cache[ip] = mac
        return mac
    return None
inputs: Complete the below
def make_subrequest(env, method=None, path=None, body=None, headers=None, agent='Swift', swift_source=None, make_env=make_env):

    ''''Makes a new swob.Request based on the current env but with the
    parameters specified.
    :param env: The WSGI environment to base the new request on.
    :param method: HTTP method of new request; default is from
    the original env.
    :param path: HTTP path of new request; default is from the
    original env. path should be compatible with what you
    would send to Request.blank. path should be quoted and it
    can include a query string. for example:
    \'/a%20space?unicode_str%E8%AA%9E=y%20es\'
    :param body: HTTP body of new request; empty by default.
    :param headers: Extra HTTP headers of new request; None by
    default.
    :param agent: The HTTP user agent to use; default \'Swift\'. You
    can put %(orig)s in the agent to have it replaced
    with the original env\'s HTTP_USER_AGENT, such as
    \'%(orig)s StaticWeb\'. You also set agent to None to
    use the original env\'s HTTP_USER_AGENT or \'\' to
    have no HTTP_USER_AGENT.
    :param swift_source: Used to mark the request as originating out of
    middleware. Will be logged in proxy logs.
    :param make_env: make_subrequest calls this make_env to help build the
    swob.Request.
    :returns: Fresh swob.Request object.'
    '''
targets: query_string = None
    path = (path or '')
    if (path and ('?' in path)):
        (path, query_string) = path.split('?', 1)
    newenv = make_env(env, method, path=unquote(path), agent=agent, query_string=query_string, swift_source=swift_source)
    if (not headers):
        headers = {}
    if body:
        return Request.blank(path, environ=newenv, body=body, headers=headers)
    else:
        return Request.blank(path, environ=newenv, headers=headers)
inputs: I wrote the below code

    op = node.op
    if (not isinstance(op, T.Rebroadcast)):
        return False
    input = node.inputs[0]
    inode = input.owner
    if (inode and isinstance(inode.op, Elemwise) and (len(inode.inputs) == 1)):
        if (hasattr(input, 'clients') and (len(input.clients) == 1)):
            rebroadcasted = T.Rebroadcast(*list(op.axis.items()))(inode.inputs[0])
            copy_stack_trace(node.outputs, rebroadcasted)
            rval = inode.op.make_node(rebroadcasted).outputs
            copy_stack_trace((node.outputs + node.inputs), rval)
            return rval
    if (inode and isinstance(inode.op, T.Rebroadcast)):
        axis = inode.op.axis.copy()
        axis.update(op.axis)
        iinput = inode.inputs[0]
        rval = [T.Rebroadcast(*list(axis.items()))(iinput)]
        copy_stack_trace((node.outputs + node.inputs), rval)
        return rval


What's a good function header?
targets: @register_canonicalize
@register_specialize
@gof.local_optimizer([T.Rebroadcast])
def local_rebroadcast_lift(node):
inputs: Complete the below
def flatten(lst):

    ''''flatten list or return scalar'
    '''
targets: if atomp(lst):
        return lst
    return _flatten(lst)
inputs: def main():
targets: """main entry point for module execution
    """
    argument_spec = dict(src=dict(type='path'), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), multiline_delimiter=dict(default='@'), force=dict(default=False, type='bool'), config=dict(), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), save=dict(default=False, type='bool'))
    mutually_exclusive = [('lines', 'src')]
    required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines'])]
    module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True)
    if (module.params['force'] is True):
        module.params['match'] = 'none'
    warnings = list()
    check_args(module, warnings)
    result = dict(changed=False, warnings=warnings)
    if module.params['backup']:
        result['__backup__'] = module.config.get_config()
    try:
        run(module, result)
    except NetworkError:
        exc = get_exception()
        module.disconnect()
        module.fail_json(msg=str(exc))
    module.disconnect()
    module.exit_json(**result)
inputs: Complete the below
def libvlc_media_player_has_vout(p_mi):

    ''''How many video outputs does this media player have?
    @param p_mi: the media player.
    @return: the number of video outputs.'
    '''
targets: f = (_Cfunctions.get('libvlc_media_player_has_vout', None) or _Cfunction('libvlc_media_player_has_vout', ((1,),), None, ctypes.c_uint, MediaPlayer))
    return f(p_mi)
inputs: I wrote the below code

    P = Vector(a[0], a[1])
    Q = Vector(b[0], b[1])
    R = Vector(c[0], c[1])
    mPQ = ((P + Q) * 0.5)
    mQR = ((Q + R) * 0.5)
    numer = (- (((((((((- mPQ.y) * R.y) + (mPQ.y * Q.y)) + (mQR.y * R.y)) - (mQR.y * Q.y)) - (mPQ.x * R.x)) + (mPQ.x * Q.x)) + (mQR.x * R.x)) - (mQR.x * Q.x)))
    denom = (((((((- Q.x) * R.y) + (P.x * R.y)) - (P.x * Q.y)) + (Q.y * R.x)) - (P.y * R.x)) + (P.y * Q.x))
    t = (numer / denom)
    cx = (((- t) * (Q.y - P.y)) + mPQ.x)
    cy = ((t * (Q.x - P.x)) + mPQ.y)
    return ((cx, cy), (P - (cx, cy)).length())


What's a good function header?
targets: def circumcircle(a, b, c):
inputs: def consistencygroup_destroy(context, consistencygroup_id):
targets: """Destroy the consistencygroup or raise if it does not exist.
    """
    return IMPL.consistencygroup_destroy(context, consistencygroup_id)
inputs: def _codec_fails_on_encode_surrogates(codec, _cache={}):
targets: """Returns if a codec fails correctly when passing in surrogates with
    a surrogatepass/surrogateescape error handler. Some codecs were broken
    in Python <3.4
    """
    try:
        return _cache[codec]
    except KeyError:
        try:
            u'\ud800\udc01'.encode(codec)
        except UnicodeEncodeError:
            _cache[codec] = True
        else:
            _cache[codec] = False
        return _cache[codec]
inputs: def keyname(vm_):
targets: """Return the keyname
    """
    return config.get_cloud_config_value('keyname', vm_, __opts__, search_global=False)
inputs: def _platform(*args):
targets: """Helper to format the platform string in a filename
    compatible format e.g. "system-version-machine".
    """
    platform = '-'.join((x.strip() for x in filter(len, args)))
    platform = platform.replace('    ', '_')
    platform = platform.replace('/', '-')
    platform = platform.replace('\\', '-')
    platform = platform.replace(':', '-')
    platform = platform.replace(';', '-')
    platform = platform.replace('"', '-')
    platform = platform.replace('(', '-')
    platform = platform.replace(')', '-')
    platform = platform.replace('unknown', '')
    while 1:
        cleaned = platform.replace('--', '-')
        if (cleaned == platform):
            break
        platform = cleaned
    while (platform[(-1)] == '-'):
        platform = platform[:(-1)]
    return platform
inputs: Complete the below
def get_sha256_str(base_str):

    ''''Returns string that represents sha256 hash of base_str (in hex format).
    sha1 and md5 are known to be breakable, so sha256 is a better option
    when the hash is being used for security purposes. If hashing passwords
    or anything else that needs to be retained for a long period a salted
    hash is better.'
    '''
targets: if isinstance(base_str, six.text_type):
        base_str = base_str.encode('utf-8')
    return hashlib.sha256(base_str).hexdigest()
inputs: Complete the below
def datatype(dbtype, description):

    ''''Helper to convert a data type into a string.'
    '''
targets: dt = connection.introspection.get_field_type(dbtype, description)
    if (type(dt) is tuple):
        return dt[0]
    else:
        return dt
inputs: Complete the below
@testing.requires_testing_data
def test_read_write_head_pos():

    ''''Test reading and writing head position quaternion parameters.'
    '''
targets: tempdir = _TempDir()
    temp_name = op.join(tempdir, 'temp.pos')
    head_pos_rand = np.random.RandomState(0).randn(20, 10)
    head_pos_read = read_head_pos(pos_fname)
    for head_pos_orig in (head_pos_rand, head_pos_read):
        write_head_pos(temp_name, head_pos_orig)
        head_pos = read_head_pos(temp_name)
        assert_allclose(head_pos_orig, head_pos, atol=0.001)
    assert_raises(TypeError, write_head_pos, 0, head_pos_read)
    assert_raises(ValueError, write_head_pos, temp_name, 'foo')
    assert_raises(ValueError, write_head_pos, temp_name, head_pos_read[:, :9])
    assert_raises(TypeError, read_head_pos, 0)
    assert_raises(IOError, read_head_pos, (temp_name + 'foo'))
inputs: Complete the below
def hex_decode(input, errors='strict'):

    ''''Decodes the object input and returns a tuple (output
    object, length consumed).
    input must be an object which provides the bf_getreadbuf
    buffer slot. Python strings, buffer objects and memory
    mapped files are examples of objects providing this slot.
    errors defines the error handling to apply. It defaults to
    \'strict\' handling which is the only currently supported
    error handling for this codec.'
    '''
targets: assert (errors == 'strict')
    output = binascii.a2b_hex(input)
    return (output, len(input))
inputs: I wrote the below code

    f = open('app.yaml', 'r')
    content = f.read()
    os.remove('app.yaml')
    content = content.replace('oppiaserver', APP_NAME)
    d = open('app.yaml', 'w+')
    d.write(content)
    if (not os.path.exists(DEPLOY_DATA_PATH)):
        raise Exception(('Could    not    find    deploy_data    directory    at    %s' % DEPLOY_DATA_PATH))
    for filename in FILES_AT_ROOT_IN_COMMON:
        src = os.path.join(DEPLOY_DATA_PATH, 'common', filename)
        dst = os.path.join(os.getcwd(), 'assets', 'common', filename)
        if (not os.path.exists(src)):
            raise Exception(('Could    not    find    source    path    %s.    Please    check    your    deploy_data    folder.' % src))
        if (not os.path.exists(dst)):
            raise Exception(('Could    not    find    destination    path    %s.    Has    the    code    been    updated    in    the    meantime?' % dst))
        shutil.copyfile(src, dst)
    for dir_name in IMAGE_DIRS:
        src_dir = os.path.join(DEPLOY_DATA_PATH, 'images', dir_name)
        dst_dir = os.path.join(os.getcwd(), 'assets', 'images', dir_name)
        if (not os.path.exists(src_dir)):
            raise Exception(('Could    not    find    source    dir    %s.    Please    check    your    deploy_data    folder.' % src_dir))
        common.ensure_directory_exists(dst_dir)
        for filename in os.listdir(src_dir):
            src = os.path.join(src_dir, filename)
            dst = os.path.join(dst_dir, filename)
            shutil.copyfile(src, dst)


What's a good function header?
targets: def preprocess_release():
inputs: Complete the below
@library.global_function
def wiki_url(path):

    ''''Create a URL pointing to Kuma.
    Look for a wiki page in the current locale, or default to given path'
    '''
targets: if ('#' in path):
        (slug, fragment) = path.split('#', 1)
    else:
        slug = path
        fragment = ''
    new_path = reverse('wiki.document', args=[slug])
    if fragment:
        new_path += ('#' + fragment)
    return new_path
inputs: I wrote the below code

    item_status = get_object_or_404(ItemStatus, pk=status_id)
    if (not request.user.profile.has_permission(item_status, mode='w')):
        return user_denied(request, message="You    don't    have    access    to    this    Item    Status", response_format=response_format)
    if request.POST:
        if ('delete' in request.POST):
            if ('trash' in request.POST):
                item_status.trash = True
                item_status.save()
            else:
                item_status.delete()
            return HttpResponseRedirect(reverse('infrastructure_settings_view'))
        elif ('cancel' in request.POST):
            return HttpResponseRedirect(reverse('infrastructure_item_view', args=[item_status.id]))
    context = _get_default_context(request)
    context.update({'item_status': item_status})
    return render_to_response('infrastructure/item_status_delete', context, context_instance=RequestContext(request), response_format=response_format)


What's a good function header?
targets: @treeio_login_required
@handle_response_format
def status_delete(request, status_id, response_format='html'):
inputs: Complete the below
def ensure_list(indices):

    ''''Return a list, even if indices is a single value
    :arg indices: A list of indices to act upon
    :rtype: list'
    '''
targets: if (not isinstance(indices, list)):
        indices = [indices]
    return indices
inputs: I wrote the below code

    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)
    async_add_devices([TOTPSensor(name, token)], True)
    return True


What's a good function header?
targets: @asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
inputs: I wrote the below code

    image = np.arange(0, 255, 4, np.uint8).reshape((8, 8))
    expected = np.array([[0, 5, 11, 16, 22, 27, 33, 38], [43, 48, 53, 58, 63, 68, 73, 77], [82, 86, 91, 95, 100, 104, 109, 113], [117, 121, 125, 129, 133, 137, 141, 145], [149, 153, 157, 160, 164, 168, 172, 175], [179, 182, 186, 189, 193, 196, 199, 203], [206, 209, 213, 216, 219, 222, 225, 228], [231, 234, 238, 241, 244, 246, 249, 252]], dtype=np.uint8)
    result = exposure.adjust_log(image, 1)
    assert_array_equal(result, expected)


What's a good function header?
targets: def test_adjust_log():
inputs: def _parse_header(fh):
targets: """Reads the font metrics header (up to the char metrics) and returns
    a dictionary mapping *key* to *val*.  *val* will be converted to the
    appropriate python type as necessary; e.g.:
    * \False\->False
    * \0\->0
    * \-168 -218 1000 898\-> [-168, -218, 1000, 898]
    Dictionary keys are
    StartFontMetrics, FontName, FullName, FamilyName, Weight,
    ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,
    UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,
    XHeight, Ascender, Descender, StartCharMetrics
    """
    headerConverters = {'StartFontMetrics': _to_float, 'FontName': _to_str, 'FullName': _to_str, 'FamilyName': _to_str, 'Weight': _to_str, 'ItalicAngle': _to_float, 'IsFixedPitch': _to_bool, 'FontBBox': _to_list_of_ints, 'UnderlinePosition': _to_int, 'UnderlineThickness': _to_int, 'Version': _to_str, 'Notice': _to_str, 'EncodingScheme': _to_str, 'CapHeight': _to_float, 'Capheight': _to_float, 'XHeight': _to_float, 'Ascender': _to_float, 'Descender': _to_float, 'StdHW': _to_float, 'StdVW': _to_float, 'StartCharMetrics': _to_int, 'CharacterSet': _to_str, 'Characters': _to_int}
    d = {}
    for line in fh:
        line = line.rstrip()
        if line.startswith('Comment'):
            continue
        lst = line.split('    ', 1)
        key = lst[0]
        if (len(lst) == 2):
            val = lst[1]
        else:
            val = ''
        try:
            d[key] = headerConverters[key](val)
        except ValueError:
            print(u'Value    error    parsing    header    in    AFM:', key, val, file=sys.stderr)
            continue
        except KeyError:
            print((u'Found    an    unknown    keyword    in    AFM    header    (was    %r)' % key), file=sys.stderr)
            continue
        if (key == 'StartCharMetrics'):
            return d
    raise RuntimeError(u'Bad    parse')
inputs: Complete the below
def EC2Token_filter_factory(global_conf, **local_conf):

    ''''Factory method for paste.deploy.'
    '''
targets: conf = global_conf.copy()
    conf.update(local_conf)
    def filter(app):
        return EC2Token(app, conf)
    return filter
inputs: I wrote the below code

    from distutils.version import StrictVersion
    from distutils.spawn import find_executable
    import re
    gcc_exe = find_executable('gcc')
    if gcc_exe:
        out = os.popen((gcc_exe + '    -dumpversion'), 'r')
        try:
            out_string = out.read()
        finally:
            out.close()
        result = re.search('(\\d+\\.\\d+\\.\\d+)', out_string)
        if result:
            gcc_version = StrictVersion(result.group(1))
        else:
            gcc_version = None
    else:
        gcc_version = None
    ld_version = None
    return (gcc_version, ld_version)


What's a good function header?
targets: def get_versions():
inputs: @frappe.whitelist()
def install_app(name):
targets: """Install app, if app is not installed in local environment, install it via git url in
    `frappe/data/app_listing/`
    """
    frappe.only_for(u'System    Manager')
    if (name not in frappe.get_all_apps(True)):
        if (not frappe.conf.disallow_app_listing):
            get_app(name)
            frappe.cache().delete_value([u'app_hooks'])
            import site
            reload(site)
        else:
            frappe.throw(_(u'Listing    app    not    allowed'))
    app_hooks = frappe.get_hooks(app_name=name)
    if app_hooks.get(u'hide_in_installer'):
        frappe.throw(_(u'You    cannot    install    this    app'))
    enqueue(u'frappe.desk.page.applications.applications.start_install', name=name)
    frappe.msgprint(_(u'Queued    for    install'))
inputs: Complete the below
@given(u'a    run    having    mixed    text    content')
def given_a_run_having_mixed_text_content(context):

    ''''Mixed here meaning it contains ``<w:tab/>``, ``<w:cr/>``, etc. elements.'
    '''
targets: r_xml = (u'                                <w:r    %s>\n                                        <w:t>abc</w:t>\n                                        <w:tab/>\n                                        <w:t>def</w:t>\n                                        <w:cr/>\n                                        <w:t>ghi</w:t>\n                                        <w:drawing/>\n                                        <w:br/>\n                                        <w:t>jkl</w:t>\n                                </w:r>' % nsdecls(u'w'))
    r = parse_xml(r_xml)
    context.run = Run(r, None)
inputs: Complete the below
def cast_to_server(context, server_params, topic, msg):

    ''''Invoke a remote method that does not return anything.
    :param context: Information that identifies the user that has made this
    request.
    :param server_params: Connection information
    :param topic: The topic to send the notification to.
    :param msg: This is a dict in the form { "method" : "method_to_invoke",
    "args" : dict_of_kwargs }
    :returns: None'
    '''
targets: return _get_impl().cast_to_server(CONF, context, server_params, topic, msg)
inputs: I wrote the below code

    for image in images:
        box = [0, 0, image.size[0], image.size[1]]
        if (border is not None):
            for (idx, val) in enumerate(box):
                box[idx] = max(0, (val - border))
            click.echo(('Cropping    "%s"    by    %dpx' % (image.filename, border)))
            (yield copy_filename(image.crop(box), image))
        else:
            (yield image)


What's a good function header?
targets: @cli.command('crop')
@click.option('-b', '--border', type=int, help='Crop    the    image    from    all    sides    by    this    amount.')
@processor
def crop_cmd(images, border):
inputs: Complete the below
def format_header_param(name, value):

    ''''Helper function to format and quote a single header parameter.
    Particularly useful for header parameters which might contain
    non-ASCII values, like file names. This follows RFC 2231, as
    suggested by RFC 2388 Section 4.4.
    :param name:
    The name of the parameter, a string expected to be ASCII only.
    :param value:
    The value of the parameter, provided as a unicode string.'
    '''
targets: if (not any(((ch in value) for ch in '"\\\r\n'))):
        result = ('%s="%s"' % (name, value))
        try:
            result.encode('ascii')
        except (UnicodeEncodeError, UnicodeDecodeError):
            pass
        else:
            return result
    if ((not six.PY3) and isinstance(value, six.text_type)):
        value = value.encode('utf-8')
    value = email.utils.encode_rfc2231(value, 'utf-8')
    value = ('%s*=%s' % (name, value))
    return value
inputs: Complete the below
def get_service(hass, config, discovery_info=None):

    ''''Get the CiscoSpark notification service.'
    '''
targets: return CiscoSparkNotificationService(config.get(CONF_TOKEN), config.get(CONF_ROOMID))
inputs: I wrote the below code

    old_keys = set(old_module_dict.keys())
    new_keys = set(new_module_dict.keys())
    for deleted_module_name in (old_keys - new_keys):
        if (old_module_dict[deleted_module_name] is None):
            continue
        segments = deleted_module_name.rsplit('.', 1)
        if (len(segments) == 2):
            parent_module = new_module_dict.get(segments[0])
            if (parent_module and hasattr(parent_module, segments[1])):
                delattr(parent_module, segments[1])
    for added_module_name in (new_keys - old_keys):
        if (new_module_dict[added_module_name] is None):
            continue
        segments = added_module_name.rsplit('.', 1)
        if (len(segments) == 2):
            parent_module = old_module_dict.get(segments[0])
            child_module = new_module_dict[added_module_name]
            if (parent_module and (getattr(parent_module, segments[1], None) is not child_module)):
                setattr(parent_module, segments[1], child_module)


What's a good function header?
targets: def ConnectAndDisconnectChildModules(old_module_dict, new_module_dict):
inputs: def _object_matcher(obj):
targets: """Retrieve a matcher function by passing an arbitrary object.
    i.e. passing a `TreeElement` such as a `Clade` or `Tree` instance returns an
    identity matcher, passing a type such as the `PhyloXML.Taxonomy` class
    returns a class matcher, and passing a dictionary returns an attribute
    matcher.
    The resulting \match\ function returns True when given an object matching
    the specification (identity, type or attribute values), otherwise False.
    This is useful for writing functions that search the tree, and probably
    shouldn\t be used directly by the end user.
    """
    if isinstance(obj, TreeElement):
        return _identity_matcher(obj)
    if isinstance(obj, type):
        return _class_matcher(obj)
    if isinstance(obj, basestring):
        return _string_matcher(obj)
    if isinstance(obj, dict):
        return _attribute_matcher(obj)
    if callable(obj):
        return _function_matcher(obj)
    raise ValueError(('%s    (type    %s)    is    not    a    valid    type    for    comparison.' % (obj, type(obj))))
inputs: Complete the below
def inject_into_urllib3():

    ''''Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'
    '''
targets: connectionpool.ssl_wrap_socket = ssl_wrap_socket
    util.HAS_SNI = HAS_SNI
inputs: def _uninstall_helper(verbosity=0):
targets: """Helper to support a clean default uninstall process on Windows
    Note that calling this function may alter os.environ.
    """
    try:
        import pip
    except ImportError:
        return
    if (pip.__version__ != _PIP_VERSION):
        msg = 'ensurepip    will    only    uninstall    a    matching    version    ({!r}    installed,    {!r}    bundled)'
        print(msg.format(pip.__version__, _PIP_VERSION), file=sys.stderr)
        return
    _require_ssl_for_pip()
    _disable_pip_configuration_settings()
    args = ['uninstall', '-y', '--disable-pip-version-check']
    if verbosity:
        args += [('-' + ('v' * verbosity))]
    _run_pip((args + [p[0] for p in reversed(_PROJECTS)]))
inputs: Complete the below
def _clean_credentials(credentials):

    ''''Cleans a dictionary of credentials of potentially sensitive info before
    sending to less secure functions.
    Not comprehensive - intended for user_login_failed signal'
    '''
targets: SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
    CLEANSED_SUBSTITUTE = '********************'
    for key in credentials:
        if SENSITIVE_CREDENTIALS.search(key):
            credentials[key] = CLEANSED_SUBSTITUTE
    return credentials
inputs: Complete the below
def choose_best_location(locations, **kwargs):

    ''''Choose best location from image location list by configured strategy.
    :param locations: The original image location list.
    :param kwargs: Strategy-specific arguments for under layer strategy module.
    :returns: The best location from image location list.'
    '''
targets: locations = get_ordered_locations(locations, **kwargs)
    if locations:
        return locations[0]
    else:
        return None
inputs: I wrote the below code

    fig = plt.figure()
    ax1 = plt.subplot2grid((3, 3), (0, 0))
    ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
    ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
    ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
    example_plot(ax1)
    example_plot(ax2)
    example_plot(ax3)
    example_plot(ax4)
    plt.tight_layout()


What's a good function header?
targets: @image_comparison(baseline_images=[u'tight_layout4'], freetype_version=(u'2.5.5', u'2.6.1'))
def test_tight_layout4():