code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def process_exception_message(exception):
"""
Process an exception message.
Args:
exception: The exception to process.
Returns:
A filtered string summarizing the exception.
"""
exception_message = str(exception)
for replace_char in ['\t',... | Process an exception message.
Args:
exception: The exception to process.
Returns:
A filtered string summarizing the exception. |
def endStep(self,key):
"""
Record the end time for the step.
If key==None, simply record ptime as end time for class to represent
the overall runtime since the initialization of the class.
"""
ptime = _ptime()
if key is not None:
self.steps[key]['end'... | Record the end time for the step.
If key==None, simply record ptime as end time for class to represent
the overall runtime since the initialization of the class. |
def change_email(*_, user_id=None, new_email=None):
""" Change email for a user """
click.echo(green('\nChange email:'))
click.echo(green('-' * 40))
with get_app().app_context():
user = find_user(dict(id=user_id))
if not user:
click.echo(red('User not found\n'))
... | Change email for a user |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = TabLayout(self.get_context(), None, d.style) | Create the underlying widget. |
def getStatus(self) :
"""returns a word describing the status of the collection (loaded, loading, deleted, unloaded, newborn) instead of a number, if you prefer the number it's in self.status"""
if self.status == CONST.COLLECTION_LOADING_STATUS :
return "loading"
elif self.status == ... | returns a word describing the status of the collection (loaded, loading, deleted, unloaded, newborn) instead of a number, if you prefer the number it's in self.status |
def async_save_result(self):
"""
Retrieves the result of this subject's asynchronous save.
- Returns `True` if the subject was saved successfully.
- Raises `concurrent.futures.CancelledError` if the save was cancelled.
- If the save failed, raises the relevant exception.
... | Retrieves the result of this subject's asynchronous save.
- Returns `True` if the subject was saved successfully.
- Raises `concurrent.futures.CancelledError` if the save was cancelled.
- If the save failed, raises the relevant exception.
- Returns `False` if the subject hasn't finished... |
def extra_create_kwargs(self):
"""
Inject the domain of the current user in the new model instances.
"""
user = self.get_agnocomplete_context()
if user:
_, domain = user.email.split('@')
return {
'domain': domain
}
retur... | Inject the domain of the current user in the new model instances. |
def _request(self, service, **kw):
"""Do the actual request to Fastbill's API server.
If successful returns the RESPONSE section the of response, in
case of an error raises a subclass of FastbillError.
"""
fb_request = {
'service': service,
}
for key ... | Do the actual request to Fastbill's API server.
If successful returns the RESPONSE section the of response, in
case of an error raises a subclass of FastbillError. |
def create(gandi, resource, domain, duration, owner, admin, tech, bill,
nameserver, extra_parameter, background):
"""Buy a domain."""
if domain:
gandi.echo('/!\ --domain option is deprecated and will be removed '
'upon next release.')
gandi.echo("You should use 'gan... | Buy a domain. |
def headerHTML(header,fname):
"""given the bytestring ABF header, make and launch HTML."""
html="<html><body><code>"
html+="<h2>%s</h2>"%(fname)
html+=pprint.pformat(header, indent=1)
html=html.replace("\n",'<br>').replace(" "," ")
html=html.replace(r"\x00","")
... | given the bytestring ABF header, make and launch HTML. |
def parse_args(spectypes):
"""
Return arguments object formed by parsing the command line used to launch
the program.
"""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
"-c", "--constants",
help="emit constants instead of spec dict",
action="store_true"
... | Return arguments object formed by parsing the command line used to launch
the program. |
def import_domaindump():
"""
Parses ldapdomaindump files and stores hosts and users in elasticsearch.
"""
parser = argparse.ArgumentParser(
description="Imports users, groups and computers result files from the ldapdomaindump tool, will resolve the names from domain_computers output for IPs"... | Parses ldapdomaindump files and stores hosts and users in elasticsearch. |
def _tile(self, n):
"""Get the update tile surrounding particle `n` """
pos = self._trans(self.pos[n])
return Tile(pos, pos).pad(self.support_pad) | Get the update tile surrounding particle `n` |
def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
# if no actual arguments, print help
if len(self.actual_arguments) < 1:
return self.print_help(short=True)
# check if we have a recognized tool switc... | Perform command and return the appropriate exit code.
:rtype: int |
def _query_zendesk(self, endpoint, object_type, *endpoint_args, **endpoint_kwargs):
"""
Query Zendesk for items. If an id or list of ids are passed, attempt to locate these items
in the relevant cache. If they cannot be found, or no ids are passed, execute a call to Zendesk
to retrieve... | Query Zendesk for items. If an id or list of ids are passed, attempt to locate these items
in the relevant cache. If they cannot be found, or no ids are passed, execute a call to Zendesk
to retrieve the items.
:param endpoint: target endpoint.
:param object_type: object type we are ex... |
def propagate_defaults(config_doc):
"""
Propagate default values to sections of the doc.
"""
for group_name, group_doc in config_doc.items():
if isinstance(group_doc, dict):
defaults = group_doc.get('defaults', {})
for item_name, item_doc in group_doc.items():
... | Propagate default values to sections of the doc. |
def server(self):
"""Returns the size of remote files
"""
try:
tar = urllib2.urlopen(self.registry)
meta = tar.info()
return int(meta.getheaders("Content-Length")[0])
except (urllib2.URLError, IndexError):
return " " | Returns the size of remote files |
def menucheck(self, window_name, object_name):
"""
Check (click) a menu item.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
... | Check (click) a menu item.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name convention, or a Unix glob. Or menu heirarchy
... |
def makeAsn(segID,N, CA, C, O, geo):
'''Creates an Asparagine residue'''
##R-Group
CA_CB_length=geo.CA_CB_length
C_CA_CB_angle=geo.C_CA_CB_angle
N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle
CB_CG_length=geo.CB_CG_length
CA_CB_CG_angle=geo.CA_CB_CG_angle
N_CA_CB_CG_diangle=geo.N_CA_CB_CG_... | Creates an Asparagine residue |
def get_ad_via_hitid(hit_id):
''' Get ad via HIT id '''
username = CONFIG.get('psiTurk Access', 'psiturk_access_key_id')
password = CONFIG.get('psiTurk Access', 'psiturk_secret_access_id')
try:
req = requests.get('https://api.psiturk.org/api/ad/lookup/' + hit_id,
auth=... | Get ad via HIT id |
def user_remove(name,
database=None,
user=None,
password=None,
host=None,
port=None):
'''
Remove a cluster admin or a database user.
If a database is specified: it will remove the database user.
If a database is not specifi... | Remove a cluster admin or a database user.
If a database is specified: it will remove the database user.
If a database is not specified: it will remove the cluster admin.
name
User name to remove
database
The database to remove the user from
user
User name for the new use... |
def _parse_reserved_marker(self, fptr):
"""Marker range between 0xff30 and 0xff39.
"""
the_id = '0x{0:x}'.format(self._marker_id)
segment = Segment(marker_id=the_id, offset=self._offset, length=0)
return segment | Marker range between 0xff30 and 0xff39. |
def step_undefined_step_snippets_should_not_exist_for_table(context):
"""
Checks if undefined-step snippets are not provided.
EXAMPLE:
Then undefined-step snippets should not exist for:
| Step |
| When an known step is used |
| Then another known step is used |
... | Checks if undefined-step snippets are not provided.
EXAMPLE:
Then undefined-step snippets should not exist for:
| Step |
| When an known step is used |
| Then another known step is used | |
def _format_regular_value(self, str_in):
# type: (Text) -> Text
""" we need to reformat integer strings, as there can be different
strings for the same integer. The
strategy of unification here is to first parse the integer
string to an Integer type. Thus all of
... | we need to reformat integer strings, as there can be different
strings for the same integer. The
strategy of unification here is to first parse the integer
string to an Integer type. Thus all of
'+13', ' 13', '13' will be parsed to 13. We then convert the
integer ... |
def matches(self, name):
"""Does the name match my requirements?
To match, a name must match config.testMatch OR config.include
and it must not match config.exclude
"""
return ((self.match.search(name)
or (self.include and
filter(None,
... | Does the name match my requirements?
To match, a name must match config.testMatch OR config.include
and it must not match config.exclude |
def restart(name, timeout=90, with_deps=False, with_parents=False):
'''
Restart the named service. This issues a stop command followed by a start.
Args:
name: The name of the service to restart.
.. note::
If the name passed is ``salt-minion`` a scheduled task is
... | Restart the named service. This issues a stop command followed by a start.
Args:
name: The name of the service to restart.
.. note::
If the name passed is ``salt-minion`` a scheduled task is
created and executed to restart the salt-minion service.
timeo... |
def reset(self):
"""
Deactivate all cells.
"""
self.activeCells = np.empty(0, dtype="uint32")
self.activeDeltaSegments = np.empty(0, dtype="uint32")
self.activeFeatureLocationSegments = np.empty(0, dtype="uint32") | Deactivate all cells. |
def get_commands_from(self, args):
""" We have to code the key names for each depth. This method scans
for each level and returns a list of the command arguments. """
commands = []
for i in itertools.count(0):
try:
commands.append(getattr(args, self.arg_label... | We have to code the key names for each depth. This method scans
for each level and returns a list of the command arguments. |
def create_df_file_with_query(self, query, output):
""" Dumps in df in chunks to avoid crashes.
"""
chunk_size = 100000
offset = 0
data = defaultdict(lambda : defaultdict(list))
with open(output, 'wb') as outfile:
query = query.replace(';', '')
qu... | Dumps in df in chunks to avoid crashes. |
def _do_identity_role_list(args):
"""Lists the current on-chain configuration values.
"""
rest_client = RestClient(args.url)
state = rest_client.list_state(subtree=IDENTITY_NAMESPACE + _ROLE_PREFIX)
head = state['head']
state_values = state['data']
printable_roles = []
for state_value i... | Lists the current on-chain configuration values. |
def numdiff(fun, args):
"""Vectorized numerical differentiation"""
# vectorized version
epsilon = 1e-8
args = list(args)
v0 = fun(*args)
N = v0.shape[0]
l_v = len(v0)
dvs = []
for i, a in enumerate(args):
l_a = (a).shape[1]
dv = numpy.zeros((N, l_v, l_a))
na... | Vectorized numerical differentiation |
def locations(self, exists=True):
""" Return the location of the config file(s).
A given directory will be scanned for ``*.conf`` files, in alphabetical order.
Any duplicates will be eliminated.
If ``exists`` is True, only existing configuration locations are returned.
... | Return the location of the config file(s).
A given directory will be scanned for ``*.conf`` files, in alphabetical order.
Any duplicates will be eliminated.
If ``exists`` is True, only existing configuration locations are returned. |
def get_videos_for_ids(
edx_video_ids,
sort_field=None,
sort_dir=SortDirection.asc
):
"""
Returns an iterator of videos that match the given list of ids.
Args:
edx_video_ids (list)
sort_field (VideoSortField)
sort_dir (SortDirection)
Returns:
A g... | Returns an iterator of videos that match the given list of ids.
Args:
edx_video_ids (list)
sort_field (VideoSortField)
sort_dir (SortDirection)
Returns:
A generator expression that contains the videos found, sorted by the
given field and direction, with ties broken by e... |
def getmembers(obj, *predicates):
""" Return all the members of an object as a list of `(key, value)` tuples, sorted by name.
The optional list of predicates can be used to filter the members.
The default predicate drops members whose name starts with '_'. To disable it, pass `None` as the first predicate... | Return all the members of an object as a list of `(key, value)` tuples, sorted by name.
The optional list of predicates can be used to filter the members.
The default predicate drops members whose name starts with '_'. To disable it, pass `None` as the first predicate.
:param obj: Object to list the memb... |
def quote_single_identifier(self, string):
"""
Quotes a single identifier (no dot chain separation).
:param string: The identifier name to be quoted.
:type string: str
:return: The quoted identifier string.
:rtype: str
"""
c = self.get_identifier_quote_c... | Quotes a single identifier (no dot chain separation).
:param string: The identifier name to be quoted.
:type string: str
:return: The quoted identifier string.
:rtype: str |
def run(self, command):
"""
Execute a command on the remote host. Return a tuple containing
an integer status and a two strings, the first containing stdout
and the second containing stderr from the command.
"""
boto.log.debug('running:%s on %s' % (command, self.server.i... | Execute a command on the remote host. Return a tuple containing
an integer status and a two strings, the first containing stdout
and the second containing stderr from the command. |
def attach_network_interface(device_index, name=None, network_interface_id=None,
instance_name=None, instance_id=None,
region=None, key=None, keyid=None, profile=None):
'''
Attach an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Exa... | Attach an Elastic Network Interface.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.attach_network_interface my_eni instance_name=salt-master device_index=0 |
def get(self, *args, **kwargs):
"""
Get the sub interfaces for this VlanInterface
>>> itf = engine.interface.get(3)
>>> list(itf.vlan_interface)
[Layer3PhysicalInterfaceVlan(name=VLAN 3.3), Layer3PhysicalInterfaceVlan(name=VLAN 3.5),
Layer3Physica... | Get the sub interfaces for this VlanInterface
>>> itf = engine.interface.get(3)
>>> list(itf.vlan_interface)
[Layer3PhysicalInterfaceVlan(name=VLAN 3.3), Layer3PhysicalInterfaceVlan(name=VLAN 3.5),
Layer3PhysicalInterfaceVlan(name=VLAN 3.4)]
:par... |
def flatten(repertoire, big_endian=False):
"""Flatten a repertoire, removing empty dimensions.
By default, the flattened repertoire is returned in little-endian order.
Args:
repertoire (np.ndarray or None): A repertoire.
Keyword Args:
big_endian (boolean): If ``True``, flatten the rep... | Flatten a repertoire, removing empty dimensions.
By default, the flattened repertoire is returned in little-endian order.
Args:
repertoire (np.ndarray or None): A repertoire.
Keyword Args:
big_endian (boolean): If ``True``, flatten the repertoire in big-endian
order.
Retu... |
def _init_rgb(self, r: int, g: int, b: int) -> None:
""" Initialize from red, green, blue args. """
if self.rgb_mode:
self.rgb = (r, g, b)
self.hexval = rgb2hex(r, g, b)
else:
self.rgb = hex2rgb(rgb2termhex(r, g, b))
self.hexval = rgb2termhex(r, g,... | Initialize from red, green, blue args. |
def save(self, filename=None):
"""
saves the configuration in the given filename,
if it is none the filename at load time is used.
:param filename: the file name
:type filename: string
:return:
"""
content = self.data.yaml()
with open(Config.path_e... | saves the configuration in the given filename,
if it is none the filename at load time is used.
:param filename: the file name
:type filename: string
:return: |
def delete_invalid_route(self):
"""
Delete any invalid routes for this interface. An invalid route is
a left over when an interface is changed to a different network.
:return: None
"""
try:
routing = self._engine.routing.get(self.interface_id)
... | Delete any invalid routes for this interface. An invalid route is
a left over when an interface is changed to a different network.
:return: None |
def chgrp(path, group):
'''
Change the group of a file
Under Windows, this will do nothing.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility fea... | Change the group of a file
Under Windows, this will do nothing.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, N... |
def getrawpart(self, msgid, stream=sys.stdout):
"""Get the first part from the message and print it raw.
"""
for hdr, part in self._get(msgid):
pl = part.get_payload(decode=True)
if pl != None:
print(pl, file=stream)
break | Get the first part from the message and print it raw. |
def stop(self):
"""Stop the Heartbeat Checker.
:return:
"""
self._running.clear()
with self._lock:
if self._timer:
self._timer.cancel()
self._timer = None | Stop the Heartbeat Checker.
:return: |
def on(self):
"""!
\~english
Open Audio output. set pin mode to ALT0
@return a boolean value. if True means open audio output is OK otherwise failed to open.
\~chinese
打开音频输出。 将引脚模式设置为ALT0
@return 布尔值。 如果 True 表示打开音频输出成功,否则不成功。
"""
isOK = True
... | !
\~english
Open Audio output. set pin mode to ALT0
@return a boolean value. if True means open audio output is OK otherwise failed to open.
\~chinese
打开音频输出。 将引脚模式设置为ALT0
@return 布尔值。 如果 True 表示打开音频输出成功,否则不成功。 |
def records(self):
"""
Access the records
:returns: twilio.rest.api.v2010.account.usage.record.RecordList
:rtype: twilio.rest.api.v2010.account.usage.record.RecordList
"""
if self._records is None:
self._records = RecordList(self._version, account_sid=self._s... | Access the records
:returns: twilio.rest.api.v2010.account.usage.record.RecordList
:rtype: twilio.rest.api.v2010.account.usage.record.RecordList |
def _estimate_AICc(self, y, mu, weights=None):
"""
estimate the corrected Akaike Information Criterion
relies on the estimated degrees of freedom, which must be computed
before.
Parameters
----------
y : array-like of shape (n_samples,)
output data v... | estimate the corrected Akaike Information Criterion
relies on the estimated degrees of freedom, which must be computed
before.
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,)
exp... |
def serial(self, may_block=True):
""" Get the YubiKey serial number (requires YubiKey 2.2). """
if not self.capabilities.have_serial_number():
raise yubikey_base.YubiKeyVersionError("Serial number unsupported in YubiKey %s" % self.version() )
return self._read_serial(may_block) | Get the YubiKey serial number (requires YubiKey 2.2). |
def width(self, level):
"""
Width at given level
:param level:
:return:
"""
return self.x_at_y(level, reverse=True) - self.x_at_y(level) | Width at given level
:param level:
:return: |
def split_signature(klass, signature):
"""Return a list of the element signatures of the topmost signature tuple.
If the signature is not a tuple, it returns one element with the entire
signature. If the signature is an empty tuple, the result is [].
This is useful for e. g. iterating ... | Return a list of the element signatures of the topmost signature tuple.
If the signature is not a tuple, it returns one element with the entire
signature. If the signature is an empty tuple, the result is [].
This is useful for e. g. iterating over method parameters which are
passed as... |
def lm_deltat(freqs, damping_times, modes):
"""Return the minimum delta_t of all the modes given, with delta_t given by
the inverse of the frequency at which the amplitude of the ringdown falls to
1/1000 of the peak amplitude.
"""
dt = {}
for lmn in modes:
l, m, nmodes = int(lmn[0]), in... | Return the minimum delta_t of all the modes given, with delta_t given by
the inverse of the frequency at which the amplitude of the ringdown falls to
1/1000 of the peak amplitude. |
def clone(self, **kwargs):
"""
Clone a part.
.. versionadded:: 2.3
:param kwargs: (optional) additional keyword=value arguments
:type kwargs: dict
:return: cloned :class:`models.Part`
:raises APIError: if the `Part` could not be cloned
Example
-... | Clone a part.
.. versionadded:: 2.3
:param kwargs: (optional) additional keyword=value arguments
:type kwargs: dict
:return: cloned :class:`models.Part`
:raises APIError: if the `Part` could not be cloned
Example
-------
>>> bike = client.model('Bike')
... |
def register_event(self, event_type, pattern, handler):
""" When ``event_type`` is observed for ``pattern``, triggers ``handler``.
For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and
the base screen state.
"""
if event_type not in self._supported_eve... | When ``event_type`` is observed for ``pattern``, triggers ``handler``.
For "CHANGE" events, ``pattern`` should be a tuple of ``min_changed_pixels`` and
the base screen state. |
def add_relationship(self, rel_uri, obj):
"""
Add a new relationship to the RELS-EXT for this object.
Calls :meth:`API_M.addRelationship`.
Example usage::
isMemberOfCollection = 'info:fedora/fedora-system:def/relations-external#isMemberOfCollection'
collection_u... | Add a new relationship to the RELS-EXT for this object.
Calls :meth:`API_M.addRelationship`.
Example usage::
isMemberOfCollection = 'info:fedora/fedora-system:def/relations-external#isMemberOfCollection'
collection_uri = 'info:fedora/foo:456'
object.add_relationship... |
def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
posterior_model = self.posterior_model
if self.dims is None:
dims = {}
else:
dims = self.dims
observed_names = self.observed_data
if isinstance(observed_names, str):
... | Convert observed data to xarray. |
def init(self, context):
"""Initializes sitetree to handle new request.
:param Context|None context:
"""
self.cache = Cache()
self.current_page_context = context
self.current_request = context.get('request', None) if context else None
self.current_lang = get_lang... | Initializes sitetree to handle new request.
:param Context|None context: |
def _Close(self):
"""Closes the file system object.
Raises:
IOError: if the close failed.
"""
self._vslvm_volume_group = None
self._vslvm_handle.close()
self._vslvm_handle = None
self._file_object.close()
self._file_object = None | Closes the file system object.
Raises:
IOError: if the close failed. |
def init(options=None, ini_paths=None, argv=None,
strict=False, **parser_kwargs):
"""Initialize singleton config and read/parse configuration.
:keyword bool strict: when true, will error out on invalid arguments
(default behavior is to ignore them)
:returns: the loaded configuration.
"... | Initialize singleton config and read/parse configuration.
:keyword bool strict: when true, will error out on invalid arguments
(default behavior is to ignore them)
:returns: the loaded configuration. |
def preview_email_marketing_campaign(self, email_marketing_campaign):
"""Returns HTML and text previews of an EmailMarketingCampaign.
"""
url = self.api.join('/'.join([
self.EMAIL_MARKETING_CAMPAIGN_URL,
str(email_marketing_campaign.constant_contact_id),
'prev... | Returns HTML and text previews of an EmailMarketingCampaign. |
def get (self, key, def_val=None):
"""Return lowercase key value."""
assert isinstance(key, basestring)
return dict.get(self, key.lower(), def_val) | Return lowercase key value. |
def dump(result):
"""Dump result into a string, useful for debugging."""
if isinstance(result, dict):
# Result is a search result.
statuses = result['results']
else:
# Result is a lookup result.
statuses = result
status_str_list = []
... | Dump result into a string, useful for debugging. |
def setup(docker_mount=None, force=False):
'''
Prepare a vanilla server by installing docker, curl, and sshpass. If a file called ``dot_dockercfg``
exists in the current working directory, it is uploaded as ``~/.dockercfg``.
Args:
* docker_mount=None: Partition that will be mounted as /var/lib/... | Prepare a vanilla server by installing docker, curl, and sshpass. If a file called ``dot_dockercfg``
exists in the current working directory, it is uploaded as ``~/.dockercfg``.
Args:
* docker_mount=None: Partition that will be mounted as /var/lib/docker |
def new_dxworkflow(title=None, summary=None, description=None, output_folder=None, init_from=None, **kwargs):
'''
:param title: Workflow title (optional)
:type title: string
:param summary: Workflow summary (optional)
:type summary: string
:param description: Workflow description (optional)
... | :param title: Workflow title (optional)
:type title: string
:param summary: Workflow summary (optional)
:type summary: string
:param description: Workflow description (optional)
:type description: string
:param output_folder: Default output folder of the workflow (optional)
:type output_fold... |
def telnet_config(self, status):
"""
status:
false - Telnet is disabled
true - Telnet is enabled
"""
ret = self.command(
'configManager.cgi?action=setConfig&Telnet.Enable={0}'.format(
status)
)
return ret.content.decode... | status:
false - Telnet is disabled
true - Telnet is enabled |
def incr(self, name, amount=1):
"""
Increase the value at key ``name`` by ``amount``. If no key exists, the value
will be initialized as ``amount`` .
Like **Redis.INCR**
:param string name: the key name
:param int amount: increments
:return: the integer value at... | Increase the value at key ``name`` by ``amount``. If no key exists, the value
will be initialized as ``amount`` .
Like **Redis.INCR**
:param string name: the key name
:param int amount: increments
:return: the integer value at key ``name``
:rtype: int
>>> ssdb.... |
def ping(dest_ip=None, **kwargs):
'''
Send a ping RPC to a device
dest_ip
The IP of the device to ping
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
rapid : False
When ``True``, executes ping at 100pps instead of 1pps
ttl
Maximum number of IP routers (IP... | Send a ping RPC to a device
dest_ip
The IP of the device to ping
dev_timeout : 30
The NETCONF RPC timeout (in seconds)
rapid : False
When ``True``, executes ping at 100pps instead of 1pps
ttl
Maximum number of IP routers (IP hops) allowed between source and
dest... |
def from_custom_template(cls, searchpath, name):
"""
Factory function for creating a subclass of ``Styler``
with a custom template and Jinja environment.
Parameters
----------
searchpath : str or list
Path or paths of directories containing the templates
... | Factory function for creating a subclass of ``Styler``
with a custom template and Jinja environment.
Parameters
----------
searchpath : str or list
Path or paths of directories containing the templates
name : str
Name of your custom template to use for re... |
def load(self, config_data):
"""
Loads sanitizers according to rulesets defined in given already parsed
configuration file.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any]
"""
if not isinstance(config_data, d... | Loads sanitizers according to rulesets defined in given already parsed
configuration file.
:param config_data: Already parsed configuration data, as dictionary.
:type config_data: dict[str,any] |
def next(self):
"""Returns the next line from this input reader as (lineinfo, line) tuple.
Returns:
The next input from this input reader, in the form of a 2-tuple.
The first element of the tuple describes the source, it is itself
a tuple (blobkey, filenumber, byteoffset).
The second ... | Returns the next line from this input reader as (lineinfo, line) tuple.
Returns:
The next input from this input reader, in the form of a 2-tuple.
The first element of the tuple describes the source, it is itself
a tuple (blobkey, filenumber, byteoffset).
The second element of the tuple is... |
def read_ttl(path):
''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read()
'''
warnings.warn("Document.read_ttl() is deprecated and will be removed in near future. Use read... | Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read() |
def create(self, fname, lname, group, type, group_api):
"""Create an LDAP User."""
self.__username(fname, lname)
self.client.add(
self.__distinguished_name(type, fname=fname, lname=lname),
API.__object_class(),
self.__ldap_attr(fname, lname, type, group, group... | Create an LDAP User. |
def get_environ(self, sock):
"""Create WSGI environ entries to be merged into each request."""
cipher = sock.cipher()
ssl_environ = {
"wsgi.url_scheme": "https",
"HTTPS": "on",
'SSL_PROTOCOL': cipher[1],
'SSL_CIPHER': cipher[0]
## SSL_VE... | Create WSGI environ entries to be merged into each request. |
def process_results(self):
""" Process results by providers """
for result in self._results:
provider = result.provider
self.providers.append(provider)
if result.error:
self.failed_providers.append(provider)
continue
if not ... | Process results by providers |
def lpc(blk, order=None):
"""
Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation is based on the
covariance method, assuming a zero-mean stochastic process, finding
the coefficients iteratively and greedily like the lattice implementati... | Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation is based on the
covariance method, assuming a zero-mean stochastic process, finding
the coefficients iteratively and greedily like the lattice implementation
in Levinson-Durbin algorithm,... |
def transpose(self):
"""Return the transpose of the QuantumChannel."""
kraus_l, kraus_r = self._data
kraus_l = [k.T for k in kraus_l]
if kraus_r is not None:
kraus_r = [k.T for k in kraus_r]
return Kraus((kraus_l, kraus_r),
input_dims=self.output_... | Return the transpose of the QuantumChannel. |
def arc(pRA, pDecl, sRA, sDecl, mcRA, lat):
""" Returns the arc of direction between a Promissor
and Significator. It uses the generic proportional
semi-arc method.
"""
pDArc, pNArc = utils.dnarcs(pDecl, lat)
sDArc, sNArc = utils.dnarcs(sDecl, lat)
# Select meridian and arcs to b... | Returns the arc of direction between a Promissor
and Significator. It uses the generic proportional
semi-arc method. |
def put(self, request, bot_id, id, format=None):
"""
Update existing MessengerBot
---
serializer: MessengerBotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
... | Update existing MessengerBot
---
serializer: MessengerBotUpdateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request |
def editText(self, y, x, w, record=True, **kwargs):
'Wrap global editText with `preedit` and `postedit` hooks.'
v = self.callHook('preedit') if record else None
if not v or v[0] is None:
with EnableCursor():
v = editText(self.scr, y, x, w, **kwargs)
else:
... | Wrap global editText with `preedit` and `postedit` hooks. |
def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Simulate mouse left button drag from point x1, y1 drop to point x2, y2.
x1: int.
y1: int.
x2: int.
y2: int.
moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move f... | Simulate mouse left button drag from point x1, y1 drop to point x2, y2.
x1: int.
y1: int.
x2: int.
y2: int.
moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster.
waitTime: float. |
def ordered_storage(config, name=None):
'''Return ordered storage system based on the specified config.
The canonical example of such a storage container is
``defaultdict(list)``. Thus, the return value of this method contains
keys and values. The values are ordered lists with the last added
item a... | Return ordered storage system based on the specified config.
The canonical example of such a storage container is
``defaultdict(list)``. Thus, the return value of this method contains
keys and values. The values are ordered lists with the last added
item at the end.
Args:
config (dict): De... |
def compact(self):
"""
Switch to the compact variant of the live form template.
By default, this will simply create a loader for the
C{self.compactFragmentName} template and compact all of this form's
parameters.
"""
self.docFactory = webtheme.getLoader(self.comp... | Switch to the compact variant of the live form template.
By default, this will simply create a loader for the
C{self.compactFragmentName} template and compact all of this form's
parameters. |
def get_memory_info(self):
"""Return a tuple with the process' RSS and VMS size."""
rss, vms = _psutil_osx.get_process_memory_info(self.pid)[:2]
return nt_meminfo(rss, vms) | Return a tuple with the process' RSS and VMS size. |
def delete(self, name):
"""
Deletes the named entry in the cache.
:param name: the name.
:return: true if it is deleted.
"""
if name in self._cache:
del self._cache[name]
self.writeCache()
# TODO clean files
return True
... | Deletes the named entry in the cache.
:param name: the name.
:return: true if it is deleted. |
def update(self, portfolio, date, perfs=None):
'''
Actualizes the portfolio universe with the alog state
'''
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date | Actualizes the portfolio universe with the alog state |
def remove_item(self, item_id, assessment_part_id):
"""Removes an ``Item`` from an ``AssessmentPartId``.
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
arg: assessment_part_id (osid.id.Id): ``Id`` of the
``AssessmentPartId``
raise: NotFound - ``item_id`` ``not... | Removes an ``Item`` from an ``AssessmentPartId``.
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
arg: assessment_part_id (osid.id.Id): ``Id`` of the
``AssessmentPartId``
raise: NotFound - ``item_id`` ``not found in
assessment_part_id``
raise: ... |
def endpoint_from_model_data(self, model_s3_location, deployment_image, initial_instance_count, instance_type,
name=None, role=None, wait=True, model_environment_vars=None, model_vpc_config=None,
accelerator_type=None):
"""Create and deploy to an... | Create and deploy to an ``Endpoint`` using existing model data stored in S3.
Args:
model_s3_location (str): S3 URI of the model artifacts to use for the endpoint.
deployment_image (str): The Docker image which defines the runtime code to be used as
the entry point for ac... |
def check_slice_perms(self, slice_id):
"""
Check if user can access a cached response from slice_json.
This function takes `self` since it must have the same signature as the
the decorated method.
"""
form_data, slc = get_form_data(slice_id, use_slice_data=True)
datasource_type = slc.datas... | Check if user can access a cached response from slice_json.
This function takes `self` since it must have the same signature as the
the decorated method. |
def expand_config(d, dirs):
"""
Expand configuration XDG variables, environmental variables, and tildes.
Parameters
----------
d : dict
config information
dirs : appdirs.AppDirs
XDG application mapping
Notes
-----
*Environmentable variables* are expanded via :py:fun... | Expand configuration XDG variables, environmental variables, and tildes.
Parameters
----------
d : dict
config information
dirs : appdirs.AppDirs
XDG application mapping
Notes
-----
*Environmentable variables* are expanded via :py:func:`os.path.expandvars`.
So ``${PWD}`... |
def next_token(self, tok, include_extra=False):
"""
Returns the next token after the given one. If include_extra is True, includes non-coding
tokens from the tokenize module, such as NL and COMMENT.
"""
i = tok.index + 1
if not include_extra:
while is_non_coding_token(self._tokens[i].type)... | Returns the next token after the given one. If include_extra is True, includes non-coding
tokens from the tokenize module, such as NL and COMMENT. |
def write_int8(self, value, little_endian=True):
"""
Pack the value as a signed byte and write 1 byte to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written.
... | Pack the value as a signed byte and write 1 byte to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. |
def rewrite_elife_authors_json(json_content, doi):
""" this does the work of rewriting elife authors json """
# Convert doi from testing doi if applicable
article_doi = elifetools.utils.convert_testing_doi(doi)
# Edge case fix an affiliation name
if article_doi == "10.7554/eLife.06956":
fo... | this does the work of rewriting elife authors json |
def remove_server_data(server_id):
"""
Remove a server from the server data
Args:
server_id (int): The server to remove from the server data
"""
logger.debug("Removing server from serverdata")
# Remove the server from data
data = datatools.get_data()
if server_id in data["disco... | Remove a server from the server data
Args:
server_id (int): The server to remove from the server data |
def force_invalidate(self, vts):
"""Force invalidation of a VersionedTargetSet."""
for vt in vts.versioned_targets:
self._invalidator.force_invalidate(vt.cache_key)
vt.valid = False
self._invalidator.force_invalidate(vts.cache_key)
vts.valid = False | Force invalidation of a VersionedTargetSet. |
def cmd_link(self, args):
'''handle link commands'''
if len(args) < 1:
self.show_link()
elif args[0] == "list":
self.cmd_link_list()
elif args[0] == "add":
if len(args) != 2:
print("Usage: link add LINK")
return
... | handle link commands |
def name_variants(self):
"""A list of namedtuples representing variants of the affiliation name
with number of documents referring to this variant.
"""
out = []
variant = namedtuple('Variant', 'name doc_count')
for var in chained_get(self._json, ['name-variants', 'name-va... | A list of namedtuples representing variants of the affiliation name
with number of documents referring to this variant. |
def assign_taxonomy(dataPath, reference_sequences_fp, id_to_taxonomy_fp, read_1_seqs_fp, read_2_seqs_fp, single_ok=False, no_single_ok_generic=False,
header_id_regex=None, read_id_regex = "\S+\s+(\S+)", amplicon_id_regex = "(\S+)\s+(\S+?)\/",
output_fp=None, log_path=None, HALT_E... | Assign taxonomy to each sequence in data with the RTAX classifier
# data: open fasta file object or list of fasta lines
dataPath: path to a fasta file
output_fp: path to write output; if not provided, result will be
returned in a dict of {seq_id:(taxonomy_assignment,confidence)} |
def wait_time(departure, now=None):
"""
Calculate waiting time until the next departure time in 'HH:MM' format.
Return time-delta (as 'MM:SS') from now until next departure time in the
future ('HH:MM') given as (year, month, day, hour, minute, seconds).
Time-deltas shorter than 60 seconds are red... | Calculate waiting time until the next departure time in 'HH:MM' format.
Return time-delta (as 'MM:SS') from now until next departure time in the
future ('HH:MM') given as (year, month, day, hour, minute, seconds).
Time-deltas shorter than 60 seconds are reduced to 0. |
def _write_cvvr(self, f, data):
'''
Write compressed "data" variable to the end of the file in a CVVR
'''
f.seek(0, 2)
byte_loc = f.tell()
cSize = len(data)
block_size = CDF.CVVR_BASE_SIZE64 + cSize
section_type = CDF.CVVR_
rfuA = 0
cvvr1 ... | Write compressed "data" variable to the end of the file in a CVVR |
def gdf_from_places(queries, gdf_name='unnamed', buffer_dist=None):
"""
Create a GeoDataFrame from a list of place names to query.
Parameters
----------
queries : list
list of query strings or structured query dicts to geocode/download, one
at a time
gdf_name : string
na... | Create a GeoDataFrame from a list of place names to query.
Parameters
----------
queries : list
list of query strings or structured query dicts to geocode/download, one
at a time
gdf_name : string
name attribute metadata for GeoDataFrame (this is used to save shapefile
l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.