Muennighoff/xP3x-sample huggingface dataset:
inputs: Complete the below
def any_to_tensor_and_labels(x, labels=None):

    ''''Util for converting input x to tensor trying to
    create labels for columns if they are not provided.
    Default names for columns are [\'x0\', \'x1\', ...], for mappable
    arrays (e.g. pd.DataFrame) their names are treated as labels.
    You can override them with `labels` argument.
    If you have tensor input you should provide labels as we
    cannot get their shape directly
    If you pass dict input we cannot rely on labels order thus dict
    keys are treated as labels anyway
    Parameters
    x : np.ndarray | pd.DataFrame | tt.Variable | dict | list
    labels : list - names for columns of output tensor
    Returns
    (x, labels) - tensor and labels for its columns'
    '''
targets: if isinstance(labels, six.string_types):
        labels = [labels]
    if isinstance(x, pd.DataFrame):
        if (not labels):
            labels = x.columns
        x = x.as_matrix()
    elif isinstance(x, pd.Series):
        if (not labels):
            labels = [x.name]
        x = x.as_matrix()[:, None]
    elif isinstance(x, dict):
        try:
            x = pd.DataFrame.from_dict(x)
            labels = x.columns
            x = x.as_matrix()
        except (ValueError, TypeError):
            res = []
            labels = []
            for (k, v) in x.items():
                res.append(v)
                labels.append(k)
            x = tt.stack(res, axis=1)
            if (x.ndim == 1):
                x = x[:, None]
    elif (not isinstance(x, tt.Variable)):
        x = np.asarray(x)
        if (x.ndim == 0):
            raise ValueError('Cannot    use    scalars')
        elif (x.ndim == 1):
            x = x[:, None]
    elif (labels is not None):
        x = tt.as_tensor_variable(x)
        if (x.ndim == 0):
            raise ValueError('Cannot    use    scalars')
        elif (x.ndim == 1):
            x = x[:, None]
    else:
        pass
    if ((labels is None) and (not isinstance(x, tt.Variable))):
        labels = [('x%d' % i) for i in range(x.shape[1])]
    elif (labels is None):
        raise ValueError('Please    provide    labels    as    we    cannot    infer    shape    of    input')
    else:
        pass
    if (not isinstance(x, tt.Variable)):
        if (not (len(labels) == x.shape[1])):
            raise ValueError(('Please    provide    full    list    of    labels    for    coefficients,    got    len(labels)=%d    instead    of    %d' % (len(labels), x.shape[1])))
    else:
        pass
    if isinstance(labels, pd.RangeIndex):
        labels = [('x%d' % i) for i in labels]
    elif (not isinstance(labels, list)):
        labels = list(labels)
    if (not isinstance(x, tt.Variable)):
        x = tt.as_tensor_variable(x)
        if (x.ndim == 0):
            raise...
inputs: def RebuildProxy(func, token, serializer, kwds):
targets: """Function used for unpickling proxy objects.
    If possible the shared object is returned, or otherwise a proxy for it.
    """
    server = getattr(current_process(), '_manager_server', None)
    if (server and (server.address == token.address)):
        return server.id_to_obj[token.id][0]
    else:
        incref = (kwds.pop('incref', True) and (not getattr(current_process(), '_inheriting', False)))
        return func(token, serializer, incref=incref, **kwds)
inputs: def create_cmd(args, basename_binary=False):
targets: """Takes an array of strings to be passed to subprocess.Popen and creates
    a string that can be pasted into a terminal
    :param args:
    The array containing the binary name/path and all arguments
    :param basename_binary:
    If only the basename of the binary should be disabled instead of the full path
    :return:
    The command string
    """
    if basename_binary:
        args[0] = os.path.basename(args[0])
    if (os.name == 'nt'):
        return subprocess.list2cmdline(args)
    else:
        escaped_args = []
        for arg in args:
            if (re.search('^[a-zA-Z0-9/_^\\-\\.:=]+$', arg) is None):
                arg = ((u"'" + arg.replace(u"'", u"'\\''")) + u"'")
            escaped_args.append(arg)
        return u'    '.join(escaped_args)
inputs: def get_cert_days(module, cert_file):
targets: """Return the days the certificate in cert_file remains valid and -1
    if the file was not found.
    """
    if (not os.path.exists(cert_file)):
        return (-1)
    openssl_bin = module.get_bin_path('openssl', True)
    openssl_cert_cmd = [openssl_bin, 'x509', '-in', cert_file, '-noout', '-text']
    (_, out, _) = module.run_command(openssl_cert_cmd, check_rc=True)
    try:
        not_after_str = re.search('\\s+Not    After\\s*:\\s+(.*)', out.decode('utf8')).group(1)
        not_after = datetime.datetime.fromtimestamp(time.mktime(time.strptime(not_after_str, '%b    %d    %H:%M:%S    %Y    %Z')))
    except AttributeError:
        module.fail_json(msg="No    'Not    after'    date    found    in    {0}".format(cert_file))
    except ValueError:
        module.fail_json(msg="Failed    to    parse    'Not    after'    date    of    {0}".format(cert_file))
    now = datetime.datetime.utcnow()
    return (not_after - now).days
inputs: def isValidColor(color):
targets: """check color validity (equivalent to existing checks in _setColor)
    """
    try:
        color = float(color)
        return True
    except Exception:
        if (isinstance(color, basestring) and len(color)):
            return ((color.lower() in list(colors255.keys())) or (color[0] == '#') or (color[0:2] == '0x'))
        return ((type(color) in [tuple, list, numpy.ndarray]) or (not color))
