code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def delete_permanent(self, list_id, subscriber_hash):
"""
Delete permanently a member from a list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param subscriber_hash: The MD5 hash of the lowercase version of the
list member’s email addres... | Delete permanently a member from a list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param subscriber_hash: The MD5 hash of the lowercase version of the
list member’s email address.
:type subscriber_hash: :py:class:`str` |
def rdf_suffix(fmt: str) -> str:
""" Map the RDF format to the approproate suffix """
for k, v in SUFFIX_FORMAT_MAP.items():
if fmt == v:
return k
return 'rdf' | Map the RDF format to the approproate suffix |
def prepare_token_revocation_request(self, revocation_url, token,
token_type_hint="access_token", body='', callback=None, **kwargs):
"""Prepare a token revocation request.
:param revocation_url: Provider token revocation endpoint URL.
:param token: The ... | Prepare a token revocation request.
:param revocation_url: Provider token revocation endpoint URL.
:param token: The access or refresh token to be revoked (string).
:param token_type_hint: ``"access_token"`` (default) or
``"refresh_token"``. This is optional and if you wish to not pas... |
def create_pipeline_stage(self, pipeline_key, name, **kwargs):
'''Creates a pipeline stage with the provided attributes.
Args:
name required name string
kwargs {..} see StreakStage object for details
return (status code, stage dict)
'''
#req sanity check
if not (pipeline_key and name):
return requ... | Creates a pipeline stage with the provided attributes.
Args:
name required name string
kwargs {..} see StreakStage object for details
return (status code, stage dict) |
def remove(self, auto_confirm=False):
"""Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True)."""
if not self._can_uninstall():
return
if not self.paths:
logger.info(
"Can't uninstall '%s'. No files were found to unins... | Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True). |
def key_changed(self):
"""Checks if the key name and value fields have been set, and updates the add key button"""
if self.key_name.get() and self.key_val.get():
self.button_key_add.state(["!disabled"])
else:
self.button_key_add.state(["disabled"]) | Checks if the key name and value fields have been set, and updates the add key button |
def is_valid_resource_name(rname, exception_type=None):
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_typ... | Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whethe... |
def user_list(self, params=None):
"""Lists all users within the tenant."""
uri = 'openstack/users'
if params:
uri += '?%s' % urllib.urlencode(params)
resp, body = self.get(uri)
self.expected_success(200, resp.status)
body = json.loads(body)
return re... | Lists all users within the tenant. |
def ipaddr(value, options=None):
'''
Filters and returns only valid IP objects.
'''
ipv4_obj = ipv4(value, options=options)
ipv6_obj = ipv6(value, options=options)
if ipv4_obj is None or ipv6_obj is None:
# an IP address can be either IPv4 either IPv6
# therefofe if the value pas... | Filters and returns only valid IP objects. |
def _check_for_dictionary_key(self, logical_id, dictionary, keys):
"""
Checks a dictionary to make sure it has a specific key. If it does not, an
InvalidResourceException is thrown.
:param string logical_id: logical id of this resource
:param dict dictionary: the dictionary to c... | Checks a dictionary to make sure it has a specific key. If it does not, an
InvalidResourceException is thrown.
:param string logical_id: logical id of this resource
:param dict dictionary: the dictionary to check
:param list keys: list of keys that should exist in the dictionary |
def modify(self, management_address=None, username=None, password=None,
connection_type=None):
"""
Modifies a remote system for remote replication.
:param management_address: same as the one in `create` method.
:param username: username for accessing the remote system.
... | Modifies a remote system for remote replication.
:param management_address: same as the one in `create` method.
:param username: username for accessing the remote system.
:param password: password for accessing the remote system.
:param connection_type: same as the one in `create` metho... |
def load(store):
"""Load data from an array or group into memory.
Parameters
----------
store : MutableMapping or string
Store or path to directory in file system or name of zip file.
Returns
-------
out
If the store contains an array, out will be a numpy array. If the stor... | Load data from an array or group into memory.
Parameters
----------
store : MutableMapping or string
Store or path to directory in file system or name of zip file.
Returns
-------
out
If the store contains an array, out will be a numpy array. If the store contains
a gro... |
def process_requests(self, requests, **context):
"""
Turns a list of request objects into a list of
response objects.
:param requests: A list of tuples describing the RPC call
:type requests: list[list[callable,object,object,list]]
:param context:
A dict with... | Turns a list of request objects into a list of
response objects.
:param requests: A list of tuples describing the RPC call
:type requests: list[list[callable,object,object,list]]
:param context:
A dict with additional parameters passed to handle_request_string and process_re... |
def send_zone_event(self, zone_id, event_name, *args):
""" Send an event to a zone. """
cmd = "EVENT %s!%s %s" % (
zone_id.device_str(), event_name,
" ".join(str(x) for x in args))
return (yield from self._send_cmd(cmd)) | Send an event to a zone. |
def unzip_file_to_dir(path_to_zip, output_directory):
"""
Extract a ZIP archive to a directory
"""
z = ZipFile(path_to_zip, 'r')
z.extractall(output_directory)
z.close() | Extract a ZIP archive to a directory |
def naturalize_string(key):
"""Analyzes string in a human way to enable natural sort
:param nodename: The node name to analyze
:returns: A structure that can be consumed by 'sorted'
"""
return [int(text) if text.isdigit() else text.lower()
for text in re.split(numregex, key)] | Analyzes string in a human way to enable natural sort
:param nodename: The node name to analyze
:returns: A structure that can be consumed by 'sorted' |
def bookDF(symbol, token='', version=''):
'''Book data
https://iextrading.com/developer/docs/#book
realtime during Investors Exchange market hours
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame... | Book data
https://iextrading.com/developer/docs/#book
realtime during Investors Exchange market hours
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result |
def apply(self, func, shortcut=False, args=(), **kwargs):
"""Apply a function over each array in the group and concatenate them
together into a new array.
`func` is called like `func(ar, *args, **kwargs)` for each array `ar`
in this group.
Apply uses heuristics (like `pandas.Gr... | Apply a function over each array in the group and concatenate them
together into a new array.
`func` is called like `func(ar, *args, **kwargs)` for each array `ar`
in this group.
Apply uses heuristics (like `pandas.GroupBy.apply`) to figure out how
to stack together the array. ... |
def Main(url):
'''
Entry Point.
Args:
url: target url.
'''
# The object of Web-Scraping.
web_scrape = WebScraping()
# Execute Web-Scraping.
document = web_scrape.scrape(url)
# The object of NLP.
nlp_base = NlpBase()
# Set tokenizer. This is japanese tokenizer ... | Entry Point.
Args:
url: target url. |
def _load_wurlitzer(self):
"""Load wurlitzer extension."""
# Wurlitzer has no effect on Windows
if not os.name == 'nt':
from IPython.core.getipython import get_ipython
# Enclose this in a try/except because if it fails the
# console will be totally unusable.
... | Load wurlitzer extension. |
def _op_generic_HAdd(self, args):
"""
Halving add, for some ARM NEON instructions.
"""
components = []
for a, b in self.vector_args(args):
if self.is_signed:
a = a.sign_extend(self._vector_size)
b = b.sign_extend(self._vector_size)
... | Halving add, for some ARM NEON instructions. |
def send(scope, data):
"""
Like exec(), but does not wait for a response of the remote host after
sending the command.
:type data: string
:param data: The data that is sent.
"""
conn = scope.get('__connection__')
for line in data:
conn.send(line)
return True | Like exec(), but does not wait for a response of the remote host after
sending the command.
:type data: string
:param data: The data that is sent. |
def get_date_type(calendar):
"""Return the cftime date type for a given calendar name."""
try:
import cftime
except ImportError:
raise ImportError(
'cftime is required for dates with non-standard calendars')
else:
calendars = {
'noleap': cftime.DatetimeNoL... | Return the cftime date type for a given calendar name. |
def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts):
'''
Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,e... | Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,enable_ddns
CLI Example:
.. code-block:: bash
salt-call infoblox.get_net... |
def requestSubsystem(self, subsystem):
"""Request a subsystem and return a deferred reply.
"""
data = common.NS(subsystem)
return self.sendRequest('subsystem', data, wantReply=True) | Request a subsystem and return a deferred reply. |
def drop_dose(self):
"""
Drop the maximum dose and related response values.
"""
doses = np.array(self.individual_doses)
responses = np.array(self.responses)
mask = doses != doses.max()
self.individual_doses = doses[mask].tolist()
self.responses = responses... | Drop the maximum dose and related response values. |
def DbExportDevice(self, argin):
""" Export a device to the database
:param argin: Str[0] = Device name
Str[1] = CORBA IOR
Str[2] = Device server process host name
Str[3] = Device server process PID or string ``null``
Str[4] = Device server process version
:type: tango.DevVarStringArray
... | Export a device to the database
:param argin: Str[0] = Device name
Str[1] = CORBA IOR
Str[2] = Device server process host name
Str[3] = Device server process PID or string ``null``
Str[4] = Device server process version
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid |
def feed(f, limit=25):
"""
Pull a feed
:param f: feed name (eg: csirtgadgetes/correlated)
:param limit: return value limit (default 25)
:return: Feed dict
"""
if '/' not in f:
raise ValueError('feed name must be formatted like: '
'csirtgadgets/scanners')
... | Pull a feed
:param f: feed name (eg: csirtgadgetes/correlated)
:param limit: return value limit (default 25)
:return: Feed dict |
def is_identifier(s):
"""Check whether given string is a valid Python identifier.
Note that this excludes language keywords, even though they exhibit
a general form of an identifier. See also :func:`has_identifier_form`.
:param s: String to check
:return: Whether ``s`` is a valid Python identifier... | Check whether given string is a valid Python identifier.
Note that this excludes language keywords, even though they exhibit
a general form of an identifier. See also :func:`has_identifier_form`.
:param s: String to check
:return: Whether ``s`` is a valid Python identifier |
def detect_loud_glitches(strain, psd_duration=4., psd_stride=2.,
psd_avg_method='median', low_freq_cutoff=30.,
threshold=50., cluster_window=5., corrupt_time=4.,
high_freq_cutoff=None, output_intermediates=False):
"""Automatic identification... | Automatic identification of loud transients for gating purposes.
This function first estimates the PSD of the input time series using the
FindChirp Welch method. Then it whitens the time series using that
estimate. Finally, it computes the magnitude of the whitened series,
thresholds it and applies the... |
def get_mnist_iter(args, kv):
"""
create data iterator with NDArrayIter
"""
(train_lbl, train_img) = read_data(
'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz')
(val_lbl, val_img) = read_data(
't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz')
train = mx... | create data iterator with NDArrayIter |
def search_meta(self, attr, value=None, stronly=False):
""" Get a list of Symbols by searching a specific meta
attribute, and optionally the value.
Parameters
----------
attr : str
The meta attribute to query.
value : None, str or list
... | Get a list of Symbols by searching a specific meta
attribute, and optionally the value.
Parameters
----------
attr : str
The meta attribute to query.
value : None, str or list
The meta attribute to query. If you pass a float, or an int,
... |
def request_pdu(self):
""" Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.addr... | Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU. |
def atleast(cls, lits, bound=1, top_id=None, encoding=EncType.seqcounter):
"""
This method can be used for creating a CNF encoding of an AtLeastK
constraint, i.e. of :math:`\sum_{i=1}^{n}{x_i}\geq k`. The method
takes 1 mandatory argument ``lits`` and 3 default arguments can ... | This method can be used for creating a CNF encoding of an AtLeastK
constraint, i.e. of :math:`\sum_{i=1}^{n}{x_i}\geq k`. The method
takes 1 mandatory argument ``lits`` and 3 default arguments can be
specified: ``bound``, ``top_id``, and ``encoding``.
:param lits: a list... |
def export_file(self, data_object, destination_directory=None,
destination_filename=None, retry=False,
export_metadata=False, export_raw_file=True):
"""Export a file from Loom to some file storage location.
Default destination_directory is cwd. Default destination... | Export a file from Loom to some file storage location.
Default destination_directory is cwd. Default destination_filename is the
filename from the file data object associated with the given file_id. |
def flip(self, axis=HORIZONTAL):
"""Flips the layer, either HORIZONTAL or VERTICAL.
"""
if axis == HORIZONTAL:
self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT)
if axis == VERTICAL:
self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM) | Flips the layer, either HORIZONTAL or VERTICAL. |
def _add_meta_info(self, eopatch, request_params, service_type):
""" Adds any missing metadata info to EOPatch """
for param, eoparam in zip(['time', 'time_difference', 'maxcc'], ['time_interval', 'time_difference', 'maxcc']):
if eoparam not in eopatch.meta_info:
eopatch.met... | Adds any missing metadata info to EOPatch |
def get_gitlab_project(self):
"""Get numerical GitLab Project ID.
Returns:
int: Project ID number.
Raises:
foremast.exceptions.GitLabApiError: GitLab responded with bad status
code.
"""
self.server = gitlab.Gitlab(GIT_URL, private_token=... | Get numerical GitLab Project ID.
Returns:
int: Project ID number.
Raises:
foremast.exceptions.GitLabApiError: GitLab responded with bad status
code. |
def _load(self, scale=0.001):
"""Load the OLCI relative spectral responses
"""
ncf = Dataset(self.path, 'r')
bandnum = OLCI_BAND_NAMES.index(self.bandname)
# cam = 0
# view = 0
# resp = ncf.variables[
# 'spectral_response_function'][bandnum, cam, vie... | Load the OLCI relative spectral responses |
def MakeClass(descriptor):
"""Construct a class object for a protobuf described by descriptor.
Composite descriptors are handled by defining the new class as a member of the
parent class, recursing as deep as necessary.
This is the dynamic equivalent to:
class Parent(message.Message):
__metaclass__ = Ge... | Construct a class object for a protobuf described by descriptor.
Composite descriptors are handled by defining the new class as a member of the
parent class, recursing as deep as necessary.
This is the dynamic equivalent to:
class Parent(message.Message):
__metaclass__ = GeneratedProtocolMessageType
D... |
def one_hot2indices(one_hots):
"""
Convert an iterable of one-hot encoded targets to a list of indices.
Parameters
----------
one_hot : list
Returns
-------
indices : list
Examples
--------
>>> one_hot2indices([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
[0, 1, 2]
>>> one_h... | Convert an iterable of one-hot encoded targets to a list of indices.
Parameters
----------
one_hot : list
Returns
-------
indices : list
Examples
--------
>>> one_hot2indices([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
[0, 1, 2]
>>> one_hot2indices([[1, 0], [1, 0], [0, 1]])
[0... |
def IsDir(directory):
'''
:param unicode directory:
A path
:rtype: bool
:returns:
Returns whether the given path points to an existent directory.
:raises NotImplementedProtocol:
If the path protocol is not local or ftp
.. seealso:: FTP LIMITATIONS at this module's doc ... | :param unicode directory:
A path
:rtype: bool
:returns:
Returns whether the given path points to an existent directory.
:raises NotImplementedProtocol:
If the path protocol is not local or ftp
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information |
async def clean_up_clients_async(self):
"""
Resets the pump swallows all exceptions.
"""
if self.partition_receiver:
if self.eh_client:
await self.eh_client.stop_async()
self.partition_receiver = None
self.partition_receive_hand... | Resets the pump swallows all exceptions. |
def display(obj, detail='phrase'):
""" Friendly string for volume, using sink paths. """
try:
return obj.display(detail=detail)
except AttributeError:
return str(obj) | Friendly string for volume, using sink paths. |
def errors(self):
""" get all the errors
>>> gres = PlayMeta("operation")
>>> res_plus = BasicPlayMeta(Composable(name="plus"))
>>> gres.append(res_plus)
>>> res_plus.add_error(ValueError("invalid data"))
>>> res_moins = BasicPlayMeta(Composable(name="moins"))
>>... | get all the errors
>>> gres = PlayMeta("operation")
>>> res_plus = BasicPlayMeta(Composable(name="plus"))
>>> gres.append(res_plus)
>>> res_plus.add_error(ValueError("invalid data"))
>>> res_moins = BasicPlayMeta(Composable(name="moins"))
>>> gres.append(res_moins)
... |
def apply_op(input_layer, operation, *op_args, **op_kwargs):
"""Applies the given operation to this before without adding any summaries.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_k... | Applies the given operation to this before without adding any summaries.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_kwargs: Keyword arguments for the operation.
Returns:
A new l... |
def _enforce_txt_record_maxlen(key, value):
'''
Enforces the TXT record maximum length of 255 characters.
TXT record length includes key, value, and '='.
:param str key: Key of the TXT record
:param str value: Value of the TXT record
:rtype: str
:return: The value of the TXT record. It may... | Enforces the TXT record maximum length of 255 characters.
TXT record length includes key, value, and '='.
:param str key: Key of the TXT record
:param str value: Value of the TXT record
:rtype: str
:return: The value of the TXT record. It may be truncated if it exceeds
the maximum per... |
def parse_homer_findpeaks(self):
""" Find HOMER findpeaks logs and parse their data """
self.homer_findpeaks = dict()
for f in self.find_log_files('homer/findpeaks', filehandles=True):
self.parse_findPeaks(f)
# Filter to strip out ignored sample names
self.homer_fin... | Find HOMER findpeaks logs and parse their data |
def seek_previous_line(self):
"""
Seek previous line relative to the current file position.
:return: Position of the line or -1 if previous line was not found.
"""
where = self.file.tell()
offset = 0
while True:
if offset == where:
br... | Seek previous line relative to the current file position.
:return: Position of the line or -1 if previous line was not found. |
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today()) | Returns True when the start date is today or in the past and the
task has not yet been completed. |
def _generate_soma(self):
'''soma'''
radius = self._obj.soma.radius
return _square_segment(radius, (0., -radius)) | soma |
def _on_message(channel, method, header, body):
"""
Invoked by pika when a message is delivered from RabbitMQ. The
channel is passed for your convenience. The basic_deliver object that
is passed in carries the exchange, routing key, delivery tag and
a redelivered flag for the message. The properties... | Invoked by pika when a message is delivered from RabbitMQ. The
channel is passed for your convenience. The basic_deliver object that
is passed in carries the exchange, routing key, delivery tag and
a redelivered flag for the message. The properties passed in is an
instance of BasicProperties with the me... |
def tail_disconnect(self, index):
"""Mark all devices disconnected except target in the chain."""
try:
for device in self.devices[index + 1:]:
device.connected = False
except IndexError:
pass | Mark all devices disconnected except target in the chain. |
def parseUrl(url):
"""Return a dict containing scheme, netloc, url, params, query, fragment keys.
query is a dict where the values are always lists. If the query key appears only
once in the URL, the list will have a single value.
"""
scheme, netloc, url, params, query, fragment = urllib.parse.url... | Return a dict containing scheme, netloc, url, params, query, fragment keys.
query is a dict where the values are always lists. If the query key appears only
once in the URL, the list will have a single value. |
def do_repository_work(self,
repo_name,
repo_tag=None,
docker_executable='docker',
password=None,
force=None,
loglevel=logging.DEBUG,
note=None,
... | Commit, tag, push, tar a docker container based on the configuration we have.
@param repo_name: Name of the repository.
@param docker_executable: Defaults to 'docker'
@param password:
@param force:
@type repo_name: string
@type docker_executable: string
@type password: ... |
def trigger(self, identifier, force=True):
"""Trigger an upgrade task."""
self.debug(identifier)
url = "{base}/{identifier}".format(
base=self.local_base_url,
identifier=identifier
)
param = {}
if force:
param['force'] = force
e... | Trigger an upgrade task. |
def set_slippage(self, us_equities=None, us_futures=None):
"""Set the slippage models for the simulation.
Parameters
----------
us_equities : EquitySlippageModel
The slippage model to use for trading US equities.
us_futures : FutureSlippageModel
The slipp... | Set the slippage models for the simulation.
Parameters
----------
us_equities : EquitySlippageModel
The slippage model to use for trading US equities.
us_futures : FutureSlippageModel
The slippage model to use for trading US futures.
See Also
---... |
def clean_up_datetime(obj_map):
"""convert datetime objects to dictionaries for storage"""
clean_map = {}
for key, value in obj_map.items():
if isinstance(value, datetime.datetime):
clean_map[key] = {
'year': value.year,
'month': value.month,
... | convert datetime objects to dictionaries for storage |
def parse_0134_013b(v):
"""
Parses the O2 Sensor Value (0134 - 013B) and returns two values parsed from it:
1. Fuel-Air Equivalence [Ratio] as a float from 0 - 2
2. Current in [mA] as a float from -128 - 128
:param str v:
:return tuple of float, float:
"""
try:
trim_val = trim_ob... | Parses the O2 Sensor Value (0134 - 013B) and returns two values parsed from it:
1. Fuel-Air Equivalence [Ratio] as a float from 0 - 2
2. Current in [mA] as a float from -128 - 128
:param str v:
:return tuple of float, float: |
def set_base_prompt(
self, pri_prompt_terminator=":", alt_prompt_terminator=">", delay_factor=2
):
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
super(CoriantSSH, self).set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
... | Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output. |
def apply_chords(im, spacing=1, axis=0, trim_edges=True, label=False):
r"""
Adds chords to the void space in the specified direction. The chords are
separated by 1 voxel plus the provided spacing.
Parameters
----------
im : ND-array
An image of the porous material with void marked as `... | r"""
Adds chords to the void space in the specified direction. The chords are
separated by 1 voxel plus the provided spacing.
Parameters
----------
im : ND-array
An image of the porous material with void marked as ``True``.
spacing : int
Separation between chords. The default... |
def parse_error(text: str) -> Any:
"""
Validate and parse the BMA answer from websocket
:param text: the bma error
:return: the json data
"""
try:
data = json.loads(text)
jsonschema.validate(data, ERROR_SCHEMA)
except (TypeError, json.decoder.JSONDecodeError) as e:
r... | Validate and parse the BMA answer from websocket
:param text: the bma error
:return: the json data |
def login(self, email, password):
"""
:password: user password md5 digest
"""
payload = {
'account': email,
'password': password
}
code, msg, rv = self.request(
'mtop.alimusic.xuser.facade.xiamiuserservice.login',
payload
... | :password: user password md5 digest |
def clear_worker_output(self):
"""Drops all of the worker output collections"""
print 'Dropping all of the worker output collections... Whee!'
# Get all the collections in the workbench database
all_c = self.database.collection_names()
# Remove collections that we don't... | Drops all of the worker output collections |
def multi_packages(self, logins=None, platform=None, package_type=None,
type_=None, access=None):
"""Return the private packages for a given set of usernames/logins."""
logger.debug('')
method = self._multi_packages
new_client = True
try:
# Onl... | Return the private packages for a given set of usernames/logins. |
def _to_ned(self):
"""
Switches the reference frame to NED
"""
if self.ref_frame is 'USE':
# Rotate
return utils.use_to_ned(self.tensor), \
utils.use_to_ned(self.tensor_sigma)
elif self.ref_frame is 'NED':
# Alreadt NED
... | Switches the reference frame to NED |
def find_numeration(line):
"""Given a reference line, attempt to locate instances of citation
'numeration' in the line.
@param line: (string) the reference line.
@return: (string) the reference line after numeration has been checked
and possibly recognized/marked-up.
"""
pattern... | Given a reference line, attempt to locate instances of citation
'numeration' in the line.
@param line: (string) the reference line.
@return: (string) the reference line after numeration has been checked
and possibly recognized/marked-up. |
def _shape_union(shapes):
"""A shape containing the union of all dimensions in the input shapes.
Args:
shapes: a list of Shapes
Returns:
a Shape
"""
return Shape(sorted(list(set(sum([s.dims for s in shapes], []))))) | A shape containing the union of all dimensions in the input shapes.
Args:
shapes: a list of Shapes
Returns:
a Shape |
def group(self, labels):
""" group as list """
unique_labels, groupxs = self.group_indicies(labels)
groups = [self.take(idxs) for idxs in groupxs]
return unique_labels, groups | group as list |
def create(self, obj, ref=None):
""" Convert *obj* to a new ShaderObject. If the output is a Variable
with no name, then set its name using *ref*.
"""
if isinstance(ref, Variable):
ref = ref.name
elif isinstance(ref, string_types) and ref.startswith('gl_'):
... | Convert *obj* to a new ShaderObject. If the output is a Variable
with no name, then set its name using *ref*. |
def reloading_meta_metaclass_factory(BASE_TYPE=type):
""" hack for pyqt """
class ReloadingMetaclass2(BASE_TYPE):
def __init__(metaself, name, bases, dct):
super(ReloadingMetaclass2, metaself).__init__(name, bases, dct)
#print('Making rrr for %r' % (name,))
metaself.r... | hack for pyqt |
def add_remote_subnet(self, context_id, subnet_id):
"""Adds a remote subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the remote subnet.
:return bool: True if remote subnet addition was suc... | Adds a remote subnet to a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int subnet_id: The id-value representing the remote subnet.
:return bool: True if remote subnet addition was successful. |
def config_create(self, kernel=None, label=None, devices=[], disks=[],
volumes=[], **kwargs):
"""
Creates a Linode Config with the given attributes.
:param kernel: The kernel to boot with.
:param label: The config label
:param disks: The list of disks, starting at sd... | Creates a Linode Config with the given attributes.
:param kernel: The kernel to boot with.
:param label: The config label
:param disks: The list of disks, starting at sda, to map to this config.
:param volumes: The volumes, starting after the last disk, to map to this
config... |
def get_content_type(obj, field_name=False):
"""
Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return.
"""
content_type = ContentType.objects.get_for_model(obj)
if field_name:
return getattr(content_type, field_name, ... | Returns the content type of an object.
:param obj: A model instance.
:param field_name: Field of the object to return. |
def compile_file(env, src_path, dst_path, encoding='utf-8', base_dir=''):
"""Compiles a Jinja2 template to python code.
:param env: a Jinja2 Environment instance.
:param src_path: path to the source file.
:param dst_path: path to the destination file.
:param encoding: template encoding.
:param base_dir: th... | Compiles a Jinja2 template to python code.
:param env: a Jinja2 Environment instance.
:param src_path: path to the source file.
:param dst_path: path to the destination file.
:param encoding: template encoding.
:param base_dir: the base path to be removed from the compiled template filename. |
def _parse_labels(self, labels, element):
r"""
This private method is used for converting \'labels\' to a proper
format, including dealing with wildcards (\*).
Parameters
----------
labels : string or list of strings
The label or list of labels to be parsed. ... | r"""
This private method is used for converting \'labels\' to a proper
format, including dealing with wildcards (\*).
Parameters
----------
labels : string or list of strings
The label or list of labels to be parsed. Note that the \* can be
used as a wild... |
def check_directory_path(self, path):
"""
Ensure directory exists at the provided path
:type path: string
:param path: path to directory to check
"""
if os.path.isdir(path) is not True:
msg = "Directory Does Not Exist {}".format(path)
raise OSErro... | Ensure directory exists at the provided path
:type path: string
:param path: path to directory to check |
def _fastfood_list(args):
"""Run on `fastfood list`."""
template_pack = pack.TemplatePack(args.template_pack)
if args.stencil_set:
stencil_set = template_pack.load_stencil_set(args.stencil_set)
print("Available Stencils for %s:" % args.stencil_set)
for stencil in stencil_set.stencils... | Run on `fastfood list`. |
def get_section_header(self, section):
"""
Get a specific section header by index or name.
Args:
section(int or str): The index or name of the section header to return.
Returns:
:class:`~ELF.SectionHeader`: The section header.
Raises:
KeyErr... | Get a specific section header by index or name.
Args:
section(int or str): The index or name of the section header to return.
Returns:
:class:`~ELF.SectionHeader`: The section header.
Raises:
KeyError: The requested section header does not exist. |
def upload(identifier, files,
metadata=None,
headers=None,
access_key=None,
secret_key=None,
queue_derive=None,
verbose=None,
verify=None,
checksum=None,
delete=None,
retries=None,
retries_sleep=None... | Upload files to an item. The item will be created if it does not exist.
:type identifier: str
:param identifier: The globally unique Archive.org identifier for a given item.
:param files: The filepaths or file-like objects to upload. This value can be an
iterable or a single file-like ob... |
def register_service_agreement_consumer(storage_path, publisher_address, agreement_id, did,
service_agreement, service_definition_id, price,
encrypted_files, consumer_account, condition_ids,
consume_c... | Registers the given service agreement in the local storage.
Subscribes to the service agreement events.
:param storage_path: storage path for the internal db, str
:param publisher_address: ethereum account address of publisher, hex str
:param agreement_id: id of the agreement, hex str
:param did: D... |
def do_delete(endpoint, access_token):
'''Do an HTTP GET request and return JSON.
Args:
endpoint (str): Azure Resource Manager management endpoint.
access_token (str): A valid Azure authentication token.
Returns:
HTTP response.
'''
headers = {"Authorization": 'Bearer ' + ac... | Do an HTTP GET request and return JSON.
Args:
endpoint (str): Azure Resource Manager management endpoint.
access_token (str): A valid Azure authentication token.
Returns:
HTTP response. |
def process_rawq(self):
"""Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence.
"""
buf = b''
try:
while self.rawq:
# Handle non-IAC first (normal data).
... | Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence. |
def refresh(self):
"""Refresh the current figure
"""
for cbar in self.colorbars:
cbar.draw_all()
self.canvas.draw() | Refresh the current figure |
def parse_python_file(filepath):
"""
Retrieves the AST of the specified file.
This function performs simple caching so that the same file isn't read or
parsed more than once per process.
:param filepath: the file to parse
:type filepath: str
:returns: ast.AST
"""
with _AST_CACHE_L... | Retrieves the AST of the specified file.
This function performs simple caching so that the same file isn't read or
parsed more than once per process.
:param filepath: the file to parse
:type filepath: str
:returns: ast.AST |
def make_translations(unique_name, node):
'''
Compute and store the title that should be displayed
when linking to a given unique_name, eg in python
when linking to test_greeter_greet() we want to display
Test.Greeter.greet
'''
introspectable = not node.attrib.get('introspectable') == '0'
... | Compute and store the title that should be displayed
when linking to a given unique_name, eg in python
when linking to test_greeter_greet() we want to display
Test.Greeter.greet |
def get(self, identity):
"""
Constructs a SyncMapPermissionContext
:param identity: Identity of the user to whom the Sync Map Permission applies.
:returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext
:rtype: twilio.rest.sync.v1.service.sync... | Constructs a SyncMapPermissionContext
:param identity: Identity of the user to whom the Sync Map Permission applies.
:returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionContext
:rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionCon... |
def read( handle, id=None ):
"""
Reads a structure via PDBParser.
Simplifies life..
"""
from Bio.PDB import PDBParser
if not id:
id = os.path.basename(handle).split('.')[0] # Get from filename
p = PDBParser()
s = p.get_structure(id, handle)
return s | Reads a structure via PDBParser.
Simplifies life.. |
def spell_check(T, w):
"""Spellchecker
:param T: trie encoding the dictionary
:param w: given word
:returns: a closest word from the dictionary
:complexity: linear if distance was constant
"""
assert T is not None
dist = 0
while True: # Try increasing distances
u = search(... | Spellchecker
:param T: trie encoding the dictionary
:param w: given word
:returns: a closest word from the dictionary
:complexity: linear if distance was constant |
def feature(self,feat=None,searchforit=False,init=None):
"""
Returns value of self.feats[feat].
If searchforit==True, will search in this object's children recursively.
If not found, returns None.
"""
if feat==None:
return self.feats
if not init:
init=self
init.tick=0
init._matches=[]
feat... | Returns value of self.feats[feat].
If searchforit==True, will search in this object's children recursively.
If not found, returns None. |
def do_fontsave(self, arg):
"""Saves the session variables to a file so that the same analysis can be continued later."""
#We need to save the full paths to the staging directories for the tests that are loaded
#so far; then when the session is restored, we can reparse the results.
from ... | Saves the session variables to a file so that the same analysis can be continued later. |
def dumps(self):
"""Dump the name to string, after normalizing it."""
def _is_initial(author_name):
return len(author_name) == 1 or u'.' in author_name
def _ensure_dotted_initials(author_name):
if _is_initial(author_name) \
and u'.' not in author_name... | Dump the name to string, after normalizing it. |
def AnalizarXml(self, xml=""):
"Analiza un mensaje XML (por defecto la respuesta)"
try:
if not xml:
xml = self.XmlResponse
self.xml = SimpleXMLElement(xml)
return True
except Exception, e:
self.Excepcion = u"%s" % (e)
re... | Analiza un mensaje XML (por defecto la respuesta) |
def diag_jacobian(xs,
ys=None,
sample_shape=None,
fn=None,
parallel_iterations=10,
name=None):
"""Computes diagonal of the Jacobian matrix of `ys=fn(xs)` wrt `xs`.
If `ys` is a tensor or a list of tensors of the form `(ys_1... | Computes diagonal of the Jacobian matrix of `ys=fn(xs)` wrt `xs`.
If `ys` is a tensor or a list of tensors of the form `(ys_1, .., ys_n)` and
`xs` is of the form `(xs_1, .., xs_n)`, the function `jacobians_diag`
computes the diagonal of the Jacobian matrix, i.e., the partial derivatives
`(dys_1/dxs_1,.... |
def _requirements_sanitize(req_list):
# type: (List[str]) -> List[str]
"""
Cleanup a list of requirement strings (e.g. from requirements.txt) to only
contain entries valid for this platform and with the lowest required version
only.
Example
-------
>>> from sys import version_info
... | Cleanup a list of requirement strings (e.g. from requirements.txt) to only
contain entries valid for this platform and with the lowest required version
only.
Example
-------
>>> from sys import version_info
>>> _requirements_sanitize([
... 'foo>=3.0',
... "monotonic>=1.0,>0.1;p... |
def parse(inp, format=None, encoding='utf-8', force_types=True):
"""Parse input from file-like object, unicode string or byte string.
Args:
inp: file-like object, unicode string or byte string with the markup
format: explicitly override the guessed `inp` markup format
encoding: `inp` en... | Parse input from file-like object, unicode string or byte string.
Args:
inp: file-like object, unicode string or byte string with the markup
format: explicitly override the guessed `inp` markup format
encoding: `inp` encoding, defaults to utf-8
force_types:
if `True`, in... |
def pkcs12_kdf(hash_algorithm, password, salt, iterations, key_length, id_):
"""
KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19
:param hash_algorithm:
The string name of the hash algorithm to use: "md5", "sha1", "sha224",
"sha256", "sha384", "sha512"
:param... | KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19
:param hash_algorithm:
The string name of the hash algorithm to use: "md5", "sha1", "sha224",
"sha256", "sha384", "sha512"
:param password:
A byte string of the password to use an input to the KDF
:param s... |
def get_or_create(self, defaults=None, **kwargs):
"""
Looks up an object with the given kwargs, creating a new one if necessary.
Args:
defaults (dict): Used when we create a new object. Must map to fields
of the model.
\*\*kwargs: Used both for filtering ... | Looks up an object with the given kwargs, creating a new one if necessary.
Args:
defaults (dict): Used when we create a new object. Must map to fields
of the model.
\*\*kwargs: Used both for filtering and new object creation.
Returns:
A tuple of (obj... |
def density_2d(self, x, y, rho0, Rs, center_x=0, center_y=0):
"""
projected density
:param x:
:param y:
:param rho0:
:param a:
:param s:
:param center_x:
:param center_y:
:return:
"""
x_ = x - center_x
y_ = y - cente... | projected density
:param x:
:param y:
:param rho0:
:param a:
:param s:
:param center_x:
:param center_y:
:return: |
def cmd_cminv(self, ch=None):
"""cminv ch=chname
Invert the color map in the channel/viewer
"""
viewer = self.get_viewer(ch)
if viewer is None:
self.log("No current viewer/channel.")
return
viewer.invert_cmap() | cminv ch=chname
Invert the color map in the channel/viewer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.