Muennighoff/xP3x-sample huggingface dataset:
inputs: I wrote the below code

    from multiprocessing.sharedctypes import Array
    return Array(typecode_or_type, size_or_initializer, **kwds)


What's a good function header?
targets: def Array(typecode_or_type, size_or_initializer, **kwds):
inputs: @register.inclusion_tag('zinnia/tags/dummy.html', takes_context=True)
def get_categories(context, template='zinnia/tags/categories.html'):
targets: """Return the published categories.
    """
    return {'template': template, 'categories': Category.published.all().annotate(count_entries_published=Count('entries')), 'context_category': context.get('category')}
inputs: Complete the below
def deprecated(message=None):

    ''''A decorator for deprecated functions'
    '''
targets: def _decorator(func, message=message):
        if (message is None):
            message = ('%s    is    deprecated' % func.__name__)
        def newfunc(*args, **kwds):
            warnings.warn(message, DeprecationWarning, stacklevel=2)
            return func(*args, **kwds)
        return newfunc
    return _decorator
inputs: I wrote the below code

    parts = [directory]
    for filename in pathnames:
        if (filename != ''):
            filename = posixpath.normpath(filename)
        if (any(((sep in filename) for sep in _os_alt_seps)) or os.path.isabs(filename) or (filename == '..') or filename.startswith('../')):
            raise NotFound()
        parts.append(filename)
    return posixpath.join(*parts)


What's a good function header?
targets: def safe_join(directory, *pathnames):
inputs: I wrote the below code

    if (module_names is None):
        module_names = elementtree_modules
    for mod_name in module_names:
        try:
            ElementTree = __import__(mod_name, None, None, ['unused'])
        except ImportError:
            pass
        else:
            try:
                ElementTree.XML('<unused/>')
            except (SystemExit, MemoryError, AssertionError):
                raise
            except:
                why = sys.exc_info()[1]
                log(('Not    using    ElementTree    library    %r    because    it    failed    to    parse    a    trivial    document:    %s' % (mod_name, why)))
            else:
                return ElementTree
    else:
        raise ImportError(('No    ElementTree    library    found.    You    may    need    to    install    one.    Tried    importing    %r' % (module_names,)))


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

    (expired, invalid, user) = login_token_status(token)
    if invalid:
        do_flash(*get_message('INVALID_LOGIN_TOKEN'))
    if expired:
        send_login_instructions(user)
        do_flash(*get_message('LOGIN_EXPIRED', email=user.email, within=_security.login_within))
    if (invalid or expired):
        return redirect(url_for('login'))
    login_user(user)
    after_this_request(_commit)
    do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))
    return redirect(get_post_login_redirect())


What's a good function header?
targets: @anonymous_user_required
def token_login(token):
inputs: def gen3():
targets: """Non-restartable source sequence
    """
    for i in (0, 1, 2):
        (yield i)
inputs: I wrote the below code

    buff = raw
    if (not raw):
        buff = method2dot(mx)
    method2format(output, 'jpg', mx, buff)


What's a good function header?
targets: def method2jpg(output, mx, raw=False):
inputs: Complete the below
def currentThread():

    ''''Return the current Thread object, corresponding to the caller\'s thread of control.
    If the caller\'s thread of control was not created through the threading
    module, a dummy thread object with limited functionality is returned.'
    '''
targets: try:
        return _active[_get_ident()]
    except KeyError:
        return _DummyThread()
inputs: I wrote the below code

    if (not dork):
        return None
    headers = {}
    headers[HTTP_HEADER.USER_AGENT] = dict(conf.httpHeaders).get(HTTP_HEADER.USER_AGENT, DUMMY_SEARCH_USER_AGENT)
    headers[HTTP_HEADER.ACCEPT_ENCODING] = HTTP_ACCEPT_ENCODING_HEADER_VALUE
    try:
        req = urllib2.Request('https://www.google.com/ncr', headers=headers)
        conn = urllib2.urlopen(req)
    except Exception as ex:
        errMsg = ("unable    to    connect    to    Google    ('%s')" % getSafeExString(ex))
        raise SqlmapConnectionException(errMsg)
    gpage = (conf.googlePage if (conf.googlePage > 1) else 1)
    logger.info(('using    search    result    page    #%d' % gpage))
    url = 'https://www.google.com/search?'
    url += ('q=%s&' % urlencode(dork, convall=True))
    url += 'num=100&hl=en&complete=0&safe=off&filter=0&btnG=Search'
    url += ('&start=%d' % ((gpage - 1) * 100))
    try:
        req = urllib2.Request(url, headers=headers)
        conn = urllib2.urlopen(req)
        requestMsg = ('HTTP    request:\nGET    %s' % url)
        requestMsg += ('    %s' % httplib.HTTPConnection._http_vsn_str)
        logger.log(CUSTOM_LOGGING.TRAFFIC_OUT, requestMsg)
        page = conn.read()
        code = conn.code
        status = conn.msg
        responseHeaders = conn.info()
        page = decodePage(page, responseHeaders.get('Content-Encoding'), responseHeaders.get('Content-Type'))
        responseMsg = ('HTTP    response    (%s    -    %d):\n' % (status, code))
        if (conf.verbose <= 4):
            responseMsg += getUnicode(responseHeaders, UNICODE_ENCODING)
        elif (conf.verbose > 4):
            responseMsg += ('%s\n%s\n' % (responseHeaders, page))
        logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg)
    except urllib2.HTTPError as e:
        try:
            page = e.read()
        except Exception as ex:
            warnMsg = 'problem    occurred    while    trying    to    get    '
            warnMsg += ('an    error    page    information    (%s)' % getSafeExString(ex))
           ...

What's a good function header?
targets: def _search(dork):
inputs: def get_gif(api_key, gif_id):
targets: """Returns dict with gif informations from the API.
    """
    url = 'http://api.giphy.com/v1/gifs/{}?api_key={}'.format(gif_id, api_key)
    r = urlopen(url)
    return json.loads(r.read().decode('utf-8'))
