_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q24400 | StrategyMixin._install_wrappers | train | def _install_wrappers(self):
"""
Install our PluginLoader monkey patches and update global variables
with references to the real functions.
"""
global action_loader__get
action_loader__get = ansible_mitogen.loaders.action_loader.get
ansible_mitogen.loaders.action_... | python | {
"resource": ""
} |
q24401 | StrategyMixin._remove_wrappers | train | def _remove_wrappers(self):
"""
Uninstall the PluginLoader monkey patches.
"""
ansible_mitogen.loaders.action_loader.get = action_loader__get
| python | {
"resource": ""
} |
q24402 | StrategyMixin._add_plugin_paths | train | def _add_plugin_paths(self):
"""
Add the Mitogen plug-in directories to the ModuleLoader path, avoiding
the need for manual configuration.
"""
base_dir = os.path.join(os.path.dirname(__file__), 'plugins')
ansible_mitogen.loaders.connection_loader.add_directory(
| python | {
"resource": ""
} |
q24403 | StrategyMixin._queue_task | train | def _queue_task(self, host, task, task_vars, play_context):
"""
Many PluginLoader caches are defective as they are only populated in
the ephemeral WorkerProcess. Touch each plug-in path before forking to
ensure all workers receive a hot cache.
"""
ansible_mitogen.loaders.... | python | {
"resource": ""
} |
q24404 | expose | train | def expose(policy):
"""
Annotate a method to permit access to contexts matching an authorization
policy. The annotation may be specified multiple times. Methods lacking any
authorization policy are not accessible.
::
@mitogen.service.expose(policy=mitogen.service.AllowParents())
de... | python | {
"resource": ""
} |
q24405 | PushFileService.get | train | def get(self, path):
"""
Fetch a file from the cache.
"""
assert isinstance(path, mitogen.core.UnicodeType)
self._lock.acquire()
try:
if path in self._cache:
return self._cache[path]
| python | {
"resource": ""
} |
q24406 | PushFileService.propagate_paths_and_modules | train | def propagate_paths_and_modules(self, context, paths, modules):
"""
One size fits all method to ensure a target context has been preloaded
with a set of small files and Python modules.
"""
for path | python | {
"resource": ""
} |
q24407 | FileService.register | train | def register(self, path):
"""
Authorize a path for access by children. Repeat calls with the same
path has no effect.
:param str path:
File path.
""" | python | {
"resource": ""
} |
q24408 | FileService.register_prefix | train | def register_prefix(self, path):
"""
Authorize a path and any subpaths for access by children. Repeat calls
with the same path has no effect.
:param str path:
File path.
| python | {
"resource": ""
} |
q24409 | FileService.fetch | train | def fetch(self, path, sender, msg):
"""
Start a transfer for a registered path.
:param str path:
File path.
:param mitogen.core.Sender sender:
Sender to receive file data.
:returns:
Dict containing the file metadata:
* ``size``: F... | python | {
"resource": ""
} |
q24410 | FileService.acknowledge | train | def acknowledge(self, size, msg):
"""
Acknowledge bytes received by a transfer target, scheduling new chunks
to keep the window full. This should be called for every chunk received
by the target.
"""
stream = self.router.stream_by_id(msg.src_id)
| python | {
"resource": ""
} |
q24411 | get_subclasses | train | def get_subclasses(klass):
"""
Rather than statically import every interesting subclass, forcing it all to
be transferred and potentially disrupting the debugged environment,
| python | {
"resource": ""
} |
q24412 | simplegeneric | train | def simplegeneric(func):
"""Make a trivial single-dispatch generic function"""
registry = {}
def wrapper(*args, **kw):
ob = args[0]
try:
cls = ob.__class__
except AttributeError:
cls = type(ob)
try:
mro = cls.__mro__
except Attribut... | python | {
"resource": ""
} |
q24413 | get_importer | train | def get_importer(path_item):
"""Retrieve a PEP 302 importer for the given path item
The returned importer is cached in sys.path_importer_cache
if it was newly created by a path hook.
If there is no importer, a wrapper around the basic import
machinery is returned. This wrapper is never inserted in... | python | {
"resource": ""
} |
q24414 | iter_importers | train | def iter_importers(fullname=""):
"""Yield PEP 302 importers for the given module name
If fullname contains a '.', the importers will be for the package
containing fullname, otherwise they will be importers for sys.meta_path,
sys.path, and Python's "classic" import machinery, in that order. If
the ... | python | {
"resource": ""
} |
q24415 | get_loader | train | def get_loader(module_or_name):
"""Get a PEP 302 "loader" object for module_or_name
If the module or package is accessible via the normal import
mechanism, a wrapper around the relevant part of that machinery
is returned. Returns None if the module cannot be found or imported.
If the named module ... | python | {
"resource": ""
} |
q24416 | find_loader | train | def find_loader(fullname):
"""Find a PEP 302 "loader" object for fullname
If fullname contains dots, path must be the containing package's __path__.
Returns None if the module cannot be found or imported. This function uses
| python | {
"resource": ""
} |
q24417 | get_data | train | def get_data(package, resource):
"""Get a resource from a package.
This is a wrapper round the PEP 302 loader get_data API. The package
argument should be the name of a package, in standard module format
(foo.bar). The resource argument should be in the form of a relative
filename, using '/' as the... | python | {
"resource": ""
} |
q24418 | invoke | train | def invoke(invocation):
"""
Find a Planner subclass corresnding to `invocation` and use it to invoke
the module.
:param Invocation invocation:
:returns:
Module return dict.
:raises ansible.errors.AnsibleError:
Unrecognized/unsupported module type.
"""
(invocation.module_... | python | {
"resource": ""
} |
q24419 | getenv_int | train | def getenv_int(key, default=0):
"""
Get an integer-valued environment variable `key`, if it exists and parses
as an integer, otherwise return `default`.
"""
| python | {
"resource": ""
} |
q24420 | MuxProcess.start | train | def start(cls, _init_logging=True):
"""
Arrange for the subprocess to be started, if it is not already running.
The parent process picks a UNIX socket path the child will use prior to
fork, creates a socketpair used essentially as a semaphore, then blocks
waiting for the child t... | python | {
"resource": ""
} |
q24421 | MuxProcess._setup_master | train | def _setup_master(self):
"""
Construct a Router, Broker, and mitogen.unix listener
"""
self.broker = mitogen.master.Broker(install_watcher=False)
self.router = mitogen.master.Router(
broker=self.broker,
max_message_size=4096 * 1048576,
)
se... | python | {
"resource": ""
} |
q24422 | MuxProcess._setup_services | train | def _setup_services(self):
"""
Construct a ContextService and a thread to service requests for it
arriving from worker processes.
"""
self.pool = mitogen.service.Pool(
router=self.router,
services=[
mitogen.service.FileService(router=self.r... | python | {
"resource": ""
} |
q24423 | MuxProcess.on_broker_exit | train | def on_broker_exit(self):
"""
Respond to the broker thread about to exit by sending SIGTERM to
ourself. In future this should gracefully join the pool, but TERM is
fine for now.
"""
if not self.profiling:
# In normal operation we presently kill the process bec... | python | {
"resource": ""
} |
q24424 | utf8 | train | def utf8(s):
"""
Coerce an object to bytes if it is Unicode.
"""
| python | {
"resource": ""
} |
q24425 | EnvironmentFileWatcher._remove_existing | train | def _remove_existing(self):
"""
When a change is detected, remove keys that existed in the old file.
"""
for key in self._keys:
if key in os.environ:
| python | {
"resource": ""
} |
q24426 | ProgramRunner._get_program | train | def _get_program(self):
"""
Fetch the module binary from the master if necessary.
"""
return | python | {
"resource": ""
} |
q24427 | ProgramRunner.revert | train | def revert(self):
"""
Delete the temporary program file.
"""
if self.program_fp:
| python | {
"resource": ""
} |
q24428 | ScriptRunner._rewrite_source | train | def _rewrite_source(self, s):
"""
Mutate the source according to the per-task parameters.
"""
# While Ansible rewrites the #! using ansible_*_interpreter, it is
# never actually used to execute the script, instead it is a shell
# fragment consumed by shell/__init__.py::bu... | python | {
"resource": ""
} |
q24429 | _connect_ssh | train | def _connect_ssh(spec):
"""
Return ContextService arguments for an SSH connection.
"""
if C.HOST_KEY_CHECKING:
check_host_keys = 'enforce'
else:
check_host_keys = 'ignore'
# #334: tilde-expand private_key_file to avoid implementation difference
# between Python and OpenSSH.
... | python | {
"resource": ""
} |
q24430 | _connect_docker | train | def _connect_docker(spec):
"""
Return ContextService arguments for a Docker connection.
"""
return {
'method': 'docker',
'kwargs': {
'username': spec.remote_user(),
'container': spec.remote_addr(),
'python_path': spec.python_path(),
| python | {
"resource": ""
} |
q24431 | _connect_kubectl | train | def _connect_kubectl(spec):
"""
Return ContextService arguments for a Kubernetes connection.
"""
return {
'method': 'kubectl',
'kwargs': {
'pod': spec.remote_addr(),
'python_path': spec.python_path(),
'connect_timeout': spec.ansible_ssh_timeout() or sp... | python | {
"resource": ""
} |
q24432 | _connect_jail | train | def _connect_jail(spec):
"""
Return ContextService arguments for a FreeBSD jail connection.
"""
return {
'method': 'jail',
'kwargs': {
'username': spec.remote_user(),
'container': spec.remote_addr(),
'python_path': spec.python_path(),
| python | {
"resource": ""
} |
q24433 | _connect_lxc | train | def _connect_lxc(spec):
"""
Return ContextService arguments for an LXC Classic container connection.
"""
return {
'method': 'lxc',
'kwargs': {
'container': spec.remote_addr(),
'python_path': spec.python_path(),
| python | {
"resource": ""
} |
q24434 | _connect_lxd | train | def _connect_lxd(spec):
"""
Return ContextService arguments for an LXD container connection.
"""
return {
'method': 'lxd',
'kwargs': {
'container': spec.remote_addr(),
'python_path': spec.python_path(),
'lxc_path': spec.mitogen_lxc_path(),
| python | {
"resource": ""
} |
q24435 | _connect_setns | train | def _connect_setns(spec, kind=None):
"""
Return ContextService arguments for a mitogen_setns connection.
"""
return {
'method': 'setns',
'kwargs': {
'container': spec.remote_addr(),
'username': spec.remote_user(),
'python_path': spec.python_path(),
... | python | {
"resource": ""
} |
q24436 | _connect_su | train | def _connect_su(spec):
"""
Return ContextService arguments for su as a become method.
"""
return {
'method': 'su',
'enable_lru': True,
'kwargs': {
'username': spec.become_user(),
'password': spec.become_pass(),
| python | {
"resource": ""
} |
q24437 | _connect_sudo | train | def _connect_sudo(spec):
"""
Return ContextService arguments for sudo as a become method.
"""
return {
'method': 'sudo',
'enable_lru': True,
'kwargs': {
'username': spec.become_user(),
'password': spec.become_pass(),
'python_path': spec.python_... | python | {
"resource": ""
} |
q24438 | _connect_mitogen_su | train | def _connect_mitogen_su(spec):
"""
Return ContextService arguments for su as a first class connection.
"""
return {
'method': 'su',
'kwargs': {
'username': spec.remote_user(),
'password': spec.password(),
'python_path': spec.python_path(),
| python | {
"resource": ""
} |
q24439 | _connect_mitogen_sudo | train | def _connect_mitogen_sudo(spec):
"""
Return ContextService arguments for sudo as a first class connection.
"""
return {
'method': 'sudo',
'kwargs': {
'username': spec.remote_user(),
'password': spec.password(),
'python_path': spec.python_path(),
| python | {
"resource": ""
} |
q24440 | _connect_mitogen_doas | train | def _connect_mitogen_doas(spec):
"""
Return ContextService arguments for doas as a first class connection.
"""
return {
'method': 'doas',
'kwargs': {
'username': spec.remote_user(),
'password': spec.password(),
'python_path': spec.python_path(),
| python | {
"resource": ""
} |
q24441 | Connection.on_action_run | train | def on_action_run(self, task_vars, delegate_to_hostname, loader_basedir):
"""
Invoked by ActionModuleMixin to indicate a new task is about to start
executing. We use the opportunity to grab relevant bits from the
task-specific data.
:param dict task_vars:
Task variab... | python | {
"resource": ""
} |
q24442 | Connection.get_task_var | train | def get_task_var(self, key, default=None):
"""
Fetch the value of a task variable related to connection configuration,
or, if delegate_to is active, fetch the same variable via HostVars for
the delegated-to machine.
When running with delegate_to, Ansible tasks have variables ass... | python | {
"resource": ""
} |
q24443 | Connection._connect_broker | train | def _connect_broker(self):
"""
Establish a reference to the Broker, Router and parent context used for
connections.
"""
if not self.broker:
| python | {
"resource": ""
} |
q24444 | Connection._build_stack | train | def _build_stack(self):
"""
Construct a list of dictionaries representing the connection
configuration between the controller and the target. This is
additionally used by the integration tests "mitogen_get_stack" action
to fetch the would-be connection configuration.
"""
... | python | {
"resource": ""
} |
q24445 | Connection._connect_stack | train | def _connect_stack(self, stack):
"""
Pass `stack` to ContextService, requesting a copy of the context object
representing the last tuple element. If no connection exists yet,
ContextService will recursively establish it before returning it or
throwing an error.
See :meth... | python | {
"resource": ""
} |
q24446 | Connection._connect | train | def _connect(self):
"""
Establish a connection to the master process's UNIX listener socket,
constructing a mitogen.master.Router to communicate with the master,
and a mitogen.parent.Context to represent it.
Depending on the original transport we should emulate, trigger one of
... | python | {
"resource": ""
} |
q24447 | Connection.reset | train | def reset(self):
"""
Explicitly terminate the connection to the remote host. This discards
any local state we hold for the connection, returns the Connection to
the 'disconnected' state, and informs ContextService the connection is
bad somehow, and should be shut down and discard... | python | {
"resource": ""
} |
q24448 | Connection.spawn_isolated_child | train | def spawn_isolated_child(self):
"""
Fork or launch a new child off the target context.
:returns:
| python | {
"resource": ""
} |
q24449 | write_all | train | def write_all(fd, s, deadline=None):
"""Arrange for all of bytestring `s` to be written to the file descriptor
`fd`.
:param int fd:
File descriptor to write to.
:param bytes s:
Bytestring to write to file descriptor.
:param float deadline:
If not :data:`None`, absolute UNIX ... | python | {
"resource": ""
} |
q24450 | _upgrade_broker | train | def _upgrade_broker(broker):
"""
Extract the poller state from Broker and replace it with the industrial
strength poller for this OS. Must run on the Broker thread.
"""
# This function is deadly! The act of calling start_receive() generates log
# messages which must be silenced as the upgrade pr... | python | {
"resource": ""
} |
q24451 | stream_by_method_name | train | def stream_by_method_name(name):
"""
Given the name of a Mitogen connection method, import its implementation
module and return its Stream subclass.
"""
if name == | python | {
"resource": ""
} |
q24452 | PartialZlib.append | train | def append(self, s):
"""
Append the bytestring `s` to the compressor state and return the
final compressed output.
"""
if self._compressor is None:
return zlib.compress(self.s + s, 9)
else:
| python | {
"resource": ""
} |
q24453 | Stream.construct | train | def construct(self, max_message_size, remote_name=None, python_path=None,
debug=False, connect_timeout=None, profiling=False,
unidirectional=False, old_router=None, **kwargs):
"""Get the named context running on the local machine, creating it if
it does not exist."""
... | python | {
"resource": ""
} |
q24454 | Stream.on_shutdown | train | def on_shutdown(self, broker):
"""Request the slave gracefully shut itself down."""
LOG.debug('%r closing CALL_FUNCTION channel', self)
self._send(
mitogen.core.Message(
| python | {
"resource": ""
} |
q24455 | Stream._reap_child | train | def _reap_child(self):
"""
Reap the child process during disconnection.
"""
if self.detached and self.child_is_immediate_subprocess:
LOG.debug('%r: immediate child is detached, won\'t reap it', self)
return
if self.profiling:
LOG.info('%r: won... | python | {
"resource": ""
} |
q24456 | Stream._adorn_eof_error | train | def _adorn_eof_error(self, e):
"""
Used by subclasses to provide additional information in the case | python | {
"resource": ""
} |
q24457 | CallChain.reset | train | def reset(self):
"""
Instruct the target to forget any related exception.
"""
if not self.chain_id:
return
saved, self.chain_id = self.chain_id, None
try:
| python | {
"resource": ""
} |
q24458 | Context.shutdown | train | def shutdown(self, wait=False):
"""
Arrange for the context to receive a ``SHUTDOWN`` message, triggering
graceful shutdown.
Due to a lack of support for timers, no attempt is made yet to force
terminate a hung context using this method. This will be fixed shortly.
:par... | python | {
"resource": ""
} |
q24459 | RouteMonitor._send_one | train | def _send_one(self, stream, handle, target_id, name):
"""
Compose and send an update message on a stream.
:param mitogen.core.Stream stream:
Stream to send it on.
:param int handle:
:data:`mitogen.core.ADD_ROUTE` or :data:`mitogen.core.DEL_ROUTE`
:param i... | python | {
"resource": ""
} |
q24460 | RouteMonitor._propagate_up | train | def _propagate_up(self, handle, target_id, name=None):
"""
In a non-master context, propagate an update towards the master.
:param int handle:
:data:`mitogen.core.ADD_ROUTE` or :data:`mitogen.core.DEL_ROUTE`
:param int target_id:
ID of the connecting or disconnec... | python | {
"resource": ""
} |
q24461 | RouteMonitor._on_stream_disconnect | train | def _on_stream_disconnect(self, stream):
"""
Respond to disconnection of a local stream by propagating DEL_ROUTE for
any contexts we know were attached to it.
"""
# During a stream crash it is possible for disconnect signal to fire
# twice, in which case ignore the second... | python | {
"resource": ""
} |
q24462 | Router.get_streams | train | def get_streams(self):
"""
Return a snapshot of all streams in existence at time of call.
"""
self._write_lock.acquire()
try:
| python | {
"resource": ""
} |
q24463 | reset_logging_framework | train | def reset_logging_framework():
"""
After fork, ensure any logging.Handler locks are recreated, as a variety of
threads in the parent may have been using the logging package at the moment
of fork.
It is not possible to solve this problem in general; see
https://github.com/dw/mitogen/issues/150 f... | python | {
"resource": ""
} |
q24464 | on_fork | train | def on_fork():
"""
Should be called by any program integrating Mitogen each time the process
is forked, in the context of the new child.
"""
reset_logging_framework() # Must be first!
fixup_prngs()
mitogen.core.Latch._on_fork()
mitogen.core.Side._on_fork()
| python | {
"resource": ""
} |
q24465 | main | train | def main(log_level='INFO', profiling=_default_profiling):
"""
Convenience decorator primarily useful for writing discardable test
scripts.
In the master process, when `func` is defined in the :mod:`__main__`
module, arranges for `func(router)` to be invoked immediately, with
:py:class:`mitogen.... | python | {
"resource": ""
} |
q24466 | get_small_file | train | def get_small_file(context, path):
"""
Basic in-memory caching module fetcher. This generates one roundtrip for
every previously unseen file, so it is only a temporary solution.
:param context:
Context we should direct FileService requests to. For now (and probably
forever) this is just... | python | {
"resource": ""
} |
q24467 | spawn_isolated_child | train | def spawn_isolated_child(econtext):
"""
For helper functions executed in the fork parent context, arrange for
the context's router to be upgraded as necessary and for a new child to be
prepared.
The actual fork occurs from the 'virginal fork parent', which does not have
any Ansible modules load... | python | {
"resource": ""
} |
q24468 | write_path | train | def write_path(path, s, owner=None, group=None, mode=None,
utimes=None, sync=False):
"""
Writes bytes `s` to a filesystem `path`.
"""
path = os.path.abspath(path)
fd, tmp_path = tempfile.mkstemp(suffix='.tmp',
prefix='.ansible_mitogen_transfer-',
... | python | {
"resource": ""
} |
q24469 | AsyncRunner._update | train | def _update(self, dct):
"""
Update an async job status file.
"""
LOG.info('%r._update(%r, %r)', self, self.job_id, dct)
dct.setdefault('ansible_job_id', self.job_id)
| python | {
"resource": ""
} |
q24470 | ActionModuleMixin._make_tmp_path | train | def _make_tmp_path(self, remote_user=None):
"""
Create a temporary subdirectory as a child of the temporary directory
managed by the remote interpreter.
"""
LOG.debug('_make_tmp_path(remote_user=%r)', remote_user)
path = self._generate_tmp_path() | python | {
"resource": ""
} |
q24471 | ActionModuleMixin._fixup_perms2 | train | def _fixup_perms2(self, remote_paths, remote_user=None, execute=True):
"""
Mitogen always executes ActionBase helper methods in the context of the
target user account, so it is never necessary to modify permissions
except to ensure the execute bit is set if requested.
"""
... | python | {
"resource": ""
} |
q24472 | minimize_source | train | def minimize_source(source):
"""Remove comments and docstrings from Python `source`, preserving line
numbers and syntax of empty blocks.
:param str source:
The source to minimize.
| python | {
"resource": ""
} |
q24473 | strip_comments | train | def strip_comments(tokens):
"""Drop comment tokens from a `tokenize` stream.
Comments on lines 1-2 are kept, to preserve hashbang and encoding.
Trailing whitespace is remove from all lines.
"""
prev_typ = None
prev_end_col = 0
for typ, tok, (start_row, start_col), (end_row, end_col), line i... | python | {
"resource": ""
} |
q24474 | strip_docstrings | train | def strip_docstrings(tokens):
"""Replace docstring tokens with NL tokens in a `tokenize` stream.
Any STRING token not part of an expression is deemed a docstring.
Indented docstrings are not yet recognised.
"""
stack = []
state = 'wait_string'
for t in tokens:
typ = t[0]
if ... | python | {
"resource": ""
} |
q24475 | reindent | train | def reindent(tokens, indent=' '):
"""Replace existing indentation in a token steam, with `indent`.
"""
old_levels = []
old_level = 0
new_level = 0
for typ, tok, (start_row, start_col), (end_row, end_col), line in tokens:
if typ == tokenize.INDENT:
old_levels.append(old_level)... | python | {
"resource": ""
} |
q24476 | get_file_contents | train | def get_file_contents(path):
"""
Get the contents of a file.
"""
with open(path, 'rb') as fp:
# mitogen.core.Blob() is a bytes subclass with a repr() that returns a
# summary of the blob, rather than the raw blob data. This makes
# logging | python | {
"resource": ""
} |
q24477 | streamy_download_file | train | def streamy_download_file(context, path):
"""
Fetch a file from the FileService hosted by `context`.
"""
bio = io.BytesIO()
# FileService.get() is not actually an exposed service method, it's | python | {
"resource": ""
} |
q24478 | get_password_hash | train | def get_password_hash(username):
"""
Fetch a user's password hash.
"""
try:
h = spwd.getspnam(username)
except KeyError:
return None
# mitogen.core.Secret() is a Unicode subclass with a repr() that | python | {
"resource": ""
} |
q24479 | work_on_machine | train | def work_on_machine(context):
"""
Do stuff to a remote context.
"""
print("Created context. Context ID is", context.context_id)
# You don't need to understand any/all of this, but it's helpful to grok
# the whole chain:
# - Context.call() is a light wrapper around .call_async(), the wrappe... | python | {
"resource": ""
} |
q24480 | parse_script_interpreter | train | def parse_script_interpreter(source):
"""
Parse the script interpreter portion of a UNIX hashbang using the rules
Linux uses.
:param str source: String like "/usr/bin/env python".
:returns:
Tuple of `(interpreter, arg)`, where `intepreter` is the script
interpreter and `arg` is its... | python | {
"resource": ""
} |
q24481 | quantize | train | def quantize(image, bits_per_channel=None):
'''Reduces the number of bits per channel in the given image.'''
if bits_per_channel is None:
bits_per_channel = 6
| python | {
"resource": ""
} |
q24482 | pack_rgb | train | def pack_rgb(rgb):
'''Packs a 24-bit RGB triples into a single integer,
works on both arrays and tuples.'''
orig_shape = None
if isinstance(rgb, np.ndarray):
assert rgb.shape[-1] == 3
orig_shape = rgb.shape[:-1]
else:
assert len(rgb) == 3
rgb = np.array(rgb)
rgb | python | {
"resource": ""
} |
q24483 | unpack_rgb | train | def unpack_rgb(packed):
'''Unpacks a single integer or array of integers into one or more
24-bit RGB values.
'''
orig_shape = None
if isinstance(packed, np.ndarray):
assert packed.dtype == int
orig_shape = packed.shape
packed = packed.reshape((-1, 1))
rgb = ((packed >> 1... | python | {
"resource": ""
} |
q24484 | get_bg_color | train | def get_bg_color(image, bits_per_channel=None):
'''Obtains the background color from an image or array of RGB colors
by grouping similar colors into bins and finding the most frequent
one.
| python | {
"resource": ""
} |
q24485 | rgb_to_sv | train | def rgb_to_sv(rgb):
'''Convert an RGB image or array of RGB colors to saturation and
value, returning each one as a separate 32-bit floating point array or
value.
'''
if not isinstance(rgb, np.ndarray):
rgb = np.array(rgb)
axis = len(rgb.shape)-1
cmax = rgb.max(axis=axis).astype(np.float... | python | {
"resource": ""
} |
q24486 | postprocess | train | def postprocess(output_filename, options):
'''Runs the postprocessing command on the file provided.'''
assert options.postprocess_cmd
base, _ = os.path.splitext(output_filename)
post_filename = base + options.postprocess_ext
cmd = options.postprocess_cmd
cmd = cmd.replace('%i', output_filena... | python | {
"resource": ""
} |
q24487 | load | train | def load(input_filename):
'''Load an image with Pillow and convert it to numpy array. Also
returns the image DPI in x and y as a tuple.'''
try:
pil_img = Image.open(input_filename)
except IOError:
sys.stderr.write('warning: error opening {}\n'.format(
input_filename))
r... | python | {
"resource": ""
} |
q24488 | sample_pixels | train | def sample_pixels(img, options):
'''Pick a fixed percentage of pixels in the image, returned in random
order.'''
pixels = img.reshape((-1, 3))
num_pixels = pixels.shape[0]
| python | {
"resource": ""
} |
q24489 | get_fg_mask | train | def get_fg_mask(bg_color, samples, options):
'''Determine whether each pixel in a set of samples is foreground by
comparing it to the background color. A pixel is classified as a
foreground pixel if either its value or saturation | python | {
"resource": ""
} |
q24490 | get_palette | train | def get_palette(samples, options, return_mask=False, kmeans_iter=40):
'''Extract the palette for the set of sampled RGB values. The first
palette entry is always the background color; the rest are determined
from foreground pixels by running K-means clustering. Returns the
palette, as well as a mask corresponding ... | python | {
"resource": ""
} |
q24491 | apply_palette | train | def apply_palette(img, palette, options):
'''Apply the pallete to the given image. The first step is to set all
background pixels to the background color; then, nearest-neighbor
matching is used to map each foreground color to the closest one in
the palette.
'''
if not options.quiet:
print(' app... | python | {
"resource": ""
} |
q24492 | get_global_palette | train | def get_global_palette(filenames, options):
'''Fetch the global palette for a series of input files by merging
their samples together into one large array.
'''
input_filenames = []
all_samples = []
if not options.quiet:
print('building global palette...')
for input_filename in file... | python | {
"resource": ""
} |
q24493 | emit_pdf | train | def emit_pdf(outputs, options):
'''Runs the PDF conversion command to generate the PDF.'''
cmd = options.pdf_cmd
cmd = cmd.replace('%o', options.pdfname)
if len(outputs) > 2:
cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...']))
else:
cmd_print = cmd.replace('%i', ' '.join... | python | {
"resource": ""
} |
q24494 | notescan_main | train | def notescan_main(options):
'''Main function for this program when run as script.'''
filenames = get_filenames(options)
outputs = []
do_global = options.global_palette and len(filenames) > 1
if do_global:
filenames, palette = get_global_palette(filenames, options)
do_postprocess = ... | python | {
"resource": ""
} |
q24495 | generic_type_name | train | def generic_type_name(v):
"""
Return a descriptive type name that isn't Python specific. For example, an
int type will return 'integer' rather than 'int'.
"""
if isinstance(v, AstExampleRef):
return "reference"
elif isinstance(v, numbers.Integral):
# Must come before real numbers... | python | {
"resource": ""
} |
q24496 | unwrap | train | def unwrap(data_type):
"""
Convenience method to unwrap all Aliases and Nullables from around a
DataType. This checks for nullable wrapping aliases, as well as aliases
wrapping nullables.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool, bool]: The... | python | {
"resource": ""
} |
q24497 | get_custom_annotations_for_alias | train | def get_custom_annotations_for_alias(data_type):
"""
Given a Stone data type, returns all custom annotations applied to it.
"""
# annotations can only be applied to Aliases, but they can be wrapped in
# Nullable. also, Aliases pointing to other Aliases don't automatically
# inherit their custom ... | python | {
"resource": ""
} |
q24498 | get_custom_annotations_recursive | train | def get_custom_annotations_recursive(data_type):
"""
Given a Stone data type, returns all custom annotations applied to any of
its memebers, as well as submembers, ..., to an arbitrary depth.
"""
# because Stone structs can contain references to themselves (or otherwise
# be cyclical), we need o... | python | {
"resource": ""
} |
q24499 | UserDefined.has_documented_type_or_fields | train | def has_documented_type_or_fields(self, include_inherited_fields=False):
"""Returns whether this type, or any of its fields, are documented.
Use this when deciding whether to create a block of documentation for
this type.
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.