Muennighoff/xP3x-sample huggingface dataset:
inputs: Complete the below
def create_default_plugins(request, placeholders, template, lang):

    ''''Create all default plugins for the given ``placeholders`` if they have
    a "default_plugins" configuration value in settings.
    return all plugins, children, grandchildren (etc.) created'
    '''
targets: from cms.api import add_plugin
    def _create_default_plugins(placeholder, confs, parent=None):
        "\n                                Auxillary    function    that    builds    all    of    a    placeholder's    default    plugins\n                                at    the    current    level    and    drives    the    recursion    down    the    tree.\n                                Returns    the    plugins    at    the    current    level    along    with    all    descendants.\n                                "
        (plugins, descendants) = ([], [])
        addable_confs = (conf for conf in confs if has_plugin_permission(request.user, conf['plugin_type'], 'add'))
        for conf in addable_confs:
            plugin = add_plugin(placeholder, conf['plugin_type'], lang, target=parent, **conf['values'])
            if ('children' in conf):
                args = (placeholder, conf['children'], plugin)
                descendants += _create_default_plugins(*args)
            plugin.notify_on_autoadd(request, conf)
            plugins.append(plugin)
        if parent:
            parent.notify_on_autoadd_children(request, conf, plugins)
        return (plugins + descendants)
    unfiltered_confs = ((ph, get_placeholder_conf('default_plugins', ph.slot, template)) for ph in placeholders)
    mutable_confs = ((ph, default_plugin_confs) for (ph, default_plugin_confs) in filter(itemgetter(1), unfiltered_confs) if ph.has_change_permission(request.user))
    return sum(starmap(_create_default_plugins, mutable_confs), [])
inputs: Complete the below
def customize_compiler_for_nvcc(self):

    ''''inject deep into distutils to customize how the dispatch
    to gcc/nvcc works.
    If you subclass UnixCCompiler, it\'s not trivial to get your subclass
    injected in, and still have the right customizations (i.e.
    distutils.sysconfig.customize_compiler) run on it. So instead of going
    the OO route, I have this. Note, it\'s kindof like a wierd functional
    subclassing going on.'
    '''
targets: self.src_extensions.append('.cu')
    default_compiler_so = self.compiler_so
    super = self._compile
    def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
        if (os.path.splitext(src)[1] == '.cu'):
            self.set_executable('compiler_so', CUDA['nvcc'])
            postargs = extra_postargs['nvcc']
        else:
            postargs = extra_postargs['gcc']
        super(obj, src, ext, cc_args, postargs, pp_opts)
        self.compiler_so = default_compiler_so
    self._compile = _compile
inputs: I wrote the below code

    len_trf = (smax - smin)
    (len_x, n_ch_x) = X.shape
    (len_y, n_ch_y) = y.shape
    assert (len_x == len_y)
    n_fft = next_fast_len((((X.shape[0] + max(smax, 0)) - min(smin, 0)) - 1))
    X_fft = np.fft.rfft(X.T, n_fft)
    y_fft = np.fft.rfft(y.T, n_fft)
    ac = np.zeros((n_ch_x, n_ch_x, ((len_trf * 2) - 1)))
    for ch0 in range(n_ch_x):
        for ch1 in range(ch0, n_ch_x):
            ac_temp = np.fft.irfft((X_fft[ch0] * X_fft[ch1].conj()), n_fft)
            ac[(ch0, ch1)] = np.concatenate((ac_temp[((- len_trf) + 1):], ac_temp[:len_trf]))
            if (ch0 != ch1):
                ac[(ch1, ch0)] = ac[(ch0, ch1)][::(-1)]
    x_y = np.zeros((n_ch_y, n_ch_x, len_trf))
    for ch_in in range(n_ch_x):
        for ch_out in range(n_ch_y):
            cc_temp = np.fft.irfft((y_fft[ch_out] * X_fft[ch_in].conj()), n_fft)
            if ((smin < 0) and (smax >= 0)):
                x_y[(ch_out, ch_in)] = np.append(cc_temp[smin:], cc_temp[:smax])
            else:
                x_y[(ch_out, ch_in)] = cc_temp[smin:smax]
    x_xt = _make_x_xt(ac)
    x_y.shape = (n_ch_y, (n_ch_x * len_trf))
    return (x_xt, x_y, n_ch_x)


What's a good function header?
targets: def _compute_corrs(X, y, smin, smax):
inputs: Complete the below
def _check_copy_from_header(req):

    ''''Validate that the value from x-copy-from header is
    well formatted. We assume the caller ensures that
    x-copy-from header is present in req.headers.
    :param req: HTTP request object
    :returns: A tuple with container name and object name
    :raise HTTPPreconditionFailed: if x-copy-from value
    is not well formatted.'
    '''
targets: return _check_path_header(req, 'X-Copy-From', 2, 'X-Copy-From    header    must    be    of    the    form    <container    name>/<object    name>')
inputs: def create_apppool(name):
targets: """Create an IIS application pool.
    .. note:
    This function only validates against the application pool name, and will return
    True even if the application pool already exists with a different configuration.
    It will not modify the configuration of an existing application pool.
    :param str name: The name of the IIS application pool.
    Usage:
    .. code-block:: yaml
    site0-apppool:
    win_iis.create_apppool:
    - name: site0
    """
    ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
    current_apppools = __salt__['win_iis.list_apppools']()
    if (name in current_apppools):
        ret['comment'] = 'Application    pool    already    present:    {0}'.format(name)
        ret['result'] = True
    elif __opts__['test']:
        ret['comment'] = 'Application    pool    will    be    created:    {0}'.format(name)
        ret['changes'] = {'old': None, 'new': name}
    else:
        ret['comment'] = 'Created    application    pool:    {0}'.format(name)
        ret['changes'] = {'old': None, 'new': name}
        ret['result'] = __salt__['win_iis.create_apppool'](name)
    return ret
