_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q27700 | JvmBinaryTask.list_external_jar_dependencies | train | def list_external_jar_dependencies(self, binary):
"""Returns the external jar dependencies of the given binary.
:param binary: The jvm binary target to list transitive external dependencies for.
:type binary: :class:`pants.backend.jvm.targets.jvm_binary.JvmBinary`
:returns: A list of (jar path, coordin... | python | {
"resource": ""
} |
q27701 | JvmBinaryTask.monolithic_jar | train | def monolithic_jar(self, binary, path, manifest_classpath=None):
"""Creates a jar containing all the dependencies for a jvm_binary target.
Yields a handle to the open jarfile, so the caller can add to the jar if needed.
The yielded jar file either has all the class files for the jvm_binary target as
a ... | python | {
"resource": ""
} |
q27702 | JvmBinaryTask.shade_jar | train | def shade_jar(self, shading_rules, jar_path):
"""Shades a jar using the shading rules from the given jvm_binary.
This *overwrites* the existing jar file at ``jar_path``.
:param shading_rules: predefined rules for shading
:param jar_path: The filepath to the jar that should be shaded.
"""
self.... | python | {
"resource": ""
} |
q27703 | parse_address_family | train | def parse_address_family(address_mapper, directory):
"""Given an AddressMapper and a directory, return an AddressFamily.
The AddressFamily may be empty, but it will not be None.
"""
patterns = tuple(join(directory.path, p) for p in address_mapper.build_patterns)
path_globs = PathGlobs(include=patterns,
... | python | {
"resource": ""
} |
q27704 | addresses_from_address_families | train | def addresses_from_address_families(address_mapper, specs):
"""Given an AddressMapper and list of Specs, return matching BuildFileAddresses.
:raises: :class:`ResolveError` if:
- there were no matching AddressFamilies, or
- the Spec matches no addresses for SingleAddresses.
:raises: :class:`AddressLooku... | python | {
"resource": ""
} |
q27705 | _spec_to_globs | train | def _spec_to_globs(address_mapper, specs):
"""Given a Specs object, return a PathGlobs object for the build files that it matches."""
| python | {
"resource": ""
} |
q27706 | create_graph_rules | train | def create_graph_rules(address_mapper):
"""Creates tasks used to parse Structs from BUILD files.
:param address_mapper_key: The subject key for an AddressMapper instance.
:param symbol_table: A SymbolTable instance to provide symbols for Address lookups.
"""
@rule(AddressMapper, [])
def address_mapper_sin... | python | {
"resource": ""
} |
q27707 | PythonArtifact.with_binaries | train | def with_binaries(self, *args, **kw):
"""Add binaries tagged to this artifact.
For example: ::
provides = setup_py(
name = 'my_library',
zip_safe = True
).with_binaries(
my_command = ':my_library_bin'
)
This adds a console_script entry_point for the python_binary... | python | {
"resource": ""
} |
q27708 | Confluence.getpage | train | def getpage(self, wiki_space, page_title):
""" Fetches a page object.
Returns None if the page does not exist or otherwise could not be fetched.
"""
try:
return self._api_entrypoint.getPage(self._session_token, | python | {
"resource": ""
} |
q27709 | Confluence.storepage | train | def storepage(self, page):
"""Stores a page object, updating the page if it already exists.
returns the stored page, or None if the page could not be stored.
"""
try:
return | python | {
"resource": ""
} |
q27710 | Confluence.removepage | train | def removepage(self, page):
"""Deletes a page from confluence.
raises ConfluenceError if the page could not be removed.
"""
try:
self._api_entrypoint.removePage(self._session_token, page) | python | {
"resource": ""
} |
q27711 | Confluence.create | train | def create(self, space, title, content, parent_page=None, **pageoptions):
""" Create a new confluence page with the given title and content. Additional page options
available in the xmlrpc api can be specified as kwargs.
returns the created page or None if the page could not be stored.
raises Confluenc... | python | {
"resource": ""
} |
q27712 | SchedulerService._get_snapshot | train | def _get_snapshot(self):
"""Returns a Snapshot of the input globs"""
| python | {
"resource": ""
} |
q27713 | SchedulerService.setup | train | def setup(self, services):
"""Service setup."""
super(SchedulerService, self).setup(services)
# Register filesystem event handlers on an FSEventService instance.
self._fs_event_service.register_all_files_handler(self._enqueue_fs_event)
# N.B. We compute the invalidating fileset eagerly at launch wi... | python | {
"resource": ""
} |
q27714 | SchedulerService._process_event_queue | train | def _process_event_queue(self):
"""File event notification queue processor. """
try:
event = self._event_queue.get(timeout=0.05)
except queue.Empty:
return
try:
subscription, is_initial_event, files = (event['subscription'],
event['is_fre... | python | {
"resource": ""
} |
q27715 | SchedulerService.prefork | train | def prefork(self, options, options_bootstrapper):
"""Runs all pre-fork logic in the process context of the daemon.
:returns: `(LegacyGraphSession, TargetRoots, exit_code)`
"""
# If any nodes exist in the product graph, wait for the initial watchman event to avoid
# racing watchman startup vs invali... | python | {
"resource": ""
} |
q27716 | SchedulerService.run | train | def run(self):
"""Main service entrypoint."""
while not | python | {
"resource": ""
} |
q27717 | LoopCondition.wait | train | def wait(self, timeout):
"""Waits for the condition for at most the given timeout and returns True if the condition triggered.
Generally called in a loop until the condition triggers.
"""
| python | {
"resource": ""
} |
q27718 | Context._set_target_root_count_in_runtracker | train | def _set_target_root_count_in_runtracker(self):
"""Sets the target root count in the run tracker's daemon stats object."""
# N.B. `self._target_roots` is always an expanded list of `Target` objects as
# provided by `GoalRunner`.
| python | {
"resource": ""
} |
q27719 | Context._set_affected_target_count_in_runtracker | train | def _set_affected_target_count_in_runtracker(self):
"""Sets the realized target count in the run tracker's daemon stats object."""
target_count = | python | {
"resource": ""
} |
q27720 | Context.subproc_map | train | def subproc_map(self, f, items):
"""Map function `f` over `items` in subprocesses and return the result.
:API: public
:param f: A multiproc-friendly (importable) work function.
:param items: A iterable of pickleable arguments to f.
"""
try:
# Pool.map (and async_map().get() w/o tim... | python | {
"resource": ""
} |
q27721 | Context.new_workunit | train | def new_workunit(self, name, labels=None, cmd='', log_config=None):
"""Create a new workunit under the calling thread's current workunit.
:API: public
"""
| python | {
"resource": ""
} |
q27722 | Context.acquire_lock | train | def acquire_lock(self):
""" Acquire the global lock for the root directory associated with this context. When
a goal requires serialization, it will call this to acquire the lock.
:API: public
| python | {
"resource": ""
} |
q27723 | Context.release_lock | train | def release_lock(self):
"""Release the global lock if it's held.
Returns True if the lock was held before this call.
:API: public
"""
| python | {
"resource": ""
} |
q27724 | Context.add_new_target | train | def add_new_target(self, address, target_type, target_base=None, dependencies=None,
derived_from=None, **kwargs):
"""Creates a new target, adds it to the context and returns it.
This method ensures the target resolves files against the given target_base, creating the
directory if neede... | python | {
"resource": ""
} |
q27725 | Context.targets | train | def targets(self, predicate=None, **kwargs):
"""Selects targets in-play in this run from the target roots and their transitive dependencies.
Also includes any new synthetic targets created from the target roots or their transitive
dependencies during the course of the run.
See Target.closure_for_targe... | python | {
"resource": ""
} |
q27726 | Context.dependents | train | def dependents(self, on_predicate=None, from_predicate=None):
"""Returns a map from targets that satisfy the from_predicate to targets they depend on that
satisfy the on_predicate.
| python | {
"resource": ""
} |
q27727 | Context.scan | train | def scan(self, root=None):
"""Scans and parses all BUILD files found under ``root``.
Only BUILD files found under ``root`` are parsed as roots in the graph, but any dependencies of
targets parsed in the root tree's BUILD files will be followed and this may lead to BUILD files
outside of ``root`` being ... | python | {
"resource": ""
} |
q27728 | Context.execute_process_synchronously_or_raise | train | def execute_process_synchronously_or_raise(self, execute_process_request, name, labels=None):
"""Execute process synchronously, and throw if the return code is not 0.
See execute_process_synchronously for | python | {
"resource": ""
} |
q27729 | BundleCreate.bundle | train | def bundle(self, app, results_dir):
"""Create a self-contained application bundle.
The bundle will contain the target classes, dependencies and resources.
"""
assert(isinstance(app, BundleCreate.App))
bundle_dir = self.get_bundle_dir(app.id, results_dir)
self.context.log.debug('creating {}'.fo... | python | {
"resource": ""
} |
q27730 | BundleCreate.check_basename_conflicts | train | def check_basename_conflicts(self, targets):
"""Apps' basenames are used as bundle directory names. Ensure they are all unique."""
basename_seen = {}
for target in targets:
if target.basename in basename_seen:
raise self.BasenameConflictError('Basename must be unique, found two targets use '
... | python | {
"resource": ""
} |
q27731 | Reproducer.create_repro | train | def create_repro(self):
"""Return a Repro instance for capturing a repro of the current workspace state.
:return: a Repro instance, or None if no repro was requested.
:rtype: `pants.bin.repro.Repro`
"""
path = self.get_options().capture
if path is None:
return None
buildroot = get_bui... | python | {
"resource": ""
} |
q27732 | BuildDictionaryInfoExtracter.get_target_args | train | def get_target_args(self, alias):
"""Returns a list of FunctionArgs for the specified target_type."""
target_types = list(self._buildfile_aliases.target_types_by_alias.get(alias))
if not target_types:
| python | {
"resource": ""
} |
q27733 | RunTracker.initialize | train | def initialize(self, all_options):
"""Create run_info and relevant directories, and return the run id.
Must be called before `start`.
"""
if self.run_info:
raise AssertionError('RunTracker.initialize must not be called multiple times.')
# Initialize the run.
# Select a globally unique I... | python | {
"resource": ""
} |
q27734 | RunTracker.start | train | def start(self, report, run_start_time=None):
"""Start tracking this pants run using the given Report.
`RunTracker.initialize` must have been called first to create the run_info_dir and
run_info. TODO: This lifecycle represents a delicate dance with the `Reporting.initialize`
method, and portions of th... | python | {
"resource": ""
} |
q27735 | RunTracker.log | train | def log(self, level, *msg_elements):
"""Log a message against the current workunit."""
| python | {
"resource": ""
} |
q27736 | RunTracker.post_stats | train | def post_stats(cls, stats_url, stats, timeout=2, auth_provider=None):
"""POST stats to the given url.
:return: True if upload was successful, False otherwise.
"""
def error(msg):
# Report aleady closed, so just print error.
print('WARNING: Failed to upload stats to {}. due to {}'.format(sta... | python | {
"resource": ""
} |
q27737 | RunTracker.write_stats_to_json | train | def write_stats_to_json(cls, file_name, stats):
"""Write stats to a local json file."""
params = cls._json_dump_options(stats)
mode = 'w' if PY3 else 'wb'
try:
safe_file_dump(file_name, params, mode=mode)
except Exception as e: # | python | {
"resource": ""
} |
q27738 | RunTracker.run_information | train | def run_information(self):
"""Basic information about this run."""
run_information = self.run_info.get_as_dict()
target_data = run_information.get('target_data', None)
if target_data:
| python | {
"resource": ""
} |
q27739 | RunTracker.store_stats | train | def store_stats(self):
"""Store stats about this run in local and optionally remote stats dbs."""
stats = self._stats()
# Write stats to user-defined json file.
stats_json_file_name = self.get_options().stats_local_json_file
if stats_json_file_name:
self.write_stats_to_json(stats_json_file_na... | python | {
"resource": ""
} |
q27740 | RunTracker.end | train | def end(self):
"""This pants run is over, so stop tracking it.
Note: If end() has been called once, subsequent calls are no-ops.
:return: PANTS_SUCCEEDED_EXIT_CODE or PANTS_FAILED_EXIT_CODE
"""
if self._end_memoized_result is not None:
return self._end_memoized_result
if self._background... | python | {
"resource": ""
} |
q27741 | RunTracker._create_dict_with_nested_keys_and_val | train | def _create_dict_with_nested_keys_and_val(cls, keys, value):
"""Recursively constructs a nested dictionary with the keys pointing to the value.
For example:
Given the list of keys ['a', 'b', 'c', 'd'] and a primitive
value 'hello world', the method will produce the nested dictionary
{'a': {'b': {'c... | python | {
"resource": ""
} |
q27742 | RunTracker._merge_list_of_keys_into_dict | train | def _merge_list_of_keys_into_dict(cls, data, keys, value, index=0):
"""Recursively merge list of keys that points to the given value into data.
Will override a primitive value with another primitive value, but will not
override a primitive with a dictionary.
For example:
Given the dictionary {'a':... | python | {
"resource": ""
} |
q27743 | RunTracker.report_target_info | train | def report_target_info(self, scope, target, keys, val):
"""Add target information to run_info under target_data.
Will Recursively construct a nested dict with the keys provided.
Primitive values can be overwritten with other primitive values,
but a primitive value cannot be overwritten with a dictiona... | python | {
"resource": ""
} |
q27744 | Executor.runner | train | def runner(self, classpath, main, jvm_options=None, args=None, cwd=None):
"""Returns an `Executor.Runner` for the given java command."""
| python | {
"resource": ""
} |
q27745 | Executor.execute | train | def execute(self, classpath, main, jvm_options=None, args=None, stdout=None, stderr=None,
cwd=None):
"""Launches the java program defined by the classpath and main.
:param list classpath: the classpath for the java program
:param string main: the fully qualified class name of the java program's entry... | python | {
"resource": ""
} |
q27746 | SubprocessExecutor.spawn | train | def spawn(self, classpath, main, jvm_options=None, args=None, cwd=None, **subprocess_args):
"""Spawns the java program passing any extra subprocess kwargs on to subprocess.Popen.
Returns the Popen process object handle to the spawned java program subprocess.
:API: public
:raises: :class:`Executor.Err... | python | {
"resource": ""
} |
q27747 | NailgunClientSession._set_exit_timeout | train | def _set_exit_timeout(self, timeout, reason):
"""Set a timeout for the remainder of the session, along with an exception to raise.
which is implemented by NailgunProtocol.
This method may be called by a signal handler to set a timeout for the remainder of the
session. If the session completes before th... | python | {
"resource": ""
} |
q27748 | NailgunClientSession.maybe_timeout_options | train | def maybe_timeout_options(self):
"""Implements the NailgunProtocol.TimeoutProvider interface."""
if self._exit_timeout_start_time:
return | python | {
"resource": ""
} |
q27749 | NailgunClientSession._process_session | train | def _process_session(self):
"""Process the outputs of the nailgun session.
:raises: :class:`NailgunProtocol.ProcessStreamTimeout` if a timeout set from a signal handler
with .set_exit_timeout() completes.
:raises: :class:`Exception` if the session ... | python | {
"resource": ""
} |
q27750 | NailgunClient.try_connect | train | def try_connect(self):
"""Creates a socket, connects it to the nailgun and returns the connected socket.
:returns: a connected `socket.socket`.
:raises: `NailgunClient.NailgunConnectionError` on failure to connect.
"""
sock = RecvBufferedSocket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
... | python | {
"resource": ""
} |
q27751 | NailgunClient.execute | train | def execute(self, main_class, cwd=None, *args, **environment):
"""Executes the given main_class with any supplied args in the given environment.
:param string main_class: the fully qualified class name of the main entrypoint
:param string cwd: Set the working directory for this command
:param list args... | python | {
"resource": ""
} |
q27752 | GoFetch._fetch_pkg | train | def _fetch_pkg(self, gopath, pkg, rev):
"""Fetch the package and setup symlinks."""
fetcher = self._get_fetcher(pkg)
root = fetcher.root()
root_dir = os.path.join(self.workdir, 'fetches', root, rev)
# Only fetch each remote root once.
if not os.path.exists(root_dir):
with temporary_dir() ... | python | {
"resource": ""
} |
q27753 | GoFetch._resolve | train | def _resolve(self, dependent_remote_lib, address, pkg, rev, implicit_ok):
"""Resolves the GoRemoteLibrary at `address` defining the given `pkg`.
If `implicit_ok` is True, then a GoRemoteLibrary to own `pkg` is always synthesized if it does
not already exist; otherwise the address must already exist in the ... | python | {
"resource": ""
} |
q27754 | GoFetch._get_remote_import_paths | train | def _get_remote_import_paths(self, pkg, gopath=None):
"""Returns the remote import paths declared by the given remote Go `pkg`.
NB: This only includes production code imports, no test code imports.
"""
import_listing = self.import_oracle.list_imports(pkg, gopath=gopath) | python | {
"resource": ""
} |
q27755 | GoFetch._write_import_root_map_file | train | def _write_import_root_map_file(path, import_root_map):
"""Writes a file mapping import paths to roots."""
with safe_concurrent_creation(path) as safe_path:
with open(safe_path, 'w') as fp:
| python | {
"resource": ""
} |
q27756 | declares_namespace_package | train | def declares_namespace_package(filename):
"""Given a filename, walk its ast and determine if it declares a namespace package."""
import ast
with open(filename) as fp:
init_py = ast.parse(fp.read(), filename)
calls = [node for node in ast.walk(init_py) if isinstance(node, ast.Call)]
for call in calls:
... | python | {
"resource": ""
} |
q27757 | TargetAncestorIterator.iter_target_siblings_and_ancestors | train | def iter_target_siblings_and_ancestors(self, target):
"""Produces an iterator over a target's siblings and ancestor lineage.
:returns: A target iterator yielding the target and its siblings and then it ancestors from
nearest to furthest removed.
"""
def iter_targets_in_spec_path(spec_path... | python | {
"resource": ""
} |
q27758 | ExportedTargetDependencyCalculator._walk | train | def _walk(self, target, visitor):
"""Walks the dependency graph for the given target.
:param target: The target to start the walk from.
:param visitor: A function that takes a target and returns `True` if its dependencies should
also be visited.
"""
visited = set() | python | {
"resource": ""
} |
q27759 | ExportedTargetDependencyCalculator._closure | train | def _closure(self, target):
"""Return the target closure as defined by this dependency calculator's definition of a walk."""
closure = set()
def collect(current):
| python | {
"resource": ""
} |
q27760 | ExportedTargetDependencyCalculator.reduced_dependencies | train | def reduced_dependencies(self, exported_target):
"""Calculates the reduced transitive dependencies for an exported target.
The reduced set of dependencies will be just those transitive dependencies "owned" by
the `exported_target`.
A target is considered "owned" if:
1. It's "3rdparty" and "directl... | python | {
"resource": ""
} |
q27761 | SetupPy.iter_entry_points | train | def iter_entry_points(cls, target):
"""Yields the name, entry_point pairs of binary targets in this PythonArtifact."""
for name, binary_target in target.provided_binaries.items():
concrete_target = binary_target
if not isinstance(concrete_target, PythonBinary) or concrete_target.entry_point is None:... | python | {
"resource": ""
} |
q27762 | SetupPy.nearest_subpackage | train | def nearest_subpackage(cls, package, all_packages):
"""Given a package, find its nearest parent in all_packages."""
def shared_prefix(candidate):
zipped = zip(package.split('.'), candidate.split('.'))
matching = itertools.takewhile(lambda pair: pair[0] == pair[1], zipped)
| python | {
"resource": ""
} |
q27763 | SetupPy.find_packages | train | def find_packages(self, root_target, chroot):
"""Detect packages, namespace packages and resources from an existing chroot.
:returns: a tuple of:
set(packages)
set(namespace_packages)
map(package => set(files))
"""
base = os.path.join(chroot.path(), self.... | python | {
"resource": ""
} |
q27764 | SetupPy.write_contents | train | def write_contents(self, root_target, reduced_dependencies, chroot):
"""Write contents of the target."""
def write_target_source(target, src):
chroot.copy(os.path.join(get_buildroot(), target.target_base, src),
os.path.join(self.SOURCE_ROOT, src))
# check parent __init__.pys to see... | python | {
"resource": ""
} |
q27765 | SetupPy.write_setup | train | def write_setup(self, root_target, reduced_dependencies, chroot):
"""Write the setup.py of a target.
Must be run after writing the contents to the chroot.
"""
setup_keywords = root_target.provides.setup_py_keywords.copy()
package_dir = {'': self.SOURCE_ROOT}
packages, namespace_packages, resou... | python | {
"resource": ""
} |
q27766 | ArtifactCacheStats.get_all | train | def get_all(self):
"""Returns the cache stats as a list of dicts."""
ret = []
for cache_name, stat in self.stats_per_cache.items():
ret.append({
'cache_name': cache_name,
| python | {
"resource": ""
} |
q27767 | ScalaPlatform._tool_classpath | train | def _tool_classpath(self, tool, products, scheduler):
"""Return the proper classpath based on products and scala version."""
classpath = self.tool_classpath_from_products(products,
self.versioned_tool_name(tool, self.version),
| python | {
"resource": ""
} |
q27768 | ScalaPlatform.style_classpath | train | def style_classpath(self, products, scheduler):
"""Returns classpath as paths for scalastyle."""
classpath_entries = | python | {
"resource": ""
} |
q27769 | ScalaPlatform.suffix_version | train | def suffix_version(self, name):
"""Appends the platform version to the given artifact name.
Also validates that the name doesn't already end with the version.
"""
if self.version == 'custom':
suffix = self.get_options().suffix_version
if suffix:
return '{0}_{1}'.format(name, suffix)... | python | {
"resource": ""
} |
q27770 | BashCompletion._get_all_cmd_line_scopes | train | def _get_all_cmd_line_scopes():
"""Return all scopes that may be explicitly specified on the cmd line, in no particular order.
Note that this includes only task scope, and not, | python | {
"resource": ""
} |
q27771 | BashCompletion.get_autocomplete_options_by_scope | train | def get_autocomplete_options_by_scope(self):
"""Return all cmd-line options.
These are of two types: scoped and unscoped. Scoped options are explicitly scoped
(e.g., --goal-task-foo-bar) and may appear anywhere on the cmd line. Unscoped options
may only appear in the appropriate cmd line scope (e.g., ... | python | {
"resource": ""
} |
q27772 | CppToolchain.register_tool | train | def register_tool(self, tool, name=None):
"""Check tool and see if it is installed in the local cpp toolchain.
All cpp tasks should request their tools using this method. Tools are validated
and cached for quick lookup.
:param string tool: Name or path of program tool, eg 'g++'
:param string name:... | python | {
"resource": ""
} |
q27773 | retry_on_exception | train | def retry_on_exception(func, max_retries, exception_types, backoff_func=lambda n: 0):
"""Retry a callable against a set of exceptions, optionally sleeping between retries.
:param callable func: The callable to retry.
:param int max_retries: The maximum number of times to attempt running the function.
:param tu... | python | {
"resource": ""
} |
q27774 | RoundManager.get_dependencies | train | def get_dependencies(self):
"""Returns the set of data dependencies as producer infos corresponding to data requirements."""
producer_infos = set()
for product_type in self._dependencies:
| python | {
"resource": ""
} |
q27775 | M2Coordinate.unversioned | train | def unversioned(cls, coord):
"""The coordinate without the version.
:param M2Coordinate coord: an M2Coordinate or JarDependency.
:return: the coordinate without the version.
:rtype: M2Coordinate
"""
| python | {
"resource": ""
} |
q27776 | M2Coordinate.artifact_filename | train | def artifact_filename(self):
"""Returns the canonical maven-style filename for an artifact pointed at by this coordinate.
:API: public
:rtype: string
"""
def maybe_compenent(component):
return '-{}'.format(component) if component else ''
return '{org}-{name}{rev}{classifier}.{ext}'.form... | python | {
"resource": ""
} |
q27777 | M2Coordinate.copy | train | def copy(self, **replacements):
"""Returns a clone of this M2Coordinate with the given replacements kwargs overlaid."""
cls = type(self)
kwargs = {'org': self.org, 'name': | python | {
"resource": ""
} |
q27778 | Reporter.handle_log | train | def handle_log(self, workunit, level, *msg_elements):
"""Handle a message logged by pants code.
level: One of the constants above.
Each element in msg_elements is either a message or a (message, detail) pair.
A subclass must show the message, but may choose to show the detail in some
sensible way ... | python | {
"resource": ""
} |
q27779 | GoalExecutor.attempt | train | def attempt(self, explain):
"""Attempts to execute the goal's tasks in installed order.
:param bool explain: If ``True`` then the goal plan will be explained instead of being
executed.
"""
goal_workdir = os.path.join(self._context.options.for_global_scope().pants_workdir,
... | python | {
"resource": ""
} |
q27780 | TrailingWhitespace.build_exception_map | train | def build_exception_map(cls, tokens):
"""Generates a set of ranges where we accept trailing slashes, specifically within comments
and strings.
"""
exception_ranges = defaultdict(list)
for token in tokens:
token_type, _, token_start, token_end = token[0:4]
if token_type in (tokenize.CO... | python | {
"resource": ""
} |
q27781 | GoWorkspaceTask.ensure_workspace | train | def ensure_workspace(self, target):
"""Ensures that an up-to-date Go workspace exists for the given target.
Creates any necessary symlinks to source files based on the target and its transitive
dependencies, and removes any symlinks which do not correspond to any needed dep.
"""
gopath = self.get_g... | python | {
"resource": ""
} |
q27782 | GoWorkspaceTask.remove_unused_links | train | def remove_unused_links(dirpath, required_links):
"""Recursively remove any links in dirpath which are not contained in required_links.
:param str dirpath: Absolute path of directory to search.
:param container required_links: Container of "in use" | python | {
"resource": ""
} |
q27783 | GoWorkspaceTask._symlink_local_src | train | def _symlink_local_src(self, gopath, go_local_src, required_links):
"""Creates symlinks from the given gopath to the source files of the given local package.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the sym... | python | {
"resource": ""
} |
q27784 | GoWorkspaceTask._symlink_remote_lib | train | def _symlink_remote_lib(self, gopath, go_remote_lib, required_links):
"""Creates symlinks from the given gopath to the source files of the given remote lib.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the syml... | python | {
"resource": ""
} |
q27785 | ScopeInfoIterator.iterate | train | def iterate(self, scopes):
"""Yields ScopeInfo instances for the specified scopes, plus relevant related scopes.
Relevant scopes are:
- All tasks in a requested goal.
- All subsystems tied to a request scope.
Yields in a sensible order: Sorted by scope, but with subsystems tied to a request sc... | python | {
"resource": ""
} |
q27786 | ScopeInfoIterator._expand_tasks | train | def _expand_tasks(self, scopes):
"""Add all tasks in any requested goals.
Returns the requested scopes, plus the added tasks, sorted by scope name.
"""
expanded_scopes = set(scopes)
for scope, info in self._scope_to_info.items():
if info.category == ScopeInfo.TASK:
outer = enclosing_s... | python | {
"resource": ""
} |
q27787 | ScopeInfoIterator._expand_subsystems | train | def _expand_subsystems(self, scope_infos):
"""Add all subsystems tied to a scope, right after that scope."""
# Get non-global subsystem dependencies of the specified subsystem client.
def subsys_deps(subsystem_client_cls):
for dep in subsystem_client_cls.subsystem_dependencies_iter():
if dep.... | python | {
"resource": ""
} |
q27788 | JvmdocGen.generate_doc | train | def generate_doc(self, language_predicate, create_jvmdoc_command):
"""
Generate an execute method given a language predicate and command to create documentation
language_predicate: a function that accepts a target and returns True if the target is of that
language
create_jvmdoc_... | python | {
"resource": ""
} |
q27789 | JvmTask.classpath | train | def classpath(self, targets, classpath_prefix=None, classpath_product=None, exclude_scopes=None,
include_scopes=None):
"""Builds a transitive classpath for the given targets.
Optionally includes a classpath prefix or building from a non-default classpath product.
:param targets: the target... | python | {
"resource": ""
} |
q27790 | atomic_copy | train | def atomic_copy(src, dst):
"""Copy the file src to dst, overwriting dst atomically."""
with temporary_file(root_dir=os.path.dirname(dst)) | python | {
"resource": ""
} |
q27791 | safe_temp_edit | train | def safe_temp_edit(filename):
"""Safely modify a file within context that automatically reverts any changes afterwards
The file mutatation occurs in place. The file is backed up in a temporary file before edits
occur and when the context is closed, the mutated file is discarded and replaced with the backup.
W... | python | {
"resource": ""
} |
q27792 | create_size_estimators | train | def create_size_estimators():
"""Create a dict of name to a function that returns an estimated size for a given target.
The estimated size is used to build the largest targets first (subject to dependency constraints).
Choose 'random' to choose random sizes for each target, which may be useful for distributed
... | python | {
"resource": ""
} |
q27793 | fallible_to_exec_result_or_raise | train | def fallible_to_exec_result_or_raise(fallible_result, request):
"""Converts a FallibleExecuteProcessResult to a ExecuteProcessResult or raises an error."""
if fallible_result.exit_code == 0:
return ExecuteProcessResult(
| python | {
"resource": ""
} |
q27794 | PythonFile.parse | train | def parse(cls, filename, root=None):
"""Parses the file at filename and returns a PythonFile.
If root is specified, it will open the file with root prepended to the path. The idea is to
allow for errors to contain a friendlier file path than the full absolute path.
"""
if root is not None:
if... | python | {
"resource": ""
} |
q27795 | PythonFile.translate_logical_line | train | def translate_logical_line(start, end, contents, indent_stack, endmarker=False):
"""Translate raw contents to logical lines"""
# Remove leading blank lines.
while contents[0] == '\n':
start += 1
contents.pop(0)
# Remove trailing blank lines.
while contents[-1] == '\n':
| python | {
"resource": ""
} |
q27796 | PythonFile.line_range | train | def line_range(self, line_number):
"""Return a slice for the given line number"""
if line_number <= 0 or line_number > len(self.lines):
raise IndexError('NOTE: Python file line numbers are offset by 1.')
if line_number not in self.logical_lines: | python | {
"resource": ""
} |
q27797 | NativeTask.strict_deps_for_target | train | def strict_deps_for_target(self, target, predicate=None):
"""Get the dependencies of `target` filtered by `predicate`, accounting for 'strict_deps'.
If 'strict_deps' is on, instead of using the transitive closure of dependencies, targets will
only be able to see their immediate dependencies declared in the... | python | {
"resource": ""
} |
q27798 | AntlrJavaGen._rearrange_output_for_package | train | def _rearrange_output_for_package(self, target_workdir, java_package):
"""Rearrange the output files to match a standard Java structure.
Antlr emits a directory structure based on the relative path provided
for the grammar file. If the source root of the file is different from
the Pants build root, the... | python | {
"resource": ""
} |
q27799 | AntlrJavaGen._scrub_generated_timestamps | train | def _scrub_generated_timestamps(self, target_workdir):
"""Remove the first line of comment from each file if it contains a timestamp."""
for root, _, filenames in safe_walk(target_workdir):
for filename in filenames:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.