inputs: I wrote the below code

    parsed = urlparse(uri)
    if (parsed.path in schema_paths):
        schema = schema_paths[parsed.path]
        if callable(schema):
            return schema(**dict(parse_qsl(parsed.query)))
        return schema
    raise jsonschema.RefResolutionError((u'%s    could    not    be    resolved' % uri))


What's a good function header?
targets: def resolve_ref(uri):
inputs: Complete the below
def delimitedList(expr, delim=',', combine=False):

    ''''Helper to define a delimited list of expressions - the delimiter defaults to \',\'.
    By default, the list elements and delimiters can have intervening whitespace, and
    comments, but this can be overridden by passing \'combine=True\' in the constructor.
    If combine is set to True, the matching tokens are returned as a single token
    string, with the delimiters included; otherwise, the matching tokens are returned
    as a list of tokens, with the delimiters suppressed.'
    '''
targets: dlName = (((((_ustr(expr) + '    [') + _ustr(delim)) + '    ') + _ustr(expr)) + ']...')
    if combine:
        return Combine((expr + ZeroOrMore((delim + expr)))).setName(dlName)
    else:
        return (expr + ZeroOrMore((Suppress(delim) + expr))).setName(dlName)
inputs: I wrote the below code

    global XCODE_VERSION_CACHE
    if XCODE_VERSION_CACHE:
        return XCODE_VERSION_CACHE
    try:
        version_list = GetStdout(['xcodebuild', '-version']).splitlines()
        if (len(version_list) < 2):
            raise GypError('xcodebuild    returned    unexpected    results')
    except:
        version = CLTVersion()
        if version:
            version = re.match('(\\d\\.\\d\\.?\\d*)', version).groups()[0]
        else:
            raise GypError('No    Xcode    or    CLT    version    detected!')
        version_list = [version, '']
    version = version_list[0]
    build = version_list[(-1)]
    version = version.split()[(-1)].replace('.', '')
    version = (version + ('0' * (3 - len(version)))).zfill(4)
    if build:
        build = build.split()[(-1)]
    XCODE_VERSION_CACHE = (version, build)
    return XCODE_VERSION_CACHE


What's a good function header?
targets: def XcodeVersion():
inputs: Complete the below
def _create_transformations(all_tokens, seen_ts):

    ''''Create the objects that need to know about tabstops.'
    '''
targets: for (parent, token) in all_tokens:
        if isinstance(token, TransformationToken):
            if (token.number not in seen_ts):
                raise RuntimeError(('Tabstop    %i    is    not    known    but    is    used    by    a    Transformation' % token.number))
            Transformation(parent, seen_ts[token.number], token)
inputs: Complete the below
@decorators.memoize
def _check_imgadm():

    ''''Looks to see if imgadm is present on the system'
    '''
targets: return salt.utils.path.which('imgadm')
inputs: I wrote the below code

    net_connect.disconnect()


What's a good function header?
targets: def test_disconnect(net_connect, commands, expected_responses):
inputs: Complete the below
@testing.requires_testing_data
@requires_mayavi
def test_coreg_model():

    ''''Test CoregModel.'
    '''
targets: from mne.gui._coreg_gui import CoregModel
    tempdir = _TempDir()
    trans_dst = op.join(tempdir, 'test-trans.fif')
    model = CoregModel()
    assert_raises(RuntimeError, model.save_trans, 'blah.fif')
    model.mri.use_high_res_head = False
    model.mri.subjects_dir = subjects_dir
    model.mri.subject = 'sample'
    assert_false(model.mri.fid_ok)
    model.mri.lpa = [[(-0.06), 0, 0]]
    model.mri.nasion = [[0, 0.05, 0]]
    model.mri.rpa = [[0.08, 0, 0]]
    assert_true(model.mri.fid_ok)
    model.hsp.file = raw_path
    assert_allclose(model.hsp.lpa, [[(-0.07137), 0, 5.122e-09]], 0.0001)
    assert_allclose(model.hsp.rpa, [[(+ 0.07527), 0, 5.588e-09]], 0.0001)
    assert_allclose(model.hsp.nasion, [[(+ 3.725e-09), 0.1026, 4.191e-09]], 0.0001)
    assert_true(model.has_fid_data)
    lpa_distance = model.lpa_distance
    nasion_distance = model.nasion_distance
    rpa_distance = model.rpa_distance
    avg_point_distance = np.mean(model.point_distance)
    model.fit_auricular_points()
    old_x = ((lpa_distance ** 2) + (rpa_distance ** 2))
    new_x = ((model.lpa_distance ** 2) + (model.rpa_distance ** 2))
    assert_true((new_x < old_x))
    model.fit_fiducials()
    old_x = (((lpa_distance ** 2) + (rpa_distance ** 2)) + (nasion_distance ** 2))
    new_x = (((model.lpa_distance ** 2) + (model.rpa_distance ** 2)) + (model.nasion_distance ** 2))
    assert_true((new_x < old_x))
    model.fit_hsp_points()
    assert_true((np.mean(model.point_distance) < avg_point_distance))
    model.save_trans(trans_dst)
    trans = mne.read_trans(trans_dst)
    assert_allclose(trans['trans'], model.head_mri_trans)
    (x, y, z, rot_x, rot_y, rot_z) = (0.1, 0.2, 0.05, 1.5, 0.1, (-1.2))
    model.trans_x = x
    model.trans_y = y
    model.trans_z = z
    model.rot_x = rot_x
    model.rot_y = rot_y
    model.rot_z = rot_z
    trans = model.head_mri_trans
    model.reset_traits(['trans_x', 'trans_y', 'trans_z', 'rot_x', 'rot_y', 'rot_z'])
    assert_equal(model.trans_x, 0)
    model.set_trans(trans)
   ...
