Muennighoff/xP3x-sample huggingface dataset:
inputs: def generate_control(tests, kernels=None, platform=None, is_server=False, profilers=(), client_control_file='', profile_only=None, upload_kernel_config=False):
targets: """Generate a control file for a sequence of tests.
    :param tests A sequence of test control files to run.
    :param kernels A sequence of kernel info dictionaries configuring which
    kernels to boot for this job and other options for them
    :param platform A platform object with a kernel_config attribute.
    :param is_server bool, Is this a server control file rather than a client?
    :param profilers A list of profiler objects to enable during the tests.
    :param client_control_file Contents of a client control file to run as the
    last test after everything in tests.  Requires is_server=False.
    :param profile_only bool, should this control file run all tests in
    profile_only mode by default
    :param upload_kernel_config: if enabled it will generate server control
    file code that uploads the kernel config file to the client and
    tells the client of the new (local) path when compiling the kernel;
    the tests must be server side tests
    :return: The control file text as a string.
    """
    _sanity_check_generate_control(is_server=is_server, kernels=kernels, client_control_file=client_control_file, upload_kernel_config=upload_kernel_config)
    control_file_text = ''
    if kernels:
        control_file_text = get_kernel_stanza(kernels, platform, is_server=is_server, upload_kernel_config=upload_kernel_config)
    else:
        control_file_text = EMPTY_TEMPLATE
    (prepend, append) = _get_profiler_commands(profilers, is_server, profile_only)
    control_file_text += get_tests_stanza(tests, is_server, prepend, append, client_control_file)
    return control_file_text
inputs: Complete the below
def cumsum(x, axis=None):

    ''''Return the cumulative sum of the elements along a given axis.
    Wraping of numpy.cumsum.
    Parameters
    x
    Input tensor variable.
    axis
    The axis along which the cumulative sum is computed.
    The default (None) is to compute the cumsum over the flattened array.
    .. versionadded:: 0.7'
    '''
targets: return CumOp(axis=axis, mode='add')(x)
inputs: I wrote the below code

    input = numpy.asarray(input)
    def derivative(input, axis, output, mode, cval, sigma, **kwargs):
        order = ([0] * input.ndim)
        order[axis] = 1
        return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs)
    return generic_gradient_magnitude(input, derivative, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs)


What's a good function header?
targets: @docfiller
def gaussian_gradient_magnitude(input, sigma, output=None, mode='reflect', cval=0.0, **kwargs):
inputs: Complete the below
def get_ami_metadata():

    ''''Fetch ami metadata for the local instance. Returns a dict of \'key\':\'value\'. eg: \'instance-id\':\'i-e7f7e69b\'.'
    '''
targets: res = {}
    base_url = 'http://169.254.169.254/latest/meta-data'
    instance_id = run(('curl    %s/instance-id' % base_url))
    assert re.match('i-[0-9a-f]{8}', instance_id)
    res['instance-id'] = instance_id
    return res
inputs: Complete the below
def encode(body, binary=False, maxlinelen=76, eol=NL):

    ''''Encode with quoted-printable, wrapping at maxlinelen characters.
    If binary is False (the default), end-of-line characters will be converted
    to the canonical email end-of-line sequence \r\n.  Otherwise they will
    be left verbatim.
    Each line of encoded text will end with eol, which defaults to "\n".  Set
    this to "\r\n" if you will be using the result of this function directly
    in an email.
    Each line will be wrapped at, at most, maxlinelen characters (defaults to
    76 characters).  Long lines will have the `soft linefeed\' quoted-printable
    character "=" appended to them, so the decoded text will be identical to
    the original text.'
    '''
targets: if (not body):
        return body
    if (not binary):
        body = fix_eols(body)
    encoded_body = ''
    lineno = (-1)
    lines = body.splitlines(1)
    for line in lines:
        if line.endswith(CRLF):
            line = line[:(-2)]
        elif (line[(-1)] in CRLF):
            line = line[:(-1)]
        lineno += 1
        encoded_line = ''
        prev = None
        linelen = len(line)
        for j in range(linelen):
            c = line[j]
            prev = c
            if bqre.match(c):
                c = quote(c)
            elif ((j + 1) == linelen):
                if (c not in '     DCTB '):
                    encoded_line += c
                prev = c
                continue
            if ((len(encoded_line) + len(c)) >= maxlinelen):
                encoded_body += ((encoded_line + '=') + eol)
                encoded_line = ''
            encoded_line += c
        if (prev and (prev in '     DCTB ')):
            if ((lineno + 1) == len(lines)):
                prev = quote(prev)
                if ((len(encoded_line) + len(prev)) > maxlinelen):
                    encoded_body += (((encoded_line + '=') + eol) + prev)
                else:
                    encoded_body += (encoded_line + prev)
            else:
                encoded_body += (((encoded_line + prev) + '=') + eol)
            encoded_line = ''
        if (lines[lineno].endswith(CRLF) or (lines[lineno][(-1)] in CRLF)):
            encoded_body += (encoded_line + eol)
        else:
            encoded_body += encoded_line
        encoded_line = ''
    return encoded_body
