text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def gnu_getopt(args, shortopts, longopts=[]):
"""getopt(args, options[, long_options]) -> opts, args
This function works like getopt(), except that GNU style scanning
mode is used by default. This means that option and non-option
arguments may be intermixed. The getopt() function stops
processing o... | 0.000693 |
def recursively_collect_orders(
name, ctx, all_inputs, orders=None, blacklist=None
):
'''For each possible recipe ordering, try to add the new recipe name
to that order. Recursively do the same thing with all the
dependencies of each recipe.
'''
name = name.lower()
if orders is ... | 0.000484 |
def _multi_get(self, cache_api_name, fmt_url_path, url_params, query_params=None):
"""Makes multiple GETs to an OpenDNS endpoint.
Args:
cache_api_name: string api_name for caching
fmt_url_path: format string for building URL paths
url_params: An enumerable of strings... | 0.004405 |
def _single_learnable_state(state, state_id=0, learnable=True):
"""Returns an initial (maybe learnable) state.
This function does not create any variable scopes, and it should be called
from a Sonnet module. This function also makes sure that all the rows of its
`state` argument have the same value.
Args:
... | 0.011127 |
def send(self, data):
"""
Send date to server
Parameters
----------
data: object that can be serialized to JSON
"""
answer = None
try:
logging.info("Client conntecting to {server}".format(server=self.server_address))
if ... | 0.006881 |
def get_hosted_service_properties(self, service_name, embed_detail=False):
'''
Retrieves system properties for the specified hosted service. These
properties include the service name and service type; the name of the
affinity group to which the service belongs, or its location if it is
... | 0.002058 |
def remove_edge(self, id1, id2):
""" Remove edges between nodes with given id's.
"""
for e in list(self.edges):
if id1 in (e.node1.id, e.node2.id) and \
id2 in (e.node1.id, e.node2.id):
e.node1.links.remove(e.node2)
e.n... | 0.010444 |
def rect(self):
"""Rectangle containing the annot"""
CheckParent(self)
val = _fitz.Annot_rect(self)
val = Rect(val)
return val | 0.011905 |
def install_dap(name, version='', update=False, update_allpaths=False, first=True,
force=False, nodeps=False, reinstall=False, __ui__=''):
'''Install a dap from dapi
If update is True, it will remove previously installed daps of the same name'''
m, d = _get_metadap_dap(name, version)
if ... | 0.006104 |
def remove_tweets(self, url):
"""Tries to remove cached tweets."""
try:
del self.cache[url]
self.mark_updated()
return True
except KeyError:
return False | 0.008889 |
def _assert_is_type(name, value, value_type):
"""Assert that a value must be a given type."""
if not isinstance(value, value_type):
if type(value_type) is tuple:
types = ', '.join(t.__name__ for t in value_type)
raise ValueError('{0} must be one of ({1})'.format(name, types))
... | 0.002262 |
def md5_digest(instr):
'''
Generate an md5 hash of a given string.
'''
return salt.utils.stringutils.to_unicode(
hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest()
) | 0.004854 |
def send_request(self):
"""Send request.
[:rfc:`2131#section-3.1`]::
a client retransmitting as described in section 4.1 might retransmit
the DHCPREQUEST message four times, for a total delay of 60 seconds
.. todo::
- The maximum number of retransmitted REQUESTs is... | 0.000944 |
def _serialize_into_store(profile, filter=None):
"""
Takes data from app layer and serializes the models into the store.
"""
# ensure that we write and retrieve the counter in one go for consistency
current_id = InstanceIDModel.get_current_instance_and_increment_counter()
with transaction.atomi... | 0.004438 |
def define_system_args(subparsers):
"""Append the parser arguments for the 'system' commands"""
system_parser = subparsers.add_parser("system", help='Available commands: \'info\'')
system_subparsers = system_parser.add_subparsers(help='System commands')
# system info arguments
info_parser = system_... | 0.00638 |
def create_log_group(awsclient, log_group_name):
"""Creates a log group with the specified name.
:param log_group_name: log group name
:return:
"""
client_logs = awsclient.get_client('logs')
response = client_logs.create_log_group(
logGroupName=log_group_name,
) | 0.003333 |
def attention_bias_local_block(mesh, block_length, memory_length,
dtype=tf.int32):
"""Bias for attention for local blocks where attention to right is disallowed.
Create the bias matrix by using two separate masks, one for the memory part
which doesn't overlap with the query and sec... | 0.008264 |
def streamweigths_get(self, session):
'''taobao.wangwang.eservice.streamweigths.get 获取分流权重接口
获取当前登录用户自己的店铺内的分流权重设置'''
request = TOPRequest('taobao.wangwang.eservice.streamweigths.get')
self.create(self.execute(request, session))
return self.staff_stream_weights | 0.009677 |
def registerDeferred(self, event, d):
"""
Register a defer to be fired at the firing of a specific event.
:param string event: Currently supported values are `connect`. Another
value may be `_dtor` which will register an event to fire when this
object has been completely des... | 0.001867 |
def print(root):
# type: (Union[Nonterminal,Terminal,Rule])-> str
"""
Transform the parsed tree to the string. Expects tree like structure.
You can see example output below.
(R)SplitRules26
|--(N)Iterate
| `--(R)SplitRules30
| `--(N)Symb
| ... | 0.003176 |
def compute_bayes_cone(preds, starting_value=1.):
"""
Compute 5, 25, 75 and 95 percentiles of cumulative returns, used
for the Bayesian cone.
Parameters
----------
preds : numpy.array
Multiple (simulated) cumulative returns.
starting_value : int (optional)
Have cumulative re... | 0.001266 |
def from_callback(cls, cb, ny=None, nparams=None, dep_transf_cbs=None,
indep_transf_cbs=None, roots_cb=None, **kwargs):
"""
Create an instance from a callback.
Analogous to :func:`SymbolicSys.from_callback`.
Parameters
----------
cb : callable
... | 0.003835 |
def is_command(self, text: str) -> bool:
"""
checks for presence of shebang in the first character of the text
"""
if text[0] in self.shebangs:
return True
return False | 0.00905 |
def fav_songs(self):
"""
FIXME: 支持获取所有的收藏歌曲
"""
if self._fav_songs is None:
songs_data = self._api.user_favorite_songs(self.identifier)
self._fav_songs = []
if not songs_data:
return
for song_data in songs_data:
... | 0.004464 |
def in_clip(self, x, y):
"""Tests whether the given point is inside the area
that would be visible through the current clip,
i.e. the area that would be filled by a :meth:`paint` operation.
See :meth:`clip`, and :meth:`clip_preserve`.
:param x: X coordinate of the point to test... | 0.003623 |
def get(ctx):
"""Get info for current project, by project_name, or user/project_name.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
To get current project:
\b
```bash
$ polyaxon project get
```
To get a project by name
\b
```bash
$ polyaxon project get... | 0.002538 |
def main_crop():
"""This function does the real work. It is called by main() in
pdfCropMargins.py, which just handles catching exceptions and cleaning up."""
##
## Process some of the command-line arguments.
##
if args.verbose:
print("\nProcessing the PDF with pdfCropMargins (version"... | 0.008001 |
def list_prefix(self):
""" List prefixes and return JSON encoded result.
"""
# fetch attributes from request.json
attr = XhrController.extract_prefix_attr(request.json)
try:
prefixes = Prefix.list(attr)
except NipapError, e:
return json.dumps({'e... | 0.006912 |
def _cachedSqlType(cls):
"""
Cache the sqlType() into class, because it's heavy used in `toInternal`.
"""
if not hasattr(cls, "_cached_sql_type"):
cls._cached_sql_type = cls.sqlType()
return cls._cached_sql_type | 0.011407 |
def order_derived_variables(regime):
"""
Finds ordering of derived_variables.
@param regime: Dynamics Regime containing derived variables.
@type regime: lems.model.dynamics.regime
@return: Returns ordered list of derived variables.
@rtype: list(string)
@raise SimBuildError: Raised when a ... | 0.004699 |
def linear_elasticity(grid, spacing=None, E=1e5, nu=0.3, format=None):
"""Linear elasticity problem discretizes with Q1 finite elements on a regular rectangular grid.
Parameters
----------
grid : tuple
length 2 tuple of grid sizes, e.g. (10, 10)
spacing : tuple
length 2 tuple of gri... | 0.001523 |
async def request(self, api_commands):
"""Make a request."""
if not isinstance(api_commands, list):
result = await self._execute(api_commands)
return result
commands = (self._execute(api_command) for api_command in api_commands)
command_results = await asyncio.ga... | 0.005208 |
def _parse_message(self, data):
"""Interpret each message datagram from device and do the needful.
This function receives datagrams from _assemble_buffer and inerprets
what they mean. It's responsible for maintaining the internal state
table for each device attribute and also for firin... | 0.001593 |
def __find_another_nearest_medoid(self, point_index, current_medoid_index):
"""!
@brief Finds the another nearest medoid for the specified point that is differ from the specified medoid.
@param[in] point_index: index of point in dataspace for that searching of medoid in current lis... | 0.010508 |
def makeLambdaPicklable(lambda_function):
"""Take input lambda function l and makes it picklable."""
if isinstance(lambda_function,
type(lambda: None)) and lambda_function.__name__ == '<lambda>':
def __reduce_ex__(proto):
# TODO: argdefs, closure
return unpickle... | 0.004425 |
def show_raslog_output_cmd_status_error_msg(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
output = ET.SubElement(show_raslog, "output")
cmd_status_error_msg = ET.SubElement(ou... | 0.003914 |
def remove_game_containers(name_filter: str) -> None:
"""
:raises docker.exceptions.APIError
"""
for container in docker_client.containers.list(filters={"name": name_filter}, all=True):
container.stop()
container.remove() | 0.007905 |
def match(self, p_todo):
"""
Performs a match on a priority in the todo.
It gets priority from p_todo and compares it with user-entered
expression based on the given operator (default ==). It does that however
in reversed order to obtain more intuitive result. Example: (>B) will... | 0.004539 |
def _warnCount(self, warnings, warningCount=None):
"""
Calculate the count of each warning, being given a list of them.
@param warnings: L{list} of L{dict}s that come from
L{tools.parsePyLintWarnings}.
@param warningCount: A L{dict} produced by this method previously, if
... | 0.00232 |
def nsDefs(self):
"""Get the namespace of a node """
ret = libxml2mod.xmlNodeGetNsDefs(self._o)
if ret is None:return None
__tmp = xmlNs(_obj=ret)
return __tmp | 0.020101 |
def download_as_file(self, url: str, folder: Path, name: str, delay: float = 0) -> str:
"""
Download the given url to the given target folder.
:param url: link
:type url: str
:param folder: target folder
:type folder: ~pathlib.Path
:param name: target file name
... | 0.004329 |
def use_dill( self ):
"""Make the cluster use Dill as pickler for transferring results. This isn't
generally needed, but is sometimes useful for particularly complex experiments
such as those involving closures. (Or, to put it another way, if you find yourself
tempted to use this method,... | 0.019763 |
def setup_and_run_analysis(self):
"""Execute analysis after the tab is displayed.
Please check the code in dock.py accept(). It should follow
approximately the same code.
"""
self.show_busy()
# Read user's settings
self.read_settings()
# Prepare impact fu... | 0.000546 |
def next_close(self, dt):
"""
Given a dt, returns the next close.
Parameters
----------
dt: pd.Timestamp
The dt for which to get the next close.
Returns
-------
pd.Timestamp
The UTC timestamp of the next close.
"""
... | 0.004484 |
def is_punctuation(text):
"""Check if given string is a punctuation"""
return not (text.lower() in config.AVRO_VOWELS or
text.lower() in config.AVRO_CONSONANTS) | 0.005435 |
def assure_migrations_table_setup(db):
"""
Make sure the migrations table is set up in the database.
"""
from mig.models import MigrationData
if not MigrationData.__table__.exists(db.bind):
MigrationData.metadata.create_all(
db.bind, tables=[MigrationData.__table__]) | 0.003247 |
def gep(self, indices):
"""
Call getelementptr on this pointer constant.
"""
if not isinstance(self.type, types.PointerType):
raise TypeError("can only call gep() on pointer constants, not '%s'"
% (self.type,))
outtype = self.type
... | 0.004184 |
def get_assessment_taken_query_session_for_bank(self, bank_id):
"""Gets the ``OsidSession`` associated with the assessment taken query service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the bank
return: (osid.assessment.AssessmentTakenQuerySession) - an
``As... | 0.004263 |
def reencrypt_row_content(db,
table,
row_id,
decrypt_func,
encrypt_func,
logger):
"""
Re-encrypt a row from ``table`` with ``id`` of ``row_id``.
"""
q = (select([table.c.cont... | 0.001404 |
def msg_nocr(self, msg, opts={}):
""" Convenience short-hand for self.debugger.intf[-1].msg_nocr """
try:
return(self.debugger.intf[-1].msg_nocr(msg))
except EOFError:
# FIXME: what do we do here?
pass
return None | 0.007117 |
def astext(data):
"""
Given a unicode/str/bytes always return str.
We prefer to work with the 'native' string type for the version of python
we run on, and this gets us that.
"""
if isinstance(data, str):
return data
elif isinstance(data, text_type):
return data.encode("utf-... | 0.002114 |
def builtin_lookup(name):
"""lookup a name into the builtin module
return the list of matching statements and the astroid for the builtin
module
"""
builtin_astroid = MANAGER.ast_from_module(builtins)
if name == "__dict__":
return builtin_astroid, ()
try:
stmts = builtin_astr... | 0.002439 |
def generate(self, text):
"""Generate and save avatars, return a list of file name: [filename_s, filename_m, filename_l].
:param text: The text used to generate image.
"""
sizes = current_app.config['AVATARS_SIZE_TUPLE']
path = current_app.config['AVATARS_SAVE_PATH']
suf... | 0.005256 |
def get_or_create(cls, **kwargs):
"""
Implements get_or_create logic for models that inherit from
representatives.models.HashableModel because we don't have access to model
methods in a migration scenario.
"""
try:
obj = cls.objects.get(**kwargs)
created = False
except cls.D... | 0.002188 |
def del_record(cls, fqdn, name, type):
"""Delete record for a domain."""
meta = cls.get_fqdn_info(fqdn)
url = meta['domain_records_href']
delete_url = url
if name:
delete_url = '%s/%s' % (delete_url, name)
if type:
delete_url = '%s/%s' % (delete_ur... | 0.005391 |
def cutadaptit_single(data, sample):
"""
Applies quality and adapter filters to reads using cutadapt. If the ipyrad
filter param is set to 0 then it only filters to hard trim edges and uses
mintrimlen. If filter=1, we add quality filters. If filter=2 we add
adapter filters.
"""
sname = sa... | 0.010087 |
def si_prefix(value):
""" By Forrest Green (2010)"""
#standard si prefixes
prefixes = ['y','z','a','f','p','n','u','m','','k','M','G','T','P','E','Z','Y']
from math import log
#closest 1000 exponent
if value == 0: return (value, "")
exp = int(log(value,1000)//1) + 8
if exp < 0: exp = 0
... | 0.060606 |
def synonyms(self):
"""Return a dict of term synonyms"""
syns = {}
for k, v in self._declared_terms.items():
k = k.strip()
if v.get('synonym'):
syns[k.lower()] = v['synonym']
if not '.' in k:
syns[ROOT_TERM + '.' + k.l... | 0.008264 |
def load_balancer_delete(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a load balancer.
:param name: The name of the load balancer to delete.
:param resource_group: The resource group name assigned to the
load balancer.
CLI Example:
.. code-block:: bash
... | 0.001214 |
def requires_authentication(fn):
"""
Requires that the calling Subject be authenticated before allowing access.
"""
@functools.wraps(fn)
def wrap(*args, **kwargs):
subject = WebYosai.get_current_subject()
if not subject.authenticated:
msg... | 0.00956 |
def accept_transfer(transfer, comment=None):
'''Accept an incoming a transfer request'''
TransferResponsePermission(transfer).test()
transfer.responded = datetime.now()
transfer.responder = current_user._get_current_object()
transfer.status = 'accepted'
transfer.response_comment = comment
t... | 0.001669 |
def is_authenticated(user):
"""Return whether or not a User is authenticated.
Function provides compatibility following deprecation of method call to
`is_authenticated()` in Django 2.0.
This is *only* required to support Django < v1.10 (i.e. v1.9 and earlier),
as `is_authenticated` was introduced ... | 0.00266 |
def delete(self, user):
"""Delete a resource"""
if user:
can_delete = yield self.can_delete(user)
else:
can_delete = False
if not can_delete:
raise exceptions.Unauthorized('User may not delete the resource')
doc = {
'_id': self.id... | 0.003636 |
def sudo_remove_dirtree(dir_name):
"""Removes directory tree as a superuser.
Args:
dir_name: name of the directory to remove.
This function is necessary to cleanup directories created from inside a
Docker, since they usually written as a root, thus have to be removed as a
root.
"""
try:
subproce... | 0.00823 |
def _assemble_gef(stmt):
"""Assemble Gef statements into text."""
subj_str = _assemble_agent_str(stmt.gef)
obj_str = _assemble_agent_str(stmt.ras)
stmt_str = subj_str + ' is a GEF for ' + obj_str
return _make_sentence(stmt_str) | 0.004049 |
def authenticate_swift_user(self, keystone, user, password, tenant):
"""Authenticates a regular user with swift api."""
self.log.debug('Authenticating swift user ({})...'.format(user))
ep = keystone.service_catalog.url_for(service_type='identity',
in... | 0.00271 |
def model_fields(model, allow_pk=False, only=None, exclude=None,
field_args=None, converter=None):
"""
Generate a dictionary of fields for a given Peewee model.
See `model_form` docstring for description of parameters.
"""
converter = converter or ModelConverter()
field_args = ... | 0.00117 |
def create_port_binding(self, port, host):
"""Enqueue port binding create"""
if not self.get_instance_type(port):
return
for pb_key in self._get_binding_keys(port, host):
pb_res = MechResource(pb_key, a_const.PORT_BINDING_RESOURCE,
a_cons... | 0.005348 |
def encrypt_text(self, text, *args, **kwargs):
"""
Encrypt a string.
input: unicode str, output: unicode str
"""
b = text.encode("utf-8")
token = self.encrypt(b, *args, **kwargs)
return base64.b64encode(token).decode("utf-8") | 0.007092 |
def _capture(f, t, t0, factor):
'''
capture signal and return its standard deviation
#TODO: more detail
'''
n_per_sec = len(t) / t[-1]
# len of one split:
n = int(t0 * factor * n_per_sec)
s = len(f) // n
m = s * n
f = f[:m]
ff = np.split(f, s)
m = np.mean(ff... | 0.002833 |
def remove_mock(self, mock):
"""
Removes a specific mock instance by object reference.
Arguments:
mock (pook.Mock): mock instance to remove.
"""
self.mocks = [m for m in self.mocks if m is not mock] | 0.007968 |
def get_endpoint(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Return the endpoint of an RDS instance.
CLI example::
salt myminion boto_rds.get_endpoint myrds
'''
endpoint = False
res = __salt__['boto_rds.exists'](name, tags, region, key, keyi... | 0.002268 |
def create_mapping(self, mapped_class, configuration=None):
"""
Creates a new mapping for the given mapped class and representer
configuration.
:param configuration: configuration for the new data element class.
:type configuration: :class:`RepresenterConfiguration`
:ret... | 0.002052 |
def diffuser_curved(Di1, Di2, l):
r'''Returns loss coefficient for any curved wall pipe expansion
as shown in [1]_.
.. math::
K_1 = \phi(1.43-1.3\beta^2)(1-\beta^2)^2
.. math::
\phi = 1.01 - 0.624\frac{l}{d_1} + 0.30\left(\frac{l}{d_1}\right)^2
- 0.074\left(\frac{l}{d_1}\right)... | 0.002831 |
def cnxml_to_html(cnxml_source):
"""Transform the CNXML source to HTML"""
source = _string2io(cnxml_source)
xml = etree.parse(source)
# Run the CNXML to HTML transform
xml = _transform('cnxml-to-html5.xsl', xml,
version='"{}"'.format(version))
xml = XHTML_MODULE_BODY_XPATH(x... | 0.002801 |
def extract_files(file_paths, target_path):
""" Unpack all files to the given path. """
os.makedirs(target_path, exist_ok=True)
extracted = []
for file_path in file_paths:
with tarfile.open(file_path, 'r') as archive:
archive.extractall(target_path)
... | 0.004193 |
def fullConn (self, preCellsTags, postCellsTags, connParam):
from .. import sim
''' Generates connections between all pre and post-syn cells '''
if sim.cfg.verbose: print('Generating set of all-to-all connections (rule: %s) ...' % (connParam['label']))
# get list of params that have a lambda function
... | 0.016736 |
def get_config():
'''Gather and sanity-check volume configuration data'''
volume_config = {}
config = hookenv.config()
errors = False
if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'):
volume_config['ephemeral'] = True
else:
volume_config['ephemeral'] = ... | 0.000597 |
def make_tensor_value_info(
name, # type: Text
elem_type, # type: int
shape, # type: Optional[Sequence[Union[Text, int]]]
doc_string="", # type: Text
shape_denotation=None, # type: Optional[List[Text]]
): # type: (...) -> ValueInfoProto
"""Makes a ValueInfoProto based o... | 0.000512 |
def addReward(self, r=None):
""" A filtered mapping towards performAction of the underlying
environment.
"""
r = self.getReward() if r is None else r
# by default, the cumulative reward is just the sum over the episode
if self.discount:
self.cumulativeRew... | 0.004785 |
def start_output (self):
"""Write start of checking info."""
super(HtmlLogger, self).start_output()
header = {
"encoding": self.get_charset_encoding(),
"title": configuration.App,
"body": self.colorbackground,
"link": self.colorlink,
"v... | 0.007707 |
def availability(self, availability):
"""Sets the availability of this Product.
:param availability: The availability of this Product.
:type: str
"""
allowed_values = ["available", "comingSoon", "retired"]
if availability is not None and availability not in allowed_valu... | 0.003697 |
def deserialize_from_text(cls, data, content_type=None):
# type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any
"""Decode data according to content-type.
Accept a stream of data as well, but will be load at once in memory for now.
If no content-type, will return the string version... | 0.004014 |
def _get_action(trans):
"""
Return the action inferred from the transformation `trans`.
and the parameter going with this action
An _Action.ADD_MARK goes with a Mark
while an _Action.ADD_ACCENT goes with an Accent
"""
# TODO: VIQR-like convention
mark_action = {
'^': (_Action.ADD... | 0.001006 |
def parse_gaf(path_or_buffer, gene_ontology, valid_genes=None,
db=None, ev_codes=None):
"""Parse a GAF 2.1 file containing GO annotations.
Parameters
----------
path_or_buffer : str or buffer
The GAF file.
gene_ontology : `GeneOntology`
The Gene Ontology.
valid... | 0.001248 |
def add_versioned_targets_to_INSTALLED_FILES(target, source, env):
""" An emitter that adds all target files to the list stored in the
_INSTALLED_FILES global variable. This way all installed files of one
scons call will be collected.
"""
global _INSTALLED_FILES, _UNIQUE_INSTALLED_FILES
Verbose ... | 0.00292 |
def crick_angles(p, reference_axis, tag=True, reference_axis_name='ref_axis'):
"""Returns the Crick angle for each CA atom in the `Polymer`.
Notes
-----
The final value is in the returned list is `None`, since the angle
calculation requires pairs of points on both the primitive and
reference_ax... | 0.000531 |
def order_lots(id_or_ins, amount, price=None, style=None):
"""
指定手数发送买/卖单。如有需要落单类型当做一个参量传入,如果忽略掉落单类型,那么默认是市价单(market order)。
:param id_or_ins: 下单标的物
:type id_or_ins: :class:`~Instrument` object | `str`
:param int amount: 下单量, 正数代表买入,负数代表卖出。将会根据一手xx股来向下调整到一手的倍数,比如中国A股就是调整成100股的倍数。
:param float... | 0.004859 |
def from_str(cls, s):
# type: (Union[Text, bytes]) -> FmtStr
r"""
Return a FmtStr representing input.
The str() of a FmtStr is guaranteed to produced the same FmtStr.
Other input with escape sequences may not be preserved.
>>> fmtstr("|"+fmtstr("hey", fg='red', bg='blue... | 0.002262 |
def delete_key(key_name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a key. Always returns True
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.delete_key mykey
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
key ... | 0.001949 |
def pretty_print_str(self):
'''
Create a string to pretty-print this trie to standard output.
'''
retval = ''
# dfs
todo = [self.root]
while todo:
current = todo.pop()
for char in reversed(sorted(current.keys())):
todo.appen... | 0.004184 |
def setup(self, mujoco_objects, table_top_offset, table_size):
"""
Args:
Mujoco_objcts(MujocoObject * n_obj): object to be placed
table_top_offset(float * 3): location of table top center
table_size(float * 3): x,y,z-FULLsize of the table
"""
self.mujo... | 0.004175 |
def to_unicode_or_none(value):
"""Converts C char arrays to unicode and C NULL values to None.
C char arrays are decoded from UTF-8.
"""
if value == ffi.NULL:
return None
elif isinstance(value, ffi.CData):
return ffi.string(value).decode('utf-8')
else:
raise ValueError('... | 0.002857 |
def error(self, message):
'''Suppress default exit behavior'''
message = self._remessage_invalid_subparser(message)
raise utils.UsageError(message) | 0.011696 |
def has_predecessor(self, graph, dest, orig, branch, turn, tick, *, forward=None):
"""Return whether an edge connects the destination to the origin at the given time.
Doesn't require the edge's index, which makes it slower than retrieving a
particular edge.
"""
if forward is No... | 0.013187 |
def save(self, file_tag='2016', add_header='N'):
"""
save table to folder in appropriate files
NOTE - ONLY APPEND AT THIS STAGE - THEN USE DATABASE
"""
fname = self.get_filename(file_tag)
with open(fname, 'a') as f:
if add_header == 'Y':
f.writ... | 0.011494 |
def create_job(self, phases, name=None, input=None):
"""CreateJob
https://apidocs.joyent.com/manta/api.html#CreateJob
"""
log.debug('CreateJob')
path = '/%s/jobs' % self.account
body = {"phases": phases}
if name:
body["name"] = name
if input:
... | 0.002389 |
def _total_microsec(t1, t2):
"""
Calculate difference between two datetime stamps in microseconds.
:type t1: :class: `datetime.datetime`
:type t2: :class: `datetime.datetime`
:return: int
.. rubric:: Example
>>> print(_total_microsec(UTCDateTime(2013, 1, 1).datetime,
... ... | 0.002075 |
def append(self, item):
"""
Add the given item as children
"""
if self.url:
raise TypeError('Menu items with URL cannot have childrens')
# Look for already present common node
if not item.is_leaf():
for current_item in self.items:
... | 0.00369 |
def fail(self):
"""Fail a vector."""
if self.failed is True:
raise AttributeError("Cannot fail {} - it has already failed.".format(self))
else:
self.failed = True
self.time_of_death = timenow()
for t in self.transmissions():
t.fail... | 0.009317 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.