_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q276500
_get_mro
test
def _get_mro(cls): """Get an mro for a type or classic class""" if not isinstance(cls, type): class cls(cls, object): pass return cls.__mro__[1:] return cls.__mro__
python
{ "resource": "" }
q276501
_find_adapter
test
def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" for t in _get_mro(getattr(ob, '__class__', type(ob))): if t in registry: return registry[t]
python
{ "resource": "" }
q276502
ensure_directory
test
def ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname)
python
{ "resource": "" }
q276503
WorkingSet.iter_entry_points
test
def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution ord...
python
{ "resource": "" }
q276504
Environment.can_add
test
def can_add(self, dist): """Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned. """ return (self.python is None or dist.py_vers...
python
{ "resource": "" }
q276505
Environment.best_match
test
def best_match(self, req, working_set, installer=None): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitabl...
python
{ "resource": "" }
q276506
MarkerEvaluation.evaluate_marker
test
def evaluate_marker(cls, text, extra=None): """ Evaluate a PEP 426 environment marker on CPython 2.4+. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid. This implementation uses the 'parser' module, which is not implemente...
python
{ "resource": "" }
q276507
MarkerEvaluation._markerlib_evaluate
test
def _markerlib_evaluate(cls, text): """ Evaluate a PEP 426 environment marker using markerlib. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid. """ from pip._vendor import _markerlib # markerlib implements ...
python
{ "resource": "" }
q276508
IndentingFormatter.format
test
def format(self, record): """ Calls the standard formatter, but will indent all of the log messages by our current indentation level. """ formatted = logging.Formatter.format(self, record) formatted = "".join([ (" " * get_indentation()) + line for ...
python
{ "resource": "" }
q276509
format_currency
test
def format_currency(number, currency, format=None, locale=LC_NUMERIC, currency_digits=True, format_type='standard', decimal_quantization=True): """Return formatted currency value. >>> format_currency(1099.98, 'USD', locale='en_US') u'$1,099.98' >>> format_curren...
python
{ "resource": "" }
q276510
parse_pattern
test
def parse_pattern(pattern): """Parse number format patterns""" if isinstance(pattern, NumberPattern): return pattern def _match_number(pattern): rv = number_re.search(pattern) if rv is None: raise ValueError('Invalid number pattern %r' % pattern) return rv.groups...
python
{ "resource": "" }
q276511
get_decimal_quantum
test
def get_decimal_quantum(precision): """Return minimal quantum of a number, as defined by precision.""" assert isinstance(precision, (int, decimal.Decimal)) return decimal.Decimal(10) ** (-precision)
python
{ "resource": "" }
q276512
get_decimal_precision
test
def get_decimal_precision(number): """Return maximum precision of a decimal instance's fractional part. Precision is extracted from the fractional part only. """ # Copied from: https://github.com/mahmoud/boltons/pull/59 assert isinstance(number, decimal.Decimal) decimal_tuple = number.normalize(...
python
{ "resource": "" }
q276513
NumberPattern.scientific_notation_elements
test
def scientific_notation_elements(self, value, locale): """ Returns normalized scientific notation components of a value.""" # Normalize value to only have one lead digit. exp = value.adjusted() value = value * get_decimal_quantum(exp) assert value.adjusted() == 0 # Shift...
python
{ "resource": "" }
q276514
total_seconds
test
def total_seconds(td): """Python 2.6 compatability""" if hasattr(td, 'total_seconds'): return td.total_seconds() ms = td.microseconds secs = (td.seconds + td.days * 24 * 3600) return (ms + secs * 10**6) / 10**6
python
{ "resource": "" }
q276515
parse_requirements
test
def parse_requirements(strs): """Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof. """ # create a steppable iterator, so we can handle \-continuations lines = iter(yield_lines(strs)) def scan_list(ITEM, TERMINATOR, ...
python
{ "resource": "" }
q276516
_get_unpatched
test
def _get_unpatched(cls): """Protect against re-patching the distutils if reloaded Also ensures that no other distutils extension monkeypatched the distutils first. """ while cls.__module__.startswith('setuptools'): cls, = cls.__bases__ if not cls.__module__.startswith('distutils'): ...
python
{ "resource": "" }
q276517
check_requirements
test
def check_requirements(dist, attr, value): """Verify that install_requires is a valid requirements list""" try: list(pkg_resources.parse_requirements(value)) except (TypeError, ValueError) as error: tmpl = ( "{attr!r} must be a string or list of strings " "containing ...
python
{ "resource": "" }
q276518
Distribution.fetch_build_egg
test
def fetch_build_egg(self, req): """Fetch an egg needed for building""" try: cmd = self._egg_fetcher cmd.package_index.to_scan = [] except AttributeError: from setuptools.command.easy_install import easy_install dist = self.__class__({'script_args'...
python
{ "resource": "" }
q276519
do_dice_roll
test
def do_dice_roll(): """ Roll n-sided dice and return each result and the total """ options = get_options() dice = Dice(options.sides) rolls = [dice.roll() for n in range(options.number)] for roll in rolls: print('rolled', roll) if options.number > 1: print('total', sum(rolls))
python
{ "resource": "" }
q276520
price_converter
test
def price_converter(obj): """Ensures that string prices are converted into Price objects.""" if isinstance(obj, str): obj = PriceClass.parse(obj) return obj
python
{ "resource": "" }
q276521
price
test
def price(*args, **kwargs): """Price field for attrs. See `help(attr.ib)` for full signature. Usage: >>> from pricing import fields ... @attr.s ... class Test: ... price: Price = fields.price(default='USD 5.00') ... ... Test() Test(price=USD 5.0...
python
{ "resource": "" }
q276522
Service.validate
test
def validate(self, request): """Validate JSON-RPC request. :param request: RPC request object :type request: dict """ try: validate_version(request) validate_method(request) validate_params(request) validate_id(request) e...
python
{ "resource": "" }
q276523
Service.get_method
test
def get_method(self, args): """Get request method for service application.""" try: method = self.app[args['method']] except KeyError: method_not_found(args['id']) else: return method
python
{ "resource": "" }
q276524
Service.apply
test
def apply(self, method, args): """Apply application method.""" try: params = args['params'] if isinstance(params, dict): result = method(**params) else: result = method(*params) except Exception as error: server_err...
python
{ "resource": "" }
q276525
Request.module
test
def module(self): """The name of the current module if the request was dispatched to an actual module. This is deprecated functionality, use blueprints instead. """ from warnings import warn warn(DeprecationWarning('modules were deprecated in favor of ' ...
python
{ "resource": "" }
q276526
Request.blueprint
test
def blueprint(self): """The name of the current blueprint""" if self.url_rule and '.' in self.url_rule.endpoint: return self.url_rule.endpoint.rsplit('.', 1)[0]
python
{ "resource": "" }
q276527
attach_enctype_error_multidict
test
def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key...
python
{ "resource": "" }
q276528
make_abstract_dist
test
def make_abstract_dist(req_to_install): """Factory to make an abstract dist object. Preconditions: Either an editable req with a source_dir, or satisfied_by or a wheel link, or a non-editable req with a source_dir. :return: A concrete DistAbstraction. """ if req_to_install.editable: re...
python
{ "resource": "" }
q276529
RequirementSet.add_requirement
test
def add_requirement(self, install_req, parent_req_name=None): """Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we coul...
python
{ "resource": "" }
q276530
RequirementSet._walk_req_to_install
test
def _walk_req_to_install(self, handler): """Call handler for all pending reqs. :param handler: Handle a single requirement. Should take a requirement to install. Can optionally return an iterable of additional InstallRequirements to cover. """ # The list() here i...
python
{ "resource": "" }
q276531
RequirementSet._check_skip_installed
test
def _check_skip_installed(self, req_to_install, finder): """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only ...
python
{ "resource": "" }
q276532
RequirementSet._to_install
test
def _to_install(self): """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. """ # The current implementation, which we may cha...
python
{ "resource": "" }
q276533
install_egg_info._get_all_ns_packages
test
def _get_all_ns_packages(self): """Return sorted list of all package namespaces""" nsp = set() for pkg in self.distribution.namespace_packages or []: pkg = pkg.split('.') while pkg: nsp.add('.'.join(pkg)) pkg.pop() return sorted(nsp...
python
{ "resource": "" }
q276534
JsonResponseEncoder.default
test
def default(self, obj): """ Convert QuerySet objects to their list counter-parts """ if isinstance(obj, models.Model): return self.encode(model_to_dict(obj)) elif isinstance(obj, models.query.QuerySet): return serializers.serialize('json', obj) els...
python
{ "resource": "" }
q276535
tokenize_annotated
test
def tokenize_annotated(doc, annotation): """Tokenize a document and add an annotation attribute to each token """ tokens = tokenize(doc, include_hrefs=False) for tok in tokens: tok.annotation = annotation return tokens
python
{ "resource": "" }
q276536
html_annotate_merge_annotations
test
def html_annotate_merge_annotations(tokens_old, tokens_new): """Merge the annotations from tokens_old into tokens_new, when the tokens in the new document already existed in the old document. """ s = InsensitiveSequenceMatcher(a=tokens_old, b=tokens_new) commands = s.get_opcodes() for command,...
python
{ "resource": "" }
q276537
copy_annotations
test
def copy_annotations(src, dest): """ Copy annotations from the tokens listed in src to the tokens in dest """ assert len(src) == len(dest) for src_tok, dest_tok in zip(src, dest): dest_tok.annotation = src_tok.annotation
python
{ "resource": "" }
q276538
compress_tokens
test
def compress_tokens(tokens): """ Combine adjacent tokens when there is no HTML between the tokens, and they share an annotation """ result = [tokens[0]] for tok in tokens[1:]: if (not result[-1].post_tags and not tok.pre_tags and result[-1].annotation == tok....
python
{ "resource": "" }
q276539
markup_serialize_tokens
test
def markup_serialize_tokens(tokens, markup_func): """ Serialize the list of tokens into a list of text chunks, calling markup_func around text to add annotations. """ for token in tokens: for pre in token.pre_tags: yield pre html = token.html() html = markup_func(...
python
{ "resource": "" }
q276540
expand_tokens
test
def expand_tokens(tokens, equal=False): """Given a list of tokens, return a generator of the chunks of text for the data in the tokens. """ for token in tokens: for pre in token.pre_tags: yield pre if not equal or not token.hide_when_equal: if token.trailing_white...
python
{ "resource": "" }
q276541
locate_unbalanced_end
test
def locate_unbalanced_end(unbalanced_end, pre_delete, post_delete): """ like locate_unbalanced_start, except handling end tags and possibly moving the point earlier in the document. """ while 1: if not unbalanced_end: # Success break finding = unbalanced_end[-1] ...
python
{ "resource": "" }
q276542
fixup_chunks
test
def fixup_chunks(chunks): """ This function takes a list of chunks and produces a list of tokens. """ tag_accum = [] cur_word = None result = [] for chunk in chunks: if isinstance(chunk, tuple): if chunk[0] == 'img': src = chunk[1] tag, tra...
python
{ "resource": "" }
q276543
flatten_el
test
def flatten_el(el, include_hrefs, skip_tag=False): """ Takes an lxml element el, and generates all the text chunks for that tag. Each start tag is a chunk, each word is a chunk, and each end tag is a chunk. If skip_tag is true, then the outermost container tag is not returned (just its contents)."...
python
{ "resource": "" }
q276544
split_words
test
def split_words(text): """ Splits some text into words. Includes trailing whitespace on each word when appropriate. """ if not text or not text.strip(): return [] words = split_words_re.findall(text) return words
python
{ "resource": "" }
q276545
start_tag
test
def start_tag(el): """ The text representation of the start tag for a tag. """ return '<%s%s>' % ( el.tag, ''.join([' %s="%s"' % (name, html_escape(value, True)) for name, value in el.attrib.items()]))
python
{ "resource": "" }
q276546
end_tag
test
def end_tag(el): """ The text representation of an end tag for a tag. Includes trailing whitespace when appropriate. """ if el.tail and start_whitespace_re.search(el.tail): extra = ' ' else: extra = '' return '</%s>%s' % (el.tag, extra)
python
{ "resource": "" }
q276547
serialize_html_fragment
test
def serialize_html_fragment(el, skip_outer=False): """ Serialize a single lxml element as HTML. The serialized form includes the elements tail. If skip_outer is true, then don't serialize the outermost tag """ assert not isinstance(el, basestring), ( "You should pass in an element, not a...
python
{ "resource": "" }
q276548
_fixup_ins_del_tags
test
def _fixup_ins_del_tags(doc): """fixup_ins_del_tags that works on an lxml document in-place """ for tag in ['ins', 'del']: for el in doc.xpath('descendant-or-self::%s' % tag): if not _contains_block_level_tag(el): continue _move_el_inside_block(el, tag=tag) ...
python
{ "resource": "" }
q276549
extract_constant
test
def extract_constant(code, symbol, default=-1): """Extract the constant value of 'symbol' from 'code' If the name 'symbol' is bound to a constant value by the Python code object 'code', return that value. If 'symbol' is bound to an expression, return 'default'. Otherwise, return 'None'. Return v...
python
{ "resource": "" }
q276550
AmazonCall.cache_url
test
def cache_url(self, **kwargs): """A simplified URL to be used for caching the given query.""" query = { 'Operation': self.Operation, 'Service': "AWSECommerceService", 'Version': self.Version, } query.update(kwargs) service_domain = SERVICE_DOM...
python
{ "resource": "" }
q276551
autolink
test
def autolink(el, link_regexes=_link_regexes, avoid_elements=_avoid_elements, avoid_hosts=_avoid_hosts, avoid_classes=_avoid_classes): """ Turn any URLs into links. It will search for links identified by the given regular expressions (by default mailto and http(s) ...
python
{ "resource": "" }
q276552
Cleaner.kill_conditional_comments
test
def kill_conditional_comments(self, doc): """ IE conditional comments basically embed HTML that the parser doesn't normally see. We can't allow anything like that, so we'll kill any comments that could be conditional. """ bad = [] self._kill_elements( ...
python
{ "resource": "" }
q276553
document_fromstring
test
def document_fromstring(html, guess_charset=True, parser=None): """Parse a whole document into a string.""" if not isinstance(html, _strings): raise TypeError('string required') if parser is None: parser = html_parser return parser.parse(html, useChardet=guess_charset).getroot()
python
{ "resource": "" }
q276554
api_returns
test
def api_returns(return_values): """ Define the return schema of an API. 'return_values' is a dictionary mapping HTTP return code => documentation In addition to validating that the status code of the response belongs to one of the accepted status codes, it also validates that the returned o...
python
{ "resource": "" }
q276555
getTreeWalker
test
def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support treeType - the name of the tree type required (case-insensitive). Supported values are: "dom" - The xml.dom.minidom DOM implementation ...
python
{ "resource": "" }
q276556
Subversion.export
test
def export(self, location): """Export the svn repository at the url to the destination location""" url, rev = self.get_url_rev() rev_options = get_rev_options(url, rev) logger.info('Exporting svn repository %s to %s', url, location) with indent_log(): if os.path.exist...
python
{ "resource": "" }
q276557
Subversion.get_revision
test
def get_revision(self, location): """ Return the maximum revision for all files under a given location """ # Note: taken from setuptools.command.egg_info revision = 0 for base, dirs, files in os.walk(location): if self.dirname not in dirs: dir...
python
{ "resource": "" }
q276558
setupmethod
test
def setupmethod(f): """Wraps a method so that it performs a check in debug mode if the first request was already handled. """ def wrapper_func(self, *args, **kwargs): if self.debug and self._got_first_request: raise AssertionError('A setup function was called after the ' ...
python
{ "resource": "" }
q276559
Flask.name
test
def name(self): """The name of the application. This is usually the import name with the difference that it's guessed from the run file if the import name is main. This name is used as a display name when Flask needs the name of the application. It can be set and overridden to...
python
{ "resource": "" }
q276560
Flask.propagate_exceptions
test
def propagate_exceptions(self): """Returns the value of the `PROPAGATE_EXCEPTIONS` configuration value in case it's set, otherwise a sensible default is returned. .. versionadded:: 0.7 """ rv = self.config['PROPAGATE_EXCEPTIONS'] if rv is not None: return rv ...
python
{ "resource": "" }
q276561
Flask.auto_find_instance_path
test
def auto_find_instance_path(self): """Tries to locate the instance path if it was not provided to the constructor of the application class. It will basically calculate the path to a folder named ``instance`` next to your main file or the package. .. versionadded:: 0.8 "...
python
{ "resource": "" }
q276562
Flask.update_template_context
test
def update_template_context(self, context): """Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the origin...
python
{ "resource": "" }
q276563
Flask.handle_http_exception
test
def handle_http_exception(self, e): """Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionadded:: 0.3 """ handlers = self.error_handler_spec.get(request.blueprint) ...
python
{ "resource": "" }
q276564
Flask.trap_http_exception
test
def trap_http_exception(self, e): """Checks if an HTTP exception should be trapped or not. By default this will return `False` for all exceptions except for a bad request key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to `True`. It also returns `True` if ``TRAP_HTTP_EXCEPTIONS`` is se...
python
{ "resource": "" }
q276565
Flask.handle_exception
test
def handle_exception(self, e): """Default exception handling that kicks in when an exception occurs that is not caught. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler ...
python
{ "resource": "" }
q276566
Flask.raise_routing_exception
test
def raise_routing_exception(self, request): """Exceptions that are recording during routing are reraised with this method. During debug we are not reraising redirect requests for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising a different error instead to help debug sit...
python
{ "resource": "" }
q276567
Flask.full_dispatch_request
test
def full_dispatch_request(self): """Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. .. versionadded:: 0.7 """ self.try_trigger_before_first_request_functions() try: ...
python
{ "resource": "" }
q276568
Flask.make_default_options_response
test
def make_default_options_response(self): """This method is called to create the default `OPTIONS` response. This can be changed through subclassing to change the default behavior of `OPTIONS` responses. .. versionadded:: 0.7 """ adapter = _request_ctx_stack.top.url_adapt...
python
{ "resource": "" }
q276569
Flask.create_url_adapter
test
def create_url_adapter(self, request): """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6 .. versionchanged:: 0.9 This can now a...
python
{ "resource": "" }
q276570
Flask.inject_url_defaults
test
def inject_url_defaults(self, endpoint, values): """Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7 """ funcs = self.url_default_functions...
python
{ "resource": "" }
q276571
unique
test
def unique(iterable): """ Yield unique values in iterable, preserving order. """ seen = set() for value in iterable: if not value in seen: seen.add(value) yield value
python
{ "resource": "" }
q276572
handle_requires
test
def handle_requires(metadata, pkg_info, key): """ Place the runtime requirements from pkg_info into metadata. """ may_requires = defaultdict(list) for value in pkg_info.get_all(key): extra_match = EXTRA_RE.search(value) if extra_match: groupdict = extra_match.groupdict() ...
python
{ "resource": "" }
q276573
requires_to_requires_dist
test
def requires_to_requires_dist(requirement): """Compose the version predicates for requirement in PEP 345 fashion.""" requires_dist = [] for op, ver in requirement.specs: requires_dist.append(op + ver) if not requires_dist: return '' return " (%s)" % ','.join(requires_dist)
python
{ "resource": "" }
q276574
pkginfo_to_metadata
test
def pkginfo_to_metadata(egg_info_path, pkginfo_path): """ Convert .egg-info directory with PKG-INFO to the Metadata 1.3 aka old-draft Metadata 2.0 format. """ pkg_info = read_pkg_info(pkginfo_path) pkg_info.replace_header('Metadata-Version', '2.0') requires_path = os.path.join(egg_info_path,...
python
{ "resource": "" }
q276575
PathFinder.modules
test
def modules(self): """return modules that match module_name""" # since the module has to be importable we go ahead and put the # basepath as the very first path to check as that should minimize # namespace collisions, this is what unittest does also sys.path.insert(0, self.based...
python
{ "resource": "" }
q276576
PathFinder.classes
test
def classes(self): """the partial self.class_name will be used to find actual TestCase classes""" for module in self.modules(): cs = inspect.getmembers(module, inspect.isclass) class_name = getattr(self, 'class_name', '') class_regex = '' if class_name: ...
python
{ "resource": "" }
q276577
PathFinder.method_names
test
def method_names(self): """return the actual test methods that matched self.method_name""" for c in self.classes(): #ms = inspect.getmembers(c, inspect.ismethod) # http://stackoverflow.com/questions/17019949/ ms = inspect.getmembers(c, lambda f: inspect.ismethod(f) or...
python
{ "resource": "" }
q276578
PathFinder._find_basename
test
def _find_basename(self, name, basenames, is_prefix=False): """check if name combined with test prefixes or postfixes is found anywhere in the list of basenames :param name: string, the name you're searching for :param basenames: list, a list of basenames to check :param is_pref...
python
{ "resource": "" }
q276579
PathFinder._is_module_path
test
def _is_module_path(self, path): """Returns true if the passed in path is a test module path :param path: string, the path to check, will need to start or end with the module test prefixes or postfixes to be considered valid :returns: boolean, True if a test module path, False other...
python
{ "resource": "" }
q276580
PathFinder.walk
test
def walk(self, basedir): """Walk all the directories of basedir except hidden directories :param basedir: string, the directory to walk :returns: generator, same as os.walk """ system_d = SitePackagesDir() filter_system_d = system_d and os.path.commonprefix([system_d, ba...
python
{ "resource": "" }
q276581
PathFinder.paths
test
def paths(self): ''' given a basedir, yield all test modules paths recursively found in basedir that are test modules return -- generator ''' module_name = getattr(self, 'module_name', '') module_prefix = getattr(self, 'prefix', '') filepath = getattr(sel...
python
{ "resource": "" }
q276582
_dump_arg_defaults
test
def _dump_arg_defaults(kwargs): """Inject default arguments for dump functions.""" if current_app: kwargs.setdefault('cls', current_app.json_encoder) if not current_app.config['JSON_AS_ASCII']: kwargs.setdefault('ensure_ascii', False) kwargs.setdefault('sort_keys', current_ap...
python
{ "resource": "" }
q276583
_load_arg_defaults
test
def _load_arg_defaults(kwargs): """Inject default arguments for load functions.""" if current_app: kwargs.setdefault('cls', current_app.json_decoder) else: kwargs.setdefault('cls', JSONDecoder)
python
{ "resource": "" }
q276584
BaseCache.set_many
test
def set_many(self, mapping, timeout=None): """Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key (if not specified, it uses the default timeout). :returns: Whether all...
python
{ "resource": "" }
q276585
BaseCache.inc
test
def inc(self, key, delta=1): """Increments the value of a key by `delta`. If the key does not yet exist it is initialized with `delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to add. :returns: The ne...
python
{ "resource": "" }
q276586
RedisCache.dump_object
test
def dump_object(self, value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t in integer_types: return str(value).encode('ascii') return b'!' + pickle.d...
python
{ "resource": "" }
q276587
_build_editable_options
test
def _build_editable_options(req): """ This method generates a dictionary of the query string parameters contained in a given editable URL. """ regexp = re.compile(r"[\?#&](?P<name>[^&=]+)=(?P<value>[^&=]+)") matched = regexp.findall(req) if matched: ret = dict() for...
python
{ "resource": "" }
q276588
InstallRequirement.populate_link
test
def populate_link(self, finder, upgrade): """Ensure that if a link can be found for this, that it is found. Note that self.link may still be None - if Upgrade is False and the requirement is already installed. """ if self.link is None: self.link = finder.find_require...
python
{ "resource": "" }
q276589
InstallRequirement.ensure_has_source_dir
test
def ensure_has_source_dir(self, parent_dir): """Ensure that a source_dir is set. This will create a temporary build dir if the name of the requirement isn't known yet. :param parent_dir: The ideal pip parent_dir for the source_dir. Generally src_dir for editables and build_...
python
{ "resource": "" }
q276590
InstallRequirement.remove_temporary_source
test
def remove_temporary_source(self): """Remove the source files from this requirement, if they are marked for deletion""" if self.source_dir and os.path.exists( os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)): logger.debug('Removing source in %s', self.source...
python
{ "resource": "" }
q276591
InstallRequirement.get_dist
test
def get_dist(self): """Return a pkg_resources.Distribution built from self.egg_info_path""" egg_info = self.egg_info_path('').rstrip('/') base_dir = os.path.dirname(egg_info) metadata = pkg_resources.PathMetadata(base_dir, egg_info) dist_name = os.path.splitext(os.path.basename(e...
python
{ "resource": "" }
q276592
BaseRequest.get_data
test
def get_data(self, cache=True, as_text=False, parse_form_data=False): """This reads the buffered incoming data from the client into one bytestring. By default this is cached but that behavior can be changed by setting `cache` to `False`. Usually it's a bad idea to call this method with...
python
{ "resource": "" }
q276593
BaseResponse.get_wsgi_headers
test
def get_wsgi_headers(self, environ): """This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the loc...
python
{ "resource": "" }
q276594
iri_to_uri
test
def iri_to_uri(iri, charset='utf-8', errors='strict', safe_conversion=False): r""" Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always uses utf-8 URLs internally because this is what browsers and HTTP do as well. In some places where it accepts an URL it also accepts a unicode IRI...
python
{ "resource": "" }
q276595
user_cache_dir
test
def user_cache_dir(appname): r""" Return full path to the user-specific cache dir for this application. "appname" is the name of application. Typical user cache directories are: Mac OS X: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Windows: ...
python
{ "resource": "" }
q276596
user_data_dir
test
def user_data_dir(appname, roaming=False): """ Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "roaming" (boolean, default False) can be set True to use the Windows ...
python
{ "resource": "" }
q276597
user_log_dir
test
def user_log_dir(appname): """ Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. Typical user cache directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ...
python
{ "resource": "" }
q276598
user_config_dir
test
def user_config_dir(appname, roaming=True): """Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "roaming" (boolean, default True) can be set False to not use the Windo...
python
{ "resource": "" }
q276599
site_config_dirs
test
def site_config_dirs(appname): """Return a list of potential user-shared config dirs for this application. "appname" is the name of application. Typical user config directories are: Mac OS X: /Library/Application Support/<AppName>/ Unix: /etc or $XDG_CONFIG_DIRS[i]/<AppName>/ f...
python
{ "resource": "" }