inputs: @task
@use_master
def update_supported_locales_single(id, latest=False, **kw):
targets: """Update supported_locales for an individual app. Set latest=True to use the
    latest current version instead of the most recent public version.
    """
    from mkt.webapps.models import Webapp
    try:
        app = Webapp.objects.get(pk=id)
    except Webapp.DoesNotExist:
        log.info((u'[Webapp:%s]    Did    not    find    webapp    to    update    supported    locales.' % id))
        return
    try:
        if app.update_supported_locales(latest=latest):
            log.info((u'[Webapp:%s]    Updated    supported    locales.' % app.id))
    except Exception:
        log.info((u'[Webapp%s]    Updating    supported    locales    failed.' % app.id), exc_info=True)
inputs: I wrote the below code

    Services = get_sdk(ResourceType.DATA_STORAGE, 'models#Services')
    if (set(string) - set('bqtf')):
        raise ValueError
    return Services(_str=''.join(set(string)))


What's a good function header?
targets: def services_type(string):
inputs: Complete the below
def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):

    ''''Creates an instance of the target class from the string contents.
    Args:
    target_class: class The class which will be instantiated and populated
    with the contents of the XML. This class must have a _tag and a
    _namespace class variable.
    xml_string: str A string which contains valid XML. The root element
    of the XML string should match the tag and namespace of the desired
    class.
    string_encoding: str The character encoding which the xml_string should
    be converted to before it is interpreted and translated into
    objects. The default is None in which case the string encoding
    is not changed.
    Returns:
    An instance of the target class with members assigned according to the
    contents of the XML - or None if the root XML tag and namespace did not
    match those of the target class.'
    '''
targets: encoding = (string_encoding or XML_STRING_ENCODING)
    if (encoding and isinstance(xml_string, unicode)):
        xml_string = xml_string.encode(encoding)
    tree = ElementTree.fromstring(xml_string)
    return _CreateClassFromElementTree(target_class, tree)
inputs: def create_or_verify_database(url, engine_options={}):
targets: """Check that the database is use-able, possibly creating it if empty (this is
    the only time we automatically create tables, otherwise we force the
    user to do it using the management script so they can create backups).
    1) Empty database --> initialize with latest version and return
    2) Database older than migration support --> fail and require manual update
    3) Database at state where migrate support introduced --> add version control information but make no changes (might still require manual update)
    4) Database versioned but out of date --> fail with informative message, user must run "sh manage_db.sh upgrade"
    """
    engine = create_engine(url, **engine_options)
    meta = MetaData(bind=engine)
    try:
        Table('galaxy_user', meta, autoload=True)
    except NoSuchTableError:
        log.info('No    database,    initializing')
        try:
            db_schema = schema.ControlledSchema.create(engine, migrate_repository)
        except:
            db_schema = schema.ControlledSchema(engine, migrate_repository)
        migrate_to_current_version(engine, db_schema)
        return
    try:
        Table('migrate_version', meta, autoload=True)
    except NoSuchTableError:
        log.info('Adding    version    control    to    existing    database')
        try:
            Table('metadata_file', meta, autoload=True)
            schema.ControlledSchema.create(engine, migrate_repository, version=2)
        except NoSuchTableError:
            schema.ControlledSchema.create(engine, migrate_repository, version=1)
    db_schema = schema.ControlledSchema(engine, migrate_repository)
    if (migrate_repository.versions.latest != db_schema.version):
        exception_msg = ("Your    database    has    version    '%d'    but    this    code    expects    version    '%d'.        " % (db_schema.version, migrate_repository.versions.latest))
        exception_msg += 'Back    up    your    database    and    then    migrate    the    schema    by    running    the    following    from    your    Galaxy    installation    directory:'
        exception_msg += '\n\nsh    manage_db.sh    upgrade    tool_shed\n'
        raise Exception(exception_msg)
    else:
        log.info(('At    database    version    %d' % db_schema.version))
inputs: Complete the below
def gettext_noop(message):

    ''''Marks strings for translation but doesn\'t translate them now. This can be
    used to store strings in global variables that should stay in the base
    language (because they might be used externally) and will be translated
    later.'
    '''
targets: return message
inputs: def ProtosToIndexDefinitions(protos):
targets: """Transform multiple index protocol buffers to index definitions.
    Args:
    A list of entity_pb.Index records.
    """
    return [ProtoToIndexDefinition(definition) for definition in protos]
inputs: Complete the below
def identify_names(code):

    ''''Builds a codeobj summary by identifying and resovles used names
    >>> code = \'\'\'
    ... from a.b import c
    ... import d as e
    ... print(c)
    ... e.HelloWorld().f.g
    >>> for name, o in sorted(identify_names(code).items()):
    ...     print(name, o[\'name\'], o[\'module\'], o[\'module_short\'])
    c c a.b a.b
    e.HelloWorld HelloWorld d d'
    '''
targets: finder = NameFinder()
    finder.visit(ast.parse(code))
    example_code_obj = {}
    for (name, full_name) in finder.get_mapping():
        (module, attribute) = full_name.rsplit('.', 1)
        module_short = get_short_module_name(module, attribute)
        cobj = {'name': attribute, 'module': module, 'module_short': module_short}
        example_code_obj[name] = cobj
    return example_code_obj
inputs: I wrote the below code

    html = markdown(value, extensions=[u'mdx_gfm'])
    return mark_safe(html)


What's a good function header?
targets: @register.filter(is_safe=True)
def gfm(value):
inputs: def get_certificate_footer_context():
targets: """Return data to be used in Certificate Footer,
    data returned should be customized according to the site configuration.
    """
    data = dict()
    terms_of_service_and_honor_code = branding_api.get_tos_and_honor_code_url()
    if (terms_of_service_and_honor_code != branding_api.EMPTY_URL):
        data.update({'company_tos_url': terms_of_service_and_honor_code})
    privacy_policy = branding_api.get_privacy_url()
    if (privacy_policy != branding_api.EMPTY_URL):
        data.update({'company_privacy_url': privacy_policy})
    about = branding_api.get_about_url()
    if (about != branding_api.EMPTY_URL):
        data.update({'company_about_url': about})
    return data
