code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def normalized(self):
"""
Returns a normalized copy of this vector.
"""
norm = self.magnitude()
return Vector(self.x / norm, self.y / norm, self.z / norm) | Returns a normalized copy of this vector. |
def create_countries_geo_zone(cls, countries_geo_zone, **kwargs):
"""Create CountriesGeoZone
Create a new CountriesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_countries_geo_... | Create CountriesGeoZone
Create a new CountriesGeoZone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_countries_geo_zone(countries_geo_zone, async=True)
>>> result = thread.get()
... |
def can_fetch(self, request: Request, file=None) -> bool:
'''Return whether the request can fetched.
Args:
request: Request.
file: A file object to where the robots.txt contents are written.
Coroutine.
'''
try:
return self.can_fetch_pool(requ... | Return whether the request can fetched.
Args:
request: Request.
file: A file object to where the robots.txt contents are written.
Coroutine. |
def parse(ascii_armor_message: str, signing_key: Optional[SigningKey] = None,
sender_pubkeys: Optional[List[str]] = None) -> dict:
"""
Return a dict with parsed content (decrypted message, signature validation) ::
{
'message':
{
... | Return a dict with parsed content (decrypted message, signature validation) ::
{
'message':
{
'fields': {},
'content': str,
},
'signatures': [
{'pubkey': str, 'valid': bool,... |
def _AddMessageMethods(message_descriptor, cls):
"""Adds implementations of all Message methods to cls."""
_AddListFieldsMethod(message_descriptor, cls)
_AddHasFieldMethod(message_descriptor, cls)
_AddClearFieldMethod(message_descriptor, cls)
if message_descriptor.is_extendable:
_AddClearExtensionMethod(c... | Adds implementations of all Message methods to cls. |
def restore(self, request):
""" Push the request back onto the queue.
Args:
request (Request): Reference to a request object that should be pushed back
onto the request queue.
"""
self._connection.connection.rpush(self._request_key, pickle.dump... | Push the request back onto the queue.
Args:
request (Request): Reference to a request object that should be pushed back
onto the request queue. |
def as_operation(self):
"""Obtains a single `Operation` representing this instances contents.
Returns:
:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`
"""
result = encoding.CopyProtoMessage(self._op)
names = sorted(self._metric_values_by_name_th... | Obtains a single `Operation` representing this instances contents.
Returns:
:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation` |
def doc_create(self,index,itype,value):
'''
Creates a document
'''
request = self.session
url = 'http://%s:%s/%s/%s/' % (self.host, self.port, index, itype)
if self.verbose:
print value
response = request.post(url,value)
return response | Creates a document |
def create_relationship(self, relationship_form=None):
"""Creates a new ``Relationship``.
arg: relationship_form (osid.relationship.RelationshipForm):
the form for this ``Relationship``
return: (osid.relationship.Relationship) - the new
``Relationship``
... | Creates a new ``Relationship``.
arg: relationship_form (osid.relationship.RelationshipForm):
the form for this ``Relationship``
return: (osid.relationship.Relationship) - the new
``Relationship``
raise: IllegalState - ``relationship_form`` already used in a
... |
def pre_gradient_update(self):
""" First step of Nesterov momentum method:
take step in direction of accumulated gradient
"""
updates = zip(self.velocity, self.model.n_parameters * [1.])
self.model.update_parameters(updates) | First step of Nesterov momentum method:
take step in direction of accumulated gradient |
def _load_config(config_path=None):
"""
Load config files.
Parameters
-----------
config_path : None or :obj:`str` or dict
See class definition for more information.
Returns
-------
:obj:`collections.OrderedDict`
eDisGo configurat... | Load config files.
Parameters
-----------
config_path : None or :obj:`str` or dict
See class definition for more information.
Returns
-------
:obj:`collections.OrderedDict`
eDisGo configuration data from config files. |
def _notify_create_process(self, event):
"""
Notify the creation of a new process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
... | Notify the creation of a new process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{Fal... |
def resource(ref: str, delimiter: str = None) -> str:
"""
Given a (URI) reference, return up to its delimiter (exclusively), or all of it if there is none.
:param ref: reference
:param delimiter: delimiter character (default None maps to '#', or ';' introduces identifiers)
"""
return ref.split... | Given a (URI) reference, return up to its delimiter (exclusively), or all of it if there is none.
:param ref: reference
:param delimiter: delimiter character (default None maps to '#', or ';' introduces identifiers) |
def list_street_poi_parking(self, **kwargs):
"""Obtain a list of addresses and POIs.
This endpoint uses an address to perform the search
Args:
lang (str): Language code (*es* or *en*).
address (str): Address in which to perform the search.
Returns:
... | Obtain a list of addresses and POIs.
This endpoint uses an address to perform the search
Args:
lang (str): Language code (*es* or *en*).
address (str): Address in which to perform the search.
Returns:
Status boolean and parsed response (list[ParkingPoi]), o... |
def merge_scrfiles(self, remove_scrfiles=True):
"""
This method is called when all the q-points have been computed.
It runs `mrgscr` in sequential on the local machine to produce
the final SCR file in the outdir of the `Work`.
If remove_scrfiles is True, the partial SCR files are... | This method is called when all the q-points have been computed.
It runs `mrgscr` in sequential on the local machine to produce
the final SCR file in the outdir of the `Work`.
If remove_scrfiles is True, the partial SCR files are removed after the merge. |
def extract_param(param, args, type=None):
"""
From a list of args, extract the one param if supplied,
returning the value and unused args.
>>> extract_param('port', ['foo', '--port=999', 'bar'], type=int)
(999, ['foo', 'bar'])
>>> extract_param('port', ['foo', '--port', '999', 'bar'], type=int... | From a list of args, extract the one param if supplied,
returning the value and unused args.
>>> extract_param('port', ['foo', '--port=999', 'bar'], type=int)
(999, ['foo', 'bar'])
>>> extract_param('port', ['foo', '--port', '999', 'bar'], type=int)
(999, ['foo', 'bar'])
>>> extract_param('port... |
def request_networks(blink):
"""Request all networks information."""
url = "{}/networks".format(blink.urls.base_url)
return http_get(blink, url) | Request all networks information. |
def _check_sane_and_get_gpg_version(self):
"""Check that everything runs alright, and grab the gpg binary's
version number while we're at it, storing it as :data:`binary_version`.
:raises RuntimeError: if we cannot invoke the gpg binary.
"""
proc = self._open_subprocess(["--list... | Check that everything runs alright, and grab the gpg binary's
version number while we're at it, storing it as :data:`binary_version`.
:raises RuntimeError: if we cannot invoke the gpg binary. |
def start(self):
"""Start the firewall."""
self.clear()
self.setDefaultPolicy()
self.acceptIcmp()
self.acceptInput('lo') | Start the firewall. |
def get_response(self, url, username=None, password=None):
"""
does the dirty work of actually getting the rsponse object using urllib2
and its HTTP auth builtins.
"""
scheme, netloc, path, query, frag = urlparse.urlsplit(url)
req = self.get_request(url)
stored_u... | does the dirty work of actually getting the rsponse object using urllib2
and its HTTP auth builtins. |
def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per RFC 1918.
"""
private_10 = IPv4Network('10.0.0.0/8')
private_172 = IPv4Network('172.16.0.0/12')
private_192 = IPv4Network... | Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per RFC 1918. |
def sharedFiles(self):
'iterate over shared files and get their public URI'
for f in self.sharing.files.iterchildren():
yield (f.attrib['name'], f.attrib['uuid'],
'https://www.jottacloud.com/p/%s/%s' % (self.jfs.username, f.publicURI.text)) | iterate over shared files and get their public URI |
def sav_to_pandas_savreader(input_file):
"""
SPSS .sav files to Pandas DataFrame through savreader module
:param input_file: string
:return:
"""
from savReaderWriter import SavReader
lines = []
with SavReader(input_file, returnHeader=True) as reader:
header = next(reader)
... | SPSS .sav files to Pandas DataFrame through savreader module
:param input_file: string
:return: |
def extract(self, vlr_type):
""" Returns the list of vlrs of the requested type
The difference with get is that the returned vlrs will be removed from the list
Parameters
----------
vlr_type: str
the class name of the vlr
Returns
-------
... | Returns the list of vlrs of the requested type
The difference with get is that the returned vlrs will be removed from the list
Parameters
----------
vlr_type: str
the class name of the vlr
Returns
-------
list
a List of vlrs matchin... |
def roc(self, num_thresholds, target_class, probability_column=None):
"""Get true positive rate, false positive rate values from evaluation results.
Args:
num_thresholds: an integer. Number of thresholds.
target_class: a string indciating the target class, i.e. "daisy" in flower classification.
... | Get true positive rate, false positive rate values from evaluation results.
Args:
num_thresholds: an integer. Number of thresholds.
target_class: a string indciating the target class, i.e. "daisy" in flower classification.
probability_column: the name of the probability column. If None, defaults ... |
def start_delta_string(self):
"""A convenient string representation of how long after the run started we started.
:API: public
"""
delta = int(self.start_time) - int(self.root().start_time)
return '{:02}:{:02}'.format(int(delta / 60), delta % 60) | A convenient string representation of how long after the run started we started.
:API: public |
def put_replication(Bucket, Role, Rules,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration w... | Given a valid config, update the replication configuration for a bucket.
Returns {updated: true} if replication configuration was updated and returns
{updated: False} if replication configuration was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_replication ... |
def drop(
self,
labels=None,
axis=0,
index=None,
columns=None,
level=None,
inplace=False,
errors="raise",
):
"""Return new object with labels in requested axis removed.
Args:
labels: Index or column labels to dro... | Return new object with labels in requested axis removed.
Args:
labels: Index or column labels to drop.
axis: Whether to drop labels from the index (0 / 'index') or
columns (1 / 'columns').
index, columns: Alternative to specifying axis (labels, axis=1 is
... |
def to_bounding_box(self):
"""
Convert this polygon to a bounding box tightly containing the whole polygon.
Returns
-------
imgaug.BoundingBox
Tight bounding box around the polygon.
"""
# TODO get rid of this deferred import
from imgaug.augme... | Convert this polygon to a bounding box tightly containing the whole polygon.
Returns
-------
imgaug.BoundingBox
Tight bounding box around the polygon. |
def _single_replace(self, to_replace, method, inplace, limit):
"""
Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method
"""
if self.ndim != 1:
raise TypeError('cannot replace {0} with method {1} on a {2}'
... | Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method |
def load_hdf(cls, filename, path='', name=None):
"""
A class method to load a saved StarModel from an HDF5 file.
File must have been created by a call to :func:`StarModel.save_hdf`.
:param filename:
H5 file to load.
:param path: (optional)
Path within H... | A class method to load a saved StarModel from an HDF5 file.
File must have been created by a call to :func:`StarModel.save_hdf`.
:param filename:
H5 file to load.
:param path: (optional)
Path within HDF file.
:return:
:class:`StarModel` object. |
def dateRange(*args):
"""
Accepted forms:
* ``dateRange(day)``
* ``dateRange(day1, day2)``
* ``dateRange(mon)``
* ``dateRange(month1, month2)``
* ``dateRange(year)``
* ``dateRange(year1, year2)``
* ``dateRange(day1, month1, day2, month2)``
* ``dateRange(month1, year1, month2, ye... | Accepted forms:
* ``dateRange(day)``
* ``dateRange(day1, day2)``
* ``dateRange(mon)``
* ``dateRange(month1, month2)``
* ``dateRange(year)``
* ``dateRange(year1, year2)``
* ``dateRange(day1, month1, day2, month2)``
* ``dateRange(month1, year1, month2, year2)``
* ``dateRange(day1, mon... |
def activate_user(self, username, activation_key):
"""
Activate an :class:`User` by supplying a valid ``activation_key``.
If the key is valid and an user is found, activates the user and
return it. Also sends the ``activation_complete`` signal.
:param activation_key:
... | Activate an :class:`User` by supplying a valid ``activation_key``.
If the key is valid and an user is found, activates the user and
return it. Also sends the ``activation_complete`` signal.
:param activation_key:
String containing the secret SHA1 for a valid activation.
:r... |
def pop(self, timeout=None):
"""
:param timeout: OPTIONAL DURATION
:return: None, IF timeout PASSES
"""
with self.lock:
while not self.please_stop:
if self.db.status.end > self.start:
value = self.db[str(self.start)]
... | :param timeout: OPTIONAL DURATION
:return: None, IF timeout PASSES |
def get_parameter_dict(self, include_frozen=False):
"""
Get an ordered dictionary of the parameters
Args:
include_frozen (Optional[bool]): Should the frozen parameters be
included in the returned value? (default: ``False``)
"""
return OrderedDict(zip... | Get an ordered dictionary of the parameters
Args:
include_frozen (Optional[bool]): Should the frozen parameters be
included in the returned value? (default: ``False``) |
def update(fatal=False):
"""Update local yum cache."""
cmd = ['yum', '--assumeyes', 'update']
log("Update with fatal: {}".format(fatal))
_run_yum_command(cmd, fatal) | Update local yum cache. |
def parse(fpath, **kwargs):
""" parse file contents, via parser plugins, to dict like object
NB: the longest file regex will be used from plugins
Parameters
----------
fpath : file_like
string, object with 'open' and 'name' attributes, or
object with 'readline' and 'name' attribut... | parse file contents, via parser plugins, to dict like object
NB: the longest file regex will be used from plugins
Parameters
----------
fpath : file_like
string, object with 'open' and 'name' attributes, or
object with 'readline' and 'name' attributes
kwargs :
to pass to p... |
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self._data = data
self.allowCameraUpload = cast(bool, data.attrib.get('allowCameraUpload'))
self.allowChannelAccess = cast(bool, data.attrib.get('allowChannelAccess'))
self.allowMediaDeletion = cast(... | Load attribute values from Plex XML response. |
def lendbook(self, currency, parameters=None):
"""
curl "https://api.bitfinex.com/v1/lendbook/btc"
{"bids":[{"rate":"5.475","amount":"15.03894663","period":30,"timestamp":"1395112149.0","frr":"No"},{"rate":"2.409","amount":"14.5121868","period":7,"timestamp":"1395497599.0","frr":"No"}],"asks":[... | curl "https://api.bitfinex.com/v1/lendbook/btc"
{"bids":[{"rate":"5.475","amount":"15.03894663","period":30,"timestamp":"1395112149.0","frr":"No"},{"rate":"2.409","amount":"14.5121868","period":7,"timestamp":"1395497599.0","frr":"No"}],"asks":[{"rate":"6.351","amount":"15.5180735","period":5,"timestamp":"13955... |
def convert_weights(wgts:Weights, stoi_wgts:Dict[str,int], itos_new:Collection[str]) -> Weights:
"Convert the model `wgts` to go with a new vocabulary."
dec_bias, enc_wgts = wgts.get('1.decoder.bias', None), wgts['0.encoder.weight']
wgts_m = enc_wgts.mean(0)
if dec_bias is not None: bias_m = dec_bias.me... | Convert the model `wgts` to go with a new vocabulary. |
def get_partitions(self, persistence=None):
""" Returns the partitioned data based on a specified
persistence level.
@ In, persistence, a floating point value specifying the
size of the smallest feature we want to track.
Default = None means consider all features.... | Returns the partitioned data based on a specified
persistence level.
@ In, persistence, a floating point value specifying the
size of the smallest feature we want to track.
Default = None means consider all features.
@ Out, a dictionary lists where each key is... |
def fetch_plaintext(self, msg_nums):
"""
Given a message number that we found with imap_search,
get the text/plain content.
@Params
msg_nums - message number to get message for
@Returns
Plaintext content of message matched by message number
"""
if ... | Given a message number that we found with imap_search,
get the text/plain content.
@Params
msg_nums - message number to get message for
@Returns
Plaintext content of message matched by message number |
def is_flat(neurite, tol, method='tolerance'):
'''Check if neurite is flat using the given method
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
method(string): the method of flatness estimation:
'tolerance' returns true if any extent of the tree is smal... | Check if neurite is flat using the given method
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
method(string): the method of flatness estimation:
'tolerance' returns true if any extent of the tree is smaller
than the given tolerance
'... |
def getParentAddress(self):
"""get Thread device's parent extended address and rloc16 short address
Returns:
The extended address of parent in hex format
"""
print '%s call getParentAddress' % self.port
parentInfo = []
parentInfo = self.__stripValue(self.__se... | get Thread device's parent extended address and rloc16 short address
Returns:
The extended address of parent in hex format |
def flush(self):
"""Empty the local queue and send its elements to be executed remotely.
"""
for elem in self:
if elem.id[0] != scoop.worker:
elem._delete()
self.socket.sendFuture(elem)
self.ready.clear()
self.movable.clear() | Empty the local queue and send its elements to be executed remotely. |
def Create_Random_Forest(train):
"""
Fits Random Forest to training set.
:param train: This is the file name of a csv file we wish to have fitted to a Random Forest, does not need to have features already extracted.
:returns: Returns sklearn.ensemble.Random_Forest_Classifier fitted to training set.... | Fits Random Forest to training set.
:param train: This is the file name of a csv file we wish to have fitted to a Random Forest, does not need to have features already extracted.
:returns: Returns sklearn.ensemble.Random_Forest_Classifier fitted to training set. |
def list_tables(self):
'''
Load existing tables and their descriptions.
:return:
'''
if not self._tables:
for table_name in os.listdir(self.db_path):
self._tables[table_name] = self._load_table(table_name)
return self._tables.keys() | Load existing tables and their descriptions.
:return: |
def array(source_array, ctx=None, dtype=None):
"""Creates a sparse array from any object exposing the array interface.
Parameters
----------
source_array : RowSparseNDArray, CSRNDArray or scipy.sparse.csr.csr_matrix
The source sparse array
ctx : Context, optional
The default context... | Creates a sparse array from any object exposing the array interface.
Parameters
----------
source_array : RowSparseNDArray, CSRNDArray or scipy.sparse.csr.csr_matrix
The source sparse array
ctx : Context, optional
The default context is ``source_array.context`` if ``source_array`` is an... |
def get(self, item, cache=None):
"""Lookup a torrent info property.
If cache is True, check the cache first. If the cache is empty, then
fetch torrent info before returning it.
"""
if item not in self._keys:
raise KeyError(item)
if self._use_cache(cache) and... | Lookup a torrent info property.
If cache is True, check the cache first. If the cache is empty, then
fetch torrent info before returning it. |
def run(cmd, **kwargs):
"""Echo a command before running it. Defaults to repo as cwd"""
log.info('> ' + list2cmdline(cmd))
kwargs.setdefault('cwd', HERE)
kwargs.setdefault('shell', os.name == 'nt')
if not isinstance(cmd, (list, tuple)) and os.name != 'nt':
cmd = shlex.split(cmd)
cmd[0] ... | Echo a command before running it. Defaults to repo as cwd |
def _merge_ex_dicts(sexdict, oexdict):
"""Merge callable look-up tables from two objects."""
# pylint: disable=R0101
for okey, ovalue in oexdict.items():
# Keys in other dictionary are callable paths or
# callables ids depending on the full_cname argument
# of the handler
if ... | Merge callable look-up tables from two objects. |
def is_equal(self, other):
"""
Whether two strings are equal
"""
other = StringCell.coerce(other)
empties = [None,'']
if self.value in empties and other.value in empties:
return True
return self.value == other.value | Whether two strings are equal |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'concepts') and self.concepts is not None:
_dict['concepts'] = self.concepts._to_dict()
if hasattr(self, 'emotion') and self.emotion is not None:
_dict['emotion... | Return a json dictionary representing this model. |
def get_queue(self, queue_name):
"""Get a client for a queue entity.
:param queue_name: The name of the queue.
:type queue_name: str
:rtype: ~azure.servicebus.servicebus_client.QueueClient
:raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not... | Get a client for a queue entity.
:param queue_name: The name of the queue.
:type queue_name: str
:rtype: ~azure.servicebus.servicebus_client.QueueClient
:raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
:raises: ~azure.servicebus.c... |
def _apply_transformation(inputs):
"""
Helper method for multiprocessing of apply_transformation. Must not be
in the class so that it can be pickled.
Args:
inputs: Tuple containing the transformed structure, the transformation
to be applied, a boolean indicating whether to extend th... | Helper method for multiprocessing of apply_transformation. Must not be
in the class so that it can be pickled.
Args:
inputs: Tuple containing the transformed structure, the transformation
to be applied, a boolean indicating whether to extend the
collection, and a boolean indicat... |
def remove_orphans(self, instance, **kwargs):
"""
When an item is deleted, first delete any Activity object that has been created
on its behalf.
"""
from activity_monitor.models import Activity
try:
instance_content_type = ContentType.objects.get_for_model(instance)
t... | When an item is deleted, first delete any Activity object that has been created
on its behalf. |
def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub):
"""
Split the query string into individual keywords, discarding spaces
and grouping quoted words together.
>>> normalize_query(' some random... | Split the query string into individual keywords, discarding spaces
and grouping quoted words together.
>>> normalize_query(' some random words "with quotes " and spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces'] |
def policy_map_clss_map_dscp_mutation(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
po_name_key = ET.SubElement(policy_map, "po-name")
po_name_key.te... | Auto Generated Code |
def _children(self):
"""Yield all direct children of this object."""
if self.method_of:
yield self.method_of
for codeobj in self.arguments:
if isinstance(codeobj, CodeExpression):
yield codeobj | Yield all direct children of this object. |
def add_file(self, user, file_obj, **metadata):
"""Add a new file.
:returns: file handle
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
user_dir.mkdir(mode=0o775)
handle = str(uuid1())
file_path = user_dir / handle
with file_pa... | Add a new file.
:returns: file handle |
def get_client(self):
"""
Retrieves or creates a client instance from this configuration object. If instantiated from this configuration,
the resulting object is also cached in the property ``client`` and a reference to this configuration is stored
on the client object.
:return:... | Retrieves or creates a client instance from this configuration object. If instantiated from this configuration,
the resulting object is also cached in the property ``client`` and a reference to this configuration is stored
on the client object.
:return: Client object instance.
:rtype: d... |
def _inject_language(self, src, strings):
"""Injects languages into (potentially) template strings."""
if src not in self.sources:
raise ValueError("Invalid source for '{0}': {1}".format(self.name, src))
def _format_string(s):
if "{0}" in s and "{1}" and "{src}" in s:
return s.format(*so... | Injects languages into (potentially) template strings. |
def read_coils(self, bit_addr, bit_nb=1):
"""Modbus function READ_COILS (0x01)
:param bit_addr: bit address (0 to 65535)
:type bit_addr: int
:param bit_nb: number of bits to read (1 to 2000)
:type bit_nb: int
:returns: bits list or None if error
:rtype: list of b... | Modbus function READ_COILS (0x01)
:param bit_addr: bit address (0 to 65535)
:type bit_addr: int
:param bit_nb: number of bits to read (1 to 2000)
:type bit_nb: int
:returns: bits list or None if error
:rtype: list of bool or None |
def on_deckbuilder(self, *args):
"""Bind my deckbuilder to update my ``scroll``, and my ``scroll`` to
update my deckbuilder.
"""
if self.deckbuilder is None:
return
att = 'deck_{}_hint_offsets'.format(
'x' if self.orientation == 'horizontal' else 'y'
... | Bind my deckbuilder to update my ``scroll``, and my ``scroll`` to
update my deckbuilder. |
def _validate_auth_scheme(self, req):
""" Check if the request has auth & the proper scheme
Remember NOT to include the error related info in
the WWW-Authenticate header for these conditions.
:raise:
AuthRequired
"""
if not req.auth:
raise AuthR... | Check if the request has auth & the proper scheme
Remember NOT to include the error related info in
the WWW-Authenticate header for these conditions.
:raise:
AuthRequired |
def calc_point_distance_vary(self, chi_coords, point_fupper, mus):
"""
Calculate distance between point and the bank allowing the metric to
vary based on varying upper frequency cutoff. Slower than
calc_point_distance, but more reliable when upper frequency cutoff can
change a lo... | Calculate distance between point and the bank allowing the metric to
vary based on varying upper frequency cutoff. Slower than
calc_point_distance, but more reliable when upper frequency cutoff can
change a lot.
Parameters
-----------
chi_coords : numpy.array
... |
def resetn(self):
"""
reset a core. After a call to this function, the core
is running
"""
#Regular reset will kick NRF out of DBG mode
logging.debug("target_nrf51.reset: enable reset pin")
self.write_memory(RESET, RESET_ENABLE)
#reset
logging.debu... | reset a core. After a call to this function, the core
is running |
def has_key(self, key):
"""Check if a :attr:`~libinput.constant.DeviceCapability.KEYBOARD`
device has a given key.
Args:
key (int): Key to check for, see ``input.h`` for key definitions.
Returns:
bool: :obj:`True` if the device has this key, :obj:`False` if
it does not.
Raises:
AssertionError
"... | Check if a :attr:`~libinput.constant.DeviceCapability.KEYBOARD`
device has a given key.
Args:
key (int): Key to check for, see ``input.h`` for key definitions.
Returns:
bool: :obj:`True` if the device has this key, :obj:`False` if
it does not.
Raises:
AssertionError |
def _traverse_results(value, fields, row, path):
"""
Helper method for parse_results().
Traverses through ordered dict and recursively calls itself when encountering a dictionary
"""
for f, v in value.iteritems(): # for each item in obj
field_name = '{path}.{name}'.format(path=path, name=f... | Helper method for parse_results().
Traverses through ordered dict and recursively calls itself when encountering a dictionary |
def eval_objfn(self):
r"""Compute components of objective function as well as total
contribution to objective function. The objective function is
:math:`\| \mathbf{x} \|_1` and the constraint violation
measure is :math:`P(\mathbf{x}) - \mathbf{x}` where
:math:`P(\mathbf{x})` is ... | r"""Compute components of objective function as well as total
contribution to objective function. The objective function is
:math:`\| \mathbf{x} \|_1` and the constraint violation
measure is :math:`P(\mathbf{x}) - \mathbf{x}` where
:math:`P(\mathbf{x})` is the projection into the constr... |
def basic_lstm(inputs, state, num_units, name=None):
"""Basic LSTM."""
input_shape = common_layers.shape_list(inputs)
# reuse parameters across time-steps.
cell = tf.nn.rnn_cell.BasicLSTMCell(
num_units, name=name, reuse=tf.AUTO_REUSE)
if state is None:
state = cell.zero_state(input_shape[0], tf.flo... | Basic LSTM. |
def get_elements_attributes(parent_to_parse, element_path=None, attrib_name=None):
"""
:return: list of text representing an attribute of parent or each element at element path,
or a list of dicts representing all the attributes parsed from each element
"""
attrs = _get_elements_property(p... | :return: list of text representing an attribute of parent or each element at element path,
or a list of dicts representing all the attributes parsed from each element |
def fit(self, X, y=None, eval_data=None, eval_metric='acc',
epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None,
work_load_list=None, monitor=None, eval_end_callback=LogValidationMetricsCallback(),
eval_batch_end_callback=None):
"""Fit the model.
... | Fit the model.
Parameters
----------
X : DataIter, or numpy.ndarray/NDArray
Training data. If `X` is a `DataIter`, the name or (if name not available)
the position of its outputs should match the corresponding variable
names defined in the symbolic graph.
... |
def list_files(path):
"""Recursively collects a list of files at a path."""
files = []
if os.path.isdir(path):
for stats in os.walk(path):
for f in stats[2]:
files.append(os.path.join(stats[0], f))
elif os.path.isfile(path):
files = [path]
return files | Recursively collects a list of files at a path. |
def get_package(self):
"""Create the analogous package.
Returns:
`Package` object.
"""
# get and validate package data
package_data = self._get_data()
package_data = package_schema.validate(package_data)
# check compatibility with rez version
... | Create the analogous package.
Returns:
`Package` object. |
def setup_document(self, content, **kwargs):
"""
Setup `response` object without real network requests.
Useful for testing and debuging.
All ``**kwargs`` will be passed to `Document` constructor.
"""
self.reset()
if isinstance(content, six.text_type):
... | Setup `response` object without real network requests.
Useful for testing and debuging.
All ``**kwargs`` will be passed to `Document` constructor. |
def get_oauth_request(self):
"""Return an OAuth Request object for the current request."""
try:
method = os.environ['REQUEST_METHOD']
except:
method = 'GET'
postdata = None
if method in ('POST', 'PUT'):
postdata = self.request.body
r... | Return an OAuth Request object for the current request. |
def _get_encoder_module(self) -> Tuple[mx.mod.BucketingModule, int]:
"""
Returns a BucketingModule for the encoder. Given a source sequence, it returns
the initial decoder states of the model.
The bucket key for this module is the length of the source sequence.
:return: Tuple of... | Returns a BucketingModule for the encoder. Given a source sequence, it returns
the initial decoder states of the model.
The bucket key for this module is the length of the source sequence.
:return: Tuple of encoder module and default bucket key. |
def table_or_view_exists(engine: Engine, table_or_view_name: str) -> bool:
"""
Does the named table/view exist (either as a table or as a view) in the
database?
"""
tables_and_views = get_table_names(engine) + get_view_names(engine)
return table_or_view_name in tables_and_views | Does the named table/view exist (either as a table or as a view) in the
database? |
def set_blacklisted_plugins(self, plugins):
"""
sets blacklisted plugins.
`plugins` may be a single object or iterable.
"""
plugins = util.return_list(plugins)
self.blacklisted_plugins = plugins | sets blacklisted plugins.
`plugins` may be a single object or iterable. |
def users(self,
start=1,
num=10,
sortField="fullName",
sortOrder="asc",
role=None):
"""
Lists all the members of the organization. The start and num paging
parameters are supported.
Inputs:
start - The numb... | Lists all the members of the organization. The start and num paging
parameters are supported.
Inputs:
start - The number of the first entry in the result set response.
The index number is 1-based.
The default value of start is 1 (that is, the first
... |
def replace_type(items, spec, loader, found, find_embeds=True, deepen=True):
# type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any
""" Go through and replace types in the 'spec' mapping"""
if isinstance(items, MutableMapping):
# recursively check these fields for types to replace
... | Go through and replace types in the 'spec' mapping |
def _tuple_of_big_endian_int(bit_groups: Tuple[np.ndarray, ...]
) -> Tuple[int, ...]:
"""Returns the big-endian integers specified by groups of bits.
Args:
bit_groups: Groups of descending bits, each specifying a big endian
integer with the 1s bit at the end.
... | Returns the big-endian integers specified by groups of bits.
Args:
bit_groups: Groups of descending bits, each specifying a big endian
integer with the 1s bit at the end.
Returns:
A tuple containing the integer for each group. |
def phi( n ):
"""Return the Euler totient function of n."""
assert isinstance( n, integer_types )
if n < 3: return 1
result = 1
ff = factorization( n )
for f in ff:
e = f[1]
if e > 1:
result = result * f[0] ** (e-1) * ( f[0] - 1 )
else:
result = result * ( f[0] - 1 )
return resu... | Return the Euler totient function of n. |
def update_tag(self, tag_name, description=None,
custom_properties=None, **kwargs):
"""update a tag by name
Args:
tag_name (string): name of tag to update
description (optional[string]): a description
custom_properties (optional[dict]): dictionary ... | update a tag by name
Args:
tag_name (string): name of tag to update
description (optional[string]): a description
custom_properties (optional[dict]): dictionary of custom properties |
def restore_state(self):
""" Method should be called on obj. initialization
When called, the method will attempt to restore
IO expander and RPi coherence and restore
local knowledge across a possible power failure
"""
current_mask = get_IO_reg(ControlCluster... | Method should be called on obj. initialization
When called, the method will attempt to restore
IO expander and RPi coherence and restore
local knowledge across a possible power failure |
async def spawn(self, agent_cls, *args, addr=None, **kwargs):
"""Spawn a new agent in a slave environment.
:param str agent_cls:
`qualname`` of the agent class.
That is, the name should be in the form ``pkg.mod:cls``, e.g.
``creamas.core.agent:CreativeAgent``.
... | Spawn a new agent in a slave environment.
:param str agent_cls:
`qualname`` of the agent class.
That is, the name should be in the form ``pkg.mod:cls``, e.g.
``creamas.core.agent:CreativeAgent``.
:param str addr:
Optional. Address for the slave enviroment... |
def write(self, file=None, callback=None):
'''Write the contents of the body to the optionally provided file and
providing progress to the optional callback. The callback will be
invoked 3 different ways:
* First as ``callback(start=self)``
* For each chunk of data written as
... | Write the contents of the body to the optionally provided file and
providing progress to the optional callback. The callback will be
invoked 3 different ways:
* First as ``callback(start=self)``
* For each chunk of data written as
``callback(wrote=chunk_size_in_bytes, total=al... |
def _max_form(f, colname):
"""
Assumes dataframe with hierarchical columns with first index equal to the
use and second index equal to the attribute.
e.g. f.columns equal to::
mixedoffice building_cost
building_revenue
b... | Assumes dataframe with hierarchical columns with first index equal to the
use and second index equal to the attribute.
e.g. f.columns equal to::
mixedoffice building_cost
building_revenue
building_size
max_prof... |
def nltides_gw_phase_diff_isco(f_low, f0, amplitude, n, m1, m2):
"""Calculate the gravitational-wave phase shift bwtween
f_low and f_isco due to non-linear tides.
Parameters
----------
f_low: float
Frequency from which to compute phase. If the other
arguments are passed as numpy arr... | Calculate the gravitational-wave phase shift bwtween
f_low and f_isco due to non-linear tides.
Parameters
----------
f_low: float
Frequency from which to compute phase. If the other
arguments are passed as numpy arrays then the value
of f_low is duplicated for all elements in th... |
def edit(self, body):
"""Edit this comment.
:param str body: (required), new body of the comment, Markdown
formatted
:returns: bool
"""
if body:
json = self._json(self._patch(self._api,
data=dumps({'body': body})), 200)
... | Edit this comment.
:param str body: (required), new body of the comment, Markdown
formatted
:returns: bool |
def floordiv(self, other, axis="columns", level=None, fill_value=None):
"""Divides this DataFrame against another DataFrame/Series/scalar.
Args:
other: The object to use to apply the divide against this.
axis: The axis to divide over.
level: The Multilevel inde... | Divides this DataFrame against another DataFrame/Series/scalar.
Args:
other: The object to use to apply the divide against this.
axis: The axis to divide over.
level: The Multilevel index level to apply divide over.
fill_value: The value to fill NaNs with.
... |
def emit(self, span_datas):
"""
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
"""
envelopes = [self.span_data_to_envelope(sd) for sd in span_d... | :type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit |
def get_model_class(settings_entry_name):
"""Returns a certain sitetree model as defined in the project settings.
:param str|unicode settings_entry_name:
:rtype: TreeItemBase|TreeBase
"""
app_name, model_name = get_app_n_model(settings_entry_name)
try:
model = apps_get_model(app_name, ... | Returns a certain sitetree model as defined in the project settings.
:param str|unicode settings_entry_name:
:rtype: TreeItemBase|TreeBase |
def avail_locations(call=None):
'''
Return a dict of all available regions.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
ret['loc... | Return a dict of all available regions. |
def getpath(cmd, name=None, url=None, cfg="~/.jcvirc", warn="exit"):
"""
Get install locations of common binaries
First, check ~/.jcvirc file to get the full path
If not present, ask on the console and store
"""
p = which(cmd) # if in PATH, just returns it
if p:
return p
PATH =... | Get install locations of common binaries
First, check ~/.jcvirc file to get the full path
If not present, ask on the console and store |
def dpod_port_id_operation(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
dpod = ET.SubElement(config, "dpod", xmlns="urn:brocade.com:mgmt:brocade-license")
port_id = ET.SubElement(dpod, "port-id")
port_id_key = ET.SubElement(port_id, "port-id")... | Auto Generated Code |
def check_categories(lines):
'''
find out how many row and col categories are available
'''
# count the number of row categories
rcat_line = lines[0].split('\t')
# calc the number of row names and categories
num_rc = 0
found_end = False
# skip first tab
for inst_string in rcat_line[1:]:
if ins... | find out how many row and col categories are available |
def delete(self):
"""Delete the note, removing it from it's task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist.')
>>> note = task.ad... | Delete the note, removing it from it's task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> task = project.add_task('Install PyTodoist.')
>>> note = task.add_note('https://pypi.python.o... |
def get_base_kwargs(self):
"""Get base kwargs for API call."""
kwargs = {
'HostedZoneId': self.hosted_zone_id
}
if self.max_items is not None:
kwargs.update({
'MaxItems': str(self.max_items)
})
return kwargs | Get base kwargs for API call. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.