_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q278700 | handle_jobs | test | async def handle_jobs(job_handler, host, port, *, loop):
"""
Connects to the remote master and continuously receives calls, executes
them, then returns a response until interrupted.
"""
try:
try:
reader, writer = await asyncio.open_connection(host, port, loop=loop)
exce... | python | {
"resource": ""
} |
q278701 | worker_main | test | def worker_main(job_handler, host, port):
"""
Starts an asyncio event loop to connect to the master and run jobs.
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
loop.run_until_complete(handle_jobs(job_handler, host, port, loop=loop))
loop.close() | python | {
"resource": ""
} |
q278702 | run_worker_pool | test | def run_worker_pool(job_handler, host="localhost", port=48484,
*, max_workers=None):
"""
Runs a pool of workers which connect to a remote HighFive master and begin
executing calls.
"""
if max_workers is None:
max_workers = multiprocessing.cpu_count()
processes = [... | python | {
"resource": ""
} |
q278703 | CompanyDetailCompany.classification | test | def classification(self, classification):
"""
Sets the classification of this CompanyDetailCompany.
Classification of Company
:param classification: The classification of this CompanyDetailCompany.
:type: str
"""
allowed_values = ["Public Limited Indian Non-Gover... | python | {
"resource": ""
} |
q278704 | LWLink._send_message | test | def _send_message(self, msg):
"""Add message to queue and start processing the queue."""
LWLink.the_queue.put_nowait(msg)
if LWLink.thread is None or not LWLink.thread.isAlive():
LWLink.thread = Thread(target=self._send_queue)
LWLink.thread.start() | python | {
"resource": ""
} |
q278705 | LWLink.turn_on_light | test | def turn_on_light(self, device_id, name):
"""Create the message to turn light on."""
msg = "!%sFdP32|Turn On|%s" % (device_id, name)
self._send_message(msg) | python | {
"resource": ""
} |
q278706 | LWLink.turn_on_switch | test | def turn_on_switch(self, device_id, name):
"""Create the message to turn switch on."""
msg = "!%sF1|Turn On|%s" % (device_id, name)
self._send_message(msg) | python | {
"resource": ""
} |
q278707 | LWLink.turn_on_with_brightness | test | def turn_on_with_brightness(self, device_id, name, brightness):
"""Scale brightness from 0..255 to 1..32."""
brightness_value = round((brightness * 31) / 255) + 1
# F1 = Light on and F0 = light off. FdP[0..32] is brightness. 32 is
# full. We want that when turning the light on.
m... | python | {
"resource": ""
} |
q278708 | LWLink.turn_off | test | def turn_off(self, device_id, name):
"""Create the message to turn light or switch off."""
msg = "!%sF0|Turn Off|%s" % (device_id, name)
self._send_message(msg) | python | {
"resource": ""
} |
q278709 | LWLink._send_queue | test | def _send_queue(self):
"""If the queue is not empty, process the queue."""
while not LWLink.the_queue.empty():
self._send_reliable_message(LWLink.the_queue.get_nowait()) | python | {
"resource": ""
} |
q278710 | LWLink._send_reliable_message | test | def _send_reliable_message(self, msg):
"""Send msg to LightwaveRF hub."""
result = False
max_retries = 15
trans_id = next(LWLink.transaction_id)
msg = "%d,%s" % (trans_id, msg)
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \
as... | python | {
"resource": ""
} |
q278711 | create_adapter | test | def create_adapter(cmph, ffi, obj):
""" Generates a wrapped adapter for the given object
Parameters
----------
obj : list, buffer, array, or file
Raises
------
ValueError
If presented with an object that cannot be adapted
Returns
-------
CMPH capable adapter
"""
... | python | {
"resource": ""
} |
q278712 | YearlyFinancials.nature | test | def nature(self, nature):
"""
Sets the nature of this YearlyFinancials.
Nature of the balancesheet
:param nature: The nature of this YearlyFinancials.
:type: str
"""
allowed_values = ["STANDALONE"]
if nature not in allowed_values:
raise ValueE... | python | {
"resource": ""
} |
q278713 | Section.update_ | test | def update_(self, sct_dict, conf_arg=True):
"""Update values of configuration section with dict.
Args:
sct_dict (dict): dict indexed with option names. Undefined
options are discarded.
conf_arg (bool): if True, only options that can be set in a config
... | python | {
"resource": ""
} |
q278714 | Section.reset_ | test | def reset_(self):
"""Restore default values of options in this section."""
for opt, meta in self.defaults_():
self[opt] = meta.default | python | {
"resource": ""
} |
q278715 | ConfigurationManager.set_config_files_ | test | def set_config_files_(self, *config_files):
"""Set the list of config files.
Args:
config_files (pathlike): path of config files, given in the order
of reading.
"""
self._config_files = tuple(pathlib.Path(path) for path in config_files) | python | {
"resource": ""
} |
q278716 | ConfigurationManager.opt_vals_ | test | def opt_vals_(self):
"""Iterator over sections, option names, and option values.
This iterator is also implemented at the section level. The two loops
produce the same output::
for sct, opt, val in conf.opt_vals_():
print(sct, opt, val)
for sct in conf.... | python | {
"resource": ""
} |
q278717 | ConfigurationManager.defaults_ | test | def defaults_(self):
"""Iterator over sections, option names, and option metadata.
This iterator is also implemented at the section level. The two loops
produce the same output::
for sct, opt, meta in conf.defaults_():
print(sct, opt, meta.default)
for ... | python | {
"resource": ""
} |
q278718 | ConfigurationManager.create_config_ | test | def create_config_(self, index=0, update=False):
"""Create config file.
Create config file in :attr:`config_files_[index]`.
Parameters:
index(int): index of config file.
update (bool): if set to True and :attr:`config_files_` already
exists, its content ... | python | {
"resource": ""
} |
q278719 | ConfigurationManager.update_ | test | def update_(self, conf_dict, conf_arg=True):
"""Update values of configuration options with dict.
Args:
conf_dict (dict): dict of dict indexed with section and option
names.
conf_arg (bool): if True, only options that can be set in a config
file a... | python | {
"resource": ""
} |
q278720 | ConfigurationManager.read_config_ | test | def read_config_(self, cfile):
"""Read a config file and set config values accordingly.
Returns:
dict: content of config file.
"""
if not cfile.exists():
return {}
try:
conf_dict = toml.load(str(cfile))
except toml.TomlDecodeError:
... | python | {
"resource": ""
} |
q278721 | ConfigurationManager.read_configs_ | test | def read_configs_(self):
"""Read config files and set config values accordingly.
Returns:
(dict, list, list): respectively content of files, list of
missing/empty files and list of files for which a parsing error
arised.
"""
if not self.config_files_:... | python | {
"resource": ""
} |
q278722 | _names | test | def _names(section, option):
"""List of cli strings for a given option."""
meta = section.def_[option]
action = meta.cmd_kwargs.get('action')
if action is internal.Switch:
names = ['-{}'.format(option), '+{}'.format(option)]
if meta.shortname is not None:
names.append('-{}'.f... | python | {
"resource": ""
} |
q278723 | CLIManager.sections_list | test | def sections_list(self, cmd=None):
"""List of config sections used by a command.
Args:
cmd (str): command name, set to ``None`` or ``''`` for the bare
command.
Returns:
list of str: list of configuration sections used by that command.
"""
... | python | {
"resource": ""
} |
q278724 | CLIManager._cmd_opts_solver | test | def _cmd_opts_solver(self, cmd_name):
"""Scan options related to one command and enrich _opt_cmds."""
sections = self.sections_list(cmd_name)
cmd_dict = self._opt_cmds[cmd_name] if cmd_name else self._opt_bare
for sct in reversed(sections):
for opt, opt_meta in self._conf[sct... | python | {
"resource": ""
} |
q278725 | CLIManager._add_options_to_parser | test | def _add_options_to_parser(self, opts_dict, parser):
"""Add options to a parser."""
store_bool = ('store_true', 'store_false')
for opt, sct in opts_dict.items():
meta = self._conf[sct].def_[opt]
kwargs = copy.deepcopy(meta.cmd_kwargs)
action = kwargs.get('acti... | python | {
"resource": ""
} |
q278726 | CLIManager._build_parser | test | def _build_parser(self):
"""Build command line argument parser.
Returns:
:class:`argparse.ArgumentParser`: the command line argument parser.
You probably won't need to use it directly. To parse command line
arguments and update the :class:`ConfigurationManager` insta... | python | {
"resource": ""
} |
q278727 | CLIManager.parse_args | test | def parse_args(self, arglist=None):
"""Parse arguments and update options accordingly.
Args:
arglist (list of str): list of arguments to parse. If set to None,
``sys.argv[1:]`` is used.
Returns:
:class:`Namespace`: the argument namespace returned by the
... | python | {
"resource": ""
} |
q278728 | CLIManager._zsh_comp_command | test | def _zsh_comp_command(self, zcf, cmd, grouping, add_help=True):
"""Write zsh _arguments compdef for a given command.
Args:
zcf (file): zsh compdef file.
cmd (str): command name, set to None or '' for bare command.
grouping (bool): group options (zsh>=5.4).
... | python | {
"resource": ""
} |
q278729 | CLIManager.zsh_complete | test | def zsh_complete(self, path, cmd, *cmds, sourceable=False):
"""Write zsh compdef script.
Args:
path (path-like): desired path of the compdef script.
cmd (str): command name that should be completed.
cmds (str): extra command names that should be completed.
... | python | {
"resource": ""
} |
q278730 | CLIManager._bash_comp_command | test | def _bash_comp_command(self, cmd, add_help=True):
"""Build a list of all options for a given command.
Args:
cmd (str): command name, set to None or '' for bare command.
add_help (bool): add an help option.
Returns:
list of str: list of CLI options strings.
... | python | {
"resource": ""
} |
q278731 | CLIManager.bash_complete | test | def bash_complete(self, path, cmd, *cmds):
"""Write bash complete script.
Args:
path (path-like): desired path of the complete script.
cmd (str): command name that should be completed.
cmds (str): extra command names that should be completed.
"""
path... | python | {
"resource": ""
} |
q278732 | start_master | test | async def start_master(host="", port=48484, *, loop=None):
"""
Starts a new HighFive master at the given host and port, and returns it.
"""
loop = loop if loop is not None else asyncio.get_event_loop()
manager = jobs.JobManager(loop=loop)
workers = set()
server = await loop.create_server(
... | python | {
"resource": ""
} |
q278733 | WorkerProtocol.connection_made | test | def connection_made(self, transport):
"""
Called when a remote worker connection has been found. Finishes setting
up the protocol object.
"""
if self._manager.is_closed():
logger.debug("worker tried to connect while manager was closed")
return
lo... | python | {
"resource": ""
} |
q278734 | WorkerProtocol.line_received | test | def line_received(self, line):
"""
Called when a complete line is found from the remote worker. Decodes
a response object from the line, then passes it to the worker object.
"""
response = json.loads(line.decode("utf-8"))
self._worker.response_received(response) | python | {
"resource": ""
} |
q278735 | WorkerProtocol.connection_lost | test | def connection_lost(self, exc):
"""
Called when the connection to the remote worker is broken. Closes the
worker.
"""
logger.debug("worker connection lost")
self._worker.close()
self._workers.remove(self._worker) | python | {
"resource": ""
} |
q278736 | Worker._job_loaded | test | def _job_loaded(self, job):
"""
Called when a job has been found for the worker to run. Sends the job's
RPC to the remote worker.
"""
logger.debug("worker {} found a job".format(id(self)))
if self._closed:
self._manager.return_job(job)
return
... | python | {
"resource": ""
} |
q278737 | Worker.response_received | test | def response_received(self, response):
"""
Called when a response to a job RPC has been received. Decodes the
response and finalizes the result, then reports the result to the
job manager.
"""
if self._closed:
return
assert self._job is not None
... | python | {
"resource": ""
} |
q278738 | Worker.close | test | def close(self):
"""
Closes the worker. No more jobs will be handled by the worker, and any
running job is immediately returned to the job manager.
"""
if self._closed:
return
self._closed = True
if self._job is not None:
self._manager.r... | python | {
"resource": ""
} |
q278739 | Master.run | test | def run(self, job_list):
"""
Runs a job set which consists of the jobs in an iterable job list.
"""
if self._closed:
raise RuntimeError("master is closed")
return self._manager.add_job_set(job_list) | python | {
"resource": ""
} |
q278740 | Master.close | test | def close(self):
"""
Starts closing the HighFive master. The server will be closed and
all queued job sets will be cancelled.
"""
if self._closed:
return
self._closed = True
self._server.close()
self._manager.close()
for worker in se... | python | {
"resource": ""
} |
q278741 | Results._change | test | def _change(self):
"""
Called when a state change has occurred. Waiters are notified that a
change has occurred.
"""
for waiter in self._waiters:
if not waiter.done():
waiter.set_result(None)
self._waiters = [] | python | {
"resource": ""
} |
q278742 | Results.add | test | def add(self, result):
"""
Adds a new result.
"""
assert not self._complete
self._results.append(result)
self._change() | python | {
"resource": ""
} |
q278743 | Results.wait_changed | test | async def wait_changed(self):
"""
Waits until the result set changes. Possible changes can be a result
being added or the result set becoming complete. If the result set is
already completed, this method returns immediately.
"""
if not self.is_complete():
wai... | python | {
"resource": ""
} |
q278744 | JobSet._load_job | test | def _load_job(self):
"""
If there is still a job in the job iterator, loads it and increments
the active job count.
"""
try:
next_job = next(self._jobs)
except StopIteration:
self._on_deck = None
else:
if not isinstance(next_jo... | python | {
"resource": ""
} |
q278745 | JobSet._done | test | def _done(self):
"""
Marks the job set as completed, and notifies all waiting tasks.
"""
self._results.complete()
waiters = self._waiters
for waiter in waiters:
waiter.set_result(None)
self._manager.job_set_done(self) | python | {
"resource": ""
} |
q278746 | JobSet.add_result | test | def add_result(self, result):
"""
Adds the result of a completed job to the result list, then decrements
the active job count. If the job set is already complete, the result is
simply discarded instead.
"""
if self._active_jobs == 0:
return
self._res... | python | {
"resource": ""
} |
q278747 | JobSet.cancel | test | def cancel(self):
"""
Cancels the job set. The job set is immediately finished, and all
queued jobs are discarded.
"""
if self._active_jobs == 0:
return
self._jobs = iter(())
self._on_deck = None
self._return_queue.clear()
self._activ... | python | {
"resource": ""
} |
q278748 | JobSet.wait_done | test | async def wait_done(self):
"""
Waits until the job set is finished. Returns immediately if the job set
is already finished.
"""
if self._active_jobs > 0:
future = self._loop.create_future()
self._waiters.append(future)
await future | python | {
"resource": ""
} |
q278749 | JobManager._distribute_jobs | test | def _distribute_jobs(self):
"""
Distributes jobs from the active job set to any waiting get_job
callbacks.
"""
while (self._active_js.job_available()
and len(self._ready_callbacks) > 0):
job = self._active_js.get_job()
self._job_sources[jo... | python | {
"resource": ""
} |
q278750 | JobManager.add_job_set | test | def add_job_set(self, job_list):
"""
Adds a job set to the manager's queue. If there is no job set running,
it is activated immediately. A new job set handle is returned.
"""
assert not self._closed
results = Results(loop=self._loop)
js = JobSet(job_list, result... | python | {
"resource": ""
} |
q278751 | JobManager.get_job | test | def get_job(self, callback):
"""
Calls the given callback function when a job becomes available.
"""
assert not self._closed
if self._active_js is None or not self._active_js.job_available():
self._ready_callbacks.append(callback)
else:
job = sel... | python | {
"resource": ""
} |
q278752 | JobManager.return_job | test | def return_job(self, job):
"""
Returns a job to its source job set to be run again later.
"""
if self._closed:
return
js = self._job_sources[job]
if len(self._ready_callbacks) > 0:
callback = self._ready_callbacks.popleft()
callback(j... | python | {
"resource": ""
} |
q278753 | JobManager.add_result | test | def add_result(self, job, result):
"""
Adds the result of a job to the results list of the job's source job
set.
"""
if self._closed:
return
js = self._job_sources[job]
del self._job_sources[job]
js.add_result(result) | python | {
"resource": ""
} |
q278754 | JobManager.job_set_done | test | def job_set_done(self, js):
"""
Called when a job set has been completed or cancelled. If the job set
was active, the next incomplete job set is loaded from the job set
queue and is activated.
"""
if self._closed:
return
if self._active_js != js:
... | python | {
"resource": ""
} |
q278755 | JobManager.close | test | def close(self):
"""
Closes the job manager. No more jobs will be assigned, no more job sets
will be added, and any queued or active job sets will be cancelled.
"""
if self._closed:
return
self._closed = True
if self._active_js is not None:
... | python | {
"resource": ""
} |
q278756 | _uniquify | test | def _uniquify(_list):
"""Remove duplicates in a list."""
seen = set()
result = []
for x in _list:
if x not in seen:
result.append(x)
seen.add(x)
return result | python | {
"resource": ""
} |
q278757 | _match_regex | test | def _match_regex(regex, obj):
"""
Returns true if the regex matches the object, or a string in the object
if it is some sort of container.
:param regex: A regex.
:type regex: ``regex``
:param obj: An arbitrary object.
:type object: ``object``
:rtype: ``bool``
"""
if isinstance(... | python | {
"resource": ""
} |
q278758 | get_entries | test | def get_entries(latest, filters, exclude, limit=None):
"""
Lists all available instances.
:param latest: If true, ignores the cache and grabs the latest list.
:type latest: ``bool``
:param filters: Filters to apply to results. A result will only be shown
if it includes all text ... | python | {
"resource": ""
} |
q278759 | get_region | test | def get_region():
"""Use the environment to get the current region"""
global _REGION
if _REGION is None:
region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1"
region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")}
if region_name not in region_dict:
r... | python | {
"resource": ""
} |
q278760 | filter_entries | test | def filter_entries(entries, filters, exclude):
"""
Filters a list of host entries according to the given filters.
:param entries: A list of host entries.
:type entries: [:py:class:`HostEntry`]
:param filters: Regexes that must match a `HostEntry`.
:type filters: [``str``]
:param exclude: Re... | python | {
"resource": ""
} |
q278761 | get_host | test | def get_host(name):
"""
Prints the public dns name of `name`, if it exists.
:param name: The instance name.
:type name: ``str``
"""
f = {'instance-state-name': 'running', 'tag:Name': name}
ec2 = boto.connect_ec2(region=get_region())
rs = ec2.get_all_instances(filters=f)
if len(rs) =... | python | {
"resource": ""
} |
q278762 | HostEntry.from_dict | test | def from_dict(cls, entry_dict):
"""Deserialize a HostEntry from a dictionary.
This is more or less the same as calling
HostEntry(**entry_dict), but is clearer if something is
missing.
:param entry_dict: A dictionary in the format outputted by to_dict().
:type entry_dict... | python | {
"resource": ""
} |
q278763 | HostEntry._get_attrib | test | def _get_attrib(self, attr, convert_to_str=False):
"""
Given an attribute name, looks it up on the entry. Names that
start with ``tags.`` are looked up in the ``tags`` dictionary.
:param attr: Name of attribute to look up.
:type attr: ``str``
:param convert_to_str: Conve... | python | {
"resource": ""
} |
q278764 | HostEntry.sort_by | test | def sort_by(cls, entries, attribute):
"""
Sorts a list of entries by the given attribute.
"""
def key(entry):
return entry._get_attrib(attribute, convert_to_str=True)
return sorted(entries, key=key) | python | {
"resource": ""
} |
q278765 | HostEntry.repr_as_line | test | def repr_as_line(self, additional_columns=None, only_show=None, sep=','):
"""
Returns a representation of the host as a single line, with columns
joined by ``sep``.
:param additional_columns: Columns to show in addition to defaults.
:type additional_columns: ``list`` of ``str``
... | python | {
"resource": ""
} |
q278766 | HostEntry.from_boto_instance | test | def from_boto_instance(cls, instance):
"""
Loads a ``HostEntry`` from a boto instance.
:param instance: A boto instance object.
:type instance: :py:class:`boto.ec2.instanceInstance`
:rtype: :py:class:`HostEntry`
"""
return cls(
name=instance.tags.get... | python | {
"resource": ""
} |
q278767 | HostEntry.matches | test | def matches(self, _filter):
"""
Returns whether the instance matches the given filter text.
:param _filter: A regex filter. If it starts with `<identifier>:`, then
the part before the colon will be used as an attribute
and the part after will be a... | python | {
"resource": ""
} |
q278768 | HostEntry.display | test | def display(self):
"""
Returns the best name to display for this host. Uses the instance
name if available; else just the public IP.
:rtype: ``str``
"""
if isinstance(self.name, six.string_types) and len(self.name) > 0:
return '{0} ({1})'.format(self.name, se... | python | {
"resource": ""
} |
q278769 | HostEntry.render_entries | test | def render_entries(cls, entries, additional_columns=None,
only_show=None, numbers=False):
"""
Pretty-prints a list of entries. If the window is wide enough to
support printing as a table, runs the `print_table.render_table`
function on the table. Otherwise, constru... | python | {
"resource": ""
} |
q278770 | add_timestamp | test | def add_timestamp(logger_class, log_method, event_dict):
''' Attach the event time, as unix epoch '''
event_dict['timestamp'] = calendar.timegm(time.gmtime())
return event_dict | python | {
"resource": ""
} |
q278771 | setup | test | def setup(level='debug', output=None):
''' Hivy formated logger '''
output = output or settings.LOG['file']
level = level.upper()
handlers = [
logbook.NullHandler()
]
if output == 'stdout':
handlers.append(
logbook.StreamHandler(sys.stdout,
... | python | {
"resource": ""
} |
q278772 | logger | test | def logger(name=__name__, output=None, uuid=False, timestamp=False):
''' Configure and return a new logger for hivy modules '''
processors = []
if output == 'json':
processors.append(structlog.processors.JSONRenderer())
if uuid:
processors.append(add_unique_id)
if uuid:
proc... | python | {
"resource": ""
} |
q278773 | setup | test | def setup(title, output='json', timezone=None):
''' Implement celery workers using json and redis '''
timezone = timezone or dna.time_utils._detect_timezone()
broker_url = 'redis://{}:{}/{}'.format(
os.environ.get('BROKER_HOST', 'localhost'),
os.environ.get('BROKER_PORT', 6379),
0
... | python | {
"resource": ""
} |
q278774 | RestfulWorker.get | test | def get(self, worker_id):
''' Return status report '''
code = 200
if worker_id == 'all':
report = {'workers': [{
'id': job,
'report': self._inspect_worker(job)}
for job in self.jobs]
}
elif worker_id in self.jobs:
... | python | {
"resource": ""
} |
q278775 | RestfulWorker.delete | test | def delete(self, worker_id):
''' Stop and remove a worker '''
code = 200
if worker_id in self.jobs:
# NOTE pop it if done ?
self.jobs[worker_id]['worker'].revoke(terminate=True)
report = {
'id': worker_id,
'revoked': True
... | python | {
"resource": ""
} |
q278776 | switch_opt | test | def switch_opt(default, shortname, help_msg):
"""Define a switchable ConfOpt.
This creates a boolean option. If you use it in your CLI, it can be
switched on and off by prepending + or - to its name: +opt / -opt.
Args:
default (bool): the default value of the swith option.
shortname (s... | python | {
"resource": ""
} |
q278777 | config_conf_section | test | def config_conf_section():
"""Define a configuration section handling config file.
Returns:
dict of ConfOpt: it defines the 'create', 'update', 'edit' and 'editor'
configuration options.
"""
config_dict = OrderedDict((
('create',
ConfOpt(None, True, None, {'action': ... | python | {
"resource": ""
} |
q278778 | set_conf_str | test | def set_conf_str(conf, optstrs):
"""Set options from a list of section.option=value string.
Args:
conf (:class:`~loam.manager.ConfigurationManager`): the conf to update.
optstrs (list of str): the list of 'section.option=value' formatted
string.
"""
falsy = ['0', 'no', 'n', ... | python | {
"resource": ""
} |
q278779 | config_cmd_handler | test | def config_cmd_handler(conf, config='config'):
"""Implement the behavior of a subcmd using config_conf_section
Args:
conf (:class:`~loam.manager.ConfigurationManager`): it should contain a
section created with :func:`config_conf_section` function.
config (str): name of the configura... | python | {
"resource": ""
} |
q278780 | create_complete_files | test | def create_complete_files(climan, path, cmd, *cmds, zsh_sourceable=False):
"""Create completion files for bash and zsh.
Args:
climan (:class:`~loam.cli.CLIManager`): CLI manager.
path (path-like): directory in which the config files should be
created. It is created if it doesn't exi... | python | {
"resource": ""
} |
q278781 | render_columns | test | def render_columns(columns, write_borders=True, column_colors=None):
"""
Renders a list of columns.
:param columns: A list of columns, where each column is a list of strings.
:type columns: [[``str``]]
:param write_borders: Whether to write the top and bottom borders.
:type write_borders: ``boo... | python | {
"resource": ""
} |
q278782 | render_row | test | def render_row(num, columns, widths, column_colors=None):
"""
Render the `num`th row of each column in `columns`.
:param num: Which row to render.
:type num: ``int``
:param columns: The list of columns.
:type columns: [[``str``]]
:param widths: The widths of each column.
:type widths: [... | python | {
"resource": ""
} |
q278783 | render_table | test | def render_table(table, write_borders=True, column_colors=None):
"""
Renders a table. A table is a list of rows, each of which is a list
of arbitrary objects. The `.str` method will be called on each element
of the row. Jagged tables are ok; in this case, each row will be expanded
to the maximum row... | python | {
"resource": ""
} |
q278784 | prepare_rows | test | def prepare_rows(table):
"""
Prepare the rows so they're all strings, and all the same length.
:param table: A 2D grid of anything.
:type table: [[``object``]]
:return: A table of strings, where every row is the same length.
:rtype: [[``str``]]
"""
num_columns = max(len(row) for row in... | python | {
"resource": ""
} |
q278785 | color | test | def color(number):
"""
Returns a function that colors a string with a number from 0 to 255.
"""
if supports_256():
template = "\033[38;5;{number}m{text}\033[0m"
else:
template = "\033[{number}m{text}\033[0m"
def _color(text):
if not all([sys.stdout.isatty(), sys.stderr.is... | python | {
"resource": ""
} |
q278786 | get_color_hash | test | def get_color_hash(string, _min=MIN_COLOR_BRIGHT, _max=MAX_COLOR_BRIGHT):
"""
Hashes a string and returns a number between ``min`` and ``max``.
"""
hash_num = int(hashlib.sha1(string.encode('utf-8')).hexdigest()[:6], 16)
_range = _max - _min
num_in_range = hash_num % _range
return color(_min... | python | {
"resource": ""
} |
q278787 | random_color | test | def random_color(_min=MIN_COLOR, _max=MAX_COLOR):
"""Returns a random color between min and max."""
return color(random.randint(_min, _max)) | python | {
"resource": ""
} |
q278788 | get_input | test | def get_input(prompt, default=None, exit_msg='bye!'):
"""
Reads stdin, exits with a message if interrupted, EOF, or a quit message.
:return: The entered input. Converts to an integer if possible.
:rtype: ``str`` or ``int``
"""
try:
response = six.moves.input(prompt)
except (Keyboard... | python | {
"resource": ""
} |
q278789 | check_credentials | test | def check_credentials(username, password):
''' Verify basic http authentification '''
user = models.User.objects(
username=username,
password=password
).first()
return user or None | python | {
"resource": ""
} |
q278790 | check_token | test | def check_token(token):
''' Verify http header token authentification '''
user = models.User.objects(api_key=token).first()
return user or None | python | {
"resource": ""
} |
q278791 | requires_token_auth | test | def requires_token_auth(resource):
'''
Flask decorator protecting ressources using token scheme
'''
@functools.wraps(resource)
def decorated(*args, **kwargs):
''' Check provided token '''
token = flask.request.headers.get('Authorization')
user = check_token(token)
if... | python | {
"resource": ""
} |
q278792 | is_running | test | def is_running(process):
''' `pgrep` returns an error code if no process was found '''
try:
pgrep = sh.Command('/usr/bin/pgrep')
pgrep(process)
flag = True
except sh.ErrorReturnCode_1:
flag = False
return flag | python | {
"resource": ""
} |
q278793 | dynamic_import | test | def dynamic_import(mod_path, obj_name=None):
''' Take a string and return the corresponding module '''
try:
module = __import__(mod_path, fromlist=['whatever'])
except ImportError, error:
raise errors.DynamicImportFailed(
module='.'.join([mod_path, obj_name]), reason=error)
#... | python | {
"resource": ""
} |
q278794 | self_ip | test | def self_ip(public=False):
''' Utility for logbook information injection '''
try:
if public:
data = str(urlopen('http://checkip.dyndns.com/').read())
ip_addr = re.compile(
r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
else:
sock = soc... | python | {
"resource": ""
} |
q278795 | ApiClient.request | test | def request(self, method, url, query_params=None, headers=None,
post_params=None, body=None):
"""
Makes the HTTP request using RESTClient.
"""
if method == "GET":
return self.rest_client.GET(url,
query_params=query_param... | python | {
"resource": ""
} |
q278796 | ApiClient.prepare_post_parameters | test | def prepare_post_parameters(self, post_params=None, files=None):
"""
Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files.
"""
params = {}
if post_params:
param... | python | {
"resource": ""
} |
q278797 | App.serve | test | def serve(self, app_docopt=DEFAULT_DOC, description=''):
''' Configure from cli and run the server '''
exit_status = 0
if isinstance(app_docopt, str):
args = docopt(app_docopt, version=description)
elif isinstance(app_docopt, dict):
args = app_docopt
else... | python | {
"resource": ""
} |
q278798 | WYSIWYGWidget.render | test | def render(self, name, value, attrs=None):
"""Include a hidden input to stored the serialized upload value."""
context = attrs or {}
context.update({'name': name, 'value': value, })
return render_to_string(self.template_name, context) | python | {
"resource": ""
} |
q278799 | stream_command | test | def stream_command(command, formatter=None, write_stdin=None, ignore_empty=False):
"""
Starts `command` in a subprocess. Prints every line the command prints,
prefaced with `description`.
:param command: The bash command to run. Must use fully-qualified paths.
:type command: ``str``
:param form... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.