inputs: def ReadVFS(pathspec, offset, length, progress_callback=None):
targets: """Read from the VFS and return the contents.
    Args:
    pathspec: path to read from
    offset: number of bytes to skip
    length: number of bytes to read
    progress_callback: A callback to indicate that the open call is still
    working but needs more time.
    Returns:
    VFS file contents
    """
    fd = VFSOpen(pathspec, progress_callback=progress_callback)
    fd.Seek(offset)
    return fd.Read(length)
inputs: Complete the below
def host_memory_extents(obj):

    ''''Returns (start, end) the start and end pointer of the array (half open).'
    '''
targets: return mviewbuf.memoryview_get_extents(obj)
inputs: I wrote the below code

    _set_ndarray_class(ndarray_class)
    plist = ctypes.POINTER(ctypes.c_char_p)()
    size = ctypes.c_uint()
    check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist)))
    op_names = []
    for i in range(size.value):
        op_names.append(py_str(plist[i]))
    module_obj = _sys.modules[('%s.ndarray' % root_namespace)]
    module_internal = _sys.modules[('%s._ndarray_internal' % root_namespace)]
    module_contrib = _sys.modules[('%s.contrib.ndarray' % root_namespace)]
    for name in op_names:
        hdl = OpHandle()
        check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))
        function = _make_ndarray_function(hdl, name)
        if function.__name__.startswith('_contrib_'):
            function.__name__ = function.__name__[9:]
            function.__module__ = 'mxnet.contrib.ndarray'
            setattr(module_contrib, function.__name__, function)
        elif function.__name__.startswith('_'):
            setattr(module_internal, function.__name__, function)
        else:
            setattr(module_obj, function.__name__, function)


What's a good function header?
targets: def _init_ndarray_module(ndarray_class, root_namespace):
inputs: def enumerate():
targets: """Return a list of all Thread objects currently alive.
    The list includes daemonic threads, dummy thread objects created by
    current_thread(), and the main thread. It excludes terminated threads and
    threads that have not yet been started.
    """
    with _active_limbo_lock:
        return (_active.values() + _limbo.values())
inputs: I wrote the below code

    if re.match(VALID_APP_NAME_CHARS_REGEX, app_name):
        return True
    else:
        return False


What's a good function header?
targets: def is_app_name_valid(app_name):
inputs: @ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@coach_dashboard
def set_grading_policy(request, course, ccx=None):
targets: """Set grading policy for the CCX.
    """
    if (not ccx):
        raise Http404
    override_field_for_ccx(ccx, course, 'grading_policy', json.loads(request.POST['policy']))
    responses = SignalHandler.course_published.send(sender=ccx, course_key=CCXLocator.from_course_locator(course.id, unicode(ccx.id)))
    for (rec, response) in responses:
        log.info('Signal    fired    when    course    is    published.    Receiver:    %s.    Response:    %s', rec, response)
    url = reverse('ccx_coach_dashboard', kwargs={'course_id': CCXLocator.from_course_locator(course.id, unicode(ccx.id))})
    return redirect(url)
inputs: def fullmodname(path):
targets: """Return a plausible module name for the path.
    """
    comparepath = os.path.normcase(path)
    longest = ''
    for dir in sys.path:
        dir = os.path.normcase(dir)
        if (comparepath.startswith(dir) and (comparepath[len(dir)] == os.sep)):
            if (len(dir) > len(longest)):
                longest = dir
    if longest:
        base = path[(len(longest) + 1):]
    else:
        base = path
    (drive, base) = os.path.splitdrive(base)
    base = base.replace(os.sep, '.')
    if os.altsep:
        base = base.replace(os.altsep, '.')
    (filename, ext) = os.path.splitext(base)
    return filename.lstrip('.')
inputs: def decode_fvwi(byts, flag_size=4):
targets: """Decode encoded fvwi. Returns number, flags, consumed
    """
    (arg, consumed) = decint(bytes(byts))
    val = (arg >> flag_size)
    flags = 0
    for i in xrange(flag_size):
        flags |= (arg & (1 << i))
    return (val, flags, consumed)
inputs: def compile(pattern, flags=0):
targets: """Compile a regular expression pattern, returning a pattern object.
    """
    return _compile(pattern, flags)
inputs: Complete the below
def getparser(use_datetime=False, use_builtin_types=False):

    ''''getparser() -> parser, unmarshaller
    Create an instance of the fastest available parser, and attach it
    to an unmarshalling object.  Return both objects.'
    '''
targets: if (FastParser and FastUnmarshaller):
        if use_builtin_types:
            mkdatetime = _datetime_type
            mkbytes = base64.decodebytes
        elif use_datetime:
            mkdatetime = _datetime_type
            mkbytes = _binary
        else:
            mkdatetime = _datetime
            mkbytes = _binary
        target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault)
        parser = FastParser(target)
    else:
        target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
        if FastParser:
            parser = FastParser(target)
        else:
            parser = ExpatParser(target)
    return (parser, target)
inputs: I wrote the below code

    abbreviation = name[0:3].lower()
    try:
        return WEEKDAYS[abbreviation]
    except KeyError:
        raise KeyError(name)


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

    for leaf in name_leafs:
        leaf.remove()
    children = [Leaf(token.NAME, 'from'), Leaf(token.NAME, package_name, prefix='    '), Leaf(token.NAME, 'import', prefix='    '), Node(syms.import_as_names, name_leafs)]
    imp = Node(syms.import_from, children)
    return imp


What's a good function header?
targets: def FromImport(package_name, name_leafs):
inputs: Complete the below
@register.filter(is_safe=True)
def markdown(value, arg=''):

    ''''Runs Markdown over a given value, optionally using various
    extensions python-markdown supports.
    Syntax::
    {{ value|markdown:"extension1_name,extension2_name..." }}
    To enable safe mode, which strips raw HTML and only returns HTML
    generated by actual Markdown syntax, pass "safe" as the first
    extension in the list.
    If the version of Markdown in use does not support extensions,
    they will be silently ignored.'
    '''
