code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def suspendJustTabProviders(installation):
"""
Replace INavigableElements with facades that indicate their suspension.
"""
if installation.suspended:
raise RuntimeError("Installation already suspended")
powerups = list(installation.allPowerups)
for p in powerups:
if INavigableEle... | Replace INavigableElements with facades that indicate their suspension. |
def num_adjacent(self, i, j):
""" Counts the number of adjacent nonzero pixels to a given pixel.
Parameters
----------
i : int
row index of query pixel
j : int
col index of query pixel
Returns
-------
int
number of adj... | Counts the number of adjacent nonzero pixels to a given pixel.
Parameters
----------
i : int
row index of query pixel
j : int
col index of query pixel
Returns
-------
int
number of adjacent nonzero pixels |
def sorted_timeseries(self, ascending=True):
"""Returns a sorted copy of the TimeSeries, preserving the original one.
As an assumption this new TimeSeries is not ordered anymore if a new value is added.
:param boolean ascending: Determines if the TimeSeries will be ordered ascending
... | Returns a sorted copy of the TimeSeries, preserving the original one.
As an assumption this new TimeSeries is not ordered anymore if a new value is added.
:param boolean ascending: Determines if the TimeSeries will be ordered ascending
or descending.
:return: Returns a new T... |
def download_media(self, media_id):
"""
下载多媒体文件
详情请参考 http://mp.weixin.qq.com/wiki/10/78b15308b053286e2a66b33f0f0f5fb6.html
:param media_id: 媒体文件 ID
:return: requests 的 Response 实例
"""
return self.request.get(
'https://api.weixin.qq.com/cgi-bin/media/g... | 下载多媒体文件
详情请参考 http://mp.weixin.qq.com/wiki/10/78b15308b053286e2a66b33f0f0f5fb6.html
:param media_id: 媒体文件 ID
:return: requests 的 Response 实例 |
def stream(self, to=values.unset, from_=values.unset,
date_sent_before=values.unset, date_sent=values.unset,
date_sent_after=values.unset, limit=None, page_size=None):
"""
Streams MessageInstance records from the API as a generator stream.
This operation lazily load... | Streams MessageInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode to: Filter by messages sent to th... |
def plot_wfdb(record=None, annotation=None, plot_sym=False,
time_units='samples', title=None, sig_style=[''],
ann_style=['r*'], ecg_grids=[], figsize=None, return_fig=False):
"""
Subplot individual channels of a wfdb record and/or annotation.
This function implements the base fu... | Subplot individual channels of a wfdb record and/or annotation.
This function implements the base functionality of the `plot_items`
function, while allowing direct input of wfdb objects.
If the record object is input, the function will extract from it:
- signal values, from the `p_signal` (priority)... |
def removeDataset(self, dataset):
"""
Removes the specified dataset from this repository. This performs
a cascading removal of all items within this dataset.
"""
for datasetRecord in models.Dataset.select().where(
models.Dataset.id == dataset.getId()):
... | Removes the specified dataset from this repository. This performs
a cascading removal of all items within this dataset. |
def invariant_image_similarity(image1, image2,
local_search_iterations=0, metric='MI',
thetas=np.linspace(0,360,5),
thetas2=np.linspace(0,360,5),
thetas3=np.linspace(0,360,5),
... | Similarity metrics between two images as a function of geometry
Compute similarity metric between two images as image is rotated about its
center w/ or w/o optimization
ANTsR function: `invariantImageSimilarity`
Arguments
---------
image1 : ANTsImage
reference image
image2 : ... |
def setsebools(pairs, persist=False):
'''
Set the value of multiple booleans
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebools '{virt_use_usb: on, squid_use_tproxy: off}'
'''
if not isinstance(pairs, dict):
return {}
if persist:
cmd = 'setsebool -P '
... | Set the value of multiple booleans
CLI Example:
.. code-block:: bash
salt '*' selinux.setsebools '{virt_use_usb: on, squid_use_tproxy: off}' |
def run(self, arguments=None, get_unknowns=False):
"""
Init point to execute the script.
If `arguments` string is given, will evaluate the arguments, else
evaluates sys.argv. Any inheriting class should extend the run method
(but first calling BaseCmdLineTool.run(self)).
... | Init point to execute the script.
If `arguments` string is given, will evaluate the arguments, else
evaluates sys.argv. Any inheriting class should extend the run method
(but first calling BaseCmdLineTool.run(self)). |
def search(self,
start_predictions: torch.Tensor,
start_state: StateType,
step: StepFunctionType) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given a starting state and a step function, apply beam search to find the
most likely target sequences.
... | Given a starting state and a step function, apply beam search to find the
most likely target sequences.
Notes
-----
If your step function returns ``-inf`` for some log probabilities
(like if you're using a masked log-softmax) then some of the "best"
sequences returned ma... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkerChannelContext for this WorkerChannelInstance
:rtype: twilio.rest.taskrouter.v1.workspace.w... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkerChannelContext for this WorkerChannelInstance
:rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_channel.WorkerChannelCont... |
def multi_select(self, elements_to_select):
"""
Multi-select any number of elements.
:param elements_to_select: list of WebElement instances
:return: None
"""
# Click the first element
first_element = elements_to_select.pop()
self.click(first_element)
... | Multi-select any number of elements.
:param elements_to_select: list of WebElement instances
:return: None |
def prepend_items(self, items, **kwargs):
"""Method to prepend data to multiple :class:`~.Item` objects.
.. seealso:: :meth:`append_items`
"""
rv = self.prepend_multi(items, **kwargs)
for k, v in items.dict.items():
if k.success:
k.value = v['fragment'... | Method to prepend data to multiple :class:`~.Item` objects.
.. seealso:: :meth:`append_items` |
def _table_materialize(table):
"""
Force schema resolution for a joined table, selecting all fields from
all tables.
"""
if table._is_materialized():
return table
op = ops.MaterializedJoin(table)
return op.to_expr() | Force schema resolution for a joined table, selecting all fields from
all tables. |
def before_after_apply(self, before_fn, after_fn, leaf_fn=None):
"""Applies the functions to each node in a subtree using an traversal in which
encountered twice: once right before its descendants, and once right
after its last descendant
"""
stack = [self]
while stack:
... | Applies the functions to each node in a subtree using an traversal in which
encountered twice: once right before its descendants, and once right
after its last descendant |
def generate_colormap(self,colormap=None,reverse=False):
"""use 1 colormap for the whole abf. You can change it!."""
if colormap is None:
colormap = pylab.cm.Dark2
self.cm=colormap
self.colormap=[]
for i in range(self.sweeps): #TODO: make this the only colormap
... | use 1 colormap for the whole abf. You can change it!. |
def get_layer_modes(subcategory):
"""Return all sorted layer modes from exposure or hazard.
:param subcategory: Hazard or Exposure key.
:type subcategory: str
:returns: List of layer modes definition.
:rtype: list
"""
layer_modes = definition(subcategory)['layer_modes']
return sorted(l... | Return all sorted layer modes from exposure or hazard.
:param subcategory: Hazard or Exposure key.
:type subcategory: str
:returns: List of layer modes definition.
:rtype: list |
def pieces(self):
"""
Number of pieces the content is split into or ``None`` if :attr:`piece_size`
returns ``None``
"""
if self.piece_size is None:
return None
else:
return math.ceil(self.size / self.piece_size) | Number of pieces the content is split into or ``None`` if :attr:`piece_size`
returns ``None`` |
def setPalette(self, palette):
"""
Sets the palette for this node to the inputed palette. If None is
provided, then the scene's palette will be used for this node.
:param palette | <XNodePalette> || None
"""
self._palette = XNodePalette(palette) if palette ... | Sets the palette for this node to the inputed palette. If None is
provided, then the scene's palette will be used for this node.
:param palette | <XNodePalette> || None |
def _is_already_configured(configuration_details):
"""Returns `True` when alias already in shell config."""
path = Path(configuration_details.path).expanduser()
with path.open('r') as shell_config:
return configuration_details.content in shell_config.read() | Returns `True` when alias already in shell config. |
def fprocess(infilep,outfilep):
"""
Scans an input file for LA equations between double square brackets,
e.g. [[ M3_mymatrix = M3_anothermatrix^-1 ]], and replaces the expression
with a comment containing the equation followed by nested function calls
that implement the equation as C code. A trailin... | Scans an input file for LA equations between double square brackets,
e.g. [[ M3_mymatrix = M3_anothermatrix^-1 ]], and replaces the expression
with a comment containing the equation followed by nested function calls
that implement the equation as C code. A trailing semi-colon is appended.
The equation w... |
def pbkdf2(hash_algorithm, password, salt, iterations, key_length):
"""
Implements PBKDF2 from PKCS#5 v2.2 in pure Python
:param hash_algorithm:
The string name of the hash algorithm to use: "md5", "sha1", "sha224",
"sha256", "sha384", "sha512"
:param password:
A byte string of... | Implements PBKDF2 from PKCS#5 v2.2 in pure Python
: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 salt:
A cryptograph... |
def do_kpl_on(self, args):
"""Turn on a KeypadLinc button.
Usage:
kpl_on address group
"""
params = args.split()
address = None
group = None
try:
address = params[0]
group = int(params[1])
except IndexError:
... | Turn on a KeypadLinc button.
Usage:
kpl_on address group |
def is_connected(self):
"""
Return `True` if the Xmrs represents a connected graph.
Subgraphs can be connected through things like arguments,
QEQs, and label equalities.
"""
nids = set(self._nodeids) # the nids left to find
if len(nids) == 0:
raise X... | Return `True` if the Xmrs represents a connected graph.
Subgraphs can be connected through things like arguments,
QEQs, and label equalities. |
def contains(self, other):
"""
Estimate whether the bounding box contains a point.
Parameters
----------
other : tuple of number or imgaug.Keypoint
Point to check for.
Returns
-------
bool
True if the point is contained in the bou... | Estimate whether the bounding box contains a point.
Parameters
----------
other : tuple of number or imgaug.Keypoint
Point to check for.
Returns
-------
bool
True if the point is contained in the bounding box, False otherwise. |
def as_nonlinear(self, params=None):
"""Return a `Model` equivalent to this object. The nonlinear solver is less
efficient, but lets you freeze parameters, compute uncertainties, etc.
If the `params` argument is provided, solve() will be called on the
returned object with those paramete... | Return a `Model` equivalent to this object. The nonlinear solver is less
efficient, but lets you freeze parameters, compute uncertainties, etc.
If the `params` argument is provided, solve() will be called on the
returned object with those parameters. If it is `None` and this object
has ... |
def prepare_read(data, method='readlines', mode='r'):
"""Prepare various input types for parsing.
Args:
data (iter): Data to read
method (str): Method to process data with
mode (str): Custom mode to process with, if data is a file
Returns:
list: List suitable for parsing
... | Prepare various input types for parsing.
Args:
data (iter): Data to read
method (str): Method to process data with
mode (str): Custom mode to process with, if data is a file
Returns:
list: List suitable for parsing
Raises:
TypeError: Invalid value for data |
def convert_to_array(pmap, nsites, imtls, inner_idx=0):
"""
Convert the probability map into a composite array with header
of the form PGA-0.1, PGA-0.2 ...
:param pmap: probability map
:param nsites: total number of sites
:param imtls: a DictArray with IMT and levels
:returns: a composite a... | Convert the probability map into a composite array with header
of the form PGA-0.1, PGA-0.2 ...
:param pmap: probability map
:param nsites: total number of sites
:param imtls: a DictArray with IMT and levels
:returns: a composite array of lenght nsites |
def linked(prefix):
"""Return set of canonical names of linked packages in `prefix`."""
logger.debug(str(prefix))
if not isdir(prefix):
return set()
meta_dir = join(prefix, 'conda-meta')
if not isdir(meta_dir):
# We might have nothing in linked (and no c... | Return set of canonical names of linked packages in `prefix`. |
def create_endpoint(port=0, service_name='unknown', ipv4=None, ipv6=None):
"""Create a zipkin Endpoint object.
An Endpoint object holds information about the network context of a span.
:param port: int value of the port. Defaults to 0
:param service_name: service name as a str. Defaults to 'unknown'
... | Create a zipkin Endpoint object.
An Endpoint object holds information about the network context of a span.
:param port: int value of the port. Defaults to 0
:param service_name: service name as a str. Defaults to 'unknown'
:param ipv4: ipv4 host address
:param ipv6: ipv6 host address
:returns:... |
def add_input(self, name, value=None):
'''Create a new input variable called ``name`` for this process
and initialize it with the given ``value``.
Quantity is accessible in two ways:
* as a process attribute, i.e. ``proc.name``
* as a member of the input dictionary,
... | Create a new input variable called ``name`` for this process
and initialize it with the given ``value``.
Quantity is accessible in two ways:
* as a process attribute, i.e. ``proc.name``
* as a member of the input dictionary,
i.e. ``proc.input['name']``
Us... |
def all_requests_view(request):
'''
Show user a list of enabled request types, the number of requests of each
type and a link to see them all.
'''
# Pseudo-dictionary, actually a list with items of form
# (request_type.name.title(), number_of_type_requests, name, enabled,
# glyphicon)
ty... | Show user a list of enabled request types, the number of requests of each
type and a link to see them all. |
def fallback(message: str, ex: Exception) -> None:
"""
Fallback procedure when a cli command fails.
:param message: message to be logged
:param ex: Exception which caused the failure
"""
logging.error('%s', message)
logging.exception('%s', ex)
sys.exit(1) | Fallback procedure when a cli command fails.
:param message: message to be logged
:param ex: Exception which caused the failure |
def convert_upload_string_to_file(i):
"""
Input: {
file_content_base64 - string transmitted through Internet
(filename) - file name to write (if empty, generate tmp file)
}
Output: {
return - return code = 0, if successful
... | Input: {
file_content_base64 - string transmitted through Internet
(filename) - file name to write (if empty, generate tmp file)
}
Output: {
return - return code = 0, if successful
> 0, if... |
def create(self, data, resource='data'):
"""Create an object of resource:
* data
* project
* processor
* trigger
* template
:param data: Object values
:type data: dict
:param resource: Resource name
:type resource: string
"""
... | Create an object of resource:
* data
* project
* processor
* trigger
* template
:param data: Object values
:type data: dict
:param resource: Resource name
:type resource: string |
def stsci2(hdulist, filename):
"""For STScI GEIS files, need to do extra steps."""
# Write output file name to the primary header
instrument = hdulist[0].header.get('INSTRUME', '')
if instrument in ("WFPC2", "FOC"):
hdulist[0].header['FILENAME'] = filename | For STScI GEIS files, need to do extra steps. |
def remove_permission(self, queue, label):
"""
Remove a permission from a queue.
:type queue: :class:`boto.sqs.queue.Queue`
:param queue: The queue object
:type label: str or unicode
:param label: The unique label associated with the permission
bei... | Remove a permission from a queue.
:type queue: :class:`boto.sqs.queue.Queue`
:param queue: The queue object
:type label: str or unicode
:param label: The unique label associated with the permission
being removed.
:rtype: bool
:return: True if succ... |
def characterize_local_files(filedir, max_bytes=MAX_FILE_DEFAULT):
"""
Collate local file info as preperation for Open Humans upload.
Note: Files with filesize > max_bytes are not included in returned info.
:param filedir: This field is target directory to get files from.
:param max_bytes: This fi... | Collate local file info as preperation for Open Humans upload.
Note: Files with filesize > max_bytes are not included in returned info.
:param filedir: This field is target directory to get files from.
:param max_bytes: This field is the maximum file size to consider. Its
default value is 128m. |
def parse_shifts(self):
"""
Parse shifts from TOI report
:returns: self if successfule else None
"""
lx_doc = self.html_doc()
pl_heads = lx_doc.xpath('//td[contains(@class, "playerHeading")]')
for pl in pl_heads:
sh_sum = { }
... | Parse shifts from TOI report
:returns: self if successfule else None |
def write_languages(f, l):
"""Write language information."""
f.write("Languages = {%s" % os.linesep)
for lang in sorted(l):
f.write(" %r: %r,%s" % (lang, l[lang], os.linesep))
f.write("}%s" % os.linesep) | Write language information. |
def exclude_states(omega, gamma, r, Lij, states, excluded_states):
"""Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states.
"""
Ne = len(omega)
excluded_indices = [i for i in range(Ne) if states[i] in excluded_states]
omega_new = ... | Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states. |
def get_available_ip6_for_vip(self, id_evip, name):
"""
Get and save a available IP in the network ipv6 for vip request
:param id_evip: Vip environment identifier. Integer value and greater than zero.
:param name: Ip description
:return: Dictionary with the following structure:... | Get and save a available IP in the network ipv6 for vip request
:param id_evip: Vip environment identifier. Integer value and greater than zero.
:param name: Ip description
:return: Dictionary with the following structure:
::
{'ip': {'bloco1':<bloco1>,
'bloco2... |
def sys_dup2(self, fd, newfd):
"""
Duplicates an open fd to newfd. If newfd is open, it is first closed
:rtype: int
:param fd: the open file descriptor to duplicate.
:param newfd: the file descriptor to alias the file described by fd.
:return: newfd.
"""
t... | Duplicates an open fd to newfd. If newfd is open, it is first closed
:rtype: int
:param fd: the open file descriptor to duplicate.
:param newfd: the file descriptor to alias the file described by fd.
:return: newfd. |
def make_valid_string(self, string=''):
""" Inputting a value for the first time """
if not self.is_valid_str(string):
if string in self.val_map and not self.allow_dups:
raise IndexError("Value {} has already been given to the sanitizer".format(string))
internal_n... | Inputting a value for the first time |
def _getUserSid(user):
'''
return a state error dictionary, with 'sid' as a field if it could be returned
if user is None, sid will also be None
'''
ret = {}
sid_pattern = r'^S-1(-\d+){1,}$'
if user and re.match(sid_pattern, user, re.I):
try:
sid = win32security.GetBina... | return a state error dictionary, with 'sid' as a field if it could be returned
if user is None, sid will also be None |
def numSteps(self, row):
"""Gets the number of steps for the parameter at
index *row* will yeild
"""
param = self._parameters[row]
return self.nStepsForParam(param) | Gets the number of steps for the parameter at
index *row* will yeild |
def submit_form_id(self, id_):
"""
Submit the form with given id (used to disambiguate between multiple
forms).
"""
form = ElementSelector(
world.browser,
str('id("{id}")'.format(id=id_)),
)
assert form, "Cannot find a form with ID '{}' on the page.".format(id_)
form.subm... | Submit the form with given id (used to disambiguate between multiple
forms). |
def get_hash(self, salt, plain_password):
"""Return the hashed password, salt + SHA-256."""
return hashlib.sha256(salt.encode() + plain_password.encode()).hexdigest() | Return the hashed password, salt + SHA-256. |
def cigarRead(fileHandleOrFile):
"""Reads a list of pairwise alignments into a pairwise alignment structure.
Query and target are reversed!
"""
fileHandle = _getFileHandle(fileHandleOrFile)
#p = re.compile("cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+(... | Reads a list of pairwise alignments into a pairwise alignment structure.
Query and target are reversed! |
def process_shells_ordered(self, shells):
"""Processing a list of shells one after the other."""
output = []
for shell in shells:
entry = shell['entry']
config = ShellConfig(script=entry['script'], title=entry['title'] if 'title' in entry else '',
... | Processing a list of shells one after the other. |
async def remove(self, device, force=False, detach=False, eject=False,
lock=False):
"""
Unmount or lock the device depending on device type.
:param device: device object, block device path or mount path
:param bool force: recursively remove all child devices
... | Unmount or lock the device depending on device type.
:param device: device object, block device path or mount path
:param bool force: recursively remove all child devices
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lo... |
def event_payment(self, date, time, pid, commerce_id, transaction_id, request_ip, token, webpay_server):
'''Record the payment event
Official handler writes this information to TBK_EVN%Y%m%d file.
'''
raise NotImplementedError("Logging Handler must implement event_payment") | Record the payment event
Official handler writes this information to TBK_EVN%Y%m%d file. |
def update_constants(nmrstar2cfg="", nmrstar3cfg="", resonance_classes_cfg="", spectrum_descriptions_cfg=""):
"""Update constant variables.
:return: None
:rtype: :py:obj:`None`
"""
nmrstar_constants = {}
resonance_classes = {}
spectrum_descriptions = {}
this_directory = os.path.dirname... | Update constant variables.
:return: None
:rtype: :py:obj:`None` |
def make_pattern(self, pattern, listsep=','):
"""Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for ty... | Make pattern for a data type with the specified cardinality.
.. code-block:: python
yes_no_pattern = r"yes|no"
many_yes_no = Cardinality.one_or_more.make_pattern(yes_no_pattern)
:param pattern: Regular expression for type (as string).
:param listsep: List separator f... |
def migration(self, from_ver: int, to_ver: int):
"""Decorator to create and register a migration.
>>> manager = MigrationManager()
>>> @manager.migration(0, 1)
... def migrate(conn):
... pass
"""
def decorator(func):
migration = Migration(from_ver... | Decorator to create and register a migration.
>>> manager = MigrationManager()
>>> @manager.migration(0, 1)
... def migrate(conn):
... pass |
def ekgi(selidx, row, element):
"""
Return an element of an entry in a column of integer type in a specified
row.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgi_c.html
:param selidx: Index of parent column in SELECT clause.
:type selidx: int
:param row: Row to fetch from.
... | Return an element of an entry in a column of integer type in a specified
row.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgi_c.html
:param selidx: Index of parent column in SELECT clause.
:type selidx: int
:param row: Row to fetch from.
:type row: int
:param element: Index of... |
def chemical_symbols(self):
"""Chemical symbols char [number of atom species][symbol length]."""
charr = self.read_value("chemical_symbols")
symbols = []
for v in charr:
s = "".join(c.decode("utf-8") for c in v)
symbols.append(s.strip())
return symbols | Chemical symbols char [number of atom species][symbol length]. |
def force_log(self, logType, message, data=None, tback=None, stdout=True, file=True):
"""
Force logging a message of a certain logtype whether logtype level is allowed or not.
:Parameters:
#. logType (string): A defined logging type.
#. message (string): Any message to log... | Force logging a message of a certain logtype whether logtype level is allowed or not.
:Parameters:
#. logType (string): A defined logging type.
#. message (string): Any message to log.
#. tback (None, str, list): Stack traceback to print and/or write to
log file. ... |
def config_param(self, conf_alias, param):
"""
Получает настройки с сервера, кеширует локально и дает простой интерфейс их получения
:param conf_alias:
:param param:
:return:
"""
data = self.data_get(conf_alias)
flat_cache = self.__data_get_flatten_cache.g... | Получает настройки с сервера, кеширует локально и дает простой интерфейс их получения
:param conf_alias:
:param param:
:return: |
def _parse_attributes(self, value):
"""Parse non standard atrributes."""
from zigpy.zcl import foundation as f
attributes = {}
attribute_names = {
1: BATTERY_VOLTAGE_MV,
3: TEMPERATURE,
4: XIAOMI_ATTR_4,
5: XIAOMI_ATTR_5,
6: XIA... | Parse non standard atrributes. |
def collect(self):
"""
Overrides the Collector.collect method
"""
# Handle collection time intervals correctly
CollectTime = int(time.time())
time_delta = float(self.config['interval'])
if not self.LastCollectTime:
self.LastCollectTime = CollectTime -... | Overrides the Collector.collect method |
def execute_dry_run(self, dialect=None, billing_tier=None):
"""Dry run a query, to check the validity of the query and return some useful statistics.
Args:
dialect : {'legacy', 'standard'}, default 'legacy'
'legacy' : Use BigQuery's legacy SQL dialect.
'standard' : Use BigQuery's stan... | Dry run a query, to check the validity of the query and return some useful statistics.
Args:
dialect : {'legacy', 'standard'}, default 'legacy'
'legacy' : Use BigQuery's legacy SQL dialect.
'standard' : Use BigQuery's standard SQL (beta), which is
compliant with the SQL 2011 sta... |
def log_stats(self):
"""Output the stats to the LOGGER."""
if not self.stats.get('counts'):
if self.consumers:
LOGGER.info('Did not receive any stats data from children')
return
if self.poll_data['processes']:
LOGGER.warning('%i process(es) di... | Output the stats to the LOGGER. |
def from_headers (strheader):
"""Parse cookie data from a string in HTTP header (RFC 2616) format.
@return: list of cookies
@raises: ValueError for incomplete or invalid data
"""
res = []
fp = StringIO(strheader)
headers = httplib.HTTPMessage(fp, seekable=True)
if "Host" not in headers:... | Parse cookie data from a string in HTTP header (RFC 2616) format.
@return: list of cookies
@raises: ValueError for incomplete or invalid data |
def affected_start(self):
"""Return affected start position in 0-based coordinates
For SNVs, MNVs, and deletions, the behaviour is the start position.
In the case of insertions, the position behind the insert position is
returned, yielding a 0-length interval together with
:py:m... | Return affected start position in 0-based coordinates
For SNVs, MNVs, and deletions, the behaviour is the start position.
In the case of insertions, the position behind the insert position is
returned, yielding a 0-length interval together with
:py:meth:`~Record.affected_end` |
def main():
"""Sanitizes the loaded *.ipynb."""
with open(sys.argv[1], 'r') as nbfile:
notebook = json.load(nbfile)
# remove kernelspec (venvs)
try:
del notebook['metadata']['kernelspec']
except KeyError:
pass
# remove outputs and metadata, set execution counts to None
... | Sanitizes the loaded *.ipynb. |
def limit(self, limit):
""" Limit the number of rows returned from the database.
:param limit: The number of rows to return in the recipe. 0 will
return all rows.
:type limit: int
"""
if self._limit != limit:
self.dirty = True
self._... | Limit the number of rows returned from the database.
:param limit: The number of rows to return in the recipe. 0 will
return all rows.
:type limit: int |
def evaluate(self, data):
"""Evaluate the code needed to compute a given Data object."""
expression_engine = data.process.requirements.get('expression-engine', None)
if expression_engine is not None:
expression_engine = self.get_expression_engine(expression_engine)
# Parse s... | Evaluate the code needed to compute a given Data object. |
def delete_snapshot_range(self, start_id, end_id):
"""Starts deleting the specified snapshot range. This is limited to
linear snapshot lists, which means there may not be any other child
snapshots other than the direct sequence between the start and end
snapshot. If the start and end sna... | Starts deleting the specified snapshot range. This is limited to
linear snapshot lists, which means there may not be any other child
snapshots other than the direct sequence between the start and end
snapshot. If the start and end snapshot point to the same snapshot this
method is comple... |
def OpenMessageDialog(self, Username, Text=u''):
"""Opens "Send an IM Message" dialog.
:Parameters:
Username : str
Message target.
Text : unicode
Message text.
"""
self.OpenDialog('IM', Username, tounicode(Text)) | Opens "Send an IM Message" dialog.
:Parameters:
Username : str
Message target.
Text : unicode
Message text. |
def get_graph_url(self, target, graphite_url=None):
"""Get Graphite URL."""
return self._graphite_url(target, graphite_url=graphite_url, raw_data=False) | Get Graphite URL. |
def image_present(name, visibility='public', protected=None,
checksum=None, location=None, disk_format='raw', wait_for=None,
timeout=30):
'''
Checks if given image is present with properties
set as specified.
An image should got through the stages 'queued', 'saving'
before becoming ... | Checks if given image is present with properties
set as specified.
An image should got through the stages 'queued', 'saving'
before becoming 'active'. The attribute 'checksum' can
only be checked once the image is active.
If you don't specify 'wait_for' but 'checksum' the function
will wait for... |
def runMultiplePass(df, model, nMultiplePass, nTrain):
"""
run CLA model through data record 0:nTrain nMultiplePass passes
"""
predictedField = model.getInferenceArgs()['predictedField']
print "run TM through the train data multiple times"
for nPass in xrange(nMultiplePass):
for j in xrange(nTrain):
... | run CLA model through data record 0:nTrain nMultiplePass passes |
def change_default_radii(def_map):
"""Change the default radii
"""
s = current_system()
rep = current_representation()
rep.radii_state.default = [def_map[t] for t in s.type_array]
rep.radii_state.reset() | Change the default radii |
def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs): # pylint: disable=unused-argument
"""Function to get LoggingTensorHook.
Args:
every_n_iter: `int`, print the values of `tensors` once every N local
steps taken on the current worker.
tensors_to_log: List of tensor names or... | Function to get LoggingTensorHook.
Args:
every_n_iter: `int`, print the values of `tensors` once every N local
steps taken on the current worker.
tensors_to_log: List of tensor names or dictionary mapping labels to tensor
names. If not set, log _TENSORS_TO_LOG by default.
**kwargs: a dictiona... |
def time(self, pattern='%H:%M:%S', end_datetime=None):
"""
Get a time string (24h format by default)
:param pattern format
:example '15:02:34'
"""
return self.date_time(
end_datetime=end_datetime).time().strftime(pattern) | Get a time string (24h format by default)
:param pattern format
:example '15:02:34' |
def make_subdirs(self):
"""The purpose of this method is to, if necessary, create all of the
subdirectories leading up to the file to the written."""
# Pull off everything below the root.
subpath = self.full_path[len(self.context.root):]
log.debug("make_subdirs: subpath is %s", s... | The purpose of this method is to, if necessary, create all of the
subdirectories leading up to the file to the written. |
def and_(cls, obj, **kwargs):
"""Query an object
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if all `kwargs` expression are `True`, `False` otherwise.
:rtype: bool
"""
return cls.__eval_seqexp(obj, ... | Query an object
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if all `kwargs` expression are `True`, `False` otherwise.
:rtype: bool |
def sender(self, jid: str):
"""
Set jid of the sender
Args:
jid (str): jid of the sender
"""
if jid is not None and not isinstance(jid, str):
raise TypeError("'sender' MUST be a string")
self._sender = aioxmpp.JID.fromstr(jid) if jid is not None el... | Set jid of the sender
Args:
jid (str): jid of the sender |
def versionString(version):
"""Create version string.
For a sequence containing version information such as (2, 0, 0, 'pre'),
this returns a printable string such as '2.0pre'.
The micro version number is only excluded from the string if it is zero.
"""
ver = list(map(str, version))
numbers... | Create version string.
For a sequence containing version information such as (2, 0, 0, 'pre'),
this returns a printable string such as '2.0pre'.
The micro version number is only excluded from the string if it is zero. |
def disambiguate_text(self, text, language=None, entities=None):
""" Call the disambiguation service in order to get meanings.
Args:
text (str): Text to be disambiguated.
language (str): language of text (if known)
entities (list): list of entities or mentions to be ... | Call the disambiguation service in order to get meanings.
Args:
text (str): Text to be disambiguated.
language (str): language of text (if known)
entities (list): list of entities or mentions to be supplied by
the user.
Returns:
dict, int... |
def pubsub_sub(self, topic, discover=False, **kwargs):
"""Subscribe to mesages on a given topic
Subscribing to a topic in IPFS means anytime
a message is published to a topic, the subscribers
will be notified of the publication.
The connection with the pubsub topic is opened an... | Subscribe to mesages on a given topic
Subscribing to a topic in IPFS means anytime
a message is published to a topic, the subscribers
will be notified of the publication.
The connection with the pubsub topic is opened and read.
The Subscription returned should be used inside a ... |
def recruit(self):
"""Recruit participants to the experiment as needed.
This method runs whenever a participant successfully completes the
experiment (participants who fail to finish successfully are
automatically replaced). By default it recruits 1 participant at a time
until a... | Recruit participants to the experiment as needed.
This method runs whenever a participant successfully completes the
experiment (participants who fail to finish successfully are
automatically replaced). By default it recruits 1 participant at a time
until all networks are full. |
def displayMousePosition(xOffset=0, yOffset=0):
"""This function is meant to be run from the command line. It will
automatically display the location and RGB of the mouse cursor."""
print('Press Ctrl-C to quit.')
if xOffset != 0 or yOffset != 0:
print('xOffset: %s yOffset: %s' % (xOffset, yOffse... | This function is meant to be run from the command line. It will
automatically display the location and RGB of the mouse cursor. |
def get_identifier(self, origin=None):
"""Read the next token and raise an exception if it is not an identifier.
@raises dns.exception.SyntaxError:
@rtype: string
"""
token = self.get().unescape()
if not token.is_identifier():
raise dns.exception.SyntaxError... | Read the next token and raise an exception if it is not an identifier.
@raises dns.exception.SyntaxError:
@rtype: string |
def start_wsgi_server(port, addr='', registry=REGISTRY):
"""Starts a WSGI server for prometheus metrics as a daemon thread."""
app = make_wsgi_app(registry)
httpd = make_server(addr, port, app, handler_class=_SilentHandler)
t = threading.Thread(target=httpd.serve_forever)
t.daemon = True
t.start... | Starts a WSGI server for prometheus metrics as a daemon thread. |
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string | Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match |
def beautify(self, string):
"""
Wraps together all actions needed to beautify a string, i.e.
parse the string and then stringify the phrases (replace tags
with formatting codes).
Arguments:
string (str): The string to beautify/parse.
Returns:
The parsed, stringified and ultimately beautified string.... | Wraps together all actions needed to beautify a string, i.e.
parse the string and then stringify the phrases (replace tags
with formatting codes).
Arguments:
string (str): The string to beautify/parse.
Returns:
The parsed, stringified and ultimately beautified string.
Raises:
errors.ArgumentError ... |
def gcs_get_file(bucketname,
filename,
local_file,
altexts=None,
client=None,
service_account_json=None,
raiseonfail=False):
"""This gets a single file from a Google Cloud Storage bucket.
Parameters
------... | This gets a single file from a Google Cloud Storage bucket.
Parameters
----------
bucketname : str
The name of the GCS bucket to download the file from.
filename : str
The full name of the file to download, including all prefixes.
local_file : str
Path to where the downlo... |
def dictionize(fields: Sequence, records: Sequence) -> Generator:
"""Create dictionaries mapping fields to record data."""
return (dict(zip(fields, rec)) for rec in records) | Create dictionaries mapping fields to record data. |
def deterministic_crowding(self,parents,offspring,X_parents,X_offspring):
"""deterministic crowding implementation (for non-steady state).
offspring compete against the parent they are most similar to, here defined as
the parent they are most correlated with.
the offspring only replace t... | deterministic crowding implementation (for non-steady state).
offspring compete against the parent they are most similar to, here defined as
the parent they are most correlated with.
the offspring only replace their parent if they are more fit. |
def DisableCronJob(self, cronjob_id):
"""Disables a cronjob."""
job = self.cronjobs.get(cronjob_id)
if job is None:
raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id)
job.enabled = False | Disables a cronjob. |
def build(self, _resource, _cache=True, updatecontent=True, **kwargs):
"""Build a schema class from input _resource.
:param _resource: object from where get the right schema.
:param bool _cache: use _cache system.
:param bool updatecontent: if True (default) update result.
:rtyp... | Build a schema class from input _resource.
:param _resource: object from where get the right schema.
:param bool _cache: use _cache system.
:param bool updatecontent: if True (default) update result.
:rtype: Schema. |
def nth(self, n, dropna=None):
"""
Take the nth row from each group if n is an int, or a subset of rows
if n is a list of ints.
If dropna, will take the nth non-null row, dropna is either
Truthy (if a Series) or 'all', 'any' (if a DataFrame);
this is equivalent to callin... | Take the nth row from each group if n is an int, or a subset of rows
if n is a list of ints.
If dropna, will take the nth non-null row, dropna is either
Truthy (if a Series) or 'all', 'any' (if a DataFrame);
this is equivalent to calling dropna(how=dropna) before the
groupby.
... |
def validate_signature(self, signature, data, encoding='utf8'):
"""Validate the signature for the provided data.
Args:
signature (str or bytes or bytearray): Signature that was provided
for the request.
data (str or bytes or bytearray): Data string to validate ag... | Validate the signature for the provided data.
Args:
signature (str or bytes or bytearray): Signature that was provided
for the request.
data (str or bytes or bytearray): Data string to validate against
the signature.
encoding (str, optional): ... |
def render_scene(self):
"render scene one time"
self.canvas.SetCurrent ( self.context )
self.renderer.render_scene()
# Done rendering
# self.canvas.SwapBuffers()
if self.canvas.IsDoubleBuffered():
self.canvas.SwapBuffers()
print ("double buffered") # Do not want
else:
pass
# TODO: S... | render scene one time |
def add_atmost(self, lits, k, no_return=True):
"""
This method is responsible for adding a new *native* AtMostK (see
:mod:`pysat.card`) constraint into :class:`Minicard`.
**Note that none of the other solvers supports native AtMostK
constraints**.
An... | This method is responsible for adding a new *native* AtMostK (see
:mod:`pysat.card`) constraint into :class:`Minicard`.
**Note that none of the other solvers supports native AtMostK
constraints**.
An AtMostK constraint is :math:`\sum_{i=1}^{n}{x_i}\leq k`. A
... |
def find_packages(self, root_target, chroot):
"""Detect packages, namespace packages and resources from an existing chroot.
:returns: a tuple of:
set(packages)
set(namespace_packages)
map(package => set(files))
"""
base = os.path.join(chroot.path(), self.... | Detect packages, namespace packages and resources from an existing chroot.
:returns: a tuple of:
set(packages)
set(namespace_packages)
map(package => set(files)) |
def get_named_type(type_): # noqa: F811
"""Unwrap possible wrapping type"""
if type_:
unwrapped_type = type_
while is_wrapping_type(unwrapped_type):
unwrapped_type = cast(GraphQLWrappingType, unwrapped_type)
unwrapped_type = unwrapped_type.of_type
return cast(Gra... | Unwrap possible wrapping type |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.