inputs: Complete the below
def _stdin_ready_other():

    ''''Return True, assuming there\'s something to read on stdin.'
    '''
targets: return True
inputs: def get_updates_and_outputs(ls):
targets: """This function tries to recognize the updates OrderedDict, the
    list of outputs and the stopping condition returned by the
    lambda expression and arrange them in a predefined order.
    WRITEME: what is the type of ls? how is it formatted?
    if it\s not in the predefined order already, how does
    this function know how to put it in that order?
    """
    def is_outputs(elem):
        if (isinstance(elem, (list, tuple)) and all([isinstance(x, theano.Variable) for x in elem])):
            return True
        if isinstance(elem, theano.Variable):
            return True
        return False
    def is_updates(elem):
        if isinstance(elem, dict):
            if ((not isinstance(elem, compat.OrderedDict)) and (len(elem) > 1)):
                warnings.warn((('Expected    OrderedDict    or    OrderedUpdates,    got    ' + str(type(elem))) + '.    This    can    make    your    script    non-deterministic.'))
            return True
        if (isinstance(elem, (list, tuple)) and all([(isinstance(x, (list, tuple)) and (len(x) == 2)) for x in elem])):
            return True
        return False
    def is_condition(elem):
        return isinstance(elem, theano.scan_module.until)
    def _list(x):
        if isinstance(x, (list, tuple)):
            return list(x)
        else:
            return [x]
    def _filter(x):
        '\n                                Ensure    `x`    is    made    only    of    allowed    data    types.\n\n                                Return    True    iff    `x`    is    made    only    of    lists,    tuples,    dictionaries,    Theano\n                                variables    or    `theano.scan_module.until`    objects.\n\n                                '
        iter_on = None
        if (isinstance(x, list) or isinstance(x, tuple)):
            iter_on = x
        elif isinstance(x, dict):
            iter_on = iteritems(x)
        if (iter_on is not None):
            return all((_filter(y) for y in iter_on))
        else:
            return (isinstance(x, theano.Variable) or isinstance(x, theano.scan_module.until))
    if (not _filter(ls)):
        raise ValueError('The    return    value    of    your    scan    lambda    expression    may    only    be    made    of    lists,    tuples,    or    dictionaries    containing    Theano    variables    (or    `theano.scan_module.until`    objects    for   ...
inputs: def decode(encoding=None, default_encoding='utf-8'):
targets: """Replace or extend the list of charsets used to decode a request entity.
    Either argument may be a single string or a list of strings.
    encoding
    If not None, restricts the set of charsets attempted while decoding
    a request entity to the given set (even if a different charset is
    given in the Content-Type request header).
    default_encoding
    Only in effect if the \encoding\ argument is not given.
    If given, the set of charsets attempted while decoding a request
    entity is *extended* with the given value(s).
    """
    body = cherrypy.request.body
    if (encoding is not None):
        if (not isinstance(encoding, list)):
            encoding = [encoding]
        body.attempt_charsets = encoding
    elif default_encoding:
        if (not isinstance(default_encoding, list)):
            default_encoding = [default_encoding]
        body.attempt_charsets = (body.attempt_charsets + default_encoding)
inputs: I wrote the below code

    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if ('import    versioneer' in line):
                found.add('import')
            if ('versioneer.get_cmdclass()' in line):
                found.add('cmdclass')
            if ('versioneer.get_version()' in line):
                found.add('get_version')
            if ('versioneer.VCS' in line):
                setters = True
            if ('versioneer.versionfile_source' in line):
                setters = True
    if (len(found) != 3):
        print('')
        print('Your    setup.py    appears    to    be    missing    some    important    items')
        print('(but    I    might    be    wrong).    Please    make    sure    it    has    something')
        print('roughly    like    the    following:')
        print('')
        print('    import    versioneer')
        print('    setup(    version=versioneer.get_version(),')
        print('                                cmdclass=versioneer.get_cmdclass(),        ...)')
        print('')
        errors += 1
    if setters:
        print("You    should    remove    lines    like    'versioneer.VCS    =    '    and")
        print("'versioneer.versionfile_source    =    '    .    This    configuration")
        print('now    lives    in    setup.cfg,    and    should    be    removed    from    setup.py')
        print('')
        errors += 1
    return errors


What's a good function header?
targets: def scan_setup_py():
inputs: Complete the below
def hough_circle(image, radius, normalize=True, full_output=False):

    ''''Perform a circular Hough transform.
    Parameters
    image : (M, N) ndarray
    Input image with nonzero values representing edges.
    radius : scalar or sequence of scalars
    Radii at which to compute the Hough transform.
    Floats are converted to integers.
    normalize : boolean, optional (default True)
    Normalize the accumulator with the number
    of pixels used to draw the radius.
    full_output : boolean, optional (default False)
    Extend the output size by twice the largest
    radius in order to detect centers outside the
    input picture.
    Returns
    H : 3D ndarray (radius index, (M + 2R, N + 2R) ndarray)
    Hough transform accumulator for each radius.
    R designates the larger radius if full_output is True.
    Otherwise, R = 0.
    Examples
    >>> from skimage.transform import hough_circle
    >>> from skimage.draw import circle_perimeter
    >>> img = np.zeros((100, 100), dtype=np.bool_)
    >>> rr, cc = circle_perimeter(25, 35, 23)
    >>> img[rr, cc] = 1
    >>> try_radii = np.arange(5, 50)
    >>> res = hough_circle(img, try_radii)
    >>> ridx, r, c = np.unravel_index(np.argmax(res), res.shape)
    >>> r, c, try_radii[ridx]
    (25, 35, 23)'
    '''
targets: radius = np.atleast_1d(np.asarray(radius))
    return _hough_circle(image, radius.astype(np.intp), normalize=normalize, full_output=full_output)
inputs: Complete the below
def dottedQuadToNum(ip):

    ''''Convert decimal dotted quad string to long integer
    >>> int(dottedQuadToNum(\'1 \'))
    1
    >>> int(dottedQuadToNum(\' 1.2\'))
    16777218
    >>> int(dottedQuadToNum(\' 1.2.3 \'))
    16908291
    >>> int(dottedQuadToNum(\'1.2.3.4\'))
    16909060
    >>> dottedQuadToNum(\'255.255.255.255\')
    4294967295
    >>> dottedQuadToNum(\'255.255.255.256\')
    Traceback (most recent call last):
    ValueError: Not a good dotted-quad IP: 255.255.255.256'
    '''
targets: import socket, struct
    try:
        return struct.unpack('!L', socket.inet_aton(ip.strip()))[0]
    except socket.error:
        raise ValueError(('Not    a    good    dotted-quad    IP:    %s' % ip))
    return
inputs: I wrote the below code

    if (not _state):
        raise RuntimeError('no    active    input()')
    return _state.isstdin()


What's a good function header?
targets: def isstdin():
inputs: Complete the below
def get_args():

    ''''Parses command line arguments
    :returns: Parsed command line options
    :rtype: argparse.Namespace'
    '''
targets: parser = argparse.ArgumentParser(description=_DESCRIPTION)
    parser.add_argument('-c', '--apache-ctl', default='apachectl', help='path    to    the    `apachectl`    binary')
    parser.add_argument('-d', '--server-root', help='location    of    the    root    directory    of    your    Apache    configuration')
    parser.add_argument('-f', '--config-file', help='location    of    your    main    Apache    configuration    file    relative    to    the    server    root')
    args = parser.parse_args()
    if (bool(args.server_root) != bool(args.config_file)):
        sys.exit('If    either    --server-root    and    --config-file    are    specified,    they    both    must    be    included')
    elif (args.server_root and args.config_file):
        args.server_root = os.path.abspath(args.server_root)
        args.config_file = os.path.abspath(args.config_file)
        if args.config_file.startswith(args.server_root):
            args.config_file = args.config_file[(len(args.server_root) + 1):]
        else:
            sys.exit('This    script    expects    the    Apache    configuration    file    to    be    inside    the    server    root')
    return args
inputs: def groovy(registry, xml_parent, data):
targets: """yaml: groovy
    Execute a groovy script or command.
    Requires the Jenkins :jenkins-wiki:`Groovy Plugin <Groovy+plugin>`.
    :arg str file: Groovy file to run. (Alternative: you can chose a command
    instead)
    :arg str command: Groovy command to run. (Alternative: you can chose a
    script file instead)
    :arg str version: Groovy version to use. (default \(Default)\)
    :arg str parameters: Parameters for the Groovy executable. (default \\)
    :arg str script-parameters: These parameters will be passed to the script.
    (default \\)
    :arg str properties: Instead of passing properties using the -D parameter
    you can define them here. (default \\)
    :arg str java-opts: Direct access to JAVA_OPTS. Properties allows only
    -D properties, while sometimes also other properties like -XX need to
    be setup. It can be done here. This line is appended at the end of
    JAVA_OPTS string. (default \\)
    :arg str class-path: Specify script classpath here. Each line is one
    class path item. (default \\)
    Minimal Example:
    .. literalinclude:: ../../tests/builders/fixtures/groovy-minimal.yaml
    :language: yaml
    Full Example:
    .. literalinclude:: ../../tests/builders/fixtures/groovy-full.yaml
    :language: yaml
    """
    root_tag = 'hudson.plugins.groovy.Groovy'
    groovy = XML.SubElement(xml_parent, root_tag)
    groovy.append(_groovy_common_scriptSource(data))
    mappings = [('version', 'groovyName', '(Default)'), ('parameters', 'parameters', ''), ('script-parameters', 'scriptParameters', ''), ('properties', 'properties', ''), ('java-opts', 'javaOpts', ''), ('class-path', 'classPath', '')]
    convert_mapping_to_xml(groovy, data, mappings, fail_required=True)
inputs: I wrote the below code

    class __proxy__(Promise, ):
        '\n                                Encapsulate    a    function    call    and    act    as    a    proxy    for    methods    that    are\n                                called    on    the    result    of    that    function.    The    function    is    not    evaluated\n                                until    one    of    the    methods    on    the    result    is    called.\n                                '
        __dispatch = None
        def __init__(self, args, kw):
            self.__func = func
            self.__args = args
            self.__kw = kw
            if (self.__dispatch is None):
                self.__prepare_class__()
        def __reduce__(self):
            return (_lazy_proxy_unpickle, ((self.__func, self.__args, self.__kw) + resultclasses))
        def __prepare_class__(cls):
            cls.__dispatch = {}
            for resultclass in resultclasses:
                cls.__dispatch[resultclass] = {}
                for (k, v) in resultclass.__dict__.items():
                    meth = cls.__promise__(resultclass, k, v)
                    if hasattr(cls, k):
                        continue
                    setattr(cls, k, meth)
            cls._delegate_str = (str in resultclasses)
            cls._delegate_unicode = (unicode in resultclasses)
            assert (not (cls._delegate_str and cls._delegate_unicode)), 'Cannot    call    lazy()    with    both    str    and    unicode    return    types.'
            if cls._delegate_unicode:
                cls.__unicode__ = cls.__unicode_cast
            elif cls._delegate_str:
                cls.__str__ = cls.__str_cast
        __prepare_class__ = classmethod(__prepare_class__)
        def __promise__(cls, klass, funcname, func):
            def __wrapper__(self, *args, **kw):
                res = self.__func(*self.__args, **self.__kw)
                for t in type(res).mro():
                    if (t in self.__dispatch):
                        return...

What's a good function header?
targets: def lazy(func, *resultclasses):
inputs: I wrote the below code

    last_valid_line_from_code = [line for line in code.split(u'\n') if line][(-1)]
    status_code_from_last_line = int(last_valid_line_from_code.split()[0])
    status_code_from_first_digits = int(code[:3])
    if (status_code_from_last_line != status_code_from_first_digits):
        log.warning(u'FTP    response    status    code    seems    to    be    inconsistent.\nCode    received:    %s,    extracted:    %s    and    %s', code, status_code_from_last_line, status_code_from_first_digits)
    return status_code_from_last_line


What's a good function header?
targets: def get_status_code_from_code_response(code):
inputs: Complete the below
def choicify(values):

    ''''Takes an iterable and makes an iterable of tuples with it'
    '''
targets: return [(v, v) for v in values]
inputs: Complete the below
def iterkeys(d):

    ''''Return an iterator over the keys of a dictionary.'
    '''
targets: return iter(getattr(d, _iterkeys)())
inputs: def get_characteristic_subpattern(subpatterns):
targets: """Picks the most characteristic from a list of linear patterns
    Current order used is:
    names > common_names > common_chars
    """
    if (not isinstance(subpatterns, list)):
        return subpatterns
    if (len(subpatterns) == 1):
        return subpatterns[0]
    subpatterns_with_names = []
    subpatterns_with_common_names = []
    common_names = ['in', 'for', 'if', 'not', 'None']
    subpatterns_with_common_chars = []
    common_chars = '[]().,:'
    for subpattern in subpatterns:
        if any(rec_test(subpattern, (lambda x: (type(x) is str)))):
            if any(rec_test(subpattern, (lambda x: (isinstance(x, str) and (x in common_chars))))):
                subpatterns_with_common_chars.append(subpattern)
            elif any(rec_test(subpattern, (lambda x: (isinstance(x, str) and (x in common_names))))):
                subpatterns_with_common_names.append(subpattern)
            else:
                subpatterns_with_names.append(subpattern)
    if subpatterns_with_names:
        subpatterns = subpatterns_with_names
    elif subpatterns_with_common_names:
        subpatterns = subpatterns_with_common_names
    elif subpatterns_with_common_chars:
        subpatterns = subpatterns_with_common_chars
    return max(subpatterns, key=len)
inputs: @gen.coroutine
def UploadContacts(client, obj_store, user_id, device_id, request):
targets: """Creates/updates contacts metadata.
    """
    request['user_id'] = user_id
    contact_count = len(request['contacts'])
    result_contact_ids = []
    for contact in request['contacts']:
        canon_identities = set()
        identities_properties = []
        for contact_identity in contact['identities']:
            identity_key = contact_identity['identity']
            description = contact_identity.get('description', None)
            if (identity_key != Identity.Canonicalize(identity_key)):
                raise InvalidRequestError(IDENTITY_NOT_CANONICAL, identity_key=identity_key)
            canon_identities.add(identity_key)
            identities_properties.append((identity_key, description))
        contact['identities'] = list(canon_identities)
        contact['identities_properties'] = identities_properties
        contact['contact_id'] = Contact.CalculateContactId(contact)
        result_contact_ids.append(contact['contact_id'])
    (yield gen.Task(Operation.CreateAndExecute, client, user_id, device_id, 'UploadContactsOperation.Execute', request))
    logging.info(('UPLOAD    CONTACTS:    user:    %d,    device:    %d,    contact_count:    %d' % (user_id, device_id, contact_count)))
    raise gen.Return({'contact_ids': result_contact_ids})
inputs: I wrote the below code

    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if (request.method not in request_method_list):
                logger.warning('Method    Not    Allowed    (%s):    %s', request.method, request.path, extra={'status_code': 405, 'request': request})
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return inner
    return decorator


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

    if (vt_id == fake_vt['id']):
        return fake_vt
    raise exception.VolumeTypeNotFound(volume_type_id=vt_id)


What's a good function header?
targets: def vt_get_volume_type(context, vt_id):
inputs: def label(object, index=None):
targets: """label: set or get the label of the item. Specify file by name or fsspec.
    """
    object = Carbon.File.FSRef(object)
    object_alias = object.FSNewAliasMinimal()
    if (index is None):
        return _getlabel(object_alias)
    if ((index < 0) or (index > 7)):
        index = 0
    return _setlabel(object_alias, index)
inputs: Complete the below
def is_style_file(filename):

    ''''Return True if the filename looks like a style file.'
    '''
targets: return (STYLE_FILE_PATTERN.match(filename) is not None)
inputs: def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
targets: """internal. pprinter for iterables. you should probably use pprint_thing()
    rather then calling this directly.
    """
    fmt = u('{%s}')
    pairs = []
    pfmt = u('%s:    %s')
    if (max_seq_items is False):
        nitems = len(seq)
    else:
        nitems = (max_seq_items or get_option('max_seq_items') or len(seq))
    for (k, v) in list(seq.items())[:nitems]:
        pairs.append((pfmt % (pprint_thing(k, (_nest_lvl + 1), max_seq_items=max_seq_items, **kwds), pprint_thing(v, (_nest_lvl + 1), max_seq_items=max_seq_items, **kwds))))
    if (nitems < len(seq)):
        return (fmt % (',    '.join(pairs) + ',    ...'))
    else:
        return (fmt % ',    '.join(pairs))
inputs: def grid_to_graph(n_x, n_y, n_z=1, mask=None, return_as=sparse.coo_matrix, dtype=np.int):
targets: """Graph of the pixel-to-pixel connections
    Edges exist if 2 voxels are connected.
    Parameters
    n_x : int
    Dimension in x axis
    n_y : int
    Dimension in y axis
    n_z : int, optional, default 1
    Dimension in z axis
    mask : ndarray of booleans, optional
    An optional mask of the image, to consider only part of the
    pixels.
    return_as : np.ndarray or a sparse matrix class, optional
    The class to use to build the returned adjacency matrix.
    dtype : dtype, optional, default int
    The data of the returned sparse matrix. By default it is int
    Notes
    For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was
    handled by returning a dense np.matrix instance.  Going forward, np.ndarray
    returns an np.ndarray, as expected.
    For compatibility, user code relying on this method should wrap its
    calls in ``np.asarray`` to avoid type issues.
    """
    return _to_graph(n_x, n_y, n_z, mask=mask, return_as=return_as, dtype=dtype)
inputs: def file_uri(fname):
targets: """Select the right file uri scheme according to the operating system
    """
    if (os.name == 'nt'):
        if re.search('^[a-zA-Z]:', fname):
            return ('file:///' + fname)
        else:
            return ('file://' + fname)
    else:
        return ('file://' + fname)
inputs: I wrote the below code

    from pyblockchain import validate_address
    addresses = config.get(CONF_ADDRESSES)
    name = config.get(CONF_NAME)
    for address in addresses:
        if (not validate_address(address)):
            _LOGGER.error('Bitcoin    address    is    not    valid:    %s', address)
            return False
    add_devices([BlockchainSensor(name, addresses)], True)


What's a good function header?
targets: def setup_platform(hass, config, add_devices, discovery_info=None):
inputs: I wrote the below code

    (domain, username) = _GetDomainAndUserName()
    vcuser_filename = '.'.join([proj_path, domain, username, 'user'])
    user_file = MSVSUserFile.Writer(vcuser_filename, version, spec['target_name'])
    return user_file


What's a good function header?
targets: def _CreateMSVSUserFile(proj_path, version, spec):
inputs: I wrote the below code

    f = (_Cfunctions.get('libvlc_media_player_retain', None) or _Cfunction('libvlc_media_player_retain', ((1,),), None, None, MediaPlayer))
    return f(p_mi)


What's a good function header?
targets: def libvlc_media_player_retain(p_mi):
inputs: Complete the below
def chgroups(name, groups, append=False, root=None):

    ''''Change the groups to which this user belongs
    name
    User to modify
    groups
    Groups to set for the user
    append : False
    If ``True``, append the specified group(s). Otherwise, this function
    will replace the user\'s groups with the specified group(s).
    CLI Examples:
    .. code-block:: bash
    salt \'*\' user.chgroups foo wheel,root
    salt \'*\' user.chgroups foo wheel,root append=True'
    '''
targets: if isinstance(groups, six.string_types):
        groups = groups.split(',')
    ugrps = set(list_groups(name))
    if (ugrps == set(groups)):
        return True
    cmd = ['usermod']
    if (__grains__['kernel'] != 'OpenBSD'):
        if (append and (__grains__['kernel'] != 'AIX')):
            cmd.append('-a')
        cmd.append('-G')
    elif append:
        cmd.append('-G')
    else:
        cmd.append('-S')
    if (append and (__grains__['kernel'] == 'AIX')):
        cmd.extend([((','.join(ugrps) + ',') + ','.join(groups)), name])
    else:
        cmd.extend([','.join(groups), name])
    if ((root is not None) and (__grains__['kernel'] != 'AIX')):
        cmd.extend(('-R', root))
    result = __salt__['cmd.run_all'](cmd, python_shell=False)
    if ((__grains__['kernel'] != 'OpenBSD') and (__grains__['kernel'] != 'AIX')):
        if ((result['retcode'] != 0) and ('not    found    in' in result['stderr'])):
            ret = True
            for group in groups:
                cmd = ['gpasswd', '-a', '{0}'.format(name), '{0}'.format(group)]
                if (__salt__['cmd.retcode'](cmd, python_shell=False) != 0):
                    ret = False
            return ret
    return (result['retcode'] == 0)
inputs: def findObj(regex):
targets: """Return a list of objects whose typeStr matches regex
    """
    allObjs = get_all_objects()
    objs = []
    r = re.compile(regex)
    for i in allObjs:
        obj = allObjs[i]
        if r.search(typeStr(obj)):
            objs.append(obj)
    return objs
inputs: I wrote the below code

    if (transform is not None):
        path = path.transformed(transform)
    vc_tuples = [((vertices if (path_code != Path.CLOSEPOLY) else []), PATH_DICT[path_code]) for (vertices, path_code) in path.iter_segments(simplify=simplify)]
    if (not vc_tuples):
        return (np.zeros((0, 2)), [])
    else:
        (vertices, codes) = zip(*vc_tuples)
        vertices = np.array(list(itertools.chain(*vertices))).reshape((-1), 2)
        return (vertices, list(codes))


What's a good function header?
targets: def SVG_path(path, transform=None, simplify=False):
inputs: def get_course_update_items(course_updates, provided_index=0):
targets: """Returns list of course_updates data dictionaries either from new format if available or
    from old. This function don\t modify old data to new data (in db), instead returns data
    in common old dictionary format.
    New Format: {"items" : [{"id": computed_id, "date": date, "content": html-string}],
    "data": "<ol>[<li><h2>date</h2>content</li>]</ol>"}
    Old Format: {"data": "<ol>[<li><h2>date</h2>content</li>]</ol>"}
    """
    def _course_info_content(html_parsed):
        '\n                                Constructs    the    HTML    for    the    course    info    update,    not    including    the    header.\n                                '
        if (len(html_parsed) == 1):
            content = html_parsed[0].tail
        else:
            content = (html_parsed[0].tail if (html_parsed[0].tail is not None) else '')
            content += '\n'.join([html.tostring(ele) for ele in html_parsed[1:]])
        return content
    if (course_updates and getattr(course_updates, 'items', None)):
        if (provided_index and (0 < provided_index <= len(course_updates.items))):
            return course_updates.items[(provided_index - 1)]
        else:
            return list(reversed(course_updates.items))
    course_update_items = []
    if course_updates:
        try:
            course_html_parsed = html.fromstring(course_updates.data)
        except (etree.XMLSyntaxError, etree.ParserError):
            log.error(('Cannot    parse:    ' + course_updates.data))
            escaped = escape(course_updates.data)
            course_html_parsed = html.fromstring((('<ol><li>' + escaped) + '</li></ol>'))
        if (course_html_parsed.tag == 'ol'):
            for (index, update) in enumerate(course_html_parsed):
                if (len(update) > 0):
                    content = _course_info_content(update)
                    computed_id = (len(course_html_parsed) - index)
                    payload = {'id': computed_id, 'date': update.findtext('h2'), 'content': content}
                    if (provided_index == 0):
                        course_update_items.append(payload)
                    elif (provided_index == computed_id):
                        return payload
    return course_update_items
inputs: I wrote the below code

    if (using is None):
        using = DEFAULT_DB_ALIAS
    connection = connections[using]
    connection.enter_transaction_management(managed)


What's a good function header?
targets: def enter_transaction_management(managed=True, using=None):
inputs: def less_shitty_error_messages(func):
targets: """Wraps functions where the first param is a SQL statement and enforces
    any exceptions thrown will also contain the statement in the message.
    """
    @wraps(func)
    def inner(self, sql, *args, **kwargs):
        try:
            return func(self, sql, *args, **kwargs)
        except Exception as e:
            exc_info = sys.exc_info()
            msg = '{}\nSQL:    {}'.format(repr(e), sql)
            six.reraise(exc_info[0], exc_info[0](msg), exc_info[2])
    return inner
inputs: Complete the below
def detectencoding_unicode(input, final=False):

    ''''Detect the encoding of the unicode string ``input``, which contains the
    beginning of a CSS file. The encoding is detected from the charset rule
    at the beginning of ``input``. If there is no charset rule, ``"utf-8"``
    will be returned.
    If the encoding can\'t be detected yet, ``None`` is returned. ``final``
    specifies whether more data will be available in later calls or not. If
    ``final`` is true, ``detectencoding_unicode()`` will never return ``None``.'
    '''
targets: prefix = u'@charset    "'
    if input.startswith(prefix):
        pos = input.find(u'"', len(prefix))
        if (pos >= 0):
            return (input[len(prefix):pos], True)
    elif (final or (not prefix.startswith(input))):
        return ('utf-8', False)
    return (None, False)
inputs: I wrote the below code

    if (len(names) == 1):
        return str(__proxy__['rest_sample.package_status'](names[0]))


What's a good function header?
targets: def version(*names, **kwargs):
inputs: I wrote the below code

    for i in CONF['COLORS']:
        if isinstance(CONF['COLORS'][i], dict):
            for j in CONF['COLORS'][i]:
                CONF['COLORS'][i][j] = ''
        else:
            CONF['COLORS'][i] = ''


What's a good function header?
targets: def remove_colors():
inputs: Complete the below
def build_dataset(filename, sequence_length, alphabet_size, max_lines=(-1)):

    ''''Loads a text file, and turns each line into an encoded sequence.'
    '''
targets: with open(filename) as f:
        content = f.readlines()
    content = content[:max_lines]
    content = [line for line in content if (len(line) > 2)]
    seqs = np.zeros((sequence_length, len(content), alphabet_size))
    for (ix, line) in enumerate(content):
        padded_line = (line + ('    ' * sequence_length))[:sequence_length]
        seqs[:, ix, :] = string_to_one_hot(padded_line, alphabet_size)
    return seqs
inputs: I wrote the below code

    r = []
    if head:
        item = head
        while item:
            item = item.contents
            r.append((item.id, item.name))
            item = item.__next__
        try:
            libvlc_track_description_release(head)
        except NameError:
            libvlc_track_description_list_release(head)
    return r


What's a good function header?
targets: def track_description_list(head):
inputs: def direct_get_object(node, part, account, container, obj, conn_timeout=5, response_timeout=15, resp_chunk_size=None, headers={}):
targets: """Get object directly from the object server.
    :param node: node dictionary from the ring
    :param part: partition the container is on
    :param account: account name
    :param container: container name
    :param obj: object name
    :param conn_timeout: timeout in seconds for establishing the connection
    :param response_timeout: timeout in seconds for getting the response
    :param resp_chunk_size: if defined, chunk size of data to read.
    :param headers: dict to be passed into HTTPConnection headers
    :returns: a tuple of (response headers, the object\s contents) The response
    headers will be a dict and all header names will be lowercase.
    """
    path = ('/%s/%s/%s' % (account, container, obj))
    with Timeout(conn_timeout):
        conn = http_connect(node['ip'], node['port'], node['device'], part, 'GET', path, headers=headers)
    with Timeout(response_timeout):
        resp = conn.getresponse()
    if (not is_success(resp.status)):
        resp.read()
        raise ClientException(('Object    server    %s:%s    direct    GET    %s    gave    status    %s' % (node['ip'], node['port'], repr(('/%s/%s%s' % (node['device'], part, path))), resp.status)), http_host=node['ip'], http_port=node['port'], http_device=node['device'], http_status=resp.status, http_reason=resp.reason)
    if resp_chunk_size:
        def _object_body():
            buf = resp.read(resp_chunk_size)
            while buf:
                (yield buf)
                buf = resp.read(resp_chunk_size)
        object_body = _object_body()
    else:
        object_body = resp.read()
    resp_headers = {}
    for (header, value) in resp.getheaders():
        resp_headers[header.lower()] = value
    return (resp_headers, object_body)
inputs: Complete the below
def _build_target_proxy_dict(params, project_id=None):

    ''''Reformat services in Ansible Params.
    :param params: Params from AnsibleModule object
    :type params: ``dict``
    :param project_id: The GCP project ID.
    :type project_id:  ``str``
    :return: dictionary suitable for submission to GCP UrlMap API.
    :rtype ``dict``'
    '''
targets: url = ''
    if project_id:
        url = GCPUtils.build_googleapi_url(project_id)
    gcp_dict = GCPUtils.params_to_gcp_dict(params, 'target_proxy_name')
    if ('urlMap' in gcp_dict):
        gcp_dict['urlMap'] = ('%s/global/urlMaps/%s' % (url, gcp_dict['urlMap']))
    return gcp_dict
inputs: def _req_environ_property(environ_field):
targets: """Set and retrieve value of the environ_field entry in self.environ.
    (Used by both request and response)
    """
    def getter(self):
        return self.environ.get(environ_field, None)
    def setter(self, value):
        if isinstance(value, six.text_type):
            self.environ[environ_field] = value.encode('utf-8')
        else:
            self.environ[environ_field] = value
    return property(getter, setter, doc=('Get    and    set    the    %s    property    in    the    WSGI    environment' % environ_field))
inputs: def avail_images(call=None, location='local'):
targets: """Return a list of the images that are on the provider
    CLI Example:
    .. code-block:: bash
    salt-cloud --list-images my-proxmox-config
    """
    if (call == 'action'):
        raise SaltCloudSystemExit('The    avail_images    function    must    be    called    with    -f    or    --function,    or    with    the    --list-images    option')
    ret = {}
    for (host_name, host_details) in six.iteritems(avail_locations()):
        for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)):
            ret[item['volid']] = item
    return ret