targets: import warnings
    warnings.warn('The    markdown    filter    has    been    deprecated', category=DeprecationWarning)
    try:
        import markdown
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError("Error    in    'markdown'    filter:    The    Python    markdown    library    isn't    installed.")
        return force_text(value)
    else:
        markdown_vers = getattr(markdown, 'version_info', 0)
        if (markdown_vers < (2, 1)):
            if settings.DEBUG:
                raise template.TemplateSyntaxError("Error    in    'markdown'    filter:    Django    does    not    support    versions    of    the    Python    markdown    library    <    2.1.")
            return force_text(value)
        else:
            extensions = [e for e in arg.split(',') if e]
            if (extensions and (extensions[0] == 'safe')):
                extensions = extensions[1:]
                return mark_safe(markdown.markdown(force_text(value), extensions, safe_mode=True, enable_attributes=False))
            else:
                return mark_safe(markdown.markdown(force_text(value), extensions, safe_mode=False))
inputs: @nox.session
def lint(session):
targets: """Run linters.
    Returns a failure if the linters find linting errors or sufficiently
    serious code quality issues.
    """
    session.interpreter = 'python3.6'
    session.install('flake8', 'pylint', 'gcp-devrel-py-tools', *LOCAL_DEPS)
    session.install('.')
    session.run('flake8', os.path.join('google', 'cloud', 'bigquery'))
    session.run('flake8', 'tests')
    session.run('gcp-devrel-py-tools', 'run-pylint', '--config', 'pylint.config.py', '--library-filesets', 'google', '--test-filesets', 'tests', success_codes=range(0, 100))
inputs: I wrote the below code

    kwargs.setdefault('allow_redirects', False)
    return request('head', url, **kwargs)


What's a good function header?
targets: def head(url, **kwargs):
inputs: Complete the below
def get_comment_form(parser, token):

    ''''Get a (new) form object to post a new comment.
    Syntax::
    {% get_comment_form for [object] as [varname] %}
    {% get_comment_form for [app].[model] [object_id] as [varname] %}'
    '''
targets: return CommentFormNode.handle_token(parser, token)
inputs: I wrote the below code

    (record, _) = UserCourseTag.objects.get_or_create(user=user, course_id=course_id, key=key)
    record.value = value
    record.save()


What's a good function header?
targets: def set_course_tag(user, course_id, key, value):
inputs: def _blob_overlap(blob1, blob2):
targets: """Finds the overlapping area fraction between two blobs.
    Returns a float representing fraction of overlapped area.
    Parameters
    blob1 : sequence
    A sequence of ``(y,x,sigma)``, where ``x,y`` are coordinates of blob
    and sigma is the standard deviation of the Gaussian kernel which
    detected the blob.
    blob2 : sequence
    A sequence of ``(y,x,sigma)``, where ``x,y`` are coordinates of blob
    and sigma is the standard deviation of the Gaussian kernel which
    detected the blob.
    Returns
    f : float
    Fraction of overlapped area.
    """
    root2 = sqrt(2)
    r1 = (blob1[2] * root2)
    r2 = (blob2[2] * root2)
    d = hypot((blob1[0] - blob2[0]), (blob1[1] - blob2[1]))
    if (d > (r1 + r2)):
        return 0
    if (d <= abs((r1 - r2))):
        return 1
    ratio1 = ((((d ** 2) + (r1 ** 2)) - (r2 ** 2)) / ((2 * d) * r1))
    ratio1 = np.clip(ratio1, (-1), 1)
    acos1 = arccos(ratio1)
    ratio2 = ((((d ** 2) + (r2 ** 2)) - (r1 ** 2)) / ((2 * d) * r2))
    ratio2 = np.clip(ratio2, (-1), 1)
    acos2 = arccos(ratio2)
    a = (((- d) + r2) + r1)
    b = ((d - r2) + r1)
    c = ((d + r2) - r1)
    d = ((d + r2) + r1)
    area = ((((r1 ** 2) * acos1) + ((r2 ** 2) * acos2)) - (0.5 * sqrt(abs((((a * b) * c) * d)))))
    return (area / (math.pi * (min(r1, r2) ** 2)))
inputs: def libvlc_new(argc, argv):
targets: """Create and initialize a libvlc instance.
    This functions accept a list of "command line" arguments similar to the
    main(). These arguments affect the LibVLC instance default configuration.
    @note
    LibVLC may create threads. Therefore, any thread-unsafe process
    initialization must be performed before calling L{libvlc_new}(). In particular
    and where applicable:
    - setlocale() and textdomain(),
    - setenv(), unsetenv() and putenv(),
    - with the X11 display system, XInitThreads()
    (see also L{libvlc_media_player_set_xwindow}()) and
    - on Microsoft Windows, SetErrorMode().
    - sigprocmask() shall never be invoked; pthread_sigmask() can be used.
    On POSIX systems, the SIGCHLD signal must B{not} be ignored, i.e. the
    signal handler must set to SIG_DFL or a function pointer, not SIG_IGN.
    Also while LibVLC is active, the wait() function shall not be called, and
    any call to waitpid() shall use a strictly positive value for the first
    parameter (i.e. the PID). Failure to follow those rules may lead to a
    deadlock or a busy loop.
    Also on POSIX systems, it is recommended that the SIGPIPE signal be blocked,
    even if it is not, in principles, necessary.
    On Microsoft Windows Vista/2008, the process error mode
    SEM_FAILCRITICALERRORS flag B{must} with the SetErrorMode() function
    before using LibVLC. On later versions, it is optional and unnecessary.
    @param argc: the number of arguments (should be 0).
    @param argv: list of arguments (should be None).
    @return: the libvlc instance or None in case of error.
    @version Arguments are meant to be passed from the command line to LibVLC, just like VLC media player does. The list of valid arguments depends on the LibVLC version, the operating system and platform, and set of available LibVLC plugins. Invalid or unsupported arguments will cause the function to fail (i.e. return None). Also, some arguments may alter the behaviour or otherwise interfere with other LibVLC functions. @warning There is..."""
    f = (_Cfunctions.get('libvlc_new', None) or _Cfunction('libvlc_new', ((1,), (1,)), class_result(Instance), ctypes.c_void_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p)))
    return f(argc, argv)