inputs: def bzr(registry, xml_parent, data):
targets: """yaml: bzr
    Specifies the bzr SCM repository for this job.
    Requires the Jenkins :jenkins-wiki:`Bazaar Plugin <Bazaar+Plugin>`.
    :arg str url: URL of the bzr branch (required)
    :arg bool clean-tree: Clean up the workspace (using bzr) before pulling
    the branch (default false)
    :arg bool lightweight-checkout: Use a lightweight checkout instead of a
    full branch (default false)
    :arg str browser: The repository browser to use.
    :browsers supported:
    * **auto** - (default)
    * **loggerhead** - as used by Launchpad
    * **opengrok** - https://opengrok.github.io/OpenGrok/
    :arg str browser-url:
    URL for the repository browser (required if browser is set).
    :arg str opengrok-root-module:
    Root module for OpenGrok (required if browser is opengrok).
    Example:
    .. literalinclude:: /../../tests/scm/fixtures/bzr001.yaml
    :language: yaml
    """
    mapping = [('url', 'source', None), ('clean-tree', 'cleantree', False), ('lightweight-checkout', 'checkout', False)]
    scm_element = XML.SubElement(xml_parent, 'scm', {'class': 'hudson.plugins.bazaar.BazaarSCM'})
    convert_mapping_to_xml(scm_element, data, mapping, fail_required=True)
    browser_name_to_class = {'loggerhead': 'Loggerhead', 'opengrok': 'OpenGrok'}
    browser = data.get('browser', 'auto')
    if (browser == 'auto'):
        return
    if (browser not in browser_name_to_class):
        raise InvalidAttributeError('browser', browser, browser_name_to_class.keys())
    browser_element = XML.SubElement(scm_element, 'browser', {'class': 'hudson.plugins.bazaar.browsers.{0}'.format(browser_name_to_class[browser])})
    mapping = [('browser-url', 'url', None)]
    convert_mapping_to_xml(browser_element, data, mapping, fail_required=True)
    if (browser == 'opengrok'):
        mapping = [('opengrok-root-module', 'rootModule', None)]
        convert_mapping_to_xml(browser_element, data, mapping, fail_required=True)
inputs: Complete the below
def _EndsWithPython(path):

    ''''Check if given path ends with a python 2.6+ or 3.3+ name.'
    '''