inputs: I wrote the below code

    cutoffs.setdefault(u'max_iter', 100)
    cutoffchecker = CutoffChecker(cutoffs)
    if (encoding is None):
        encoding = BinaryMaxentFeatureEncoding.train(train_toks, labels=labels)
    empirical_ffreq = (calculate_empirical_fcount(train_toks, encoding) / len(train_toks))
    nfmap = calculate_nfmap(train_toks, encoding)
    nfarray = numpy.array(sorted(nfmap, key=nfmap.__getitem__), u'd')
    nftranspose = numpy.reshape(nfarray, (len(nfarray), 1))
    unattested = set(numpy.nonzero((empirical_ffreq == 0))[0])
    weights = numpy.zeros(len(empirical_ffreq), u'd')
    for fid in unattested:
        weights[fid] = numpy.NINF
    classifier = ConditionalExponentialClassifier(encoding, weights)
    if (trace > 0):
        print((u'        ==>    Training    (%d    iterations)' % cutoffs[u'max_iter']))
    if (trace > 2):
        print()
        print(u'                        Iteration                Log    Likelihood                Accuracy')
        print(u'                        ---------------------------------------')
    try:
        while True:
            if (trace > 2):
                ll = (cutoffchecker.ll or log_likelihood(classifier, train_toks))
                acc = (cutoffchecker.acc or accuracy(classifier, train_toks))
                iternum = cutoffchecker.iter
                print((u'                    %9d                %14.5f                %9.3f' % (iternum, ll, acc)))
            deltas = calculate_deltas(train_toks, classifier, unattested, empirical_ffreq, nfmap, nfarray, nftranspose, encoding)
            weights = classifier.weights()
            weights += deltas
            classifier.set_weights(weights)
            if cutoffchecker.check(classifier, train_toks):
                break
    except KeyboardInterrupt:
        print(u'                        Training    stopped:    keyboard    interrupt')
    except:
        raise
    if (trace > 2):
        ll = log_likelihood(classifier, train_toks)
        acc = accuracy(classifier, train_toks)
        print((u'            ...

What's a good function header?
targets: def train_maxent_classifier_with_iis(train_toks, trace=3, encoding=None, labels=None, **cutoffs):
inputs: def _mountpoint_to_number(mountpoint):
targets: """Translate a mountpoint like /dev/sdc into a numeric.
    """
    if mountpoint.startswith('/dev/'):
        mountpoint = mountpoint[5:]
    if re.match('^[hs]d[a-p]$', mountpoint):
        return (ord(mountpoint[2:3]) - ord('a'))
    elif re.match('^x?vd[a-p]$', mountpoint):
        return (ord(mountpoint[(-1)]) - ord('a'))
    elif re.match('^[0-9]+$', mountpoint):
        return int(mountpoint, 10)
    else:
        LOG.warning('Mountpoint    cannot    be    translated:    %s', mountpoint)
        return (-1)
inputs: def __do_query_into_hash(conn, sql_str):
targets: """Perform the query that is passed to it (sql_str).
    Returns:
    results in a dict.
    """
    mod = sys._getframe().f_code.co_name
    log.debug('{0}<--({1})'.format(mod, sql_str))
    rtn_results = []
    try:
        cursor = conn.cursor()
    except MySQLdb.MySQLError:
        log.error("{0}:    Can't    get    cursor    for    SQL->{1}".format(mod, sql_str))
        cursor.close()
        log.debug('{0}-->'.format(mod))
        return rtn_results
    try:
        _execute(cursor, sql_str)
    except MySQLdb.MySQLError:
        log.error('{0}:    try    to    execute    :    SQL->{1}'.format(mod, sql_str))
        cursor.close()
        log.debug('{0}-->'.format(mod))
        return rtn_results
    qrs = cursor.fetchall()
    for row_data in qrs:
        col_cnt = 0
        row = {}
        for col_data in cursor.description:
            col_name = col_data[0]
            row[col_name] = row_data[col_cnt]
            col_cnt += 1
        rtn_results.append(row)
    cursor.close()
    log.debug('{0}-->'.format(mod))
    return rtn_results
inputs: Complete the below
def add_site(name, domain):

    ''''Add a site to database, create directory tree'
    '''
targets: sites = Site.objects.all()
    used_ids = [v[0] for v in sites.values_list()]
    site_id = (max(used_ids) + 1)
    project_dir = os.path.realpath(os.path.join(settings.SITE_ROOT, '../'))
    site_dir = os.path.join(project_dir, ('site%s' % site_id))
    site_template = os.path.join(os.path.dirname(__file__), 'site_template')
    shutil.copytree(site_template, site_dir)
    change_dict = {'$SITE_ID': str(site_id), '$SITE_NAME': name, '$DOMAIN': domain, '$SITE_ROOT': site_dir, '$SERVE_PATH': settings.SERVE_PATH, '$PORTNUM': ('8%s' % str(site_id).zfill(3)), '$GEOSERVER_URL': settings.GEOSERVER_URL, '$PROJECT_NAME': os.path.basename(os.path.dirname(settings.PROJECT_ROOT))}
    sed(os.path.join(site_dir, 'conf/gunicorn'), change_dict)
    sed(os.path.join(site_dir, 'conf/nginx'), change_dict)
    sed(os.path.join(site_dir, 'settings.py'), change_dict)
    sed(os.path.join(site_dir, 'local_settings_template.py'), change_dict)
    sed(os.path.join(site_dir, 'wsgi.py'), change_dict)
    site = Site(id=site_id, name=name, domain=domain)
    site.save()
    dump_model(Site, os.path.join(project_dir, 'sites.json'))
inputs: I wrote the below code

    q = avatar.quit()
    q.addCallback(quitServer)
    return q


What's a good function header?
targets: def leftGroup(ignored, avatar):
inputs: Complete the below
def get_template_path_with_theme(relative_path):

    ''''Returns template path in current site\'s theme if it finds one there otherwise returns same path.
    Example:
    >> get_template_path_with_theme(\'header.html\')
    \'/red-theme/lms/templates/header.html\'
    Parameters:
    relative_path (str): template\'s path relative to the templates directory e.g. \'footer.html\'
    Returns:
    (str): template path in current site\'s theme'
    '''
targets: relative_path = os.path.normpath(relative_path)
    theme = get_current_theme()
    if (not theme):
        return relative_path
    template_name = re.sub('^/+', '', relative_path)
    template_path = (theme.template_path / template_name)
    absolute_path = ((theme.path / 'templates') / template_name)
    if absolute_path.exists():
        return str(template_path)
    else:
        return relative_path
inputs: def add_alias(alias, canonical):
targets: """Add a character set alias.
    alias is the alias name, e.g. latin-1
    canonical is the character set\s canonical name, e.g. iso-8859-1
    """
    ALIASES[alias] = canonical
inputs: I wrote the below code

    import doctest
    if (verbosity is None):
        verbosity = verbose
    else:
        verbosity = None
    save_stdout = sys.stdout
    sys.stdout = get_original_stdout()
    try:
        (f, t) = doctest.testmod(module, verbose=verbosity)
        if f:
            raise TestFailed(('%d    of    %d    doctests    failed' % (f, t)))
    finally:
        sys.stdout = save_stdout
    if verbose:
        print ('doctest    (%s)    ...    %d    tests    with    zero    failures' % (module.__name__, t))
    return (f, t)


What's a good function header?
targets: def run_doctest(module, verbosity=None):
inputs: def directional_variance(X, w):
targets: """the variance of the data in the direction w
    """
    return sum((directional_variance_i(x_i, w) for x_i in X))
inputs: Complete the below
def download_private_file(path):

    ''''Checks permissions and sends back private file'
    '''
targets: try:
        check_file_permission(path)
    except frappe.PermissionError:
        raise Forbidden(_(u"You    don't    have    permission    to    access    this    file"))
    return send_private_file(path.split(u'/private', 1)[1])
inputs: I wrote the below code

    obj = cls.__new__(cls)
    obj.__dict__.update(dict_)
    list.extend(obj, items)
    return obj


What's a good function header?
targets: def _reconstitute(cls, dict_, items):
inputs: def get_db_slave_ips():
targets: """Returns the slave datastore IPs.
    Returns:
    A list of IP of the datastore slaves.
    """
    try:
        with open(constants.SLAVES_FILE_LOC) as slaves_file:
            return [line.strip() for line in slaves_file if line.strip()]
    except IOError:
        return []
inputs: def CentralMoment(xs, k):
targets: """Computes the kth central moment of xs.
    """
    mean = RawMoment(xs, 1)
    return (sum((((x - mean) ** k) for x in xs)) / len(xs))
inputs: def dist_is_editable(dist):
targets: """Is distribution an editable install?
    """
    for path_item in sys.path:
        egg_link = os.path.join(path_item, (dist.project_name + '.egg-link'))
        if os.path.isfile(egg_link):
            return True
    return False
inputs: def debug(*args):
targets: """Prints a prettyprinted version of `args` to stderr.
    """
    try:
        out = context.environ['wsgi.errors']
    except:
        out = sys.stderr
    for arg in args:
        print >>out, pprint.pformat(arg)
    return ''