inputs: def cluster_node_present(name, node, extra_args=None):
targets: """Add a node to the Pacemaker cluster via PCS
    Should be run on one cluster node only
    (there may be races)
    Can only be run on a already setup/added node
    name
    Irrelevant, not used (recommended: pcs_setup__node_add_{{node}})
    node
    node that should be added
    extra_args
    list of extra args for the \pcs cluster node add\ command
    Example:
    .. code-block:: yaml
    pcs_setup__node_add_node1.example.com:
    pcs.cluster_node_present:
    - node: node1.example.com
    - extra_args:
    - \--start\
    - \--enable\
    """
    ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
    node_add_required = True
    current_nodes = []
    is_member_cmd = ['pcs', 'status', 'nodes', 'corosync']
    is_member = __salt__['cmd.run_all'](is_member_cmd, output_loglevel='trace', python_shell=False)
    log.trace(('Output    of    pcs    status    nodes    corosync:    ' + str(is_member)))
    for line in is_member['stdout'].splitlines():
        if (len(line.split(':')) in [2]):
            key = line.split(':')[0].strip()
            value = line.split(':')[1].strip()
            if (key in ['Offline', 'Online']):
                if (len(value.split()) > 0):
                    if (node in value.split()):
                        node_add_required = False
                        ret['comment'] += 'Node    {0}    is    already    member    of    the    cluster\n'.format(node)
                    else:
                        current_nodes += value.split()
    if (not node_add_required):
        return ret
    if __opts__['test']:
        ret['result'] = None
        ret['comment'] += 'Node    {0}    is    set    to    be    added    to    the    cluster\n'.format(node)
        return ret
    if (not isinstance(extra_args, (list, tuple))):
        extra_args = []
    node_add = __salt__['pcs.cluster_node_add'](node=node, extra_args=extra_args)
    log.trace(('Output    of    pcs.cluster_node_add:    ' + str(node_add)))
    node_add_dict = {}
    for line in node_add['stdout'].splitlines():
        log.trace(('line:    ' + line))
        log.trace(('line.split(:).len:    ' + str(len(line.split(':')))))
        if (len(line.split(':')) in [2]):
            current_node = line.split(':')[0].strip()
            current_node_add_state = line.split(':')[1].strip()
            if (current_node in (current_nodes + [node])):
                node_add_dict.update({current_node: current_node_add_state})
    log.trace(('node_add_dict:    ' + str(node_add_dict)))
    for current_node in current_nodes:
        if (current_node in...
inputs: I wrote the below code

    model = context['model']
    user = context['user']
    name_or_id = data_dict.get('id')
    organization_id = data_dict.get('organization_id')
    _check_access('package_owner_org_update', context, data_dict)
    pkg = model.Package.get(name_or_id)
    if (pkg is None):
        raise NotFound(_('Package    was    not    found.'))
    if organization_id:
        org = model.Group.get(organization_id)
        if ((org is None) or (not org.is_organization)):
            raise NotFound(_('Organization    was    not    found.'))
        pkg.owner_org = org.id
    else:
        org = None
        pkg.owner_org = None
    if context.get('add_revision', True):
        rev = model.repo.new_revision()
        rev.author = user
        if ('message' in context):
            rev.message = context['message']
        else:
            rev.message = (_(u'REST    API:    Update    object    %s') % pkg.get('name'))
    members = model.Session.query(model.Member).filter((model.Member.table_id == pkg.id)).filter((model.Member.capacity == 'organization'))
    need_update = True
    for member_obj in members:
        if (org and (member_obj.group_id == org.id)):
            need_update = False
        else:
            member_obj.state = 'deleted'
            member_obj.save()
    if (org and need_update):
        member_obj = model.Member(table_id=pkg.id, table_name='package', group=org, capacity='organization', group_id=org.id, state='active')
        model.Session.add(member_obj)
    if (not context.get('defer_commit')):
        model.Session.commit()


What's a good function header?
targets: def package_owner_org_update(context, data_dict):
inputs: I wrote the below code

    newtable = table.copy(copy_data=False)
    hdr = Header([Card(keyword=key, value=val[0], comment=val[1]) for (key, val) in GLOBAL_TIME_INFO.items()])
    newtable.meta['__coordinate_columns__'] = defaultdict(OrderedDict)
    coord_meta = newtable.meta['__coordinate_columns__']
    time_cols = table.columns.isinstance(Time)
    location = None
    for col in time_cols:
        jd12 = np.array([col.jd1, col.jd2])
        jd12 = np.rollaxis(jd12, 0, jd12.ndim)
        newtable.replace_column(col.info.name, Column(jd12, unit='d'))
        n = (table.colnames.index(col.info.name) + 1)
        coord_meta[col.info.name]['coord_type'] = col.scale.upper()
        coord_meta[col.info.name]['coord_unit'] = 'd'
        if (col.location is None):
            if (location is not None):
                warnings.warn('Time    Column    "{}"    has    no    specified    location,    but    global    Time    Position    is    present,    which    will    be    the    default    for    this    column    in    FITS    specification.'.format(col.info.name), AstropyUserWarning)
        else:
            coord_meta[col.info.name]['time_ref_pos'] = 'TOPOCENTER'
            if (col.scale in BARYCENTRIC_SCALES):
                warnings.warn('Earth    Location    "TOPOCENTER"    for    Time    Column    "{}"    is    incompatabile    with    scale    "{}".'.format(col.info.name, col.scale.upper()), AstropyUserWarning)
            if (col.location.size > 1):
                raise ValueError('Vectorized    Location    of    Time    Column    "{}"    cannot    be    written,    as    it    is    not    supported.'.format(col.info.name))
            if (location is None):
                location = col.location
                hdr.extend([Card(keyword='OBSGEO-{}'.format(dim.upper()), value=getattr(location, dim).to_value(u.m)) for dim in ('x', 'y', 'z')])
            elif (location != col.location):
                raise ValueError('Multiple    Time    Columns    with    different    geocentric    observatory    locations    ({},   ...

What's a good function header?
targets: def time_to_fits(table):
inputs: def decode_sentencepiece(text):
targets: """Decodes text that uses https://github.com/google/sentencepiece encoding.
    Assumes that pieces are separated by a space
    """
    return u''.join(text.split(u'    ')).replace(u'\u2581', u'    ').strip()
inputs: Complete the below
def get_language_from_path(path, supported=None):

    ''''Returns the language-code if there is a valid language-code
    found in the `path`.'
    '''
targets: if (supported is None):
        from django.conf import settings
        supported = dict(settings.LANGUAGES)
    regex_match = language_code_prefix_re.match(path)
    if regex_match:
        lang_code = regex_match.group(1)
        if ((lang_code in supported) and check_for_language(lang_code)):
            return lang_code
inputs: def ParseArguments(argv, die_fn=(lambda : PrintUsageExit(1))):
targets: """Parses command-line arguments.
    Prints out a help message if -h or --help is supplied.
    Args:
    argv: List of command-line arguments.
    die_fn: Function to invoke to end the program.
    Returns:
    A dictionary containing the value of command-line options.
    """
    (opts, unused_args) = getopt.getopt(argv[1:], 'h', FLAG_SPEC)
    arg_dict = {}
    arg_dict['url'] = REQUIRED_OPTION
    arg_dict['filename'] = None
    arg_dict['config_file'] = None
    arg_dict['kind'] = None
    arg_dict['batch_size'] = None
    arg_dict['num_threads'] = DEFAULT_THREAD_COUNT
    arg_dict['bandwidth_limit'] = DEFAULT_BANDWIDTH_LIMIT
    arg_dict['rps_limit'] = DEFAULT_RPS_LIMIT
    arg_dict['http_limit'] = DEFAULT_REQUEST_LIMIT
    arg_dict['application'] = ''
    arg_dict['auth_domain'] = 'gmail.com'
    arg_dict['create_config'] = False
    arg_dict['db_filename'] = None
    arg_dict['debug'] = False
    arg_dict['download'] = False
    arg_dict['dry_run'] = False
    arg_dict['dump'] = False
    arg_dict['exporter_opts'] = None
    arg_dict['has_header'] = False
    arg_dict['loader_opts'] = None
    arg_dict['log_file'] = None
    arg_dict['map'] = False
    arg_dict['mapper_opts'] = None
    arg_dict['namespace'] = ''
    arg_dict['restore'] = False
    arg_dict['result_db_filename'] = None
    arg_dict['throttle_class'] = None
    def ExpandFilename(filename):
        'Expand    shell    variables    and    ~usernames    in    filename.'
        return os.path.expandvars(os.path.expanduser(filename))
    for (option, value) in opts:
        if (option in ('-h', '--help')):
            PrintUsageExit(0)
        if (not option.startswith('--')):
            continue
        option = option[2:]
        if (option in DEPRECATED_OPTIONS):
            print >>sys.stderr, ('--%s    is    deprecated,    please    use    --%s.' % (option, DEPRECATED_OPTIONS[option]))
            option = DEPRECATED_OPTIONS[option]
        if (option in BOOL_ARGS):
            arg_dict[option] = True
        elif (option in INT_ARGS):
            arg_dict[option] = int(value)
        elif (option in FILENAME_ARGS):
            arg_dict[option] = ExpandFilename(value)
        elif (option in STRING_ARGS):
            arg_dict[option] = value
    return ProcessArguments(arg_dict, die_fn=die_fn)
inputs: def gather(boxlist, indices, fields=None):
targets: """Gather boxes from BoxList according to indices and return new BoxList.
    By default, Gather returns boxes corresponding to the input index list, as
    well as all additional fields stored in the boxlist (indexing into the
    first dimension).  However one can optionally only gather from a
    subset of fields.
    Args:
    boxlist: BoxList holding N boxes
    indices: a 1-d numpy array of type int_
    fields: (optional) list of fields to also gather from.  If None (default),
    all fields are gathered from.  Pass an empty fields list to only gather
    the box coordinates.
    Returns:
    subboxlist: a BoxList corresponding to the subset of the input BoxList
    specified by indices
    Raises:
    ValueError: if specified field is not contained in boxlist or if the
    indices are not of type int_
    """
    if indices.size:
        if ((np.amax(indices) >= boxlist.num_boxes()) or (np.amin(indices) < 0)):
            raise ValueError('indices    are    out    of    valid    range.')
    subboxlist = np_box_list.BoxList(boxlist.get()[indices, :])
    if (fields is None):
        fields = boxlist.get_extra_fields()
    for field in fields:
        extra_field_data = boxlist.get_field(field)
        subboxlist.add_field(field, extra_field_data[indices, ...])
    return subboxlist
inputs: Complete the below
def find_max_occupancy_node(dir_list):

    ''''Find node with maximum occupancy.
    :param dir_list: list of directories for each node.
    :return: number number node in list_dir'
    '''
targets: count = 0
    number = 0
    length = 0
    for dirs in dir_list:
        if (length < len(dirs)):
            length = len(dirs)
            number = count
        count += 1
    return number
inputs: I wrote the below code

    portionDirection = portionDirections[portionDirectionIndex]
    if (portionDirection.directionReversed == True):
        loopLists.append([])
    loops = loopLists[(-1)]
    interpolationOffset = derivation.interpolationDictionary['offset']
    offset = interpolationOffset.getVector3ByPortion(portionDirection)
    if (endMultiplier != None):
        if (portionDirectionIndex == 0):
            setOffsetByMultiplier(interpolationOffset.path[1], interpolationOffset.path[0], endMultiplier, offset)
        elif (portionDirectionIndex == (len(portionDirections) - 1)):
            setOffsetByMultiplier(interpolationOffset.path[(-2)], interpolationOffset.path[(-1)], endMultiplier, offset)
    scale = derivation.interpolationDictionary['scale'].getComplexByPortion(portionDirection)
    twist = derivation.interpolationDictionary['twist'].getYByPortion(portionDirection)
    projectiveSpace = euclidean.ProjectiveSpace()
    if (derivation.tiltTop == None):
        tilt = derivation.interpolationDictionary['tilt'].getComplexByPortion(portionDirection)
        projectiveSpace = projectiveSpace.getByTilt(tilt)
    else:
        normals = getNormals(interpolationOffset, offset, portionDirection)
        normalFirst = normals[0]
        normalAverage = getNormalAverage(normals)
        if (derivation.tiltFollow and (derivation.oldProjectiveSpace != None)):
            projectiveSpace = derivation.oldProjectiveSpace.getNextSpace(normalAverage)
        else:
            projectiveSpace = projectiveSpace.getByBasisZTop(normalAverage, derivation.tiltTop)
        derivation.oldProjectiveSpace = projectiveSpace
        projectiveSpace.unbuckle(derivation.maximumUnbuckling, normalFirst)
    projectiveSpace = projectiveSpace.getSpaceByXYScaleAngle(twist, scale)
    loop = []
    if ((abs(projectiveSpace.basisX) + abs(projectiveSpace.basisY)) < 0.0001):
        vector3Index = Vector3Index(len(vertexes))
        addOffsetAddToLists(loop, offset, vector3Index, vertexes)
        loops.append(loop)
        return
    for point in...

What's a good function header?
targets: def addLoop(derivation, endMultiplier, loopLists, path, portionDirectionIndex, portionDirections, vertexes):
inputs: I wrote the below code

    map = ('/boot/System.map-%s' % os.uname()[2])
    if os.path.isfile(map):
        return map
    map = ('/lib/modules/%s/build/System.map' % os.uname()[2])
    if os.path.isfile(map):
        return map
    return None


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

    import binascii
    try:
        with open(input, 'rb') as fd:
            return binascii.hexlify(fd.read())
    except IOError:
        raise TypeError


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

    (full_path, arch, osx_name, version, build) = profile
    args = ['/usr/bin/hdiutil', 'convert', '-quiet', full_path, '-format', 'UDTO', '-o', os.path.join(temp_dir, 'test')]
    run_cmd(args)
    args = ['/usr/bin/hdiutil', 'attach', '-quiet', '-nobrowse', '-noverify', '-noautoopen', '-mountpoint', '/Volumes/KernelDebugKit', os.path.join(temp_dir, 'test.cdr')]
    run_cmd(args)
    dwarf_info = os.path.join(temp_dir, 'dwarf.txt')
    if os.path.isfile('/Volumes/KernelDebugKit/kernel.dSYM'):
        kernel = '/Volumes/KernelDebugKit/kernel.dSYM'
    else:
        kernel = '/Volumes/KernelDebugKit/mach_kernel.dSYM'
    args = ['/usr/bin/dwarfdump', '-arch', arch, '-i', kernel]
    run_cmd(args, output_file=dwarf_info)
    convert_py = os.path.join(volatility_dir, 'tools/mac/convert.py')
    new_dwarf = (dwarf_info + '.conv')
    args = ['/usr/bin/python', convert_py, dwarf_info, new_dwarf]
    run_cmd(args)
    vtypes_file = (new_dwarf + '.vtypes')
    args = ['/usr/bin/python', convert_py, new_dwarf]
    run_cmd(args, output_file=vtypes_file)
    symbol_file = (dwarf_info + '.symbol.dsymutil')
    if os.path.isfile('/Volumes/KernelDebugKit/mach_kernel'):
        kernel = '/Volumes/KernelDebugKit/mach_kernel'
    else:
        kernel = '/Volumes/KernelDebugKit/kernel'
    args = ['/usr/bin/dsymutil', '-s', '-arch', arch, kernel]
    run_cmd(args, output_file=symbol_file)
    profile_name = ((osx_name + '_') + version)
    if (arch == 'i386'):
        profile_name += '_Intel'
    else:
        profile_name += '_AMD'
    profile_name += '.zip'
    zip_file = os.path.join(profile_dir, profile_name)
    args = ['/usr/bin/zip', zip_file, symbol_file, vtypes_file]
    run_cmd(args)
    args = ['/usr/bin/hdiutil', 'detach', '/Volumes/KernelDebugKit']
    run_cmd(args)
    shutil.rmtree(temp_dir)
    os.mkdir(temp_dir)


What's a good function header?
targets: def generate_profile(temp_dir, volatility_dir, profile_dir, profile):
inputs: I wrote the below code

    global _CLIENT_KWARGS, _CLIENT_HOST, _CLIENT_PORT, _METADATA_ENCRYPTION_KEY
    try:
        (host, port) = (CONF.registry_host, CONF.registry_port)
    except cfg.ConfigFileValueError:
        msg = _('Configuration    option    was    not    valid')
        LOG.error(msg)
        raise exception.BadRegistryConnectionConfiguration(msg)
    except IndexError:
        msg = _('Could    not    find    required    configuration    option')
        LOG.error(msg)
        raise exception.BadRegistryConnectionConfiguration(msg)
    _CLIENT_HOST = host
    _CLIENT_PORT = port
    _METADATA_ENCRYPTION_KEY = CONF.metadata_encryption_key
    _CLIENT_KWARGS = {'use_ssl': (CONF.registry_client_protocol.lower() == 'https'), 'key_file': CONF.registry_client_key_file, 'cert_file': CONF.registry_client_cert_file, 'ca_file': CONF.registry_client_ca_file, 'insecure': CONF.registry_client_insecure, 'timeout': CONF.registry_client_timeout}


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

    if (settings.USE_TZ and (value is not None) and timezone.is_aware(value)):
        current_timezone = timezone.get_current_timezone()
        return timezone.make_naive(value, current_timezone)
    return value


What's a good function header?
targets: def to_current_timezone(value):