inputs: I wrote the below code

    (C, J, v) = ([], ([0] * len(E)), (u - 1))
    for h in H:
        c = dmp_one(v, K)
        d = (dup_LC(h, K) * cs)
        for i in reversed(range(len(E))):
            (k, e, (t, _)) = (0, E[i], T[i])
            while (not (d % e)):
                (d, k) = ((d // e), (k + 1))
            if (k != 0):
                (c, J[i]) = (dmp_mul(c, dmp_pow(t, k, v, K), v, K), 1)
        C.append(c)
    if any(((not j) for j in J)):
        raise ExtraneousFactors
    (CC, HH) = ([], [])
    for (c, h) in zip(C, H):
        d = dmp_eval_tail(c, A, v, K)
        lc = dup_LC(h, K)
        if K.is_one(cs):
            cc = (lc // d)
        else:
            g = K.gcd(lc, d)
            (d, cc) = ((d // g), (lc // g))
            (h, cs) = (dup_mul_ground(h, d, K), (cs // d))
        c = dmp_mul_ground(c, cc, v, K)
        CC.append(c)
        HH.append(h)
    if K.is_one(cs):
        return (f, HH, CC)
    (CCC, HHH) = ([], [])
    for (c, h) in zip(CC, HH):
        CCC.append(dmp_mul_ground(c, cs, v, K))
        HHH.append(dmp_mul_ground(h, cs, 0, K))
    f = dmp_mul_ground(f, (cs ** (len(H) - 1)), u, K)
    return (f, HHH, CCC)


What's a good function header?
targets: def dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K):
inputs: Complete the below
def inverse(x, n):

    ''''Returns x^-1 (mod n)
    >>> inverse(7, 4)
    3
    >>> (inverse(143, 4) * 143) % 4
    1'
    '''
targets: (divider, inv, _) = extended_gcd(x, n)
    if (divider != 1):
        raise ValueError(('x    (%d)    and    n    (%d)    are    not    relatively    prime' % (x, n)))
    return inv
inputs: @register.tag
def debug(parser, token):
targets: """Outputs a whole load of debugging information, including the current
    context and imported modules.
    Sample usage::
    <pre>
    {% debug %}
    </pre>
    """
    return DebugNode()
inputs: I wrote the below code

    message_settings = MessageSettings.query.filter_by(action=EVENT_ROLE).first()
    if ((not message_settings) or (message_settings.mail_status == 1)):
        subject = MAILS[EVENT_ROLE]['subject'].format(role=role, event=event)
        message = MAILS[EVENT_ROLE]['message'].format(email=email, role=role, event=event, link=link)
        send_email(to=email, action=EVENT_ROLE, subject=subject, html=message)


What's a good function header?
targets: def send_email_for_event_role_invite(email, role, event, link):
inputs: I wrote the below code

    assert (u.Mbit is u.Mb)
    assert (u.megabit is u.Mb)
    assert (u.Mbyte is u.MB)
    assert (u.megabyte is u.MB)


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

    if (version is None):
        from wiki import VERSION as version
    else:
        assert (len(version) == 5)
        assert (version[3] in (u'alpha', u'beta', u'rc', u'final'))
    return version


What's a good function header?
targets: def get_complete_version(version=None):
inputs: def _import_module(name):
targets: """Import module, returning the module after the last dot.
    """
    __import__(name)
    return sys.modules[name]
inputs: I wrote the below code

    matching_headers = find_matching_headers(name, headers)
    return ','.join((str(headers[h]) for h in matching_headers if (headers[h] is not None)))


What's a good function header?
targets: def merge_headers_by_name(name, headers):
inputs: Complete the below
def _cql_from_cass_type(cass_type):

    ''''A string representation of the type for this column, such as "varchar"
    or "map<string, int>".'
    '''
targets: if issubclass(cass_type, types.ReversedType):
        return cass_type.subtypes[0].cql_parameterized_type()
    else:
        return cass_type.cql_parameterized_type()
inputs: I wrote the below code

    __tracebackhide__ = True
    raise Skipped(msg=msg)


What's a good function header?
targets: def skip(msg=''):
inputs: I wrote the below code

    r = re.compile(CONF_VARIABLE_REGEX)
    def sub(s, depth=0):
        if (depth > 100):
            logging.warn(('Max    recursion    depth    exceeded    when    substituting    jobconf    value:    %s' % s))
            return s
        m = r.search(s)
        if m:
            for g in [g for g in m.groups() if (g in conf)]:
                substr = ('${%s}' % g)
                s = s.replace(substr, sub(conf[g], (depth + 1)))
        return s
    for (k, v) in conf.items():
        conf[k] = sub(v)
    return conf


What's a good function header?
targets: def make_substitutions(conf):
inputs: I wrote the below code

    if (not hasattr(sys, 'frozen')):
        return os.listdir(path)
    (zipPath, archivePath) = splitZip(path)
    if (archivePath is None):
        return os.listdir(path)
    with zipfile.ZipFile(zipPath, 'r') as zipobj:
        contents = zipobj.namelist()
    results = set()
    for name in contents:
        if (name.startswith(archivePath) and (len(name) > len(archivePath))):
            name = name[len(archivePath):].split('/')[0]
            results.add(name)
    return list(results)


What's a good function header?
targets: def listdir(path):
inputs: def get_doc_with_call_signature(scope_node):
targets: """Return a document string including call signature.
    """
    call_signature = None
    if (scope_node.type == 'classdef'):
        for funcdef in scope_node.iter_funcdefs():
            if (funcdef.name.value == '__init__'):
                call_signature = get_call_signature(funcdef, call_string=scope_node.name.value)
    elif (scope_node.type in ('funcdef', 'lambdef')):
        call_signature = get_call_signature(scope_node)
    doc = clean_scope_docstring(scope_node)
    if (call_signature is None):
        return doc
    return ('%s\n\n%s' % (call_signature, doc))
inputs: I wrote the below code

    TextTestRunner(verbosity=verbosity).run(suite())


What's a good function header?
targets: def run(verbosity=1):
inputs: def availability_zone_list(request):
targets: """Utility method to retrieve a list of availability zones.
    """
    try:
        if api.cinder.extension_supported(request, 'AvailabilityZones'):
            return api.cinder.availability_zone_list(request)
        return []
    except Exception:
        exceptions.handle(request, _('Unable    to    retrieve    volumes    availability    zones.'))
        return []
inputs: @_ignore_in_changes
def delete_note(workspace_name, note_id):
targets: """Delete the note of id note_id on workspace workspace_name.
    Return the json response from the server.
    """
    return server.delete_note(workspace_name, note_id)
inputs: @public
def invert(f, g, *gens, **args):
targets: """Invert ``f`` modulo ``g`` when possible.
    Examples
    >>> from sympy import invert, S
    >>> from sympy.core.numbers import mod_inverse
    >>> from sympy.abc import x
    >>> invert(x**2 - 1, 2*x - 1)
    -4/3
    >>> invert(x**2 - 1, x - 1)
    Traceback (most recent call last):
    NotInvertible: zero divisor
    For more efficient inversion of Rationals,
    use the ``mod_inverse`` function:
    >>> mod_inverse(3, 5)
    2
    >>> (S(2)/5).invert(S(7)/3)
    5/2
    See Also
    sympy.core.numbers.mod_inverse
    """
    options.allowed_flags(args, ['auto', 'polys'])
    try:
        ((F, G), opt) = parallel_poly_from_expr((f, g), *gens, **args)
    except PolificationFailed as exc:
        (domain, (a, b)) = construct_domain(exc.exprs)
        try:
            return domain.to_sympy(domain.invert(a, b))
        except NotImplementedError:
            raise ComputationFailed('invert', 2, exc)
    h = F.invert(G, auto=opt.auto)
    if (not opt.polys):
        return h.as_expr()
    else:
        return h
inputs: @register.assignment_tag
def assignment_one_default(one, two='hi'):
targets: """Expected assignment_one_default __doc__
    """
    return ('assignment_one_default    -    Expected    result:    %s,    %s' % (one, two))
inputs: Complete the below
@coroutine
def component1(reactor, session):

    ''''A first component, which gets called "setup-like". When
    it returns, this signals that the component is ready for work.'
    '''
targets: (yield session.expose(api))
inputs: Complete the below
def list_available():

    ''''List available features to install
    Returns:
    str: A list of available features as returned by the
    ``Get-WindowsFeature`` PowerShell command
    CLI Example:
    .. code-block:: bash
    salt \'*\' win_servermanager.list_available'
    '''
targets: cmd = 'Import-Module    ServerManager;    Get-WindowsFeature    -ErrorAction    SilentlyContinue    -WarningAction    SilentlyContinue'
    return __salt__['cmd.shell'](cmd, shell='powershell')
inputs: Complete the below
def make_instance_save(instance, fields, fail_message):

    ''''Returns the save() method for a Form.'
    '''
targets: def save(self, commit=True):
        return save_instance(self, instance, fields, fail_message, commit)
    return save
inputs: I wrote the below code

    (c, lower) = c_and_lower
    if check_finite:
        b1 = asarray_chkfinite(b)
        c = asarray_chkfinite(c)
    else:
        b1 = asarray(b)
        c = asarray(c)
    if ((c.ndim != 2) or (c.shape[0] != c.shape[1])):
        raise ValueError('The    factored    matrix    c    is    not    square.')
    if (c.shape[1] != b1.shape[0]):
        raise ValueError('incompatible    dimensions.')
    overwrite_b = (overwrite_b or _datacopied(b1, b))
    (potrs,) = get_lapack_funcs(('potrs',), (c, b1))
    (x, info) = potrs(c, b1, lower=lower, overwrite_b=overwrite_b)
    if (info != 0):
        raise ValueError(('illegal    value    in    %d-th    argument    of    internal    potrs' % (- info)))
    return x


What's a good function header?
targets: def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):
inputs: def custom_object_scope(*args):
targets: """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape.
    Convenience wrapper for `CustomObjectScope`.
    Code within a `with` statement will be able to access custom objects
    by name. Changes to global custom objects persist
    within the enclosing `with` statement. At end of the `with` statement,
    global custom objects are reverted to state
    at beginning of the `with` statement.
    # Example
    Consider a custom object `MyObject`
    ```python
    with custom_object_scope({\MyObject\:MyObject}):
    layer = Dense(..., kernel_regularizer=\MyObject\)
    # save, load, etc. will recognize custom object by name
    # Arguments
    *args: Variable length list of dictionaries of name,
    class pairs to add to custom objects.
    # Returns
    Object of type `CustomObjectScope`.
    """
    return CustomObjectScope(*args)
inputs: I wrote the below code

    grid = DiagramGrid(diagram, groups, **hints)
    drawer = XypicDiagramDrawer()
    return drawer.draw(diagram, grid, masked, diagram_format)


What's a good function header?
targets: def xypic_draw_diagram(diagram, masked=None, diagram_format='', groups=None, **hints):
inputs: def NotUnicode(string):
targets: """Make sure a string is NOT unicode.
    """
    if isinstance(string, unicode):
        string = string.encode('utf-8')
    if (not isinstance(string, str)):
        return str(string)
    return string
inputs: def MoveFiles(rebalance, is_master):
targets: """Commit the received files into the database.
    """
    loc = data_store.DB.Location()
    if (not os.path.exists(loc)):
        return False
    if (not os.path.isdir(loc)):
        return False
    tempdir = _CreateDirectory(loc, rebalance.id)
    remove_file = _FileWithRemoveList(loc, rebalance)
    to_remove = []
    if os.path.exists(remove_file):
        to_remove = [line.decode('utf8').rstrip('\n') for line in open(remove_file, 'rb')]
    for fname in to_remove:
        if (not fname.startswith(loc)):
            logging.warning('Wrong    file    to    remove:    %s', fname)
            continue
        if (not os.path.exists(fname)):
            logging.warning('File    does    not    exist:    %s', fname)
            continue
        if (not os.path.isfile(fname)):
            logging.warning('Not    a    file:    %s', fname)
            continue
        os.unlink(fname)
        logging.info('Removing    file    %s', fname)
    try:
        os.unlink(remove_file)
    except OSError:
        pass
    try:
        _RecMoveFiles(tempdir, loc, '')
    except OSError:
        return False
    if (not is_master):
        if tempdir.startswith(loc):
            shutil.rmtree(tempdir)
    return True
inputs: def cached_resource(url, base_dir, force=False, max_size=250, directory=u'cached_resources'):
targets: """Caches a remote resource to local filesystem. Return a tuple of local file name and mime type, use primarily
    for API/WebUI.
    :param url: Resource URL
    :param force: Does not check for existence of cached resource, fetches the remote URL, ignores directory size limit
    :param max_size: Maximum allowed size of directory, in MB.
    :param directory: Name of directory to use. Default is `cached_resources`
    :return: Tuple of file path and mime type
    """
    mime_type = None
    hashed_name = hashlib.md5(url.encode(u'utf-8')).hexdigest()
    file_path = os.path.join(base_dir, directory, hashed_name)
    directory = os.path.dirname(file_path)
    if ((not os.path.exists(file_path)) or force):
        log.debug(u'caching    %s', url)
        response = requests.get(url)
        response.raise_for_status()
        mime_type = response.headers.get(u'content-type')
        content = response.content
        if (not os.path.exists(directory)):
            os.makedirs(directory)
        size = (dir_size(directory) / (1024 * 1024.0))
        if (not force):
            while (size >= max_size):
                log.debug(u'directory    %s    size    is    over    the    allowed    limit    of    %s,    trimming', size, max_size)
                trim_dir(directory)
                size = (dir_size(directory) / (1024 * 1024.0))
        with io.open(file_path, u'wb') as file:
            file.write(content)
    return (file_path, mime_type)
inputs: I wrote the below code

    _col_name_map = col_name_map
    if (join_type not in (u'inner', u'exact', u'outer')):
        raise ValueError(u"join_type    arg    must    be    either    'inner',    'exact'    or    'outer'")
    if (table_names is None):
        table_names = [u'{0}'.format((ii + 1)) for ii in range(len(arrays))]
    if (len(arrays) != len(table_names)):
        raise ValueError(u'Number    of    arrays    must    match    number    of    table_names')
    if (len(arrays) == 1):
        return arrays[0]
    col_name_map = get_col_name_map(arrays, [], uniq_col_name, table_names)
    arr_lens = [len(arr) for arr in arrays]
    if (join_type == u'exact'):
        if (len(set(arr_lens)) > 1):
            raise TableMergeError(u"Inconsistent    number    of    rows    in    input    arrays    (use    'inner'    or    'outer'    join_type    to    allow    non-matching    rows)")
        join_type = u'outer'
    if (join_type == u'inner'):
        min_arr_len = min(arr_lens)
        if (len(set(arr_lens)) > 1):
            arrays = [arr[:min_arr_len] for arr in arrays]
        arr_lens = [min_arr_len for arr in arrays]
    masked = (any((getattr(arr, u'masked', False) for arr in arrays)) or (len(set(arr_lens)) > 1))
    n_rows = max(arr_lens)
    out = _get_out_class(arrays)(masked=masked)
    for (out_name, in_names) in six.iteritems(col_name_map):
        for (name, array, arr_len) in zip(in_names, arrays, arr_lens):
            if (name is None):
                continue
            if (n_rows > arr_len):
                indices = np.arange(n_rows)
                indices[arr_len:] = 0
                out[out_name] = array[name][indices]
                try:
                    out[out_name].mask[arr_len:] = True
                except ValueError:
                    raise NotImplementedError(u"hstack    requires    masking    column    '{}'    but    column    type    {}    does    not    support    masking".format(out_name, out[out_name].__class__.__name__))
            else:
                out[out_name] =...

What's a good function header?
targets: def _hstack(arrays, join_type=u'outer', uniq_col_name=u'{col_name}_{table_name}', table_names=None, col_name_map=None):
inputs: I wrote the below code

    def wrap(self, name, value):
        paramcache = self.cache_choiceparams(name)
        old = self.get(name)
        f(self, name, value)
        if (not self.hasValidValue(name)):
            self._trch_set(name, old)
            raise exception.CmdErr, ('Invalid    value    for    %s    (%s)' % (name, value))
        for param in paramcache:
            if (param.name in util.iDict(self.cache_choiceparams(name))):
                try:
                    if (not self.getParameter(param.name).isHidden()):
                        self.set(*param)
                except (exception.CmdErr, AttributeError):
                    pass
    return wrap


What's a good function header?
targets: def safesetchoice(f):
inputs: Complete the below
def execute(func, args, msg=None, verbose=0, dry_run=0):

    ''''Perform some action that affects the outside world (eg.  by
    writing to the filesystem).  Such actions are special because they
    are disabled by the \'dry_run\' flag.  This method takes care of all
    that bureaucracy for you; all you have to do is supply the
    function to call and an argument tuple for it (to embody the
    "external action" being performed), and an optional message to
    print.'
    '''
targets: if (msg is None):
        msg = ('%s%r' % (func.__name__, args))
        if (msg[(-2):] == ',)'):
            msg = (msg[0:(-2)] + ')')
    log.info(msg)
    if (not dry_run):
        func(*args)
inputs: def apply_received_command(event):
targets: """Apply command from rfxtrx.
    """
    device_id = slugify(event.device.id_string.lower())
    if (device_id not in RFX_DEVICES):
        return
    _LOGGER.debug('Device_id:    %s    device_update.    Command:    %s', device_id, event.values['Command'])
    if ((event.values['Command'] == 'On') or (event.values['Command'] == 'Off')):
        is_on = (event.values['Command'] == 'On')
        RFX_DEVICES[device_id].update_state(is_on)
    elif (hasattr(RFX_DEVICES[device_id], 'brightness') and (event.values['Command'] == 'Set    level')):
        _brightness = ((event.values['Dim    level'] * 255) // 100)
        is_on = (_brightness > 0)
        RFX_DEVICES[device_id].update_state(is_on, _brightness)
    if RFX_DEVICES[device_id].should_fire_event:
        RFX_DEVICES[device_id].hass.bus.fire(EVENT_BUTTON_PRESSED, {ATTR_ENTITY_ID: RFX_DEVICES[device_id].entity_id, ATTR_STATE: event.values['Command'].lower()})
        _LOGGER.info('Rfxtrx    fired    event:    (event_type:    %s,    %s:    %s,    %s:    %s)', EVENT_BUTTON_PRESSED, ATTR_ENTITY_ID, RFX_DEVICES[device_id].entity_id, ATTR_STATE, event.values['Command'].lower())
inputs: Complete the below
def locate_oc_binary():

    ''''Find and return oc binary file'
    '''
targets: 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
inputs: I wrote the below code

    lib = libraries.get(library_name, None)
    if (not lib):
        templatetags_modules = get_templatetags_modules()
        tried_modules = []
        for module in templatetags_modules:
            taglib_module = ('%s.%s' % (module, library_name))
            tried_modules.append(taglib_module)
            lib = import_library(taglib_module)
            if lib:
                libraries[library_name] = lib
                break
        if (not lib):
            raise InvalidTemplateLibrary(('Template    library    %s    not    found,    tried    %s' % (library_name, ','.join(tried_modules))))
    return lib


What's a good function header?
targets: def get_library(library_name):
inputs: Complete the below
def is_target(t):

    '''''
    '''
targets: if (t == None):
        return ''
    parts = t.split(':')
    try:
        ip = is_ip_addr(parts[0])
        if (len(parts) > 1):
            port = int(parts[1])
        return t
    except Exception as e:
        raise ArgumentTypeError(('%r    is    not    a    valid    target!' % t))
inputs: def get_version(package):
targets: """Return package version as listed in `__version__` in `init.py`.
    """
    init_py = open(os.path.join(package, '__init__.py')).read()
    return re.search('__version__    =    [\'"]([^\'"]+)[\'"]', init_py).group(1)
inputs: I wrote the below code

    for body in (content_ratings or {}):
        content_ratings[body] = dehydrate_content_rating(content_ratings[body])
    return content_ratings


What's a good function header?
targets: def dehydrate_content_ratings(content_ratings):
inputs: @app.route(('%s/functions/<function>' % PATH_ROOT), methods=['DELETE'])
def delete_function(function):
targets: """Delete an existing function
    operationId: \deleteFunction\
    parameters:
    - name: \request\
    in: body
    """
    arn = func_arn(function)
    try:
        lambda_arn_to_handler.pop(arn)
    except KeyError:
        return error_response(('Function    does    not    exist:    %s' % function), 404, error_type='ResourceNotFoundException')
    event_publisher.fire_event(event_publisher.EVENT_LAMBDA_DELETE_FUNC, payload={'n': event_publisher.get_hash(function)})
    lambda_arn_to_cwd.pop(arn, None)
    lambda_arn_to_function.pop(arn, None)
    i = 0
    while (i < len(event_source_mappings)):
        mapping = event_source_mappings[i]
        if (mapping['FunctionArn'] == arn):
            del event_source_mappings[i]
            i -= 1
        i += 1
    result = {}
    return jsonify(result)
inputs: I wrote the below code

    from simplipy.api import SimpliSafeApiInterface, get_systems
    name = config.get(CONF_NAME)
    code = config.get(CONF_CODE)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    simplisafe = SimpliSafeApiInterface()
    status = simplisafe.set_credentials(username, password)
    if status:
        hass.data[DOMAIN] = simplisafe
        locations = get_systems(simplisafe)
        for location in locations:
            add_devices([SimpliSafeAlarm(location, name, code)])
    else:
        message = 'Failed    to    log    into    SimpliSafe.    Check    credentials.'
        _LOGGER.error(message)
        hass.components.persistent_notification.create(message, title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
        return False
    def logout(event):
        'Logout    of    the    SimpliSafe    API.'
        hass.data[DOMAIN].logout()
    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, logout)


What's a good function header?
targets: def setup_platform(hass, config, add_devices, discovery_info=None):
inputs: Complete the below
def activities_from_everything_followed_by_user(user_id, limit, offset):

    ''''Return activities from everything that the given user is following.
    Returns all activities where the object of the activity is anything
    (user, dataset, group...) that the given user is following.'
    '''
targets: q = _activities_from_everything_followed_by_user_query(user_id, (limit + offset))
    return _activities_at_offset(q, limit, offset)
inputs: def __virtual__():
targets: """Set the virtual pkg module if the os is supported by pkgin
    """
    supported = ['NetBSD', 'SunOS', 'DragonFly', 'Minix', 'Darwin', 'SmartOS']
    if ((__grains__['os'] in supported) and _check_pkgin()):
        return __virtualname__
    return (False, 'The    pkgin    execution    module    cannot    be    loaded:    only    available    on    {0}    systems.'.format(',    '.join(supported)))
inputs: I wrote the below code

    if (config is None):
        config = BareConfig(read_configfile=True, quietness=1)
    return LaymanAPI(config)


What's a good function header?
targets: def init_layman(config=None):
inputs: I wrote the below code

    if (not isinstance(name, (list, tuple))):
        name = [name]
    if isinstance(info, Info):
        picks = pick_types(info, meg=True, exclude=())
        if ((len(picks) > 0) and ('    ' not in info['ch_names'][picks[0]])):
            spacing = 'new'
        else:
            spacing = 'old'
    elif (info is not None):
        raise TypeError(('info    must    be    an    instance    of    Info    or    None,    not    %s' % (type(info),)))
    else:
        spacing = 'old'
    if (fname is None):
        fname = path.join(path.dirname(__file__), 'data', 'mne_analyze.sel')
    if (not path.isfile(fname)):
        raise ValueError(('The    file    %s    does    not    exist.' % fname))
    name_found = dict(((n, False) for n in name))
    with open(fname, 'r') as fid:
        sel = []
        for line in fid:
            line = line.strip()
            if ((len(line) == 0) or (line[0] == '#')):
                continue
            pos = line.find(':')
            if (pos < 0):
                logger.info('":"    delimiter    not    found    in    selections    file,    skipping    line')
                continue
            sel_name_file = line[:pos]
            for n in name:
                if (sel_name_file.find(n) >= 0):
                    sel.extend(line[(pos + 1):].split('|'))
                    name_found[n] = True
                    break
    for (n, found) in name_found.items():
        if (not found):
            raise ValueError(('No    match    for    selection    name    "%s"    found' % n))
    sel = list(set(sel))
    sel.sort()
    if (spacing == 'new'):
        sel = [s.replace('MEG    ', 'MEG') for s in sel]
    return sel


What's a good function header?
targets: @verbose
def read_selection(name, fname=None, info=None, verbose=None):
inputs: @core_helper
def get_featured_groups(count=1):
targets: """Returns a list of favourite group the form
    of organization_list action function
    """
    config_groups = config.get('ckan.featured_groups', '').split()
    groups = featured_group_org(get_action='group_show', list_action='group_list', count=count, items=config_groups)
    return groups
inputs: I wrote the below code

    (name, value) = header
    if isinstance(value, bytes):
        pat = _CLEAN_HEADER_REGEX_BYTE
    else:
        pat = _CLEAN_HEADER_REGEX_STR
    try:
        if (not pat.match(value)):
            raise InvalidHeader(('Invalid    return    character    or    leading    space    in    header:    %s' % name))
    except TypeError:
        raise InvalidHeader(('Header    value    %s    must    be    of    type    str    or    bytes,    not    %s' % (value, type(value))))


What's a good function header?
targets: def check_header_validity(header):
inputs: Complete the below
def make_or_pipe(pipe):

    ''''wraps a pipe into two pipe-like objects which are "or"d together to
    affect the real pipe. if either returned pipe is set, the wrapped pipe
    is set. when both are cleared, the wrapped pipe is cleared.'
    '''
targets: p1 = OrPipe(pipe)
    p2 = OrPipe(pipe)
    p1._partner = p2
    p2._partner = p1
    return (p1, p2)
inputs: I wrote the below code

    it = itertools.groupby(query_result, operator.itemgetter(0))
    forums = []
    if user.is_authenticated:
        for (key, value) in it:
            forums.append((key, [(item[1], item[2]) for item in value]))
    else:
        for (key, value) in it:
            forums.append((key, [(item[1], None) for item in value]))
    return forums


What's a good function header?
targets: def get_categories_and_forums(query_result, user):
inputs: Complete the below
def _find_spec_from_path(name, path=None):

    ''''Return the spec for the specified module.
    First, sys.modules is checked to see if the module was already imported. If
    so, then sys.modules[name].__spec__ is returned. If that happens to be
    set to None, then ValueError is raised. If the module is not in
    sys.modules, then sys.meta_path is searched for a suitable spec with the
    value of \'path\' given to the finders. None is returned if no spec could
    be found.
    Dotted names do not have their parent packages implicitly imported. You will
    most likely need to explicitly import all parent packages in the proper
    order for a submodule to get the correct spec.'
    '''
targets: if (name not in sys.modules):
        return _find_spec(name, path)
    else:
        module = sys.modules[name]
        if (module is None):
            return None
        try:
            spec = module.__spec__
        except AttributeError:
            raise ValueError('{}.__spec__    is    not    set'.format(name))
        else:
            if (spec is None):
                raise ValueError('{}.__spec__    is    None'.format(name))
            return spec
inputs: def KeyLEQ(key1, key2):
targets: """Compare two keys for less-than-or-equal-to.
    All keys with numeric ids come before all keys with names. None represents
    an unbounded end-point so it is both greater and less than any other key.
    Args:
    key1: An int or datastore.Key instance.
    key2: An int or datastore.Key instance.
    Returns:
    True if key1 <= key2
    """
    if ((key1 is None) or (key2 is None)):
        return True
    return (key1 <= key2)
inputs: Complete the below
def get_writer_class(writer_name):

    ''''Return the Writer class from the `writer_name` module.'
    '''
targets: writer_name = writer_name.lower()
    if (writer_name in _writer_aliases):
        writer_name = _writer_aliases[writer_name]
    try:
        module = __import__(writer_name, globals(), locals(), level=1)
    except ImportError:
        module = __import__(writer_name, globals(), locals(), level=0)
    return module.Writer
inputs: I wrote the below code

    core = CORE_MANAGER.get_core_service()
    peer = core.peer_manager.get_by_addr(neigh_ip_address)
    at_maps_key = const.ATTR_MAPS_LABEL_DEFAULT
    at_maps_dict = {}
    if (route_dist is not None):
        vrf_conf = CORE_MANAGER.vrfs_conf.get_vrf_conf(route_dist, route_family)
        if vrf_conf:
            at_maps_key = ':'.join([route_dist, route_family])
        else:
            raise RuntimeConfigError(desc=('No    VrfConf    with    rd    %s' % route_dist))
    at_maps_dict[const.ATTR_MAPS_LABEL_KEY] = at_maps_key
    at_maps_dict[const.ATTR_MAPS_VALUE] = at_maps
    peer.attribute_maps = at_maps_dict
    return True


What's a good function header?
targets: @RegisterWithArgChecks(name='neighbor.attribute_map.set', req_args=[neighbors.IP_ADDRESS, neighbors.ATTRIBUTE_MAP], opt_args=[ROUTE_DISTINGUISHER, VRF_RF])
def set_neighbor_attribute_map(neigh_ip_address, at_maps, route_dist=None, route_family=VRF_RF_IPV4):
inputs: Complete the below
@contextmanager
def webserver(app, port=0, host=None):

    ''''Context manager entry point for the \'with\' statement.
    Pass 0 as port number to dynamically allocate a free port.
    Usage:
    with webserver(wsgi_app_function, 8080) as host_url:
    do_ws_calls(host_url)'
    '''
targets: server = build_web_server(app, port, (host or '127.0.0.1'))
    (host, port) = server.socket.getsockname()
    import threading
    thread = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': 0.5})
    thread.setDaemon(True)
    thread.start()
    try:
        (yield ('http://%s:%s/' % (host, port)))
    finally:
        server.shutdown()
        server.server_close()
inputs: def getCraftedText(fileName, text, jitterRepository=None):
targets: """Jitter a gcode linear move text.
    """
    return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), jitterRepository)
inputs: I wrote the below code

    force_param = ''
    if force:
        force_param = '-force'
    return _hadoop_cmd('namenode', 'format', '-nonInteractive', force_param)


What's a good function header?
targets: def namenode_format(force=None):
inputs: I wrote the below code

    if (window_size is None):
        window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE
    magic = []
    for (obj, path) in objects:
        magic.append((obj.type_num, path, (- obj.raw_length()), obj))
    magic.sort()
    possible_bases = deque()
    for (type_num, path, neg_length, o) in magic:
        raw = o.as_raw_string()
        winner = raw
        winner_base = None
        for base in possible_bases:
            if (base.type_num != type_num):
                continue
            delta = create_delta(base.as_raw_string(), raw)
            if (len(delta) < len(winner)):
                winner_base = base.sha().digest()
                winner = delta
        (yield (type_num, o.sha().digest(), winner_base, winner))
        possible_bases.appendleft(o)
        while (len(possible_bases) > window_size):
            possible_bases.pop()


What's a good function header?
targets: def deltify_pack_objects(objects, window_size=None):
inputs: def get_issue(issue_number, repo_name=None, profile='github', output='min'):
targets: """Return information about a single issue in a named repository.
    .. versionadded:: 2016.11.0
    issue_number
    The number of the issue to retrieve.
    repo_name
    The name of the repository from which to get the issue. This argument is
    required, either passed via the CLI, or defined in the configured
    profile. A ``repo_name`` passed as a CLI argument will override the
    repo_name defined in the configured profile, if provided.
    profile
    The name of the profile configuration to use. Defaults to ``github``.
    output
    The amount of data returned by each issue. Defaults to ``min``. Change
    to ``full`` to see all issue output.
    CLI Example:
    .. code-block:: bash
    salt myminion github.get_issue 514
    salt myminion github.get_issue 514 repo_name=salt
    """
    org_name = _get_config_value(profile, 'org_name')
    if (repo_name is None):
        repo_name = _get_config_value(profile, 'repo_name')
    action = '/'.join(['repos', org_name, repo_name])
    command = ('issues/' + str(issue_number))
    ret = {}
    issue_data = _query(profile, action=action, command=command)
    issue_id = issue_data.get('id')
    if (output == 'full'):
        ret[issue_id] = issue_data
    else:
        ret[issue_id] = _format_issue(issue_data)
    return ret
inputs: def find_failing_tests(result_images, source):
targets: """Find all of the failing tests by looking for files with
    `-failed-diff` at the end of the basename.
    """
    entries = []
    for (root, dirs, files) in os.walk(result_images):
        for fname in files:
            (basename, ext) = os.path.splitext(fname)
            if basename.endswith(u'-failed-diff'):
                path = os.path.join(root, fname)
                entry = Entry(path, result_images, source)
                entries.append(entry)
    entries.sort(key=(lambda x: x.name))
    return entries
inputs: def _exception_traceback(exc_info):
targets: """Return a string containing a traceback message for the given
    exc_info tuple (as returned by sys.exc_info()).
    """
    excout = StringIO()
    (exc_type, exc_val, exc_tb) = exc_info
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
    return excout.getvalue()
inputs: def create_tree(base_dir, files, mode=511, verbose=1, dry_run=0):
targets: """Create all the empty directories under \base_dir\ needed to put \files\
    there.
    \base_dir\ is just the name of a directory which doesn\t necessarily
    exist yet; \files\ is a list of filenames to be interpreted relative to
    \base_dir\.  \base_dir\ + the directory portion of every file in \files\
    will be created if it doesn\t already exist.  \mode\, \verbose\ and
    \dry_run\ flags are as for \mkpath()\.
    """
    need_dir = {}
    for file in files:
        need_dir[os.path.join(base_dir, os.path.dirname(file))] = 1
    need_dirs = need_dir.keys()
    need_dirs.sort()
    for dir in need_dirs:
        mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
inputs: def bind_row_anchor_column(column_name):
targets: """A decorator to bind table region method to a anchor in a column.
    Typical examples of such tables are Project -> Compute -> Images, Admin
    -> System -> Flavors, Project -> Compute -> Instancies.
    The method can be used to follow the link in the anchor by the click.
    """
    def decorator(method):
        @functools.wraps(method)
        def wrapper(table, row):
            cell = row.cells[column_name]
            action_element = cell.find_element(by.By.CSS_SELECTOR, ('td.%s    >    a' % NORMAL_COLUMN_CLASS))
            return method(table, action_element, row)
        return wrapper
    return decorator
inputs: Complete the below
def add_instance_fault_from_exc(context, instance, fault, exc_info=None, fault_message=None):

    ''''Adds the specified fault to the database.'
    '''
targets: fault_obj = objects.InstanceFault(context=context)
    fault_obj.host = CONF.host
    fault_obj.instance_uuid = instance.uuid
    fault_obj.update(exception_to_dict(fault, message=fault_message))
    code = fault_obj.code
    fault_obj.details = _get_fault_details(exc_info, code)
    fault_obj.create()
inputs: def _configure_base(module, base, conf_file, disable_gpg_check):
targets: """Configure the dnf Base object.
    """
    conf = base.conf
    conf.debuglevel = 0
    conf.gpgcheck = (not disable_gpg_check)
    conf.assumeyes = True
    if conf_file:
        if (not os.access(conf_file, os.R_OK)):
            module.fail_json(msg='cannot    read    configuration    file', conf_file=conf_file)
        else:
            conf.config_file_path = conf_file
    conf.read()
inputs: Complete the below
def cummingsify(poem):

    ''''Randomly do one of the following:
    1. Return a cummingsified version of the poem.
    2. Raise a GibberishError.
    3. Raise a ValueError.'
    '''
targets: def success():
        return poem.lower()
    def gibberish():
        raise GibberishError()
    def bug():
        raise ValueError()
    return random.choice([success, gibberish, bug])()
inputs: def main(unused_argv):
targets: """Main.
    """
    server_startup.Init()
    filename = flags.FLAGS.filename
    if (not os.path.exists(filename)):
        print ('File    %s    does    not    exist' % filename)
        return
    with aff4.FACTORY.Create(filestore.NSRLFileStore.PATH, filestore.NSRLFileStore, mode='rw', token=aff4.FACTORY.root_token) as store:
        imported = ImportFile(store, filename, flags.FLAGS.start)
        data_store.DB.Flush()
        print ('Imported    %d    hashes' % imported)
inputs: def do_not_report_as_logging_caller(func):
targets: """Decorator to annotate functions we will tell logging not to log.
    """
    _caller_code_to_skip_in_logging_stack.add(func.func_code)
    return func
inputs: I wrote the below code

    checkout_path = _create_test_package(script)
    repo_url = _create_svn_repo(script, checkout_path)
    result = script.pip('install', '-e', (('svn+' + repo_url) + '#egg=version-pkg'))
    result.assert_installed('version-pkg', with_files=['.svn'])


What's a good function header?
targets: @pytest.mark.svn
def test_install_editable_from_svn(script):
inputs: def examplesfullTest(vm, prompt=Prompt):
targets: """Full (slow) test of mininet examples
    """
    installPexpect(vm, prompt)
    vm.sendline('sudo    -n    python    ~/mininet/examples/test/runner.py    -v')
inputs: Complete the below
def capitalize(s):

    ''''capitalize(s) -> string
    Return a copy of the string s with only its first character
    capitalized.'
    '''
targets: return s.capitalize()
inputs: I wrote the below code

    log.js.debug('confirm:    {}'.format(js_msg))
    if config.get('ui', 'modal-js-dialog'):
        raise CallSuper
    msg = 'From    <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()), html.escape(js_msg))
    ans = message.ask('Javascript    confirm', msg, mode=usertypes.PromptMode.yesno, abort_on=abort_on)
    return bool(ans)


What's a good function header?
targets: def javascript_confirm(url, js_msg, abort_on):
inputs: def getFirstAncestorWithSectionHeader(entry):
targets: """Visit the ancestors of C{entry} until one with at least one C{h2} child
    node is found, then return all of that node\s C{h2} child nodes.
    @type entry: A DOM Node
    @param entry: The node from which to begin traversal.  This node itself is
    excluded from consideration.
    @rtype: C{list} of DOM Nodes
    @return: All C{h2} nodes of the ultimately selected parent node.
    """
    for a in domhelpers.getParents(entry)[1:]:
        headers = domhelpers.findNodesNamed(a, 'h2')
        if (len(headers) > 0):
            return headers
    return []
inputs: I wrote the below code

    if (release not in {'2', '3'}):
        raise ValueError(("release    must    be    one    of    '2',    '3',    not    %s" % release))
    venv = '/home/vagrant/repos/test-{release}-virtualenv'.format(release=release)
    tarball_formatter_dict = tarball_formatter()
    with use_venv(release):
        make_virtualenv(venv)
        with virtualenv(venv):
            run('cp    /vagrant/release/{source}    releasetar.tar'.format(**tarball_formatter_dict))
            run('tar    xvf    releasetar.tar')
            with cd('/home/vagrant/{source-orig-notar}'.format(**tarball_formatter_dict)):
                run('python    setup.py    install')
                run('python    -c    "import    sympy;    print(sympy.__version__)"')


What's a good function header?
targets: @task
def test_tarball(release='2'):