targets: return (path and (PYTHON_BINARY_REGEX.search(path) is not None))
inputs: @main.command()
@click.option('-f', '--algofile', default=None, type=click.File('r'), help='The    file    that    contains    the    algorithm    to    run.')
@click.option('-t', '--algotext', help='The    algorithm    script    to    run.')
@click.option('-D', '--define', multiple=True, help="Define    a    name    to    be    bound    in    the    namespace    before    executing    the    algotext.    For    example    '-Dname=value'.    The    value    may    be    any    python    expression.    These    are    evaluated    in    order    so    they    may    refer    to    previously    defined    names.")
@click.option('--data-frequency', type=click.Choice({'daily', 'minute'}), default='daily', show_default=True, help='The    data    frequency    of    the    simulation.')
@click.option('--capital-base', type=float, default=10000000.0, show_default=True, help='The    starting    capital    for    the    simulation.')
@click.option('-b', '--bundle', default='quantopian-quandl', metavar='BUNDLE-NAME', show_default=True, help='The    data    bundle    to    use    for    the    simulation.')
@click.option('--bundle-timestamp', type=Timestamp(), default=pd.Timestamp.utcnow(), show_default=False, help='The    date    to    lookup    data    on    or    before.\n[default:    <current-time>]')
@click.option('-s', '--start', type=Date(tz='utc', as_timestamp=True), help='The    start    date    of    the    simulation.')
@click.option('-e', '--end', type=Date(tz='utc', as_timestamp=True), help='The    end    date    of    the    simulation.')
@click.option('-o', '--output', default='-', metavar='FILENAME', show_default=True, help="The    location    to    write    the    perf    data.    If    this    is    '-'    the    perf    will    be    written    to    stdout.")
@click.option('--print-algo/--no-print-algo', is_flag=True, default=False, help='Print    the    algorithm    to    stdout.')
@ipython_only(click.option('--local-namespace/--no-local-namespace', is_flag=True, default=None, help='Should    the   ...
targets: """Run a backtest for the given algorithm.
    """
    if ((start is None) and (end is None)):
        ctx.fail("must    specify    dates    with    '-s'    /    '--start'    and    '-e'    /    '--end'")
    if (start is None):
        ctx.fail("must    specify    a    start    date    with    '-s'    /    '--start'")
    if (end is None):
        ctx.fail("must    specify    an    end    date    with    '-e'    /    '--end'")
    if ((algotext is not None) == (algofile is not None)):
        ctx.fail("must    specify    exactly    one    of    '-f'    /    '--algofile'    or    '-t'    /    '--algotext'")
    perf = _run(initialize=None, handle_data=None, before_trading_start=None, analyze=None, algofile=algofile, algotext=algotext, defines=define, data_frequency=data_frequency, capital_base=capital_base, data=None, bundle=bundle, bundle_timestamp=bundle_timestamp, start=start, end=end, output=output, print_algo=print_algo, local_namespace=local_namespace, environ=os.environ)
    if (output == '-'):
        click.echo(str(perf))
    elif (output != os.devnull):
        perf.to_pickle(output)
    return perf
inputs: def find_intersection(x, tr_bounds, lb, ub):
targets: """Find intersection of trust-region bounds and initial bounds.
    Returns
    lb_total, ub_total : ndarray with shape of x
    Lower and upper bounds of the intersection region.
    orig_l, orig_u : ndarray of bool with shape of x
    True means that an original bound is taken as a corresponding bound
    in the intersection region.
    tr_l, tr_u : ndarray of bool with shape of x
    True means that a trust-region bound is taken as a corresponding bound
    in the intersection region.
    """
    lb_centered = (lb - x)
    ub_centered = (ub - x)
    lb_total = np.maximum(lb_centered, (- tr_bounds))
    ub_total = np.minimum(ub_centered, tr_bounds)
    orig_l = np.equal(lb_total, lb_centered)
    orig_u = np.equal(ub_total, ub_centered)
    tr_l = np.equal(lb_total, (- tr_bounds))
    tr_u = np.equal(ub_total, tr_bounds)
    return (lb_total, ub_total, orig_l, orig_u, tr_l, tr_u)
inputs: Complete the below
@loader_option()
def immediateload(loadopt, attr):

    ''''Indicate that the given attribute should be loaded using
    an immediate load with a per-attribute SELECT statement.
    This function is part of the :class:`.Load` interface and supports
    both method-chained and standalone operation.
    .. seealso::
    :ref:`loading_toplevel`
    :func:`.orm.joinedload`
    :func:`.orm.lazyload`
    :paramref:`.relationship.lazy`'
    '''
targets: loader = loadopt.set_relationship_strategy(attr, {'lazy': 'immediate'})
    return loader
inputs: def l2(x):
targets: """Computes the squared L2 norm of a tensor
    Parameters
    x : Theano tensor
    Returns
    Theano scalar
    squared l2 norm (sum of squared values of elements)
    """
    return T.sum((x ** 2))
inputs: Complete the below
@bdd.then(bdd.parsers.parse('the    javascript    message    "{message}"    should    not    be    logged'))
def javascript_message_not_logged(quteproc, message):

    ''''Make sure the given message was *not* logged via javascript.'
    '''
targets: quteproc.ensure_not_logged(category='js', function='javaScriptConsoleMessage', message='[*]    {}'.format(message))
inputs: def make_messages(locale=None, domain='django', verbosity=1, all=False, extensions=None, symlinks=False, ignore_patterns=None, no_wrap=False, no_location=False, no_obsolete=False, stdout=sys.stdout):
targets: """Uses the ``locale/`` directory from the Django SVN tree or an
    application/project to process all files with translatable literals for
    the :param domain: domain and :param locale: locale.
    """
    from django.conf import settings
    if settings.configured:
        settings.USE_I18N = True
    else:
        settings.configure(USE_I18N=True)
    if (ignore_patterns is None):
        ignore_patterns = []
    invoked_for_django = False
    if os.path.isdir(os.path.join('conf', 'locale')):
        localedir = os.path.abspath(os.path.join('conf', 'locale'))
        invoked_for_django = True
        ignore_patterns += ['contrib/*']
    elif os.path.isdir('locale'):
        localedir = os.path.abspath('locale')
    else:
        raise CommandError('This    script    should    be    run    from    the    Django    SVN    tree    or    your    project    or    app    tree.    If    you    did    indeed    run    it    from    the    SVN    checkout    or    your    project    or    application,    maybe    you    are    just    missing    the    conf/locale    (in    the    django    tree)    or    locale    (for    project    and    application)    directory?    It    is    not    created    automatically,    you    have    to    create    it    by    hand    if    you    want    to    enable    i18n    for    your    project    or    application.')
    if (domain not in ('django', 'djangojs')):
        raise CommandError("currently    makemessages    only    supports    domains    'django'    and    'djangojs'")
    if (((locale is None) and (not all)) or (domain is None)):
        message = ("Type    '%s    help    %s'    for    usage    information." % (os.path.basename(sys.argv[0]), sys.argv[1]))
        raise CommandError(message)
    output = _popen('xgettext    --version')[0]
    match = re.search('(?P<major>\\d+)\\.(?P<minor>\\d+)', output)
    if match:
        xversion = (int(match.group('major')), int(match.group('minor')))
        if (xversion < (0, 15)):
            raise CommandError(('Django    internationalization    requires    GNU    gettext    0.15    or    newer.    You    are    using    version    %s,    please    upgrade    your    gettext    toolset.' % match.group()))
    locales =...
inputs: Complete the below
@flaky(max_runs=3)
@pytest.mark.skipif((os.name == 'nt'), reason='It    times    out    on    Windows')
def test_restart_kernel(ipyconsole, qtbot):

    ''''Test that kernel is restarted correctly'
    '''
targets: shell = ipyconsole.get_current_shellwidget()
    client = ipyconsole.get_current_client()
    qtbot.waitUntil((lambda : (shell._prompt_html is not None)), timeout=SHELL_TIMEOUT)
    with qtbot.waitSignal(shell.executed):
        shell.execute('a    =    10')
    shell._prompt_html = None
    QTimer.singleShot(1000, (lambda : close_message_box(qtbot)))
    client.restart_kernel()
    qtbot.waitUntil((lambda : (shell._prompt_html is not None)), timeout=SHELL_TIMEOUT)
    assert (not shell.is_defined('a'))
inputs: @pytest.fixture(scope='module')
def genesis_fixture():
targets: """Read genesis block from fixtures.
    """
    genesis_fixture = None
    fn = os.path.join(testutils.fixture_path, 'BasicTests', 'genesishashestest.json')
    with open(fn, 'r') as f:
        genesis_fixture = json.load(f)
    assert (genesis_fixture is not None), "Could    not    read    genesishashtest.json    from    fixtures.    Make    sure    you    did    'git    submodule    init'!"
    for k in ('genesis_rlp_hex', 'genesis_state_root', 'genesis_hash'):
        assert (k in genesis_fixture)
    return genesis_fixture
inputs: I wrote the below code

    def decorator(method):
        _DECORATED_EXTEND_METHODS[method].extend(resources)
        return method
    return decorator


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

    def wrapper(cls):
        orig_vars = cls.__dict__.copy()
        slots = orig_vars.get('__slots__')
        if (slots is not None):
            if isinstance(slots, str):
                slots = [slots]
            for slots_var in slots:
                orig_vars.pop(slots_var)
        orig_vars.pop('__dict__', None)
        orig_vars.pop('__weakref__', None)
        return metaclass(cls.__name__, cls.__bases__, orig_vars)
    return wrapper


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

    cls = sender
    if cls._meta.abstract:
        setattr(cls, 'objects', AbstractManagerDescriptor(cls))
        return
    elif cls._meta.swapped:
        setattr(cls, 'objects', SwappedManagerDescriptor(cls))
        return
    if (not getattr(cls, '_default_manager', None)):
        try:
            cls._meta.get_field('objects')
            raise ValueError(("Model    %s    must    specify    a    custom    Manager,    because    it    has    a    field    named    'objects'" % cls.__name__))
        except FieldDoesNotExist:
            pass
        cls.add_to_class('objects', Manager())
        cls._base_manager = cls.objects
    elif (not getattr(cls, '_base_manager', None)):
        default_mgr = cls._default_manager.__class__
        if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):
            cls._base_manager = cls._default_manager
        else:
            for base_class in default_mgr.mro()[1:]:
                if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):
                    cls.add_to_class('_base_manager', base_class())
                    return
            raise AssertionError('Should    never    get    here.    Please    report    a    bug,    including    your    model    and    model    manager    setup.')


