code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _create_link(self, act_node, name, instance):
"""Creates a link and checks if names are appropriate
"""
act_node._links[name] = instance
act_node._children[name] = instance
full_name = instance.v_full_name
if full_name not in self._root_instance._linked_by:
... | Creates a link and checks if names are appropriate |
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.key... | UTF8 encodes all of the NVP values. |
def predict_survival_function(self, X, times=None):
"""
Predict the survival function for individuals, given their covariates. This assumes that the individual
just entered the study (that is, we do not condition on how long they have already lived for.)
Parameters
----------
... | Predict the survival function for individuals, given their covariates. This assumes that the individual
just entered the study (that is, we do not condition on how long they have already lived for.)
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy a... |
def track_from_file(file_object, filetype, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
"""
Create a track object from a file-like object.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
file_object: a file-like Python object
... | Create a track object from a file-like object.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
file_object: a file-like Python object
filetype: the file type. Supported types include mp3, ogg, wav, m4a, mp4, au
force_upload: skip... |
def guess_labels(self, doc):
"""
return a prediction of label names
"""
if doc.nb_pages <= 0:
return set()
self.label_guesser.total_nb_documents = len(self._docs_by_id.keys())
label_names = self.label_guesser.guess(doc)
labels = set()
for label... | return a prediction of label names |
def do_workers(self, args):
'''list all known workers'''
workers = self.task_master.workers(alive=not args.all)
for k in sorted(workers.iterkeys()):
self.stdout.write('{0} ({1})\n'.format(k, workers[k]))
if args.details:
heartbeat = self.task_master.get_he... | list all known workers |
def addOntology(self):
"""
Adds a new Ontology to this repo.
"""
self._openRepo()
name = self._args.name
filePath = self._getFilePath(self._args.filePath,
self._args.relativePath)
if name is None:
name = getNameFrom... | Adds a new Ontology to this repo. |
def load_data_file(filename, encoding='utf-8'):
"""Load a data file and return it as a list of lines.
Parameters:
filename: The name of the file (no directories included).
encoding: The file encoding. Defaults to utf-8.
"""
data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, f... | Load a data file and return it as a list of lines.
Parameters:
filename: The name of the file (no directories included).
encoding: The file encoding. Defaults to utf-8. |
def _onMessageNotification(self, client, userdata, pahoMessage):
"""
Internal callback for gateway notification messages, parses source device from topic string and
passes the information on to the registered device command callback
"""
try:
note = Notification(pahoMe... | Internal callback for gateway notification messages, parses source device from topic string and
passes the information on to the registered device command callback |
def open_imports(self, imported_definitions):
"""Import the I{imported} WSDLs."""
for imp in self.imports:
imp.load(self, imported_definitions) | Import the I{imported} WSDLs. |
def _get_all_attributes(network):
"""
Get all the complex mode attributes in the network so that they
can be used for mapping to resource scenarios later.
"""
attrs = network.attributes
for n in network.nodes:
attrs.extend(n.attributes)
for l in network.links:
attrs.e... | Get all the complex mode attributes in the network so that they
can be used for mapping to resource scenarios later. |
def list(gandi, domain, zone_id, output, format, limit):
"""List DNS zone records for a domain."""
options = {
'items_per_page': limit,
}
output_keys = ['name', 'type', 'value', 'ttl']
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not... | List DNS zone records for a domain. |
def add_child_catalog(self, catalog_id, child_id):
"""Adds a child to a catalog.
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: AlreadyExists - ``catalog_id`` is already a parent of
``child_id``... | Adds a child to a catalog.
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: AlreadyExists - ``catalog_id`` is already a parent of
``child_id``
raise: NotFound - ``catalog_id`` or ``child_id`` not... |
def _update_field(self, action, field, value, max_tries, tries=0):
"""
Private update_field method. Wrapped by Document.update_field.
Tracks a "tries" var to help limit recursion.
"""
# Refresh our view of the document.
self.fetch()
# Update the field.
ac... | Private update_field method. Wrapped by Document.update_field.
Tracks a "tries" var to help limit recursion. |
def convert_to_spaces(cls, ops, kwargs):
"""For all operands that are merely of type str or int, substitute
LocalSpace objects with corresponding labels:
For a string, just itself, for an int, a string version of that int.
"""
from qnet.algebra.core.hilbert_space_algebra import (
HilbertSpac... | For all operands that are merely of type str or int, substitute
LocalSpace objects with corresponding labels:
For a string, just itself, for an int, a string version of that int. |
def get(self, filename):
"""
Download a distribution archive from the configured Amazon S3 bucket.
:param filename: The filename of the distribution archive (a string).
:returns: The pathname of a distribution archive on the local file
system or :data:`None`.
:... | Download a distribution archive from the configured Amazon S3 bucket.
:param filename: The filename of the distribution archive (a string).
:returns: The pathname of a distribution archive on the local file
system or :data:`None`.
:raises: :exc:`.CacheBackendError` when any un... |
def generate_neuroml2_from_network(nl_model,
nml_file_name=None,
print_summary=True,
seed=1234,
format='xml',
base_dir=None,
... | Generate and save NeuroML2 file (in either XML or HDF5 format) from the
NeuroMLlite description |
def write_list(path_out, image_list):
"""Hepler function to write image list into the file.
The format is as below,
integer_image_index \t float_label_index \t path_to_image
Note that the blank between number and tab is only used for readability.
Parameters
----------
path_out: string
im... | Hepler function to write image list into the file.
The format is as below,
integer_image_index \t float_label_index \t path_to_image
Note that the blank between number and tab is only used for readability.
Parameters
----------
path_out: string
image_list: list |
def tag(self, value):
"""The name of the program that generated the log message.
The tag can only contain alphanumeric
characters. If the tag is longer than {MAX_TAG_LEN} characters
it will be truncated automatically.
"""
if value is None:
value = sys.argv[0... | The name of the program that generated the log message.
The tag can only contain alphanumeric
characters. If the tag is longer than {MAX_TAG_LEN} characters
it will be truncated automatically. |
def get_record(self, msg_id):
"""Get a specific Task Record, by msg_id."""
r = self._records.find_one({'msg_id': msg_id})
if not r:
# r will be '' if nothing is found
raise KeyError(msg_id)
return r | Get a specific Task Record, by msg_id. |
def _non_framed_body_length(header, plaintext_length):
"""Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:r... | Calculates the length of a non-framed message body, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int |
def hdrval(cls):
"""Construct dictionary mapping display column title to
IterationStats entries.
"""
hdrmap = {'Itn': 'Iter', 'X r': 'PrimalRsdl', 'X s': 'DualRsdl',
u('X ρ'): 'Rho', 'D cnstr': 'Cnstr', 'D dlt': 'DeltaD',
u('D η'): 'Eta'}
retu... | Construct dictionary mapping display column title to
IterationStats entries. |
def _merge_nested_if_from_else(self, ifStm: "IfContainer"):
"""
Merge nested IfContarner form else branch to this IfContainer
as elif and else branches
"""
self.elIfs.append((ifStm.cond, ifStm.ifTrue))
self.elIfs.extend(ifStm.elIfs)
self.ifFalse = ifStm.ifFalse | Merge nested IfContarner form else branch to this IfContainer
as elif and else branches |
def dskstl(keywrd, dpval):
"""
Set the value of a specified DSK tolerance or margin parameter.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskstl_c.html
:param keywrd: Code specifying parameter to set.
:type keywrd: int
:param dpval: Value of parameter.
:type dpval: f... | Set the value of a specified DSK tolerance or margin parameter.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskstl_c.html
:param keywrd: Code specifying parameter to set.
:type keywrd: int
:param dpval: Value of parameter.
:type dpval: float
:return: |
def remove(self, member):
"""Remove member."""
if not self.client.zrem(self.name, member):
raise KeyError(member) | Remove member. |
def header_output(self):
'''只输出cookie的key-value字串.
比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129
'''
result = []
for key in self.keys():
result.append(key + '=' + self.get(key).value)
return '; '.join(result) | 只输出cookie的key-value字串.
比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129 |
def as_alias_handler(alias_list):
"""Returns a list of all the names that will be called."""
list_ = list()
for alias in alias_list:
if alias.asname:
list_.append(alias.asname)
else:
list_.append(alias.name)
return list_ | Returns a list of all the names that will be called. |
def loads(cls, data, store_password, try_decrypt_keys=True):
"""
See :meth:`jks.jks.KeyStore.loads`.
:param bytes data: Byte string representation of the keystore to be loaded.
:param str password: Keystore password string
:param bool try_decrypt_keys: Whether to automatically t... | See :meth:`jks.jks.KeyStore.loads`.
:param bytes data: Byte string representation of the keystore to be loaded.
:param str password: Keystore password string
:param bool try_decrypt_keys: Whether to automatically try to decrypt any encountered key entries using the same password
... |
def _get_disk_size(self, device):
'''
Get a size of a disk.
'''
out = __salt__['cmd.run_all']("df {0}".format(device))
if out['retcode']:
msg = "Disk size info error: {0}".format(out['stderr'])
log.error(msg)
raise SIException(msg)
dev... | Get a size of a disk. |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current ind... |
def poll_parser(poll):
"""
Parses a poll object
"""
if __is_deleted(poll):
return deleted_parser(poll)
if poll['type'] not in poll_types:
raise Exception('Not a poll type')
return Poll(
poll['id'],
poll['by'],
__check_key('kids', poll), # poll and pollopt... | Parses a poll object |
def get_css(self):
""" Fetches and returns stylesheet file path or contents, for both
print and screen contexts, depending if we want a standalone
presentation or not.
"""
css = {}
print_css = os.path.join(self.theme_dir, 'css', 'print.css')
if not os.pa... | Fetches and returns stylesheet file path or contents, for both
print and screen contexts, depending if we want a standalone
presentation or not. |
def load_toml_validator_config(filename):
"""Returns a ValidatorConfig created by loading a TOML file from the
filesystem.
"""
if not os.path.exists(filename):
LOGGER.info(
"Skipping validator config loading from non-existent config file:"
" %s", filename)
return ... | Returns a ValidatorConfig created by loading a TOML file from the
filesystem. |
def open_file(self, fname, external=False):
"""
Open filename with the appropriate application
Redirect to the right widget (txt -> editor, spydata -> workspace, ...)
or open file outside Spyder (if extension is not supported)
"""
fname = to_text_string(fname)
... | Open filename with the appropriate application
Redirect to the right widget (txt -> editor, spydata -> workspace, ...)
or open file outside Spyder (if extension is not supported) |
def round(self, value_array):
"""
If value falls within bounds, just return it
otherwise return min or max, whichever is closer to the value
Assumes an 1d array with a single element as an input.
"""
min_value = self.domain[0]
max_value = self.domain[1]
... | If value falls within bounds, just return it
otherwise return min or max, whichever is closer to the value
Assumes an 1d array with a single element as an input. |
def get_binfo(self):
"""
Fetch a node's build information.
node - the node whose sources will be collected
cache - alternate node to use for the signature cache
returns - the build signature
This no longer handles the recursive descent of the
node's children's s... | Fetch a node's build information.
node - the node whose sources will be collected
cache - alternate node to use for the signature cache
returns - the build signature
This no longer handles the recursive descent of the
node's children's signatures. We expect that they're
... |
def add_equad(psr, equad, flagid=None, flags=None, seed=None):
"""Add quadrature noise of rms `equad` [s].
Optionally take a pseudorandom-number-generator seed."""
if seed is not None:
N.random.seed(seed)
# default equadvec
equadvec = N.zeros(psr.nobs)
# check that equad is scalar... | Add quadrature noise of rms `equad` [s].
Optionally take a pseudorandom-number-generator seed. |
def set_is_immediate(self, value):
"""
Setter for 'is_immediate' field.
:param value - a new value of 'is_immediate' field. Must be a boolean type.
"""
if value is None:
self.__is_immediate = value
elif not isinstance(value, bool):
raise TypeError(... | Setter for 'is_immediate' field.
:param value - a new value of 'is_immediate' field. Must be a boolean type. |
def _from_dict(cls, _dict):
"""Initialize a QueryResult object from a json dictionary."""
args = {}
xtra = _dict.copy()
if 'id' in _dict:
args['id'] = _dict.get('id')
del xtra['id']
if 'metadata' in _dict:
args['metadata'] = _dict.get('metadata... | Initialize a QueryResult object from a json dictionary. |
def postinit(self, args, body):
"""Do some setup after initialisation.
:param args: The arguments that the function takes.
:type args: Arguments
:param body: The contents of the function body.
:type body: list(NodeNG)
"""
self.args = args
self.body = bod... | Do some setup after initialisation.
:param args: The arguments that the function takes.
:type args: Arguments
:param body: The contents of the function body.
:type body: list(NodeNG) |
def widgets(self):
"""Get the items."""
widgets = []
for i, chart in enumerate(most_visited_pages_charts()):
widgets.append(Widget(html_id='most_visited_chart_%d' % i,
content=json.dumps(chart),
template='meerkat/wid... | Get the items. |
def _maketicks_selected(self, plt, branches):
"""
utility private method to add ticks to a band structure with selected branches
"""
ticks = self.get_ticks()
distance = []
label = []
rm_elems = []
for i in range(1, len(ticks['distance'])):
if t... | utility private method to add ticks to a band structure with selected branches |
def find_method_params(self):
"""Return the method params
:returns: tuple (args, kwargs) that will be passed as *args, **kwargs
"""
req = self.request
args = req.controller_info["method_args"]
kwargs = req.controller_info["method_kwargs"]
return args, kwargs | Return the method params
:returns: tuple (args, kwargs) that will be passed as *args, **kwargs |
def get_active_trips_df(trip_times: DataFrame) -> DataFrame:
"""
Count the number of trips in ``trip_times`` that are active
at any given time.
Parameters
----------
trip_times : DataFrame
Contains columns
- start_time: start time of the trip in seconds past midnight
- ... | Count the number of trips in ``trip_times`` that are active
at any given time.
Parameters
----------
trip_times : DataFrame
Contains columns
- start_time: start time of the trip in seconds past midnight
- end_time: end time of the trip in seconds past midnight
Returns
... |
def connect_job(job_id,
deployment_name,
token_manager=None,
app_url=defaults.APP_URL,
persist=False,
websocket=None,
data_url=None):
"""
connect to a running Juttle program by job_id
"""
if data_url == Non... | connect to a running Juttle program by job_id |
def get(self, task_id):
'''taobao.topats.result.get 获取异步任务结果
使用指南:http://open.taobao.com/doc/detail.htm?id=30
- 1.此接口用于获取异步任务处理的结果,传入的task_id必需属于当前的appKey才可以
- 2.此接口只返回执行完成的任务结果,未执行完的返回结果里面不包含任务结果,只有任务id,执行状态
- 3.执行完成的每个task的子任务结果内容与单个任务的结果结构一致。如:taobao.topat... | taobao.topats.result.get 获取异步任务结果
使用指南:http://open.taobao.com/doc/detail.htm?id=30
- 1.此接口用于获取异步任务处理的结果,传入的task_id必需属于当前的appKey才可以
- 2.此接口只返回执行完成的任务结果,未执行完的返回结果里面不包含任务结果,只有任务id,执行状态
- 3.执行完成的每个task的子任务结果内容与单个任务的结果结构一致。如:taobao.topats.trades.fullinfo.get返回的子任务结果就会是Tra... |
def get(self):
"""
*download the image*
"""
self.log.info('starting the ``get`` method')
ra = self.ra
dec = self.dec
if self.covered == False or self.covered == 999 or self.covered == "999":
return self.covered
self._download_sdss_image()
... | *download the image* |
def _two_to_one(datadir):
"""After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintai... | After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintained if you
wish to do a migration... |
def run(self):
"""
Run the interactive window until the user quits
"""
# pyglet.app.run() has issues like https://bitbucket.org/pyglet/pyglet/issues/199/attempting-to-resize-or-close-pyglet
# and also involves inverting your code to run inside the pyglet framework
# avoid... | Run the interactive window until the user quits |
def parse(cls, line, ns={}):
"""
Parse an options specification, returning a dictionary with
path keys and {'plot':<options>, 'style':<options>} values.
"""
parses = [p for p in cls.opts_spec.scanString(line)]
if len(parses) != 1:
raise SyntaxError("Invalid s... | Parse an options specification, returning a dictionary with
path keys and {'plot':<options>, 'style':<options>} values. |
def unschedule(self, campaign_id):
"""
Unschedule a scheduled campaign that hasn’t started sending.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str`
"""
self.campaign_id = campaign_id
return self._mc_client._post(url=self._bu... | Unschedule a scheduled campaign that hasn’t started sending.
:param campaign_id: The unique id for the campaign.
:type campaign_id: :py:class:`str` |
def has_storage(func):
""" Ensure that self/cls contains a Storage backend. """
@wraps(func)
def wrapped(*args, **kwargs):
me = args[0]
if not hasattr(me, '_storage') or \
not me._storage:
raise exceptions.ImproperConfigurationError(
'No storage ba... | Ensure that self/cls contains a Storage backend. |
def pixels_connectivity_compute(raster, i, j, idx):
"""Compute if the two given value's pixels have connectivity
Compute if the two given value's pixels of raster have connectivity between
the [i.j]pixel and its 8-neighborhood. If they have connectivity,
then put its neighborhood to List idx and g... | Compute if the two given value's pixels have connectivity
Compute if the two given value's pixels of raster have connectivity between
the [i.j]pixel and its 8-neighborhood. If they have connectivity,
then put its neighborhood to List idx and go in a recursion. If the [i,
j]pixel and its neighborh... |
def _update_record_with_name(self, old_record, rtype, new_name, content):
"""Updates existing record and changes it's sub-domain name"""
new_type = rtype if rtype else old_record['type']
new_ttl = self._get_lexicon_option('ttl')
if new_ttl is None and 'ttl' in old_record:
ne... | Updates existing record and changes it's sub-domain name |
def _determine_types(start_node, first_name, add_leaf, add_link):
"""Determines types for generic additions"""
if start_node.v_is_root:
where = first_name
else:
where = start_node._branch
if where in SUBTREE_MAPPING:
type_tuple = SUBTREE_MAPPING[where... | Determines types for generic additions |
def p_qualifierType_1(p):
"""qualifierType_1 : ':' dataType array
| ':' dataType array defaultValue
"""
dv = None
if len(p) == 5:
dv = p[4]
p[0] = (p[2], True, p[3], dv) | qualifierType_1 : ':' dataType array
| ':' dataType array defaultValue |
def result_key_for(self, op_name):
"""
Checks for the presence of a ``result_key``, which defines what data
should make up an instance.
Returns ``None`` if there is no ``result_key``.
:param op_name: The operation name to look for the ``result_key`` in.
:type op_name: s... | Checks for the presence of a ``result_key``, which defines what data
should make up an instance.
Returns ``None`` if there is no ``result_key``.
:param op_name: The operation name to look for the ``result_key`` in.
:type op_name: string
:returns: The expected key to look for d... |
def extra_prepare(self, configuration, args_dict):
"""
Called before the configuration.converters are activated
Here we make sure that we have harpoon options from ``args_dict`` in
the configuration.
We then load all the harpoon modules as specified by the
``harpoon.add... | Called before the configuration.converters are activated
Here we make sure that we have harpoon options from ``args_dict`` in
the configuration.
We then load all the harpoon modules as specified by the
``harpoon.addons`` setting.
Finally we inject into the configuration:
... |
def connectExec(connection, protocol, commandLine):
"""Connect a Protocol to a ssh exec session
"""
deferred = connectSession(connection, protocol)
@deferred.addCallback
def requestSubsystem(session):
return session.requestExec(commandLine)
return deferred | Connect a Protocol to a ssh exec session |
def dcc(self):
"""return the :class:`~irc3.dcc.DCCManager`"""
if self._dcc is None:
self._dcc = DCCManager(self)
return self._dcc | return the :class:`~irc3.dcc.DCCManager` |
def corners(self):
"""
Iterate the vector of all corners of the hyperrectangles
>>> Tile(3, dim=2).corners
array([[0, 0],
[0, 3],
[3, 0],
[3, 3]])
"""
corners = []
for ind in itertools.product(*((0,1),)*self.dim):
... | Iterate the vector of all corners of the hyperrectangles
>>> Tile(3, dim=2).corners
array([[0, 0],
[0, 3],
[3, 0],
[3, 3]]) |
def sargasso_chart (self):
""" Make the sargasso plot """
# Config for the plot
config = {
'id': 'sargasso_assignment_plot',
'title': 'Sargasso: Assigned Reads',
'ylab': '# Reads',
'cpswitch_counts_label': 'Number of Reads'
}
#We ... | Make the sargasso plot |
def airplane(self, model_mask: str = '###') -> str:
"""Generate a dummy airplane model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Airplane model.
:Example:
Boeing 727.
"""... | Generate a dummy airplane model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Airplane model.
:Example:
Boeing 727. |
def save_beat(
self,
output_file_name,
frequencys,
play_time,
sample_rate=44100,
volume=0.01
):
'''
引数で指定した条件でビートを鳴らす
Args:
frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple
play_time: 再生時間(秒)
... | 引数で指定した条件でビートを鳴らす
Args:
frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple
play_time: 再生時間(秒)
sample_rate: サンプルレート
volume: 音量
Returns:
void |
def register_postloop_hook(self, func: Callable[[None], None]) -> None:
"""Register a function to be called at the end of the command loop."""
self._validate_prepostloop_callable(func)
self._postloop_hooks.append(func) | Register a function to be called at the end of the command loop. |
def build_msg_fmtstr2(lbl, length, invert_rate, backspace):
r"""
Args:
lbl (str):
invert_rate (bool):
backspace (bool):
Returns:
str: msg_fmtstr_time
CommandLine:
python -m utool.util_progress --exec-ProgressIter.build_msg_fmt... | r"""
Args:
lbl (str):
invert_rate (bool):
backspace (bool):
Returns:
str: msg_fmtstr_time
CommandLine:
python -m utool.util_progress --exec-ProgressIter.build_msg_fmtstr2
Setup:
>>> from utool.util_progress import... |
def convert_attribute_name_to_tag(value):
"""
A utility function that converts an attribute name string into the
corresponding attribute tag.
For example: 'State' -> enums.Tags.STATE
Args:
value (string): The string name of the attribute.
Returns:
enum: The Tags enumeration va... | A utility function that converts an attribute name string into the
corresponding attribute tag.
For example: 'State' -> enums.Tags.STATE
Args:
value (string): The string name of the attribute.
Returns:
enum: The Tags enumeration value that corresponds to the attribute
name... |
def _config_convert_to_address_helper(self) -> None:
"""
converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address`
"""
to_address = self._socket_factory.to_address
for k, v in self.config.items():
if k... | converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address` |
def _WebSafeComponent(c, alt=False):
'''Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value.
... | Convert a color component to its web safe equivalent.
Parameters:
:c:
The component value [0...1]
:alt:
If True, return the alternative value instead of the nearest one.
Returns:
The web safe equivalent of the component value. |
def iter_follower_file(fname):
""" Iterator from a file of follower information and return a tuple of screen_name, follower ids.
File format is:
<iso timestamp> <screen_name> <follower_id1> <follower_ids2> ...
"""
with open(fname, 'rt') as f:
for line in f:
parts = line.split()
... | Iterator from a file of follower information and return a tuple of screen_name, follower ids.
File format is:
<iso timestamp> <screen_name> <follower_id1> <follower_ids2> ... |
def generate_additional_properties(self):
"""
Means object with keys with values defined by definition.
.. code-block:: python
{
'properties': {
'key': {'type': 'number'},
}
'additionalProperties': {'type': 'string... | Means object with keys with values defined by definition.
.. code-block:: python
{
'properties': {
'key': {'type': 'number'},
}
'additionalProperties': {'type': 'string'},
}
Valid object is containing key call... |
def retarget_with_change_points(song, cp_times, duration):
"""Create a composition of a song of a given duration that reaches
music change points at specified times. This is still under
construction. It might not work as well with more than
2 ``cp_times`` at the moment.
Here's an example of retarge... | Create a composition of a song of a given duration that reaches
music change points at specified times. This is still under
construction. It might not work as well with more than
2 ``cp_times`` at the moment.
Here's an example of retargeting music to be 40 seconds long and
hit a change point at the... |
def _mk_range_bucket(name, n1, n2, r1, r2):
"""
Create a named range specification for encoding.
:param name: The name of the range as it should appear in the result
:param n1: The name of the lower bound of the range specifier
:param n2: The name of the upper bound of the range specified
:para... | Create a named range specification for encoding.
:param name: The name of the range as it should appear in the result
:param n1: The name of the lower bound of the range specifier
:param n2: The name of the upper bound of the range specified
:param r1: The value of the lower bound (user value)
:par... |
def get_enclosed_object(self):
"""Return the enclosed object"""
if self._enclosed_object is None:
enclosed_object_id = self.get_enclosed_object_id()
package_name = enclosed_object_id.get_identifier_namespace().split('.')[0]
obj_name = enclosed_object_id.get_identifier... | Return the enclosed object |
def get_cp2k_structure(atoms):
"""Convert the atoms structure to a CP2K input file skeleton string"""
from cp2k_tools.generator import dict2cp2k
# CP2K's default unit is angstrom, convert it, but still declare it explictly:
cp2k_cell = {sym: ('[angstrom]',) + tuple(coords) for sym, coords in zip(('a',... | Convert the atoms structure to a CP2K input file skeleton string |
def create_order(self, oid, price, context=None, expires=None):
"""
CREATES a single order for object ``oid``, with price set to ``price``
and validity until ``expires``.
:type oid: ``bigint``
:param oid:
Object ID.
:type price: ``bigint``
:pa... | CREATES a single order for object ``oid``, with price set to ``price``
and validity until ``expires``.
:type oid: ``bigint``
:param oid:
Object ID.
:type price: ``bigint``
:param price:
Vingd amount (in cents) the user/buyer shall be charged upon
... |
def new(project_name):
"""Creates a new project"""
try:
locale.setlocale(locale.LC_ALL, '')
except:
print("Warning: Unable to set locale. Expect encoding problems.")
config = utils.get_config()
config['new_project']['project_name'] = project_name
values = new_project_ui(confi... | Creates a new project |
def put_on_top(self, request, queryset):
"""
Put the selected entries on top at the current date.
"""
queryset.update(publication_date=timezone.now())
self.ping_directories(request, queryset, messages=False)
self.message_user(request, _(
'The selected entries ... | Put the selected entries on top at the current date. |
def comment_request(self, request_id, body, commit=None,
filename=None, row=None):
"""
Create a comment on the request.
:param request_id: the id of the request
:param body: the comment body
:param commit: which commit to comment on
:param filename... | Create a comment on the request.
:param request_id: the id of the request
:param body: the comment body
:param commit: which commit to comment on
:param filename: which file to comment on
:param row: which line of code to comment on
:return: |
def calculate_month(birth_date):
"""
Calculates and returns a month number basing on PESEL standard.
"""
year = int(birth_date.strftime('%Y'))
month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20
return month | Calculates and returns a month number basing on PESEL standard. |
def Connect(self, Username, WaitConnected=False):
"""Connects application to user.
:Parameters:
Username : str
Name of the user to connect to.
WaitConnected : bool
If True, causes the method to wait until the connection is established.
:return: If ``... | Connects application to user.
:Parameters:
Username : str
Name of the user to connect to.
WaitConnected : bool
If True, causes the method to wait until the connection is established.
:return: If ``WaitConnected`` is True, returns the stream which can be used... |
def _is_noop_timeperiod(self, process_name, timeperiod):
""" method verifies if the given timeperiod for given process is valid or falls in-between grouping checkpoints
:param process_name: name of the process
:param timeperiod: timeperiod to verify
:return: False, if given process has n... | method verifies if the given timeperiod for given process is valid or falls in-between grouping checkpoints
:param process_name: name of the process
:param timeperiod: timeperiod to verify
:return: False, if given process has no time_grouping set or it is equal to 1.
False, if t... |
def replace(self, new_node):
"""Replace a node after first checking integrity of node stack."""
cur_node = self.cur_node
nodestack = self.nodestack
cur = nodestack.pop()
prev = nodestack[-1]
index = prev[-1] - 1
oldnode, name = prev[-2][index]
assert cur[0... | Replace a node after first checking integrity of node stack. |
def handle_cmd(self, cmd):
"""Handles a single server command."""
cmd = cmd.strip()
segments = []
for s in cmd.split():
# remove bash-like comments
if s.startswith('#'):
break
# TODO implement escape sequences (also for \#)
... | Handles a single server command. |
def mapPartitions(self, f, preservesPartitioning=False):
"""
Return a new RDD by applying a function to each partition of this RDD.
>>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()
[3, 7]
"""
... | Return a new RDD by applying a function to each partition of this RDD.
>>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()
[3, 7] |
def get_rendition_url(self, width=0, height=0):
'''get the rendition URL for a specified size
if the renditions does not exists it will be created
'''
if width == 0 and height == 0:
return self.get_master_url()
target_width, target_height = self.get_rendition_size(w... | get the rendition URL for a specified size
if the renditions does not exists it will be created |
def _read_as_table(self):
"""
Read the data contained in all entries as a list of
lists containing all of the data
:return: list of dicts containing all tabular data
"""
rows = list()
for row in self._rows:
rows.append([row[i].get() for i in range(se... | Read the data contained in all entries as a list of
lists containing all of the data
:return: list of dicts containing all tabular data |
def get_cts_metadata(self, key: str, lang: str = None) -> Literal:
""" Get easily a metadata from the CTS namespace
:param key: CTS property to retrieve
:param lang: Language in which it should be
:return: Literal value of the CTS graph property
"""
return self.metadata.... | Get easily a metadata from the CTS namespace
:param key: CTS property to retrieve
:param lang: Language in which it should be
:return: Literal value of the CTS graph property |
def reorient_image(image, axis1, axis2=None, doreflection=False, doscale=0, txfn=None):
"""
Align image along a specified axis
ANTsR function: `reorientImage`
Arguments
---------
image : ANTsImage
image to reorient
axis1 : list/tuple of integers
vector of size dim,... | Align image along a specified axis
ANTsR function: `reorientImage`
Arguments
---------
image : ANTsImage
image to reorient
axis1 : list/tuple of integers
vector of size dim, might need to play w/axis sign
axis2 : list/tuple of integers
vector of size dim f... |
def probes_used_extract_scores(full_scores, same_probes):
"""Extracts a matrix of scores for a model, given a probes_used row vector of boolean"""
if full_scores.shape[1] != same_probes.shape[0]: raise "Size mismatch"
import numpy as np
model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), 'floa... | Extracts a matrix of scores for a model, given a probes_used row vector of boolean |
def _call(self, x, out):
"""Return ``self(x)``."""
if self.domain.is_real:
# Real domain, multiply separately
out.real = self.scalar.real * x
out.imag = self.scalar.imag * x
else:
# Complex domain
out.lincomb(self.scalar, x) | Return ``self(x)``. |
def acknowledge(self, request, *args, **kwargs):
"""
To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required.
All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint
will return error with code 4... | To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required.
All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint
will return error with code 409(conflict). |
def play_song(self, song):
"""播放指定歌曲
如果目标歌曲与当前歌曲不相同,则修改播放列表当前歌曲,
播放列表会发出 song_changed 信号,player 监听到信号后调用 play 方法,
到那时才会真正的播放新的歌曲。如果和当前播放歌曲相同,则忽略。
.. note::
调用方不应该直接调用 playlist.current_song = song 来切换歌曲
"""
if song is not None and song == self.curren... | 播放指定歌曲
如果目标歌曲与当前歌曲不相同,则修改播放列表当前歌曲,
播放列表会发出 song_changed 信号,player 监听到信号后调用 play 方法,
到那时才会真正的播放新的歌曲。如果和当前播放歌曲相同,则忽略。
.. note::
调用方不应该直接调用 playlist.current_song = song 来切换歌曲 |
def set_branding(self, asset_ids):
"""Sets the branding.
arg: asset_ids (osid.id.Id[]): the new assets
raise: InvalidArgument - ``asset_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``asset_ids`` is ``null``
*complia... | Sets the branding.
arg: asset_ids (osid.id.Id[]): the new assets
raise: InvalidArgument - ``asset_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``asset_ids`` is ``null``
*compliance: mandatory -- This method must be implemen... |
def set_connection(host=None, database=None, user=None, password=None):
"""Set connection parameters. Call set_connection with no arguments to clear."""
c.CONNECTION['HOST'] = host
c.CONNECTION['DATABASE'] = database
c.CONNECTION['USER'] = user
c.CONNECTION['PASSWORD'] = password | Set connection parameters. Call set_connection with no arguments to clear. |
def _von_mises_cdf_series(x, concentration, num_terms, dtype):
"""Computes the von Mises CDF and its derivative via series expansion."""
# Keep the number of terms as a float. It should be a small integer, so
# exactly representable as a float.
num_terms = tf.cast(num_terms, dtype=dtype)
def loop_body(n, rn,... | Computes the von Mises CDF and its derivative via series expansion. |
def get_assessment_offered_mdata():
"""Return default mdata map for AssessmentOffered"""
return {
'level': {
'element_label': {
'text': 'level',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
... | Return default mdata map for AssessmentOffered |
def add_arguments(cls, parser, sys_arg_list=None):
"""
Arguments for the configfile mode.
"""
parser.add_argument('-f', '--file', dest='file', required=True,
help="config file for routing groups "
"(only in configfile mode)")
... | Arguments for the configfile mode. |
def extract_words(string):
'''Extract all alphabetic syllabified forms from 'string'.'''
return re.findall(r'[%s]+[%s\.]*[%s]+' % (A, A, A), string, flags=FLAGS) | Extract all alphabetic syllabified forms from 'string'. |
def _underscore_to_camelcase(value):
"""
Convert Python snake case back to mixed case.
"""
def camelcase():
yield str.lower
while True:
yield str.capitalize
c = camelcase()
return "".join(next(c)(x) if x else '_' for x in value.spl... | Convert Python snake case back to mixed case. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.