_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q27500 | _FFISpecification.extern_generator_send | train | def extern_generator_send(self, context_handle, func, arg):
"""Given a generator, send it the given value and return a response."""
c = self._ffi.from_handle(context_handle)
response = self._ffi.new('PyGeneratorResponse*')
try:
res = c.from_value(func[0]).send(c.from_value(arg[0]))
if isinst... | python | {
"resource": ""
} |
q27501 | _FFISpecification.extern_call | train | def extern_call(self, context_handle, func, args_ptr, args_len):
"""Given a callable, call it."""
c = self._ffi.from_handle(context_handle)
runnable = c.from_value(func[0])
| python | {
"resource": ""
} |
q27502 | _FFISpecification.extern_eval | train | def extern_eval(self, context_handle, python_code_str_ptr, python_code_str_len):
"""Given an evalable string, eval it | python | {
"resource": ""
} |
q27503 | ExternContext.identify | train | def identify(self, obj):
"""Return an Ident-shaped tuple for the given object."""
hash_ = hash(obj)
| python | {
"resource": ""
} |
q27504 | Native.binary | train | def binary(self):
"""Load and return the path to the native engine binary."""
lib_name = '{}.so'.format(NATIVE_ENGINE_MODULE)
lib_path = os.path.join(safe_mkdtemp(), lib_name)
try:
with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp:
# NB: The header stripping code ... | python | {
"resource": ""
} |
q27505 | Native.lib | train | def lib(self):
"""Load and return the native engine module."""
lib = self.ffi.dlopen(self.binary)
| python | {
"resource": ""
} |
q27506 | Native._ffi_module | train | def _ffi_module(self):
"""Load the native engine as a python module and register CFFI externs."""
native_bin_dir = os.path.dirname(self.binary)
logger.debug('loading native engine python module | python | {
"resource": ""
} |
q27507 | Native.new_scheduler | train | def new_scheduler(self,
tasks,
root_subject_types,
build_root,
work_dir,
local_store_dir,
ignore_patterns,
execution_options,
construct_directory_digest,
... | python | {
"resource": ""
} |
q27508 | parse_spec | train | def parse_spec(spec, relative_to=None, subproject_roots=None):
"""Parses a target address spec and returns the path from the root of the repo to this Target
and Target name.
:API: public
:param string spec: Target address spec.
:param string relative_to: path to use for sibling specs, ie: ':another_in_same_... | python | {
"resource": ""
} |
q27509 | Address.parse | train | def parse(cls, spec, relative_to='', subproject_roots=None):
"""Parses an address from its serialized form.
:param string spec: An address in string form <path>:<name>.
:param string relative_to: For sibling specs, ie: ':another_in_same_build_family', interprets
the missing s... | python | {
"resource": ""
} |
q27510 | Address.reference | train | def reference(self, referencing_path=None):
"""How to reference this address in a BUILD file.
:API: public
"""
if referencing_path is not None and self._spec_path == referencing_path:
return self.relative_spec
| python | {
"resource": ""
} |
q27511 | SimpleCodegenTask.is_gentarget | train | def is_gentarget(self, target):
"""Predicate which determines whether the target in question is relevant to this codegen task.
E.g., the JaxbGen task considers JaxbLibrary targets to be relevant, and nothing else.
:API: public
:param Target target: The target to check.
:return: True if this class... | python | {
"resource": ""
} |
q27512 | SimpleCodegenTask._do_validate_sources_present | train | def _do_validate_sources_present(self, target):
"""Checks whether sources is empty, and either raises a TaskError or just returns False.
The specifics of this behavior are defined by whether the user sets --allow-empty to True/False:
--allow-empty=False will result in a TaskError being raised in the event ... | python | {
"resource": ""
} |
q27513 | SimpleCodegenTask._inject_synthetic_target | train | def _inject_synthetic_target(self, vt, sources):
"""Create, inject, and return a synthetic target for the given target and workdir.
:param vt: A codegen input VersionedTarget to inject a synthetic target for.
:param sources: A FilesetWithSpec to inject for the target.
"""
target = vt.target
# ... | python | {
"resource": ""
} |
q27514 | SimpleCodegenTask._handle_duplicate_sources | train | def _handle_duplicate_sources(self, vt, sources):
"""Handles duplicate sources generated by the given gen target by either failure or deletion.
This method should be called after all dependencies have been injected into the graph, but
before injecting the synthetic version of this target.
Returns a bo... | python | {
"resource": ""
} |
q27515 | PythonNativeCode._get_targets_by_declared_platform_with_placeholders | train | def _get_targets_by_declared_platform_with_placeholders(self, targets_by_platform):
"""
Aggregates a dict that maps a platform string to a list of targets that specify the platform.
If no targets have platforms arguments, return a dict containing platforms inherited from
the PythonSetup object.
:pa... | python | {
"resource": ""
} |
q27516 | PythonNativeCode.check_build_for_current_platform_only | train | def check_build_for_current_platform_only(self, targets):
"""
Performs a check of whether the current target closure has native sources and if so, ensures
that Pants is only targeting the current platform.
:param tgts: a list of :class:`Target` objects.
:return: a boolean value indicating whether t... | python | {
"resource": ""
} |
q27517 | MissingDependencyFinder.find | train | def find(self, compile_failure_log, target):
"""Find missing deps on a best-effort basis from target's transitive dependencies.
Returns (class2deps, no_dep_found) tuple. `class2deps` contains classname
to deps that contain the class mapping. `no_dep_found` are the classnames that are
unable to find the... | python | {
"resource": ""
} |
q27518 | MissingDependencyFinder._select_target_candidates_for_class | train | def _select_target_candidates_for_class(self, classnames, target):
"""Select a target that contains the given classname.
When multiple candidates are available, not uncommon in 3rdparty dependencies,
they are ranked according to their string similiarities with the classname because
the way 3rdparty tar... | python | {
"resource": ""
} |
q27519 | PythonBinaryCreate._create_binary | train | def _create_binary(self, binary_tgt, results_dir):
"""Create a .pex file for the specified binary target."""
# Note that we rebuild a chroot from scratch, instead of using the REQUIREMENTS_PEX
# and PYTHON_SOURCES products, because those products are already-built pexes, and there's
# no easy way to mer... | python | {
"resource": ""
} |
q27520 | Matcher.matches | train | def matches(self, s):
"""Whether the pattern matches anywhere in the string s."""
regex_matches = self.compiled_regex.search(s) is not | python | {
"resource": ""
} |
q27521 | MultiMatcher.check_content | train | def check_content(self, content_pattern_names, content, encoding):
"""Check which of the named patterns matches the given content.
Returns a pair (matching, nonmatching), in which each element is a tuple of pattern names.
:param iterable content_pattern_names: names of content patterns to check.
:para... | python | {
"resource": ""
} |
q27522 | MultiMatcher.get_applicable_content_pattern_names | train | def get_applicable_content_pattern_names(self, path):
"""Return the content patterns applicable to a given path.
Returns a tuple (applicable_content_pattern_names, content_encoding).
If path matches no path patterns, the returned content_encoding will be None (and
applicable_content_pattern_names will... | python | {
"resource": ""
} |
q27523 | enum | train | def enum(all_values):
"""A datatype which can take on a finite set of values. This method is experimental and unstable.
Any enum subclass can be constructed with its create() classmethod. This method will use the first
element of `all_values` as the default value, but enum classes can override this behavior by
... | python | {
"resource": ""
} |
q27524 | DatatypeMixin.make_type_error | train | def make_type_error(cls, msg, *args, **kwargs):
"""A helper method to generate an exception type for type checking errors.
This method uses `cls.type_check_error_type` to ensure that type checking errors can be caught
with a reliable exception type. The type returned by `cls.type_check_error_type` | python | {
"resource": ""
} |
q27525 | TypeConstraint.validate_satisfied_by | train | def validate_satisfied_by(self, obj):
"""Return `obj` if the object satisfies this type constraint, or raise.
:raises: `TypeConstraintError` if `obj` does not satisfy the constraint.
"""
| python | {
"resource": ""
} |
q27526 | replace_in_file | train | def replace_in_file(workspace, src_file_path, from_str, to_str):
"""Replace from_str with to_str in the name and content of the given file.
If any edits were necessary, returns the new filename (which may be the same as the old filename).
"""
from_bytes = from_str.encode('ascii')
to_bytes = to_str.encode('as... | python | {
"resource": ""
} |
q27527 | fingerprint_file | train | def fingerprint_file(workspace, filename):
"""Given a relative filename located in a workspace, fingerprint the file.
Returns a tuple of fingerprint string and size string.
| python | {
"resource": ""
} |
q27528 | rewrite_record_file | train | def rewrite_record_file(workspace, src_record_file, mutated_file_tuples):
"""Given a RECORD file and list of mutated file tuples, update the RECORD file in place.
The RECORD file should always be a member of the mutated files, due to both containing
versions, and having a version in its filename.
"""
mutated... | python | {
"resource": ""
} |
q27529 | main | train | def main():
"""Given an input whl file and target version, create a copy of the whl with that version.
This is accomplished via string replacement in files matching a list of globs. Pass the
optional `--glob` argument to add additional globs: ie `--glob='thing-to-match*.txt'`.
"""
parser = argparse.Argument... | python | {
"resource": ""
} |
q27530 | AddressMapper.is_valid_single_address | train | def is_valid_single_address(self, single_address):
"""Check if a potentially ambiguous single address spec really exists.
:param single_address: A SingleAddress spec.
:return: True if given spec exists, False otherwise.
"""
if not isinstance(single_address, SingleAddress):
raise TypeError(
... | python | {
"resource": ""
} |
q27531 | JarDependencyManagement.resolve_version_conflict | train | def resolve_version_conflict(self, managed_coord, direct_coord, force=False):
"""Resolves an artifact version conflict between directly specified and managed jars.
This uses the user-defined --conflict-strategy to pick the appropriate artifact version (or to
raise an error).
This assumes the two confl... | python | {
"resource": ""
} |
q27532 | JarDependencyManagement.targets_by_artifact_set | train | def targets_by_artifact_set(self, targets):
"""Partitions the input targets by the sets of pinned artifacts they are managed by.
:param collections.Iterable targets: the input targets (typically just JarLibrary | python | {
"resource": ""
} |
q27533 | JarDependencyManagement.for_target | train | def for_target(self, target):
"""Computes and returns the PinnedJarArtifactSet that should be used to manage the given target.
This returns None if the target is not a JarLibrary.
:param Target target: The jar_library for which to find the managed_jar_dependencies object.
:return: The the artifact set... | python | {
"resource": ""
} |
q27534 | PinnedJarArtifactSet.id | train | def id(self):
"""A unique, stable, hashable id over the set of pinned artifacts."""
if not self._id:
# NB(gmalmquist): This id is not cheap to compute if there are a large number of artifacts.
# | python | {
"resource": ""
} |
q27535 | PinnedJarArtifactSet.put | train | def put(self, artifact):
"""Adds the given coordinate to the set, using its version to pin it.
If this set already contains an artifact with the same coordinates other than the version, it is
replaced by the new artifact.
:param M2Coordinate artifact: the artifact coordinate.
"""
artifact = M2... | python | {
"resource": ""
} |
q27536 | PinnedJarArtifactSet.get | train | def get(self, artifact):
"""Gets the coordinate with the correct version for the given artifact coordinate.
:param M2Coordinate artifact: the coordinate to lookup.
:return: a coordinate which is the same as the input, but with the correct pinned version. If
this artifact set does not pin a version fo... | python | {
"resource": ""
} |
q27537 | JarDependencyManagementSetup._compute_artifact_set | train | def _compute_artifact_set(self, management_target):
"""Computes the set of pinned artifacts specified by this target, and any of its dependencies.
An error is raised if a conflict exists between a pinned version between a
ManagedJarDependencies target and any of its dependencies, or if two versions of a ja... | python | {
"resource": ""
} |
q27538 | ui_open | train | def ui_open(*files):
"""Attempts to open the given files using the preferred desktop viewer or editor.
:raises :class:`OpenError`: if there is a problem opening any of the files.
"""
if files:
osname = | python | {
"resource": ""
} |
q27539 | TargetAddressable.factory | train | def factory(cls, target_type, alias=None):
"""Creates an addressable factory for the given target type and alias.
:returns: A factory that can capture :class:`TargetAddressable` instances.
:rtype: :class:`Addressable.Factory`
"""
class Factory(Addressable.Factory):
@property
def target_... | python | {
"resource": ""
} |
q27540 | WireGen.format_args_for_target | train | def format_args_for_target(self, target, target_workdir):
"""Calculate the arguments to pass to the command line for a single target."""
args = ['--java_out={0}'.format(target_workdir)]
# Add all params in payload to args
relative_sources, source_roots = self._compute_sources(target)
if target.p... | python | {
"resource": ""
} |
q27541 | Jar.main | train | def main(self, main):
"""Specifies a Main-Class entry for this jar's manifest.
:param string main: a fully qualified class name
"""
if not main or not isinstance(main, | python | {
"resource": ""
} |
q27542 | Jar.write | train | def write(self, src, dest=None):
"""Schedules a write of the file at ``src`` to the ``dest`` path in this jar.
If the ``src`` is a file, then ``dest`` must be specified.
If the ``src`` is a directory then by default all descendant files will be added to the jar as
entries carrying their relative path.... | python | {
"resource": ""
} |
q27543 | Jar.writejar | train | def writejar(self, jar):
"""Schedules all entries from the given ``jar``'s to be added to this jar save for the manifest.
:param string jar: the path to the pre-existing jar to graft into this jar
"""
| python | {
"resource": ""
} |
q27544 | Jar._render_jar_tool_args | train | def _render_jar_tool_args(self, options):
"""Format the arguments to jar-tool.
:param Options options:
"""
args = []
with temporary_dir() as manifest_stage_dir:
# relativize urls in canonical classpath, this needs to be stable too therefore
# do not follow the symlinks because symlinks... | python | {
"resource": ""
} |
q27545 | JarTask.open_jar | train | def open_jar(self, path, overwrite=False, compressed=True, jar_rules=None):
"""Yields a Jar that will be written when the context exits.
:API: public
:param string path: the path to the jar file
:param bool overwrite: overwrite the file at ``path`` if it exists; ``False`` by default; ie:
update ... | python | {
"resource": ""
} |
q27546 | JarBuilderTask.create_jar_builder | train | def create_jar_builder(self, jar):
"""Creates a ``JarTask.JarBuilder`` ready for use.
This method should be called during in `execute` context and only after ensuring
`JarTask.JarBuilder.prepare` has already been called in `prepare` context.
:param | python | {
"resource": ""
} |
q27547 | Watchman._make_client | train | def _make_client(self):
"""Create a new watchman client using the BSER protocol over a UNIX socket."""
self._logger.debug('setting initial watchman timeout to %s', self._startup_timeout)
return StreamableWatchmanClient(sockpath=self.socket,
| python | {
"resource": ""
} |
q27548 | Watchman.launch | train | def launch(self):
"""Launch and synchronously write metadata.
This is possible due to watchman's built-in async server startup - no double-forking required.
"""
cmd = self._construct_cmd((self._watchman_path, 'get-pid'),
state_file=self._state_file,
... | python | {
"resource": ""
} |
q27549 | Watchman._attempt_set_timeout | train | def _attempt_set_timeout(self, timeout):
"""Sets a timeout on the inner watchman client's socket."""
try:
self.client.setTimeout(timeout)
except Exception:
self._logger.debug('failed to set post-startup watchman timeout | python | {
"resource": ""
} |
q27550 | Watchman.watch_project | train | def watch_project(self, path):
"""Issues the watch-project command to watchman to begin watching the buildroot.
:param string path: the path to the watchman project root/pants build root.
"""
# TODO(kwlzn): Add a client.query(timeout=X) param to | python | {
"resource": ""
} |
q27551 | Watchman.subscribed | train | def subscribed(self, build_root, handlers):
"""Bulk subscribe generator for StreamableWatchmanClient.
:param str build_root: the build_root for all subscriptions.
:param iterable handlers: a sequence of Watchman.EventHandler namedtuple objects.
:yields: a stream of tuples in the form (subscription_name... | python | {
"resource": ""
} |
q27552 | BuildFileManipulator.add_dependency | train | def add_dependency(self, address):
"""Add a dependency to this target. This will deduplicate existing dependencies."""
if address in self._dependencies_by_address:
if self._dependencies_by_address[address].has_comment():
logger.warn('BuildFileManipulator would have added {address} as a dependency... | python | {
"resource": ""
} |
q27553 | BuildFileManipulator.clear_unforced_dependencies | train | def clear_unforced_dependencies(self):
"""Remove all dependencies not forced by a comment.
This is useful when existing analysis can infer exactly what the correct dependencies should
be. Typical use is to call `clear_unforced_dependencies`, then call | python | {
"resource": ""
} |
q27554 | BuildFileManipulator.build_file_lines | train | def build_file_lines(self):
"""Like `target_lines`, the entire BUILD file's lines after dependency manipulation."""
build_file_lines = self._build_file_source_lines[:]
target_begin, target_end = | python | {
"resource": ""
} |
q27555 | BuildFileManipulator.diff_lines | train | def diff_lines(self):
"""A diff between the original BUILD file and the resulting BUILD file."""
start_lines = self._build_file_source_lines[:]
end_lines = self.build_file_lines()
diff_generator = unified_diff(start_lines,
| python | {
"resource": ""
} |
q27556 | BuildFileManipulator.write | train | def write(self, dry_run=True):
"""Write out the changes made to the BUILD file, and print the diff to stderr.
:param dry_run: Don't actually write out the BUILD file, but do print the diff to stderr.
"""
start_lines = self._build_file_source_lines[:]
end_lines = self.build_file_lines()
diff_gen... | python | {
"resource": ""
} |
q27557 | ConanFetch._remotes_txt_content | train | def _remotes_txt_content(self):
"""Generate a file containing overrides for Conan remotes which get applied to registry.json."""
return '{}\n'.format('\n'.join(
| python | {
"resource": ""
} |
q27558 | ConanFetch._conan_user_home | train | def _conan_user_home(self, conan, in_workdir=False):
"""Create the CONAN_USER_HOME for this task fingerprint and initialize the Conan remotes.
See https://docs.conan.io/en/latest/reference/commands/consumer/config.html#conan-config-install
for docs on configuring remotes.
"""
# This argument is exp... | python | {
"resource": ""
} |
q27559 | ConanFetch.execute_codegen | train | def execute_codegen(self, target, target_workdir):
"""
Invoke the conan pex to fetch conan packages specified by a
`ExternalNativeLibrary` target.
:param ExternalNativeLibrary target: a target containing conan package specifications.
:param str target_workdir: where to copy the installed package co... | python | {
"resource": ""
} |
q27560 | Properties.load | train | def load(data):
"""Loads properties from an open stream or the contents of a string.
:API: public
:param (string | open stream) data: An open stream or a string.
:returns: A dict of parsed property data.
:rtype: dict
"""
if hasattr(data, 'read') and callable(data.read):
contents = d... | python | {
"resource": ""
} |
q27561 | Properties.dump | train | def dump(props, output):
"""Dumps a dict of properties to the specified open stream or file path.
:API: public
"""
def escape(token):
return re.sub(r'([=:\s])', r'\\\1', token)
def write(out):
for k, v in props.items():
| python | {
"resource": ""
} |
q27562 | classproperty | train | def classproperty(func):
"""Use as a decorator on a method definition to make it a class-level attribute.
This decorator can be applied to a method, a classmethod, or a staticmethod. This decorator will
bind the first argument to the class object.
Usage:
>>> class Foo(object):
... @classproperty
... ... | python | {
"resource": ""
} |
q27563 | MinimalCover._collect_internal_deps | train | def _collect_internal_deps(self, targets):
"""Collect one level of dependencies from the given targets, and then transitively walk.
This is different from directly executing `Target.closure_for_targets`, because the
resulting set will not include the roots unless the roots depend | python | {
"resource": ""
} |
q27564 | safe_args | train | def safe_args(args,
options,
max_args=None,
argfile=None,
delimiter='\n',
quoter=None,
delete=True):
"""Yields args if there are less than a limit otherwise writes args to an argfile and yields an
argument list with one argument for... | python | {
"resource": ""
} |
q27565 | JVM.get_jvm_options | train | def get_jvm_options(self):
"""Return the options to run this JVM with.
These are options to the JVM itself, such as -Dfoo=bar, -Xmx=1g, -XX:-UseParallelGC and so on.
Thus named because get_options() already exists (and returns this object's Pants options).
"""
ret = []
for opt in self.get_opti... | python | {
"resource": ""
} |
q27566 | JVM.get_program_args | train | def get_program_args(self):
"""Get the program args to run this JVM with.
These are the arguments passed to main() and are program-specific.
"""
ret = []
| python | {
"resource": ""
} |
q27567 | VersionedTargetSet.ensure_legal | train | def ensure_legal(self):
"""Return True as long as the state does not break any internal contracts."""
# Do our best to provide complete feedback, it's easy to imagine the frustration of flipping between error states.
if self._results_dir:
errors = ''
if not os.path.islink(self._results_dir):
... | python | {
"resource": ""
} |
q27568 | VersionedTargetSet.live_dirs | train | def live_dirs(self):
"""Yields directories that must exist for this VersionedTarget to function."""
# The only caller of this function is the workdir cleaning pipeline. It is not clear that the previous_results_dir
# should be returned for that purpose. And, by the time this is called, | python | {
"resource": ""
} |
q27569 | VersionedTarget.create_results_dir | train | def create_results_dir(self):
"""Ensure that the empty results directory and a stable symlink exist for these versioned targets."""
self._current_results_dir = self._cache_manager._results_dir_path(self.cache_key, stable=False)
self._results_dir = self._cache_manager._results_dir_path(self.cache_key, stable... | python | {
"resource": ""
} |
q27570 | VersionedTarget.copy_previous_results | train | def copy_previous_results(self):
"""Use the latest valid results_dir as the starting contents of the current results_dir.
Should be called after the cache is checked, since previous_results are not useful if there is
a cached artifact.
"""
# TODO(mateo): This should probably be managed by the task,... | python | {
"resource": ""
} |
q27571 | InvalidationCacheManager.update | train | def update(self, vts):
"""Mark a changed or invalidated VersionedTargetSet as successfully processed."""
for vt in vts.versioned_targets:
vt.ensure_legal()
if not vt.valid:
| python | {
"resource": ""
} |
q27572 | InvalidationCacheManager.force_invalidate | train | def force_invalidate(self, vts):
"""Force invalidation of a VersionedTargetSet."""
for vt in vts.versioned_targets:
self._invalidator.force_invalidate(vt.cache_key)
| python | {
"resource": ""
} |
q27573 | InvalidationCacheManager.check | train | def check(self,
targets,
topological_order=False):
"""Checks whether each of the targets has changed and invalidates it if so.
Returns a list of VersionedTargetSet objects (either valid or invalid). The returned sets
'cover' the input targets, with one caveat: if the FingerprintStra... | python | {
"resource": ""
} |
q27574 | InvalidationCacheManager._results_dir_path | train | def _results_dir_path(self, key, stable):
"""Return a results directory path for the given key.
:param key: A CacheKey to generate an id for.
:param stable: True to use a stable subdirectory, false to use a portion of the cache key to
generate a path unique to the key.
"""
# TODO: Shorten cac... | python | {
"resource": ""
} |
q27575 | InvalidationCacheManager.wrap_targets | train | def wrap_targets(self, targets, topological_order=False):
"""Wrap targets and their computed cache keys in VersionedTargets.
If the FingerprintStrategy opted out of providing a fingerprint for a target, that target will not
have an associated VersionedTarget returned.
Returns a list of VersionedTarget... | python | {
"resource": ""
} |
q27576 | hermetic_environment_as | train | def hermetic_environment_as(**kwargs):
"""Set the environment to the supplied values from an empty state."""
old_environment = os.environ.copy() | python | {
"resource": ""
} |
q27577 | _stdio_stream_as | train | def _stdio_stream_as(src_fd, dst_fd, dst_sys_attribute, mode):
"""Replace the given dst_fd and attribute on `sys` with an open handle to the given src_fd."""
if src_fd == -1:
src = open('/dev/null', mode)
src_fd = src.fileno()
# Capture the python and os level file handles.
old_dst = getattr(sys, dst_s... | python | {
"resource": ""
} |
q27578 | signal_handler_as | train | def signal_handler_as(sig, handler):
"""Temporarily replaces a signal handler for the given signal and restores the old handler.
:param int sig: The target signal to replace the handler for (e.g. signal.SIGINT).
:param func handler: The new temporary handler. | python | {
"resource": ""
} |
q27579 | temporary_dir | train | def temporary_dir(root_dir=None, cleanup=True, suffix='', permissions=None, prefix=tempfile.template):
"""
A with-context that creates a temporary directory.
:API: public
You may specify the following keyword args:
:param string root_dir: The parent directory to create the temporary directory.
:... | python | {
"resource": ""
} |
q27580 | temporary_file_path | train | def temporary_file_path(root_dir=None, cleanup=True, suffix='', permissions=None):
"""
A with-context that creates a temporary file and returns its path.
:API: public
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary file.
| python | {
"resource": ""
} |
q27581 | temporary_file | train | def temporary_file(root_dir=None, cleanup=True, suffix='', permissions=None, binary_mode=True):
"""
A with-context that creates a temporary file and returns a writeable file descriptor to it.
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary fil... | python | {
"resource": ""
} |
q27582 | safe_file | train | def safe_file(path, suffix=None, cleanup=True):
"""A with-context that copies a file, and copies the copy back to the original file on success.
This is useful for doing work on a file but only changing its state on success.
:param str suffix: Use this suffix to create the copy. Otherwise use a random string.
... | python | {
"resource": ""
} |
q27583 | open_zip | train | def open_zip(path_or_file, *args, **kwargs):
"""A with-context for zip files.
Passes through *args and **kwargs to zipfile.ZipFile.
:API: public
:param path_or_file: Full path to zip file.
:param args: Any extra args accepted by `zipfile.ZipFile`.
:param kwargs: Any extra keyword args accepted by `zipfil... | python | {
"resource": ""
} |
q27584 | open_tar | train | def open_tar(path_or_file, *args, **kwargs):
"""
A with-context for tar files. Passes through positional and kwargs to tarfile.open.
If path_or_file is a file, caller must close it separately.
"""
(path, fileobj) = ((path_or_file, None) if isinstance(path_or_file, string_types)
else... | python | {
"resource": ""
} |
q27585 | maybe_profiled | train | def maybe_profiled(profile_path):
"""A profiling context manager.
:param string profile_path: The path to write profile information to. If `None`, this will no-op.
"""
if not profile_path:
yield
return
import cProfile
profiler = cProfile.Profile()
try:
profiler.enable()
yield
finally:
... | python | {
"resource": ""
} |
q27586 | plugins | train | def plugins():
"""Returns a tuple of the plugin classes registered with the python style checker.
:rtype: tuple of :class:`pants.contrib.python.checks.checker.common.CheckstylePlugin` subtypes
"""
return (
ClassFactoring,
ConstantLogic,
ExceptStatements,
FutureCompatibility,
ImportOrder,
... | python | {
"resource": ""
} |
q27587 | Checker._get_nits | train | def _get_nits(self, filename):
"""Iterate over the instances style checker and yield Nits.
:param filename: str pointing to a file within the buildroot.
"""
try:
python_file = PythonFile.parse(filename, root=self._root_dir)
except CheckSyntaxError as e:
yield e.as_nit()
return
... | python | {
"resource": ""
} |
q27588 | Checker._check_file | train | def _check_file(self, filename):
"""Process python file looking for indications of problems.
:param filename: (str) Python source filename
:return: (int) number of failures
"""
# If the user specifies an invalid severity use comment.
log_threshold = Nit.SEVERITY.get(self._severity, Nit.COMMENT)... | python | {
"resource": ""
} |
q27589 | BinaryToolFetcher._select_binary_stream | train | def _select_binary_stream(self, name, urls):
"""Download a file from a list of urls, yielding a stream after downloading the file.
URLs are tried in order until they succeed.
:raises: :class:`BinaryToolFetcher.BinaryNotFound` if requests to all the given urls fail.
"""
downloaded_successfully = Fa... | python | {
"resource": ""
} |
q27590 | BinaryToolFetcher.fetch_binary | train | def fetch_binary(self, fetch_request):
"""Fulfill a binary fetch request."""
bootstrap_dir = os.path.realpath(os.path.expanduser(self._bootstrap_dir))
bootstrapped_binary_path = os.path.join(bootstrap_dir, fetch_request.download_path)
logger.debug("bootstrapped_binary_path: {}".format(bootstrapped_binar... | python | {
"resource": ""
} |
q27591 | BinaryUtil.select | train | def select(self, binary_request):
"""Fetches a file, unpacking it if necessary."""
logger.debug("binary_request: {!r}".format(binary_request))
try:
download_path = self._get_download_path(binary_request)
except self.MissingMachineInfo as e:
raise self.BinaryResolutionError(binary_request, ... | python | {
"resource": ""
} |
q27592 | safe_shlex_split | train | def safe_shlex_split(text_or_binary):
"""Split a string using shell-like syntax.
Safe even on python versions whose shlex.split() method doesn't accept unicode.
""" | python | {
"resource": ""
} |
q27593 | create_path_env_var | train | def create_path_env_var(new_entries, env=None, env_var='PATH', delimiter=':', prepend=False):
"""Join path entries, combining with an environment variable if specified."""
if env is None:
env = {}
prev_path = env.get(env_var, None)
if prev_path is None:
path_dirs = list()
| python | {
"resource": ""
} |
q27594 | pluralize | train | def pluralize(count, item_type):
"""Pluralizes the item_type if the count does not equal one.
For example `pluralize(1, 'apple')` returns '1 apple',
while `pluralize(0, 'apple') returns '0 apples'.
:return The count and inflected item_type together as a string
:rtype string
"""
def pluralize_string(x):
... | python | {
"resource": ""
} |
q27595 | strip_prefix | train | def strip_prefix(string, prefix):
"""Returns a copy of the string from which the multi-character prefix has been stripped.
Use strip_prefix() instead of lstrip() to remove a substring (instead of individual characters)
from the beginning of a string, if the substring is present. lstrip() does not match substrin... | python | {
"resource": ""
} |
q27596 | OptionableFactory.signature | train | def signature(cls):
"""Returns kwargs to construct a `TaskRule` that will construct the target Optionable.
TODO: This indirection avoids a cycle between this module and the `rules` module.
"""
snake_scope = cls.options_scope.replace('-', '_')
partial_construct_optionable = functools.partial(_constr... | python | {
"resource": ""
} |
q27597 | Optionable.get_scope_info | train | def get_scope_info(cls):
"""Returns a ScopeInfo instance representing this Optionable's options scope."""
if cls.options_scope is None or cls.options_scope_category is None:
raise OptionsError(
| python | {
"resource": ""
} |
q27598 | FilesetRelPathWrapper.to_filespec | train | def to_filespec(cls, args, root='', exclude=None):
"""Return a dict representation of this glob list, relative to the buildroot.
The format of the dict is {'globs': [ 'list', 'of' , 'strings' ]
(optional) 'exclude' : [{'globs' : ... }, ...] }
| python | {
"resource": ""
} |
q27599 | PailgunHandler._run_pants | train | def _run_pants(self, sock, arguments, environment):
"""Execute a given run with a pants runner."""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.