What's a good function header?
targets: def ensure_default_manager(sender, **kwargs):
inputs: Complete the below
def fix_uri_credentials(uri, to_quoted):

    ''''Fix the given uri\'s embedded credentials by round-tripping with
    StoreLocation.
    If to_quoted is True, the uri is assumed to have credentials that
    have not been quoted, and the resulting uri will contain quoted
    credentials.
    If to_quoted is False, the uri is assumed to have credentials that
    have been quoted, and the resulting uri will contain credentials
    that have not been quoted.'
    '''
targets: if (not uri):
        return
    location = glance.store.swift.StoreLocation({})
    if to_quoted:
        location.parse_uri = types.MethodType(legacy_parse_uri, location)
    else:
        location._get_credstring = types.MethodType(legacy__get_credstring, location)
    decrypted_uri = None
    try:
        decrypted_uri = decrypt_location(uri)
    except (TypeError, ValueError) as e:
        raise exception.Invalid(str(e))
    location.parse_uri(decrypted_uri)
    return encrypt_location(location.get_uri())
inputs: I wrote the below code

    if (not ismeetingrunning(trigger.sender)):
        bot.say(u"Can't    do    that,    start    meeting    first")
        return
    if (not trigger.group(2)):
        bot.say(u'Who    are    the    chairs?')
        return
    if (trigger.nick.lower() == meetings_dict[trigger.sender][u'head']):
        meetings_dict[trigger.sender][u'chairs'] = trigger.group(2).lower().split(u'    ')
        chairs_readable = trigger.group(2).lower().replace(u'    ', u',    ')
        logplain((u'Meeting    chairs    are:    ' + chairs_readable), trigger.sender)
        logHTML_listitem((u'<span    style="font-weight:    bold">Meeting    chairs    are:    </span>' + chairs_readable), trigger.sender)
        bot.say((u'\x02Meeting    chairs    are:\x0f    ' + chairs_readable))
    else:
        bot.say(u'Only    meeting    head    can    set    chairs')


What's a good function header?
targets: @commands(u'chairs')
@example(u'.chairs    Tyrope    Jason    elad')
def chairs(bot, trigger):
inputs: I wrote the below code

    if (discovery_info is None):
        return
    name = 'Eight'
    sensors = discovery_info[CONF_BINARY_SENSORS]
    eight = hass.data[DATA_EIGHT]
    all_sensors = []
    for sensor in sensors:
        all_sensors.append(EightHeatSensor(name, eight, sensor))
    async_add_devices(all_sensors, True)


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

    if isinstance(s, six.string_types):
        return force_text(s)
    return s


What's a good function header?
targets: def to_unicode(s):
inputs: def _append_comment(ret, comment):
targets: """append ``comment`` to ``ret[\comment\]``
    """
    if len(ret['comment']):
        ret['comment'] = ((ret['comment'].rstrip() + '\n') + comment)
    else:
        ret['comment'] = comment
    return ret
inputs: Complete the below
def get_integration_manager():

    ''''Return the integration manager for Review Board.
    Returns:
    djblets.integrations.manager.IntegrationManager:
    The integration manager used for Review Board.'
    '''
targets: global _integration_manager
    if (not _integration_manager):
        from reviewboard.integrations.models import IntegrationConfig
        _integration_manager = IntegrationManager(IntegrationConfig)
    return _integration_manager
inputs: def hazard():
targets: """REST Controller
    """
    return s3_rest_controller()
inputs: def check_headers(request):
targets: """A view that responds with value of the X-ARG-CHECK header
    """
    return HttpResponse(('HTTP_X_ARG_CHECK:    %s' % request.META.get('HTTP_X_ARG_CHECK', 'Undefined')))
inputs: I wrote the below code

    possibles = Breakpoint.bplist[(file, line)]
    for i in range(0, len(possibles)):
        b = possibles[i]
        if (b.enabled == 0):
            continue
        if (not checkfuncname(b, frame)):
            continue
        b.hits = (b.hits + 1)
        if (not b.cond):
            if (b.ignore > 0):
                b.ignore = (b.ignore - 1)
                continue
            else:
                return (b, 1)
        else:
            try:
                val = eval(b.cond, frame.f_globals, frame.f_locals)
                if val:
                    if (b.ignore > 0):
                        b.ignore = (b.ignore - 1)
                    else:
                        return (b, 1)
            except:
                return (b, 0)
    return (None, None)


What's a good function header?
targets: def effective(file, line, frame):
inputs: Complete the below
def _plot_dipole_mri_orthoview(dipole, trans, subject, subjects_dir=None, coord_frame='head', idx='gof', show_all=True, ax=None, block=False, show=True):

    ''''Plot dipoles on top of MRI slices in 3-D.'
    '''
targets: import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    from .. import Dipole
    if (not has_nibabel()):
        raise ImportError('This    function    requires    nibabel.')
    import nibabel as nib
    from nibabel.processing import resample_from_to
    if (coord_frame not in ['head', 'mri']):
        raise ValueError(("coord_frame    must    be    'head'    or    'mri'.    Got    %s." % coord_frame))
    if (not isinstance(dipole, Dipole)):
        from ..dipole import _concatenate_dipoles
        dipole = _concatenate_dipoles(dipole)
    if (idx == 'gof'):
        idx = np.argmax(dipole.gof)
    elif (idx == 'amplitude'):
        idx = np.argmax(np.abs(dipole.amplitude))
    else:
        idx = _ensure_int(idx, 'idx', 'an    int    or    one    of    ["gof",    "amplitude"]')
    subjects_dir = get_subjects_dir(subjects_dir=subjects_dir, raise_error=True)
    t1_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz')
    t1 = nib.load(t1_fname)
    vox2ras = t1.header.get_vox2ras_tkr()
    ras2vox = linalg.inv(vox2ras)
    trans = _get_trans(trans, fro='head', to='mri')[0]
    zooms = t1.header.get_zooms()
    if (coord_frame == 'head'):
        affine_to = trans['trans'].copy()
        affine_to[:3, 3] *= 1000
        aff = t1.affine.copy()
        aff[:3, :3] /= zooms
        affine_to = np.dot(affine_to, aff)
        t1 = resample_from_to(t1, ([int((t1.shape[i] * zooms[i])) for i in range(3)], affine_to))
        dipole_locs = (apply_trans(ras2vox, (dipole.pos * 1000.0)) * zooms)
        ori = dipole.ori
        scatter_points = (dipole.pos * 1000.0)
    else:
        scatter_points = (apply_trans(trans['trans'], dipole.pos) * 1000.0)
        ori = apply_trans(trans['trans'], dipole.ori, move=False)
        dipole_locs = apply_trans(ras2vox, scatter_points)
    data = t1.get_data()
    dims = len(data)
    dd = (dims / 2.0)
    dd *= t1.header.get_zooms()[0]
    if (ax is None):
        fig = plt.figure()
        ax = Axes3D(fig)
    elif (not isinstance(ax, Axes3D)):
    ...
