Muennighoff/xP3x-sample huggingface dataset:
inputs: Complete the below
def html_safe(klass):

    ''''A decorator that defines the __html__ method. This helps non-Django
    templates to detect classes whose __str__ methods return SafeText.'
    '''
targets: if ('__html__' in klass.__dict__):
        raise ValueError(("can't    apply    @html_safe    to    %s    because    it    defines    __html__()." % klass.__name__))
    if ('__str__' not in klass.__dict__):
        raise ValueError(("can't    apply    @html_safe    to    %s    because    it    doesn't    define    __str__()." % klass.__name__))
    klass_str = klass.__str__
    klass.__str__ = (lambda self: mark_safe(klass_str(self)))
    klass.__html__ = (lambda self: str(self))
    return klass
inputs: I wrote the below code

    for backend in get_backends():
        try:
            user = backend.authenticate(**credentials)
        except TypeError:
            continue
        if (user is None):
            continue
        user.backend = ('%s.%s' % (backend.__module__, backend.__class__.__name__))
        return user


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

    for child in walk(node):
        if ('lineno' in child._attributes):
            child.lineno = (getattr(child, 'lineno', 0) + n)
    return node


What's a good function header?
targets: def increment_lineno(node, n=1):
inputs: I wrote the below code

    lnum = parenlev = continued = 0
    (namechars, numchars) = ((string.ascii_letters + '_'), '0123456789')
    (contstr, needcont) = ('', 0)
    contline = None
    indents = [0]
    stashed = None
    async_def = False
    async_def_indent = 0
    async_def_nl = False
    while 1:
        try:
            line = readline()
        except StopIteration:
            line = ''
        lnum = (lnum + 1)
        (pos, max) = (0, len(line))
        if contstr:
            if (not line):
                raise TokenError('EOF    in    multi-line    string', strstart)
            endmatch = endprog.match(line)
            if endmatch:
                pos = end = endmatch.end(0)
                (yield (STRING, (contstr + line[:end]), strstart, (lnum, end), (contline + line)))
                (contstr, needcont) = ('', 0)
                contline = None
            elif (needcont and (line[(-2):] != '\\\n') and (line[(-3):] != '\\\r\n')):
                (yield (ERRORTOKEN, (contstr + line), strstart, (lnum, len(line)), contline))
                contstr = ''
                contline = None
                continue
            else:
                contstr = (contstr + line)
                contline = (contline + line)
                continue
        elif ((parenlev == 0) and (not continued)):
            if (not line):
                break
            column = 0
            while (pos < max):
                if (line[pos] == '    '):
                    column = (column + 1)
                elif (line[pos] == ' DCTB '):
                    column = (((column // tabsize) + 1) * tabsize)
                elif (line[pos] == '\x0c'):
                    column = 0
                else:
                    break
                pos = (pos + 1)
            if (pos == max):
                break
            if stashed:
                (yield stashed)
                stashed = None
            if (line[pos] in '#\r\n'):
                if (line[pos] == '#'):
                    comment_token = line[pos:].rstrip('\r\n')
   ...

What's a good function header?
targets: def generate_tokens(readline):
inputs: Complete the below
def find_igw(vpc_conn, vpc_id):

    ''''Finds the Internet gateway for the given VPC ID.
    Raises an AnsibleIgwSearchException if either no IGW can be found, or more
    than one found for the given VPC.
    Note that this function is duplicated in other ec2 modules, and should
    potentially be moved into potentially be moved into a shared module_utils'
    '''
targets: igw = vpc_conn.get_all_internet_gateways(filters={'attachment.vpc-id': vpc_id})
    if (not igw):
        raise AnsibleIgwSearchException('No    IGW    found    for    VPC    {0}'.format(vpc_id))
    elif (len(igw) == 1):
        return igw[0].id
    else:
        raise AnsibleIgwSearchException('Multiple    IGWs    found    for    VPC    {0}'.format(vpc_id))
inputs: I wrote the below code

    if isinstance(number, float):
        if (number > 1):
            number = round(number, 0)
        else:
            number = round(math.ceil(number), 0)
    return int(number)


What's a good function header?
targets: def toint(number):
inputs: Complete the below
def assert_almost_equal_ignore_nan(a, b, rtol=None, atol=None, names=('a', 'b')):

    ''''Test that two NumPy arrays are almost equal (ignoring NaN in either array).
    Combines a relative and absolute measure of approximate eqality.
    If either the relative or absolute check passes, the arrays are considered equal.
    Including an absolute check resolves issues with the relative check where all
    array values are close to zero.
    Parameters
    a : np.ndarray
    b : np.ndarray
    rtol : None or float
    The relative threshold. Default threshold will be used if set to ``None``.
    atol : None or float
    The absolute threshold. Default threshold will be used if set to ``None``.'
    '''
targets: a = np.copy(a)
    b = np.copy(b)
    nan_mask = np.logical_or(np.isnan(a), np.isnan(b))
    a[nan_mask] = 0
    b[nan_mask] = 0
    assert_almost_equal(a, b, rtol, atol, names)
inputs: I wrote the below code

    export_emails = Command()
    export_emails.run_from_argv([u'manage.py', u'export_emails', u'--format=vcard'])
    (out, err) = capsys.readouterr()
    assert (u'N:Bulgak\xf3v;Mija\xedl;;;' in out)
    assert out.startswith(u'BEGIN:VCARD')


What's a good function header?
targets: @pytest.mark.skipif(u'sys.version_info    <    (3,    0)', reason=u'issues    with    vobject    library    on    PY2x')
@pytest.mark.django_db()
def test_do_export_emails_format_vcard_start(capsys):
inputs: Complete the below
def _additional_sanity_checks(module, zone):

    ''''Run input sanity checks that depend on info from the zone/record.'
    '''
targets: overwrite = module.params['overwrite']
    record_name = module.params['record']
    record_type = module.params['type']
    state = module.params['state']
    if ((record_type == 'CNAME') and (record_name == zone.domain)):
        module.fail_json(msg='CNAME    records    cannot    match    the    zone    name', changed=False)
    if ((record_type == 'NS') and (record_name == zone.domain) and (state == 'absent')):
        module.fail_json(msg='cannot    delete    root    NS    records', changed=False)
    if ((record_type == 'NS') and (record_name == zone.domain) and overwrite):
        module.fail_json(msg='cannot    update    existing    root    NS    records', changed=False)
    if ((record_type == 'SOA') and (record_name != zone.domain)):
        module.fail_json(msg=('non-root    SOA    records    are    not    permitted,    got:    %s' % record_name), changed=False)
inputs: I wrote the below code

    (host, port) = address
    err = None
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        (af, socktype, proto, canonname, sa) = res
        sock = None
        try:
            sock = socket(af, socktype, proto)
            if (timeout is not _GLOBAL_DEFAULT_TIMEOUT):
                sock.settimeout(timeout)
            if source_address:
                sock.bind(source_address)
            sock.connect(sa)
            return sock
        except error as _:
            err = _
            if (sock is not None):
                sock.close()
    if (err is not None):
        raise err
    else:
        raise error('getaddrinfo    returns    an    empty    list')


What's a good function header?
targets: def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
inputs: def destroy(name, call=None):
targets: """To destroy a VM from the VMware environment
    CLI Example:
    .. code-block:: bash
    salt-cloud -d vmname
    salt-cloud --destroy vmname
    salt-cloud -a destroy vmname
    """
    if (call == 'function'):
        raise SaltCloudSystemExit('The    destroy    action    must    be    called    with    -d,    --destroy,    -a    or    --action.')
    __utils__['cloud.fire_event']('event', 'destroying    instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])
    vm_properties = ['name', 'summary.runtime.powerState']
    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)
    for vm in vm_list:
        if (vm['name'] == name):
            if (vm['summary.runtime.powerState'] != 'poweredOff'):
                try:
                    log.info('Powering    Off    VM    {0}'.format(name))
                    task = vm['object'].PowerOff()
                    salt.utils.vmware.wait_for_task(task, name, 'power    off')
                except Exception as exc:
                    log.error('Error    while    powering    off    VM    {0}:    {1}'.format(name, exc), exc_info_on_loglevel=logging.DEBUG)
                    return 'failed    to    destroy'
            try:
                log.info('Destroying    VM    {0}'.format(name))
                task = vm['object'].Destroy_Task()
                salt.utils.vmware.wait_for_task(task, name, 'destroy')
            except Exception as exc:
                log.error('Error    while    destroying    VM    {0}:    {1}'.format(name, exc), exc_info_on_loglevel=logging.DEBUG)
                return 'failed    to    destroy'
    __utils__['cloud.fire_event']('event', 'destroyed    instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])
    if (__opts__.get('update_cachedir', False) is True):
        __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
    return True
inputs: I wrote the below code

    group = get_object_or_404(Group, slug=slug)
    page = get_object_or_404(GroupPage, group=group, slug=page_slug)
    return render(request, template_name, {'group': group, 'page': page})


What's a good function header?
targets: def page_detail(request, slug, page_slug, template_name='groups/pages/page_detail.html'):
inputs: def _get_recarray_field(array, key):
targets: """Compatibility function for using the recarray base class\s field method.
    This incorporates the legacy functionality of returning string arrays as
    Numeric-style chararray objects.
    """
    field = np.recarray.field(array, key)
    if ((field.dtype.char in ('S', 'U')) and (not isinstance(field, chararray.chararray))):
        field = field.view(chararray.chararray)
    return field
inputs: I wrote the below code

    if isinstance(value, Model):
        value = value.key()
    if (isinstance(value, datetime.date) and (not isinstance(value, datetime.datetime))):
        value = _date_to_datetime(value)
    elif isinstance(value, datetime.time):
        value = _time_to_datetime(value)
    return value


What's a good function header?
targets: def _normalize_query_parameter(value):
inputs: Complete the below
def _get_sort_keys(sort_keys, mapping):

    ''''Returns an array containing only whitelisted keys
    :param sort_keys: an array of strings
    :param mapping: a mapping from keys to DB column names
    :returns: filtered list of sort keys'
    '''
targets: if isinstance(sort_keys, six.string_types):
        sort_keys = [sort_keys]
    return [mapping[key] for key in (sort_keys or []) if (key in mapping)]
inputs: def SimplifyNode(node):
targets: """Simplifies the node removing singleton conjunctions and others.
    """
    if (not node.getType()):
        return SimplifyNode(node.children[0])
    elif ((node.getType() == QueryParser.CONJUNCTION) and (node.getChildCount() == 1)):
        return SimplifyNode(node.children[0])
    elif ((node.getType() == QueryParser.DISJUNCTION) and (node.getChildCount() == 1)):
        return SimplifyNode(node.children[0])
    elif (((node.getType() == QueryParser.EQ) or (node.getType() == QueryParser.HAS)) and (node.getChildCount() == 1)):
        return SimplifyNode(node.children[0])
    for (i, child) in enumerate(node.children):
        node.setChild(i, SimplifyNode(child))
    return node
inputs: @utils.decorator
def transactional(func, args, kwds, **options):
targets: """Decorator to make a function automatically run in a transaction.
    Args:
    **ctx_options: Transaction options (see transaction(), but propagation
    default to TransactionOptions.ALLOWED).
    This supports two forms:
    (1) Vanilla:
    @transactional
    def callback(arg):
    (2) With options:
    @transactional(retries=1)
    def callback(arg):
    """
    return transactional_async.wrapped_decorator(func, args, kwds, **options).get_result()
inputs: Complete the below
def get(params, is_training=False, reuse=False, run_projection=True):

    ''''Factory function to get the training/pretraining im->vox model (NIPS16).
    Args:
    params: Different parameters used througout ptn, typically FLAGS (dict).
    is_training: Set to True if while training (boolean).
    reuse: Set as True if sharing variables with a model that has already
    been built (boolean).
    run_projection: Set as False if not interested in mask and projection
    images. Useful in evaluation routine (boolean).
    Returns:
    Model function for network (inputs to outputs).'
    '''
targets: def model(inputs):
        'Model    function    corresponding    to    a    specific    network    architecture.'
        outputs = {}
        encoder_fn = _get_network(params.encoder_name)
        with tf.variable_scope('encoder', reuse=reuse):
            enc_outputs = encoder_fn(inputs['images_1'], params, is_training)
            outputs['ids_1'] = enc_outputs['ids']
        decoder_fn = _get_network(params.decoder_name)
        with tf.variable_scope('decoder', reuse=reuse):
            outputs['voxels_1'] = decoder_fn(outputs['ids_1'], params, is_training)
        if run_projection:
            projector_fn = _get_network(params.projector_name)
            with tf.variable_scope('projector', reuse=reuse):
                outputs['projs_1'] = projector_fn(outputs['voxels_1'], inputs['matrix_1'], params, is_training)
            with tf.variable_scope('oracle', reuse=reuse):
                outputs['masks_1'] = projector_fn(inputs['voxels'], inputs['matrix_1'], params, False)
            for k in range(1, params.step_size):
                with tf.variable_scope('projector', reuse=True):
                    outputs[('projs_%d' % (k + 1))] = projector_fn(outputs['voxels_1'], inputs[('matrix_%d' % (k + 1))], params, is_training)
                with tf.variable_scope('oracle', reuse=True):
                    outputs[('masks_%d' % (k + 1))] = projector_fn(inputs['voxels'], inputs[('matrix_%d' % (k + 1))], params, False)
        return outputs
    return model
inputs: Complete the below
def lottery_promoted_links(sr_names, n=10):

    ''''Run weighted_lottery to order and choose a subset of promoted links.'
    '''
targets: promo_tuples = get_live_promotions(sr_names)
    weights = {p: (p.weight or 0.001) for p in promo_tuples}
    selected = []
    while (weights and (len(selected) < n)):
        s = weighted_lottery(weights)
        del weights[s]
        selected.append(s)
    return selected
inputs: @register.filter(is_safe=False)
def intword(value):
targets: """Converts a large integer to a friendly text representation. Works best
    for numbers over 1 million. For example, 1000000 becomes \1.0 million\,
    1200000 becomes \1.2 million\ and \1200000000\ becomes \1.2 billion\.
    """
    try:
        value = int(value)
    except (TypeError, ValueError):
        return value
    if (value < 1000000):
        return value
    def _check_for_i18n(value, float_formatted, string_formatted):
        u'\n                                Use    the    i18n    enabled    defaultfilters.floatformat    if    possible\n                                '
        if settings.USE_L10N:
            value = defaultfilters.floatformat(value, 1)
            template = string_formatted
        else:
            template = float_formatted
        return (template % {u'value': value})
    for (exponent, converters) in intword_converters:
        large_number = (10 ** exponent)
        if (value < (large_number * 1000)):
            new_value = (value / float(large_number))
            return _check_for_i18n(new_value, *converters(new_value))
    return value
inputs: I wrote the below code

    if package:
        name = package
        if module:
            name += ('.' + module)
    else:
        name = module
    return name


What's a good function header?
targets: def makename(package, module):
inputs: Complete the below
def create_banner(message):

    ''''Create internal shell banner'
    '''
targets: if (message is None):
        versions = get_versions()
        return ('Python    %s    %dbits    [%s]' % (versions['python'], versions['bitness'], versions['system']))
    else:
        return message
inputs: def log_warn(warnmsg):
targets: """Prints/logs any warnings that aren\t critical but should be noted.
    Args:
    warnmsg (str): The message to be logged.
    """
    try:
        warnmsg = str(warnmsg)
    except Exception as e:
        warnmsg = str(e)
    for line in warnmsg.splitlines():
        log.msg(('[WW]    %s' % line))
inputs: Complete the below
def align_check(device, part_type, partition):

    ''''Check if partition satisfies the alignment constraint of part_type.
    Type must be "minimal" or "optimal".
    CLI Example:
    .. code-block:: bash
    salt \'*\' partition.align_check /dev/sda minimal 1'
    '''
targets: _validate_device(device)
    if (part_type not in set(['minimal', 'optimal'])):
        raise CommandExecutionError('Invalid    part_type    passed    to    partition.align_check')
    try:
        int(partition)
    except Exception:
        raise CommandExecutionError('Invalid    partition    passed    to    partition.align_check')
    cmd = 'parted    -m    {0}    align-check    {1}    {2}'.format(device, part_type, partition)
    out = __salt__['cmd.run'](cmd).splitlines()
    return out
inputs: def format_date(date=None, format='medium', locale=LC_TIME):
targets: """Return a date formatted according to the given pattern.
    >>> d = date(2007, 04, 01)
    >>> format_date(d, locale=\en_US\)
    u\Apr 1, 2007\
    >>> format_date(d, format=\full\, locale=\de_DE\)
    u\Sonntag, 1. April 2007\
    If you don\t want to use the locale default formats, you can specify a
    custom date pattern:
    >>> format_date(d, "EEE, MMM d, \\yy", locale=\en\)
    u"Sun, Apr 1, \07"
    :param date: the ``date`` or ``datetime`` object; if `None`, the current
    date is used
    :param format: one of "full", "long", "medium", or "short", or a custom
    date/time pattern
    :param locale: a `Locale` object or a locale identifier
    :rtype: `unicode`
    :note: If the pattern contains time fields, an `AttributeError` will be
    raised when trying to apply the formatting. This is also true if
    the value of ``date`` parameter is actually a ``datetime`` object,
    as this function automatically converts that to a ``date``.
    """
    if (date is None):
        date = date_.today()
    elif isinstance(date, datetime):
        date = date.date()
    locale = Locale.parse(locale)
    if (format in ('full', 'long', 'medium', 'short')):
        format = get_date_format(format, locale=locale)
    pattern = parse_pattern(format)
    return pattern.apply(date, locale)
inputs: Complete the below
def _parse_ref(text, link, info):

    ''''Manage links to references.'
    '''
targets: if (link.find('/title/tt') != (-1)):
        yearK = re_yearKind_index.match(info)
        if (yearK and (yearK.start() == 0)):
            text += ('    %s' % info[:yearK.end()])
    return (text.replace('\n', '    '), link)
inputs: I wrote the below code

    import warnings
    warnings.warn('commands.getstatus()    is    deprecated', DeprecationWarning, 2)
    return getoutput(('ls    -ld' + mkarg(file)))


What's a good function header?
targets: def getstatus(file):
inputs: Complete the below
@testing.requires_testing_data
def test_fine_calibration():

    ''''Test Maxwell filter fine calibration.'
    '''
targets: raw = read_crop(raw_fname, (0.0, 1.0))
    sss_fine_cal = read_crop(sss_fine_cal_fname)
    raw_sss = maxwell_filter(raw, calibration=fine_cal_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore')
    assert_meg_snr(raw_sss, sss_fine_cal, 82, 611)
    py_cal = raw_sss.info['proc_history'][0]['max_info']['sss_cal']
    assert_true((py_cal is not None))
    assert_true((len(py_cal) > 0))
    mf_cal = sss_fine_cal.info['proc_history'][0]['max_info']['sss_cal']
    mf_cal['cal_chans'][((mf_cal['cal_chans'][:, 1] == 3022), 1)] = 3024
    assert_allclose(py_cal['cal_chans'], mf_cal['cal_chans'])
    assert_allclose(py_cal['cal_corrs'], mf_cal['cal_corrs'], rtol=0.001, atol=0.001)
    raw_missing = raw.copy().load_data()
    raw_missing.info['bads'] = ['MEG0111', 'MEG0943']
    raw_missing.info._check_consistency()
    raw_sss_bad = maxwell_filter(raw_missing, calibration=fine_cal_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore')
    raw_missing.pick_types()
    raw_sss_bad.pick_channels(raw_missing.ch_names)
    with warnings.catch_warnings(record=True):
        raw_sss_missing = maxwell_filter(raw_missing, calibration=fine_cal_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore')
    assert_meg_snr(raw_sss_missing, raw_sss_bad, 1000.0, 10000.0)
    raw_sss_3D = maxwell_filter(raw, calibration=fine_cal_fname_3d, origin=mf_head_origin, regularize=None, bad_condition='ignore')
    assert_meg_snr(raw_sss_3D, sss_fine_cal, 1.0, 6.0)
    raw_ctf = read_crop(fname_ctf_raw).apply_gradient_compensation(0)
    assert_raises(RuntimeError, maxwell_filter, raw_ctf, origin=(0.0, 0.0, 0.04), calibration=fine_cal_fname)
inputs: def extract_tokens(l, known_tokens):
targets: """Returns dictionary of known tokens with all values
    """
    assert ((l[0].strip() == '(') and (l[(-1)].strip() == ')')), ValueError(l)
    result = {}
    result_has_key = result.has_key
    result.update(known_tokens)
    i = 0
    l_len = len(l)
    while (i < l_len):
        if result_has_key(l[i]):
            token = l[i]
            i += 1
            if (i < l_len):
                if result_has_key(l[i]):
                    result[token] = ()
                elif (l[i] == '('):
                    i += 1
                    start = i
                    while ((i < l_len) and (l[i] != ')')):
                        i += 1
                    result[token] = tuple(filter((lambda v: (v != '$')), l[start:i]))
                    i += 1
                else:
                    result[token] = (l[i],)
                    i += 1
        else:
            i += 1
    return result
inputs: I wrote the below code

    import shutil
    app_template = os.path.normpath(app_template)
    for (d, subdirs, files) in os.walk(app_template):
        relative_dir = d[(len(app_template) + 1):]
        d_new = os.path.join(copy_to, relative_dir).replace('app_name', app_name)
        if (relative_dir and (not os.path.exists(d_new))):
            os.mkdir(d_new)
        for (i, subdir) in enumerate(subdirs):
            if subdir.startswith('.'):
                del subdirs[i]
        replacements = {'app_name': app_name, 'project_name': project_name}
        replacements.update(REPLACEMENTS)
        for f in files:
            if (f.endswith('.pyc') or f.startswith('.DS_Store')):
                continue
            path_old = os.path.join(d, f)
            path_new = os.path.join(d_new, f.replace('app_name', app_name))
            if os.path.exists(path_new):
                path_new = os.path.join(d_new, f)
                if os.path.exists(path_new):
                    continue
            if path_new.endswith('.tmpl'):
                path_new = path_new[:(-5)]
            fp_old = open(path_old, 'r')
            fp_new = open(path_new, 'w')
            fp_new.write(Template(fp_old.read()).render(Context(replacements)))
            fp_old.close()
            fp_new.close()
            try:
                shutil.copymode(path_old, path_new)
                _make_writeable(path_new)
            except OSError:
                sys.stderr.write(("Notice:    Couldn't    set    permission    bits    on    %s.    You're    probably    using    an    uncommon    filesystem    setup.    No    problem.\n" % path_new))


What's a good function header?
targets: def copy_template(app_template, copy_to, project_name, app_name):
inputs: I wrote the below code

    bn = BatchNormalization(input_dim, broadcastable, conserve_memory, epsilon=0.0001, mean_only=mean_only, learn_scale=learn_scale, learn_shift=learn_shift)
    bn.initialize()
    b_len = (len(input_dim) if isinstance(input_dim, collections.Sequence) else 1)
    x = tensor.TensorType(theano.config.floatX, ([False] * (b_len + 1)))()
    return (bn, x)


What's a good function header?
targets: def apply_setup(input_dim, broadcastable, conserve_memory, mean_only, learn_scale, learn_shift):
inputs: Complete the below
def importfile(path):

    ''''Import a Python source file or compiled file given its path.'
    '''
targets: magic = imp.get_magic()
    file = open(path, 'r')
    if (file.read(len(magic)) == magic):
        kind = imp.PY_COMPILED
    else:
        kind = imp.PY_SOURCE
    file.close()
    filename = os.path.basename(path)
    (name, ext) = os.path.splitext(filename)
    file = open(path, 'r')
    try:
        module = imp.load_module(name, file, path, (ext, 'r', kind))
    except:
        raise ErrorDuringImport(path, sys.exc_info())
    file.close()
    return module
inputs: I wrote the below code

    from django.utils.text import phone2numeric
    return phone2numeric(value)


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

    class metaclass(type, ):
        def __new__(cls, name, this_bases, d):
            return meta(name, bases, d)
    return type.__new__(metaclass, 'temporary_class', (), {})


What's a good function header?
targets: def with_metaclass(meta, *bases):
inputs: I wrote the below code

    env = inliner.document.settings.env
    r = None
    r = env.get_domain('py').role('obj')('obj', rawtext, etext, lineno, inliner, options, content)
    pnode = r[0][0]
    prefixes = get_import_prefixes_from_env(env)
    try:
        (name, obj, parent, modname) = import_by_name(pnode['reftarget'], prefixes)
    except ImportError:
        content_node = pnode[0]
        r[0][0] = nodes.emphasis(rawtext, content_node[0].astext(), classes=content_node['classes'])
    return r


What's a good function header?
targets: def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]):
inputs: Complete the below
def _check_guts_toc_mtime(attr, old, toc, last_build, pyc=0):

    ''''rebuild is required if mtimes of files listed in old toc are newer
    than last_build
    if pyc=1, check for .py files, too
    Use this for calculated/analysed values read from cache.'
    '''
targets: for (nm, fnm, typ) in old:
        if (misc.mtime(fnm) > last_build):
            logger.info('Building    because    %s    changed', fnm)
            return True
        elif (pyc and (misc.mtime(fnm[:(-1)]) > last_build)):
            logger.info('Building    because    %s    changed', fnm[:(-1)])
            return True
    return False
inputs: I wrote the below code

    if (not hop_length):
        hop_length = (n_fft // 2)
    ifft_config = dict(win_length=n_fft, hop_length=hop_length, center=True)
    if mag_only:
        mag = spec[:, :, 0]
        phase_angle = (np.pi * np.random.rand(*mag.shape))
    elif re_im:
        spec_real = (spec[:, :, 0] + (1j * spec[:, :, 1]))
    else:
        (mag, p) = (spec[:, :, 0], spec[:, :, 1])
        if (mask and log_mag):
            p /= (mag + (1e-13 * np.random.randn(*mag.shape)))
        if dphase:
            phase_angle = np.cumsum((p * np.pi), axis=1)
        else:
            phase_angle = (p * np.pi)
    if log_mag:
        mag = ((mag - 1.0) * 120.0)
        mag = (10 ** (mag / 20.0))
    phase = (np.cos(phase_angle) + (1j * np.sin(phase_angle)))
    spec_real = (mag * phase)
    if mag_only:
        audio = griffin_lim(mag, phase_angle, n_fft, hop_length, num_iters=num_iters)
    else:
        audio = librosa.core.istft(spec_real, **ifft_config)
    return np.squeeze((audio / audio.max()))


What's a good function header?
targets: def ispecgram(spec, n_fft=512, hop_length=None, mask=True, log_mag=True, re_im=False, dphase=True, mag_only=True, num_iters=1000):
inputs: I wrote the below code

    match = re.search(pattern, value)
    if (match is None):
        raise Exception(('Pattern    "%s"    did    not    match    value:    %s' % (pattern, value)))
    return match.groupdict()


What's a good function header?
targets: def parse_to_dict(pattern, value):
inputs: def dnsdomain_unregister(context, fqdomain):
targets: """Purge associations for the specified DNS zone.
    """
    return IMPL.dnsdomain_unregister(context, fqdomain)
inputs: I wrote the below code

    (_, local_dict) = get_twill_glocals()
    inp = raw_input(prompt)
    local_dict['__input__'] = inp
    return inp


What's a good function header?
targets: def getinput(prompt):
inputs: @pytest.mark.installed
def test_activate_has_extra_env_vars(shell):
targets: """Test that environment variables in activate.d show up when activated
    """
    shell_vars = _format_vars(shell)
    with TemporaryDirectory(prefix=ENVS_PREFIX, dir=dirname(__file__)) as envs:
        env_dirs = gen_test_env_paths(envs, shell)
        for path in [u'activate', u'deactivate']:
            dir = os.path.join(shells[shell][u'path_from'](env_dirs[0]), u'etc', u'conda', (u'%s.d' % path))
            os.makedirs(dir)
            file = os.path.join(dir, (u'test' + shells[shell][u'env_script_suffix']))
            setting = (u'test' if (path == u'activate') else u'')
            with open(file, u'w') as f:
                f.write((shells[shell][u'set_var'] + (u'TEST_VAR=%s\n' % setting)))
        commands = (shell_vars[u'command_setup'] + u'\n                                {source}    "{syspath}{binpath}activate"    "{env_dirs[0]}"\n                                {echo}    {var}\n                                ').format(envs=envs, env_dirs=env_dirs, var=shells[shell][u'var_format'].format(u'TEST_VAR'), **shell_vars)
        (stdout, stderr) = run_in(commands, shell)
        assert (not stderr)
        assert_equals(stdout, u'test', stderr)
        commands = (shell_vars[u'command_setup'] + u'\n                                {source}    "{syspath}{binpath}activate"    "{env_dirs[0]}"\n                                {source}    "{syspath}{binpath}deactivate"\n                                {echo}    {var}.\n                                ').format(envs=envs, env_dirs=env_dirs, var=shells[shell][u'var_format'].format(u'TEST_VAR'), **shell_vars)
        (stdout, stderr) = run_in(commands, shell)
        assert_equals(stdout, u'.', stderr)
inputs: I wrote the below code

    @functools.wraps(test)
    def wrapper(*args, **kwargs):
        msg = '{name}    requires    Python    2.7.x+    to    run'.format(name=test.__name__)
        if (sys.version_info < (2, 7)):
            pytest.skip(msg)
        return test(*args, **kwargs)
    return wrapper


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

    if exact:
        if (np.ndim(n) == 0):
            return (0 if (n < 0) else math.factorial(n))
        else:
            n = asarray(n)
            un = np.unique(n).astype(object)
            if (un[(-1)] > 20):
                dt = object
            elif (un[(-1)] > 12):
                dt = np.int64
            else:
                dt = np.int
            out = np.empty_like(n, dtype=dt)
            un = un[(un > 1)]
            out[(n < 2)] = 1
            out[(n < 0)] = 0
            if un.size:
                val = math.factorial(un[0])
                out[(n == un[0])] = val
                for i in xrange((len(un) - 1)):
                    prev = (un[i] + 1)
                    current = un[(i + 1)]
                    val *= _range_prod(prev, current)
                    out[(n == current)] = val
            return out
    else:
        n = asarray(n)
        vals = gamma((n + 1))
        return where((n >= 0), vals, 0)


What's a good function header?
targets: def factorial(n, exact=False):
inputs: def _use_inf_as_na(key):
targets: """Option change callback for na/inf behaviour
    Choose which replacement for numpy.isnan / -numpy.isfinite is used.
    Parameters
    flag: bool
    True means treat None, NaN, INF, -INF as null (old way),
    False means None and NaN are null, but INF, -INF are not null
    (new way).
    Notes
    This approach to setting global module values is discussed and
    approved here:
    * http://stackoverflow.com/questions/4859217/
    programmatically-creating-variables-in-python/4859312#4859312
    """
    from pandas.core.config import get_option
    flag = get_option(key)
    if flag:
        globals()['_isna'] = _isna_old
    else:
        globals()['_isna'] = _isna_new
inputs: I wrote the below code

    if ((n <= 0) or ((m is not None) and (m < 1)) or ((k is not None) and (k < 1)) or (m and k and ((m * k) < n))):
        if size:
            (yield (0, {}))
        else:
            (yield {})
        return
    if (m is None):
        m = n
    else:
        m = min(m, n)
    if (n == 0):
        if size:
            (yield (1, {0: 1}))
        else:
            (yield {0: 1})
        return
    k = min((k or n), n)
    (n, m, k) = (as_int(n), as_int(m), as_int(k))
    (q, r) = divmod(n, k)
    ms = {k: q}
    keys = [k]
    if r:
        ms[r] = 1
        keys.append(r)
    room = ((m - q) - bool(r))
    if size:
        (yield (sum(ms.values()), ms))
    else:
        (yield ms)
    while (keys != [1]):
        if (keys[(-1)] == 1):
            del keys[(-1)]
            reuse = ms.pop(1)
            room += reuse
        else:
            reuse = 0
        while 1:
            i = keys[(-1)]
            newcount = ms[i] = (ms[i] - 1)
            reuse += i
            if (newcount == 0):
                del keys[(-1)], ms[i]
            room += 1
            i -= 1
            (q, r) = divmod(reuse, i)
            need = (q + bool(r))
            if (need > room):
                if (not keys):
                    return
                continue
            ms[i] = q
            keys.append(i)
            if r:
                ms[r] = 1
                keys.append(r)
            break
        room -= need
        if size:
            (yield (sum(ms.values()), ms))
        else:
            (yield ms)


What's a good function header?
targets: def partitions(n, m=None, k=None, size=False):
inputs: def frame_from_fsnative(arg):
targets: """Takes item from argv and returns ascii native str
    or raises ValueError.
    """
    assert isinstance(arg, fsnative)
    text = fsn2text(arg, strict=True)
    if PY2:
        return text.encode('ascii')
    else:
        return text.encode('ascii').decode('ascii')
inputs: I wrote the below code

    ordering_field_columns = cl.get_ordering_field_columns()
    for (i, field_name) in enumerate(cl.list_display):
        (text, attr) = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True)
        if attr:
            field_name = _coerce_field_name(field_name, i)
            if (field_name == 'action_checkbox'):
                (yield {'text': text, 'class_attrib': mark_safe('    class="action-checkbox-column"'), 'sortable': False})
                continue
            admin_order_field = getattr(attr, 'admin_order_field', None)
            if (not admin_order_field):
                (yield {'text': text, 'class_attrib': format_html('    class="column-{}"', field_name), 'sortable': False})
                continue
        th_classes = ['sortable', 'column-{}'.format(field_name)]
        order_type = ''
        new_order_type = 'asc'
        sort_priority = 0
        sorted = False
        if (i in ordering_field_columns):
            sorted = True
            order_type = ordering_field_columns.get(i).lower()
            sort_priority = (list(ordering_field_columns).index(i) + 1)
            th_classes.append(('sorted    %sending' % order_type))
            new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]
        o_list_primary = []
        o_list_remove = []
        o_list_toggle = []
        def make_qs_param(t, n):
            return (('-' if (t == 'desc') else '') + str(n))
        for (j, ot) in ordering_field_columns.items():
            if (j == i):
                param = make_qs_param(new_order_type, j)
                o_list_primary.insert(0, param)
                o_list_toggle.append(param)
            else:
                param = make_qs_param(ot, j)
                o_list_primary.append(param)
                o_list_toggle.append(param)
                o_list_remove.append(param)
        if (i not in ordering_field_columns):
            o_list_primary.insert(0, make_qs_param(new_order_type, i))
        (yield {'text': text, 'sortable': True,...

What's a good function header?
targets: def result_headers(cl):
inputs: Complete the below
def capture_screenshot_for_step(step, when):

    ''''Useful method for debugging acceptance tests that are run in Vagrant.
    This method runs automatically before and after each step of an acceptance
    test scenario. The variable:
    world.auto_capture_screenshots
    either enables or disabled the taking of screenshots. To change the
    variable there is a convenient step defined:
    I (enable|disable) auto screenshots
    If you just want to capture a single screenshot at a desired point in code,
    you should use the method:
    world.capture_screenshot("image_name")'
    '''
targets: if world.auto_capture_screenshots:
        scenario_num = (step.scenario.feature.scenarios.index(step.scenario) + 1)
        step_num = (step.scenario.steps.index(step) + 1)
        step_func_name = step.defined_at.function.func_name
        image_name = '{prefix:03d}__{num:03d}__{name}__{postfix}'.format(prefix=scenario_num, num=step_num, name=step_func_name, postfix=when)
        world.capture_screenshot(image_name)
inputs: @mock_ec2_deprecated
def test_eip_allocate_vpc():
targets: """Allocate/release VPC EIP
    """
    conn = boto.connect_ec2(u'the_key', u'the_secret')
    with assert_raises(EC2ResponseError) as ex:
        vpc = conn.allocate_address(domain=u'vpc', dry_run=True)
    ex.exception.error_code.should.equal(u'DryRunOperation')
    ex.exception.status.should.equal(400)
    ex.exception.message.should.equal(u'An    error    occurred    (DryRunOperation)    when    calling    the    AllocateAddress    operation:    Request    would    have    succeeded,    but    DryRun    flag    is    set')
    vpc = conn.allocate_address(domain=u'vpc')
    vpc.should.be.a(boto.ec2.address.Address)
    vpc.domain.should.be.equal(u'vpc')
    logging.debug(u'vpc    alloc_id:'.format(vpc.allocation_id))
    vpc.release()
inputs: I wrote the below code

    output = s3_rest_controller()
    return output


What's a good function header?
targets: def question_metadata():
inputs: Complete the below
def convert_image(source, dest, out_format):

    ''''Convert image to other format'
    '''
targets: cmd = ('qemu-img', 'convert', '-O', out_format, source, dest)
    utils.execute(run_as_root=True, *cmd)
inputs: def auth(profile=None, **connection_args):
targets: """Set up keystone credentials. Only intended to be used within Keystone-enabled modules.
    CLI Example:
    .. code-block:: bash
    salt \*\ keystone.auth
    """
    kwargs = _get_kwargs(profile=profile, **connection_args)
    if (float(api_version(profile=profile, **connection_args).strip('v')) >= 3):
        global _OS_IDENTITY_API_VERSION
        global _TENANTS
        _OS_IDENTITY_API_VERSION = 3
        _TENANTS = 'projects'
        return client3.Client(**kwargs)
    else:
        return client.Client(**kwargs)
inputs: def _plot_connectivity_circle_onpick(event, fig=None, axes=None, indices=None, n_nodes=0, node_angles=None, ylim=[9, 10]):
targets: """Isolate connections around a single node when user left clicks a node.
    On right click, resets all connections.
    """
    if (event.inaxes != axes):
        return
    if (event.button == 1):
        if (not (ylim[0] <= event.ydata <= ylim[1])):
            return
        node_angles = (node_angles % (np.pi * 2))
        node = np.argmin(np.abs((event.xdata - node_angles)))
        patches = event.inaxes.patches
        for (ii, (x, y)) in enumerate(zip(indices[0], indices[1])):
            patches[ii].set_visible((node in [x, y]))
        fig.canvas.draw()
    elif (event.button == 3):
        patches = event.inaxes.patches
        for ii in range(np.size(indices, axis=1)):
            patches[ii].set_visible(True)
        fig.canvas.draw()
inputs: Complete the below
def Name(name, prefix=None):

    ''''Return a NAME leaf'
    '''
targets: return Leaf(token.NAME, name, prefix=prefix)
inputs: Complete the below
def Search(pattern, s):

    ''''Searches the string for the pattern, caching the compiled regexp.'
    '''
targets: if (pattern not in _regexp_compile_cache):
        _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
    return _regexp_compile_cache[pattern].search(s)
inputs: Complete the below
def length(value):

    ''''Returns the length of the value - useful for lists.'
    '''
targets: try:
        return len(value)
    except (ValueError, TypeError):
        return ''
inputs: I wrote the below code

    global _RC_CACHE
    if (_RC_CACHE is not None):
        return
    _RC_CACHE = rc_cache.ResourceClassCache(ctx)


What's a good function header?
targets: @db_api.api_context_manager.reader
def _ensure_rc_cache(ctx):
inputs: I wrote the below code

    for char in value:
        if (char not in _VISIBLE_PRINTABLE_ASCII):
            raise ValueError(('%r    must    be    visible    printable    ASCII:    %r' % (name, value)))
    if value.startswith('!'):
        raise ValueError(('%r    must    not    start    with    "!":    %r' % (name, value)))
    return value


What's a good function header?
targets: def _ValidateVisiblePrintableAsciiNotReserved(value, name):
inputs: I wrote the below code

    if (module.check_mode and (path is not None)):
        keysfile = path
        return keysfile
    try:
        user_entry = pwd.getpwnam(user)
    except KeyError:
        e = get_exception()
        if (module.check_mode and (path is None)):
            module.fail_json(msg='Either    user    must    exist    or    you    must    provide    full    path    to    key    file    in    check    mode')
        module.fail_json(msg=('Failed    to    lookup    user    %s:    %s' % (user, str(e))))
    if (path is None):
        homedir = user_entry.pw_dir
        sshdir = os.path.join(homedir, '.ssh')
        keysfile = os.path.join(sshdir, 'authorized_keys')
    else:
        sshdir = os.path.dirname(path)
        keysfile = path
    if (not write):
        return keysfile
    uid = user_entry.pw_uid
    gid = user_entry.pw_gid
    if manage_dir:
        if (not os.path.exists(sshdir)):
            os.mkdir(sshdir, int('0700', 8))
            if module.selinux_enabled():
                module.set_default_selinux_context(sshdir, False)
        os.chown(sshdir, uid, gid)
        os.chmod(sshdir, int('0700', 8))
    if (not os.path.exists(keysfile)):
        basedir = os.path.dirname(keysfile)
        if (not os.path.exists(basedir)):
            os.makedirs(basedir)
        try:
            f = open(keysfile, 'w')
        finally:
            f.close()
        if module.selinux_enabled():
            module.set_default_selinux_context(keysfile, False)
    try:
        os.chown(keysfile, uid, gid)
        os.chmod(keysfile, int('0600', 8))
    except OSError:
        pass
    return keysfile


What's a good function header?
targets: def keyfile(module, user, write=False, path=None, manage_dir=True):
inputs: I wrote the below code

    QtWebEngineWidgets = pytest.importorskip('PyQt5.QtWebEngineWidgets')
    return QtWebEngineWidgets.QWebEngineView()


What's a good function header?
targets: @pytest.fixture
def webengineview():
inputs: @utils.positional(1)
def _gql(query_string, query_class=Query):
targets: """Parse a GQL query string (internal version).
    Args:
    query_string: Full GQL query, e.g. \SELECT * FROM Kind WHERE prop = 1\.
    query_class: Optional class to use, default Query.
    Returns:
    An instance of query_class.
    """
    from .google_imports import gql
    gql_qry = gql.GQL(query_string)
    kind = gql_qry.kind()
    if (kind is None):
        modelclass = model.Expando
    else:
        modelclass = model.Model._lookup_model(kind, tasklets.get_context()._conn.adapter.default_model)
        kind = modelclass._get_kind()
    ancestor = None
    flt = gql_qry.filters()
    filters = list(modelclass._default_filters())
    for name_op in sorted(flt):
        (name, op) = name_op
        values = flt[name_op]
        op = op.lower()
        if ((op == 'is') and (name == gql.GQL._GQL__ANCESTOR)):
            if (len(values) != 1):
                raise ValueError('"is"    requires    exactly    one    value')
            [(func, args)] = values
            ancestor = _args_to_val(func, args)
            continue
        if (op not in _OPS):
            raise NotImplementedError(('Operation    %r    is    not    supported.' % op))
        for (func, args) in values:
            val = _args_to_val(func, args)
            prop = _get_prop_from_modelclass(modelclass, name)
            if (prop._name != name):
                raise RuntimeError(('Whoa!    _get_prop_from_modelclass(%s,    %r)    returned    a    property    whose    name    is    %r?!' % (modelclass.__name__, name, prop._name)))
            if isinstance(val, ParameterizedThing):
                node = ParameterNode(prop, op, val)
            elif (op == 'in'):
                node = prop._IN(val)
            else:
                node = prop._comparison(op, val)
            filters.append(node)
    if filters:
        filters = ConjunctionNode(*filters)
    else:
        filters = None
    orders = _orderings_to_orders(gql_qry.orderings(), modelclass)
    offset = gql_qry.offset()
    limit = gql_qry.limit()
    if (limit < 0):
        limit = None
    keys_only = gql_qry._keys_only
    if (not keys_only):
        keys_only = None
    options = QueryOptions(offset=offset, limit=limit, keys_only=keys_only)
    projection = gql_qry.projection()
    if...
inputs: Complete the below
def is_target_domain_use_https(domain):

    ''''è¯·æ±ç®æ ååæ¶æ¯åŠäœ¿çšhttps'
    '''
targets: if (force_https_domains == 'NONE'):
        return False
    if (force_https_domains == 'ALL'):
        return True
    if (domain in force_https_domains):
        return True
    else:
        return False
inputs: I wrote the below code

    dash = (_allowMOSFSNames and (p[:1] == '-'))
    if dash:
        q = (string.find(p, '-', 1) + 1)
    elif (p[:1] == ':'):
        q = 0
    else:
        q = (string.find(p, ':') + 1)
    s = string.find(p, '#')
    if ((s == (-1)) or (s > q)):
        s = q
    else:
        for c in p[dash:s]:
            if (c not in string.ascii_letters):
                q = 0
                break
    r = q
    if (p[q:(q + 1)] == ':'):
        r = (string.find(p, '.', (q + 1)) + 1)
        if (r == 0):
            r = len(p)
    return (p[:q], p[q:r], p[r:])


What's a good function header?
targets: def _split(p):
inputs: @deprecated(u'2.0', message=_hold_msg)
def over(func, *args, **kwargs):
targets: """Call a function with hold(True).
    Calls::
    func(*args, **kwargs)
    with ``hold(True)`` and then restores the hold state.
    """
    ax = gca()
    h = ax._hold
    ax._hold = True
    func(*args, **kwargs)
    ax._hold = h