inputs: Complete the below
def example_decorator(name, function):

    ''''decorator for notify which is used from utils.monkey_patch().
    :param name: name of the function
    :param function: - object of the function
    :returns: function -- decorated function'
    '''
targets: def wrapped_func(*args, **kwarg):
        CALLED_FUNCTION.append(name)
        return function(*args, **kwarg)
    return wrapped_func
inputs: I wrote the below code

    _reload_hooks.append(fn)


What's a good function header?
targets: def add_reload_hook(fn):
inputs: Complete the below
def get_preamble():

    ''''Get LaTeX preamble from rc.'
    '''
targets: latex_preamble = rcParams.get(u'pgf.preamble', u'')
    if (type(latex_preamble) == list):
        latex_preamble = u'\n'.join(latex_preamble)
    return latex_preamble
inputs: I wrote the below code

    class dummy:
        def __getattr__(self, attr):
            return (lambda x: x)
    return dummy()


What's a good function header?
targets: def no_style():
inputs: def exists(storage, indexname=None):
targets: """Returns True if the given Storage object contains a Whoosh index.
    :param storage: a store.Storage object.
    :param indexname: the name of the index. If None, the default index name is
    used.
    :param rtype: bool
    """
    if (indexname is None):
        indexname = _DEF_INDEX_NAME
    try:
        ix = storage.open_index(indexname)
        gen = ix.latest_generation()
        ix.close()
        return (gen > (-1))
    except EmptyIndexError:
        pass
    return False
inputs: I wrote the below code

    documented = []
    for filename in filenames:
        with codecs.open(filename, 'r', encoding='utf-8', errors='ignore') as f:
            lines = f.read().splitlines()
            documented.extend(find_autosummary_in_lines(lines, filename=filename))
    return documented


What's a good function header?
targets: def find_autosummary_in_files(filenames):
inputs: def get_hwclock():
targets: """Get current hardware clock setting (UTC or localtime)
    CLI Example:
    .. code-block:: bash
    salt \*\ timezone.get_hwclock
    """
    return 'localtime'
inputs: I wrote the below code

    errno_names = dir(errno)
    nums = [getattr(errno, k) for k in errnames if (k in errno_names)]
    return dict.fromkeys(nums).keys()


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

    defines = []
    for d in config.get('defines', []):
        if (type(d) == list):
            fd = '='.join([str(dpart) for dpart in d])
        else:
            fd = str(d)
        defines.append(fd)
    return defines


What's a good function header?
targets: def _GetDefines(config):
inputs: def global_parameters(b, c):
targets: """Return global parameters for a given intersection array.
    Given a distance-regular graph G with integers b_i, c_i,i = 0,....,d
    such that for any 2 vertices x,y in G at a distance i=d(x,y), there
    are exactly c_i neighbors of y at a distance of i-1 from x and b_i
    neighbors of y at a distance of i+1 from x.
    Thus, a distance regular graph has the global parameters,
    [[c_0,a_0,b_0],[c_1,a_1,b_1],......,[c_d,a_d,b_d]] for the
    intersection array  [b_0,b_1,.....b_{d-1};c_1,c_2,.....c_d]
    where a_i+b_i+c_i=k , k= degree of every vertex.
    Parameters
    b : list
    c : list
    Returns
    iterable
    An iterable over three tuples.
    Examples
    >>> G = nx.dodecahedral_graph()
    >>> b, c = nx.intersection_array(G)
    >>> list(nx.global_parameters(b, c))
    [(0, 0, 3), (1, 0, 2), (1, 1, 1), (1, 1, 1), (2, 0, 1), (3, 0, 0)]
    References
    .. [1] Weisstein, Eric W. "Global Parameters."
    From MathWorld--A Wolfram Web Resource.
    http://mathworld.wolfram.com/GlobalParameters.html
    See Also
    intersection_array
    """
    return ((y, ((b[0] - x) - y), x) for (x, y) in zip((b + [0]), ([0] + c)))
inputs: Complete the below
def enable_edxnotes_for_the_course(course, user_id):

    ''''Enable EdxNotes for the course.'
    '''
targets: course.tabs.append(CourseTab.load('edxnotes'))
    modulestore().update_item(course, user_id)
inputs: I wrote the below code

    if (n < 0):
        raise ValueError('n    must    be    nonnegative.')
    if (n == 0):
        n1 = (n + 1)
    else:
        n1 = n
    (x, w, mu0) = roots_hermite(n1, mu=True)
    wfunc = (lambda x: exp(((- x) * x)))
    if (n == 0):
        (x, w) = ([], [])
    hn = (((2 ** n) * _gam((n + 1))) * sqrt(pi))
    kn = (2 ** n)
    p = orthopoly1d(x, w, hn, kn, wfunc, ((- inf), inf), monic, (lambda x: eval_hermite(n, x)))
    return p


What's a good function header?
targets: def hermite(n, monic=False):
inputs: Complete the below
def join(a, *p):

    ''''Join two or more pathname components, inserting sep as needed'
    '''
targets: path = a
    for b in p:
        if isabs(b):
            path = b
        elif ((path == '') or (path[(-1):] in '/\\:')):
            path = (path + b)
        else:
            path = ((path + '/') + b)
    return path
inputs: I wrote the below code

    if (not snapshot_id):
        raise CommandExecutionError('Error:    No    snapshot    ID    has    been    provided')
    snapshot = get_snapshot(config=config, number=snapshot_id)
    try:
        updated_opts = {'description': (description if (description is not None) else snapshot['description']), 'cleanup': (cleanup if (cleanup is not None) else snapshot['cleanup']), 'userdata': (userdata if (userdata is not None) else snapshot['userdata'])}
        snapper.SetSnapshot(config, snapshot_id, updated_opts['description'], updated_opts['cleanup'], updated_opts['userdata'])
        return get_snapshot(config=config, number=snapshot_id)
    except dbus.DBusException as exc:
        raise CommandExecutionError(_dbus_exception_to_reason(exc, locals()))


What's a good function header?
targets: def modify_snapshot(snapshot_id=None, description=None, userdata=None, cleanup=None, config='root'):
inputs: I wrote the below code

    global _service_command_generator
    try:
        return _service_command_generator
    except NameError:
        command_generator = _command_generators[get_name_of_init(run)]
        _service_command_generator = _ServiceCommandGenerator(command_generator)
        return _service_command_generator


What's a good function header?
targets: def _get_service_command_generator(run=utils.run):
inputs: Complete the below
def allow_session_user(user_id):

    ''''Returns True or False if the user_id is allowed for the current logged in session'
    '''
targets: session_user_id = get_session_user_id()
    if (session_user_id and (str(user_id) != session_user_id)):
        return False
    return True
inputs: def _convert_asset_timestamp_fields(dict_):
targets: """Takes in a dict of Asset init args and converts dates to pd.Timestamps
    """
    for key in (_asset_timestamp_fields & viewkeys(dict_)):
        value = pd.Timestamp(dict_[key], tz='UTC')
        dict_[key] = (None if isnull(value) else value)
    return dict_
inputs: Complete the below
def ParseKindQuery(query, filters, orders):

    ''''Parse __kind__ (schema) queries.
    Raises exceptions for illegal queries.
    Args:
    query: A Query PB.
    filters: the normalized filters from query.
    orders: the normalized orders from query.
    Returns:
    The kind range (a ValueRange over string) requested in the query.'
    '''
targets: if query.has_ancestor():
        raise BadRequestError('ancestor    queries    on    __kind__    not    allowed')
    key_range = ParseKeyFilteredQuery(filters, orders)
    key_range.Remap(_KindKeyToString)
    return key_range
inputs: I wrote the below code

    is_bfv = compute_utils.is_volume_backed_instance(instance._context, instance)
    swap_in_gb = compute_utils.convert_mb_to_ceil_gb(flavor.swap)
    disk = (((0 if is_bfv else flavor.root_gb) + swap_in_gb) + flavor.ephemeral_gb)
    resources = {fields.ResourceClass.VCPU: flavor.vcpus, fields.ResourceClass.MEMORY_MB: flavor.memory_mb, fields.ResourceClass.DISK_GB: disk}
    if ('extra_specs' in flavor):
        _process_extra_specs(flavor.extra_specs, resources)
    return resources


What's a good function header?
targets: def resources_from_flavor(instance, flavor):
inputs: Complete the below
def fd_by_path(paths):

    ''''Return a list of file descriptors.
    This method returns list of file descriptors corresponding to
    file paths passed in paths variable.
    Arguments:
    paths: List[str]: List of file paths.
    Returns:
    List[int]: List of file descriptors.
    Example:
    >>> keep = fd_by_path([\'/dev/urandom\', \'/my/precious/\'])'
    '''
targets: stats = set()
    for path in paths:
        try:
            fd = os.open(path, os.O_RDONLY)
        except OSError:
            continue
        try:
            stats.add(os.fstat(fd)[1:3])
        finally:
            os.close(fd)
    def fd_in_stats(fd):
        try:
            return (os.fstat(fd)[1:3] in stats)
        except OSError:
            return False
    return [_fd for _fd in range(get_fdmax(2048)) if fd_in_stats(_fd)]
inputs: I wrote the below code

    if isinstance(sentence, basestring):
        try:
            from pattern.en import parse, Sentence
            sentence = Sentence(parse(sentence))
        except ImportError:
            pass
    (S, n, m) = (sentence, 0.0, 0)
    if (not (hasattr(S, 'words') and hasattr(S, 'parse_token'))):
        raise TypeError(('%s    object    is    not    a    parsed    Sentence' % repr(S.__class__.__name__)))
    if (type == EPISTEMIC):
        r = S.string.rstrip('    .!')
        for (k, v) in epistemic_weaseling.items():
            for phrase in v:
                if (phrase in r):
                    n += k
                    m += 2
        for (i, w) in enumerate(S.words):
            for (type, dict, weight) in (('MD', epistemic_MD, 4), ('VB', epistemic_VB, 2), ('RB', epistemic_RB, 2), ('JJ', epistemic_JJ, 1), ('NN', epistemic_NN, 1), ('CC', epistemic_CC_DT_IN, 1), ('DT', epistemic_CC_DT_IN, 1), ('IN', epistemic_CC_DT_IN, 1), ('PRP', epistemic_PRP, 1), ('PRP$', epistemic_PRP, 1), ('WP', epistemic_PRP, 1)):
                if ((i > 0) and (s(S[(i - 1)]) in MODIFIERS)):
                    weight += 1
                if (w.type and w.type.startswith(type)):
                    for (k, v) in dict.items():
                        if ((w.lemma or s(w)) in v):
                            if ((i > 0) and (s(S[(i - 1)]) in ('not', "n't", 'never', 'without'))):
                                k = ((- k) * 0.5)
                            n += (weight * k)
                            m += weight
                            break
            if (w.type in ('CD', '"', "'", ':', '(')):
                n += 0.75
                m += 1
    if (m == 0):
        return 1.0
    return max((-1.0), min((n / (m or 1)), (+ 1.0)))


What's a good function header?
targets: def modality(sentence, type=EPISTEMIC):
inputs: def anova_lm(*args, **kwargs):
targets: """Anova table for one or more fitted linear models.
    Parameters
    args : fitted linear model results instance
    One or more fitted linear models
    scale : float
    Estimate of variance, If None, will be estimated from the largest
    model. Default is None.
    test : str {"F", "Chisq", "Cp"} or None
    Test statistics to provide. Default is "F".
    typ : str or int {"I","II","III"} or {1,2,3}
    The type of Anova test to perform. See notes.
    robust : {None, "hc0", "hc1", "hc2", "hc3"}
    Use heteroscedasticity-corrected coefficient covariance matrix.
    If robust covariance is desired, it is recommended to use `hc3`.
    Returns
    anova : DataFrame
    A DataFrame containing.
    Notes
    Model statistics are given in the order of args. Models must have
    been fit using the formula api.
    See Also
    model_results.compare_f_test, model_results.compare_lm_test
    Examples
    >>> import statsmodels.api as sm
    >>> from statsmodels.formula.api import ols
    >>> moore = sm.datasets.get_rdataset("Moore", "car", cache=True) # load
    >>> data = moore.data
    >>> data = data.rename(columns={"partner.status" :
    ...                             "partner_status"}) # make name pythonic
    >>> moore_lm = ols(\conformity ~ C(fcategory, Sum)*C(partner_status, Sum)\,
    ...                 data=data).fit()
    >>> table = sm.stats.anova_lm(moore_lm, typ=2) # Type 2 Anova DataFrame
    >>> print(table)
    """
    typ = kwargs.get('typ', 1)
    if (len(args) == 1):
        model = args[0]
        return anova_single(model, **kwargs)
    try:
        assert (typ in [1, 'I'])
    except:
        raise ValueError(('Multiple    models    only    supported    for    type    I.    Got    type    %s' % str(typ)))
    if (len(args) == 1):
        return anova_single(*args, **kwargs)
    test = kwargs.get('test', 'F')
    scale = kwargs.get('scale', None)
    n_models = len(args)
    model_formula = []
    pr_test = ('Pr(>%s)' % test)
    names = ['df_resid', 'ssr', 'df_diff', 'ss_diff', test, pr_test]
    table = DataFrame(np.zeros((n_models, 6)), columns=names)
    if (not scale):
        scale = args[(-1)].scale
    table['ssr'] = lmap(getattr, args, (['ssr'] * n_models))
    table['df_resid'] = lmap(getattr, args, (['df_resid'] * n_models))
    table.loc[(table.index[1:], 'df_diff')] = (- np.diff(table['df_resid'].values))
    table['ss_diff'] = (- table['ssr'].diff())
    if (test == 'F'):
        table['F'] = ((table['ss_diff'] / table['df_diff']) / scale)
        table[pr_test] = stats.f.sf(table['F'], table['df_diff'], table['df_resid'])
        table[pr_test][table['F'].isnull()] = np.nan
    return table
inputs: def get_archive_formats():
targets: """Returns a list of supported formats for archiving and unarchiving.
    Each element of the returned sequence is a tuple (name, description)
    """
    formats = [(name, registry[2]) for (name, registry) in _ARCHIVE_FORMATS.items()]
    formats.sort()
    return formats
inputs: Complete the below
def deprecated_version_of(f, oldname, newname=None):

    ''''Indicates that a function is deprecated and has a new name.
    `f` is the new function, `oldname` the name of the deprecated
    function, `newname` the name of `f`, which can be automatically
    found.
    Returns
    f_deprecated
    A function that does the same thing as f, but with a docstring
    and a printed message on call which say that the function is
    deprecated and that you should use f instead.
    Examples
    >>> # The badly named method \'to_file\' is replaced by \'write_file\'
    >>> class Clip:
    >>>    def write_file(self, some args):
    >>>        # blablabla
    >>> Clip.to_file = deprecated_version_of(Clip.write_file, \'to_file\')'
    '''
targets: if (newname is None):
        newname = f.__name__
    warning = ('The    function    ``%s``    is    deprecated    and    is    kept    temporarily    for    backwards    compatibility.\nPlease    use    the    new    name,    ``%s``,    instead.' % (oldname, newname))
    def fdepr(*a, **kw):
        warnings.warn(('MoviePy:    ' + warning), PendingDeprecationWarning)
        return f(*a, **kw)
    fdepr.__doc__ = warning
    return fdepr
inputs: Complete the below
def encode_quopri(msg):

    ''''Encode the message\'s payload in quoted-printable.
    Also, add an appropriate Content-Transfer-Encoding header.'
    '''
targets: orig = msg.get_payload()
    encdata = _qencode(orig)
    msg.set_payload(encdata)
    msg['Content-Transfer-Encoding'] = 'quoted-printable'
inputs: def authenticated_userid(request):
targets: """A function that returns the value of the property
    :attr:`pyramid.request.Request.authenticated_userid`.
    .. deprecated:: 1.5
    Use :attr:`pyramid.request.Request.authenticated_userid` instead.
    """
    return request.authenticated_userid
inputs: I wrote the below code

    _check_solver_option(solver, multi_class, penalty, dual)
    X_train = X[train]
    X_test = X[test]
    y_train = y[train]
    y_test = y[test]
    if (sample_weight is not None):
        sample_weight = check_array(sample_weight, ensure_2d=False)
        check_consistent_length(y, sample_weight)
        sample_weight = sample_weight[train]
    (coefs, Cs, n_iter) = logistic_regression_path(X_train, y_train, Cs=Cs, fit_intercept=fit_intercept, solver=solver, max_iter=max_iter, class_weight=class_weight, pos_class=pos_class, multi_class=multi_class, tol=tol, verbose=verbose, dual=dual, penalty=penalty, intercept_scaling=intercept_scaling, random_state=random_state, check_input=False, max_squared_sum=max_squared_sum, sample_weight=sample_weight)
    log_reg = LogisticRegression(fit_intercept=fit_intercept)
    if (multi_class == 'ovr'):
        log_reg.classes_ = np.array([(-1), 1])
    elif (multi_class == 'multinomial'):
        log_reg.classes_ = np.unique(y_train)
    else:
        raise ValueError(('multi_class    should    be    either    multinomial    or    ovr,    got    %d' % multi_class))
    if (pos_class is not None):
        mask = (y_test == pos_class)
        y_test = np.ones(y_test.shape, dtype=np.float64)
        y_test[(~ mask)] = (-1.0)
    scores = list()
    if isinstance(scoring, six.string_types):
        scoring = SCORERS[scoring]
    for w in coefs:
        if (multi_class == 'ovr'):
            w = w[np.newaxis, :]
        if fit_intercept:
            log_reg.coef_ = w[:, :(-1)]
            log_reg.intercept_ = w[:, (-1)]
        else:
            log_reg.coef_ = w
            log_reg.intercept_ = 0.0
        if (scoring is None):
            scores.append(log_reg.score(X_test, y_test))
        else:
            scores.append(scoring(log_reg, X_test, y_test))
    return (coefs, Cs, np.array(scores), n_iter)


What's a good function header?
targets: def _log_reg_scoring_path(X, y, train, test, pos_class=None, Cs=10, scoring=None, fit_intercept=False, max_iter=100, tol=0.0001, class_weight=None, verbose=0, solver='lbfgs', penalty='l2', dual=False, intercept_scaling=1.0, multi_class='ovr', random_state=None, max_squared_sum=None, sample_weight=None):
inputs: def csrf_failure(request, reason=''):
targets: """Default view used when request fails CSRF protection
    """
    from django.middleware.csrf import REASON_NO_REFERER
    t = Template(CSRF_FAILURE_TEMPLATE)
    c = Context({'DEBUG': settings.DEBUG, 'reason': reason, 'no_referer': (reason == REASON_NO_REFERER)})
    return HttpResponseForbidden(t.render(c), content_type='text/html')
inputs: def _run_hook(shell_cmd):
targets: """Run a hook command.
    :returns: stderr if there was any
    """
    (err, _) = execute(shell_cmd)
    return err
inputs: Complete the below
@register.filter
def get_range(value):

    ''''Filter - returns a list containing range made from given value
    Usage (in template):
    <ul>{% for i in 3|get_range %}
    <li>{{ i }}. Do something</li>
    {% endfor %}</ul>
    Results with the HTML:
    <ul>
    <li>0. Do something</li>
    <li>1. Do something</li>
    <li>2. Do something</li>
    </ul>
    Instead of 3 one may use the variable set in the views'
    '''
targets: return range(value)
inputs: def libvlc_media_player_set_title(p_mi, i_title):
targets: """Set movie title.
    @param p_mi: the Media Player.
    @param i_title: title number to play.
    """
    f = (_Cfunctions.get('libvlc_media_player_set_title', None) or _Cfunction('libvlc_media_player_set_title', ((1,), (1,)), None, None, MediaPlayer, ctypes.c_int))
    return f(p_mi, i_title)
inputs: def ensemble_preds(dataset, nb_teachers, stdnt_data):
targets: """Given a dataset, a number of teachers, and some input data, this helper
    function queries each teacher for predictions on the data and returns
    all predictions in a single array. (That can then be aggregated into
    one single prediction per input using aggregation.py (cf. function
    prepare_student_data() below)
    :param dataset: string corresponding to mnist, cifar10, or svhn
    :param nb_teachers: number of teachers (in the ensemble) to learn from
    :param stdnt_data: unlabeled student training data
    :return: 3d array (teacher id, sample id, probability per class)
    """
    result_shape = (nb_teachers, len(stdnt_data), FLAGS.nb_labels)
    result = np.zeros(result_shape, dtype=np.float32)
    for teacher_id in xrange(nb_teachers):
        if FLAGS.deeper:
            ckpt_path = ((((((((FLAGS.teachers_dir + '/') + str(dataset)) + '_') + str(nb_teachers)) + '_teachers_') + str(teacher_id)) + '_deep.ckpt-') + str((FLAGS.teachers_max_steps - 1)))
        else:
            ckpt_path = ((((((((FLAGS.teachers_dir + '/') + str(dataset)) + '_') + str(nb_teachers)) + '_teachers_') + str(teacher_id)) + '.ckpt-') + str((FLAGS.teachers_max_steps - 1)))
        result[teacher_id] = deep_cnn.softmax_preds(stdnt_data, ckpt_path)
        print((('Computed    Teacher    ' + str(teacher_id)) + '    softmax    predictions'))
    return result
inputs: I wrote the below code

    if (not (os.path.exists(filename) and os.path.isdir(os.path.join(os.path.dirname(filename), '.svn')))):
        return (None, None, None)
    (svnRev, svnLastChangedRev, svnUrl) = (None, None, None)
    if ((sys.platform in ('darwin', 'freebsd')) or sys.platform.startswith('linux')):
        try:
            svninfo = shellCall(['svn', 'info', filename])
        except Exception:
            svninfo = ''
        for line in svninfo.splitlines():
            if line.startswith('URL:'):
                svnUrl = line.split()[1]
            elif line.startswith('Revision:    '):
                svnRev = line.split()[1]
            elif line.startswith('Last    Changed    Rev'):
                svnLastChangedRev = line.split()[3]
    else:
        try:
            stdout = shellCall(['subwcrev', filename])
        except Exception:
            stdout = ''
        for line in stdout.splitlines():
            if line.startswith('Last    committed    at    revision'):
                svnRev = line.split()[4]
            elif line.startswith('Updated    to    revision'):
                svnLastChangedRev = line.split()[3]
    return (svnRev, svnLastChangedRev, svnUrl)


What's a good function header?
targets: def _getSvnVersion(filename):