code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_container_instance_logs(access_token, subscription_id, resource_group, container_group_name,
container_name=None):
'''Get the container logs for containers in a container group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id... | Get the container logs for containers in a container group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
container_group_name (str): Name of container instance group.
... |
def construct_ingest_query(self, static_path, columns):
"""
Builds an ingest query for an HDFS TSV load.
:param static_path: The path on hdfs where the data is
:type static_path: str
:param columns: List of all the columns that are available
:type columns: list
"... | Builds an ingest query for an HDFS TSV load.
:param static_path: The path on hdfs where the data is
:type static_path: str
:param columns: List of all the columns that are available
:type columns: list |
def pstdev(data):
"""Calculates the population standard deviation."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/n # the population variance
return pvar**0.5 | Calculates the population standard deviation. |
def start(self):
'''
Start the actual proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(ProxyMinion, self).start()
try:
if check_... | Start the actual proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`. |
def _sync(self):
"""
Synchronize the cached data with the underlyind database.
Uses an internal transaction counter and compares to the checkpoint_operations
and checkpoint_timeout paramters to determine whether to persist the memory store.
In this implementation, this method w... | Synchronize the cached data with the underlyind database.
Uses an internal transaction counter and compares to the checkpoint_operations
and checkpoint_timeout paramters to determine whether to persist the memory store.
In this implementation, this method wraps calls to C{shelve.Shelf#sync}. |
def memory_objects_for_hash(self, n):
"""
Returns a set of :class:`SimMemoryObjects` that contain expressions that contain a variable with the hash
`h`.
"""
return set([self[i] for i in self.addrs_for_hash(n)]) | Returns a set of :class:`SimMemoryObjects` that contain expressions that contain a variable with the hash
`h`. |
def readme(filename, encoding='utf8'):
"""
Read the contents of a file
"""
with io.open(filename, encoding=encoding) as source:
return source.read() | Read the contents of a file |
def get_content(self, obj):
"""All content for a state's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
division = obj
# In case of house special election,
# use parent division.
if obj.level.name == Div... | All content for a state's page on an election day. |
def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert Average pooling.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionar... | Convert Average pooling.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for k... |
def simBirth(self,which_agents):
'''
Makes new consumers for the given indices. Slightly extends base method by also setting
pLvlErrNow = 1.0 for new agents, indicating that they correctly perceive their productivity.
Parameters
----------
which_agents : np.array(Bool)
... | Makes new consumers for the given indices. Slightly extends base method by also setting
pLvlErrNow = 1.0 for new agents, indicating that they correctly perceive their productivity.
Parameters
----------
which_agents : np.array(Bool)
Boolean array of size self.AgentCount ind... |
def _request(self, request_method, endpoint='', url='', data=None, params=None, use_api_key=False, omit_api_version=False):
"""Perform a http request via the specified method to an API endpoint.
:param string request_method: Request method.
:param string endpoint: Target endpoint. (Optional).
... | Perform a http request via the specified method to an API endpoint.
:param string request_method: Request method.
:param string endpoint: Target endpoint. (Optional).
:param string url: Override the endpoint and provide the full url (eg for pagination). (Optional).
:param dict params: P... |
def update(self, filter_, document, multi=False, **kwargs):
"""update method
"""
self._valide_update_document(document)
if multi:
return self.__collect.update_many(filter_, document, **kwargs)
else:
return self.__collect.update_one(filter_, document, **kwa... | update method |
def add(self, key):
"""
Add `key` as an item to this OrderedSet, then return its index.
If `key` is already in the OrderedSet, return the index it already
had.
"""
if key not in self.map:
self.map[key] = len(self.items)
self.items.append(key)
... | Add `key` as an item to this OrderedSet, then return its index.
If `key` is already in the OrderedSet, return the index it already
had. |
def overplot_lines(ax,
catlines_all_wave,
list_valid_islitlets,
rectwv_coeff,
global_integer_offset_x_pix, global_integer_offset_y_pix,
ds9_file, debugplot):
"""Overplot lines (arc/OH).
Parameters
----------
... | Overplot lines (arc/OH).
Parameters
----------
ax : matplotlib axes
Current plot axes.
catlines_all_wave : numpy array
Array with wavelengths of the lines to be overplotted.
list_valid_islitlets : list of integers
List with numbers of valid slitlets.
rectwv_coeff : RectW... |
def isObservableElement(self, elementName):
"""
Mention if an element is an observable element.
:param str ElementName: the element name to evaluate
:return: true if is an observable element, otherwise false.
:rtype: bool
"""
if not(isinstance(elementName, str)):... | Mention if an element is an observable element.
:param str ElementName: the element name to evaluate
:return: true if is an observable element, otherwise false.
:rtype: bool |
def is_admin_user(self):
"""
Checks if the user is the admin or a SiteAdmin user.
:return: Boolean
"""
user = api.user.get_current()
roles = user.getRoles()
return "LabManager" in roles or "Manager" in roles | Checks if the user is the admin or a SiteAdmin user.
:return: Boolean |
def _finish_add(self, num_bytes_to_add, num_partition_bytes_to_add):
# type: (int, int) -> None
'''
An internal method to do all of the accounting needed whenever
something is added to the ISO. This method should only be called by
public API implementations.
Parameters:... | An internal method to do all of the accounting needed whenever
something is added to the ISO. This method should only be called by
public API implementations.
Parameters:
num_bytes_to_add - The number of additional bytes to add to all
descriptors.
... |
def convert_H2OFrame_2_DMatrix(self, predictors, yresp, h2oXGBoostModel):
'''
This method requires that you import the following toolboxes: xgboost, pandas, numpy and scipy.sparse.
This method will convert an H2OFrame to a DMatrix that can be used by native XGBoost. The H2OFrame contains
... | This method requires that you import the following toolboxes: xgboost, pandas, numpy and scipy.sparse.
This method will convert an H2OFrame to a DMatrix that can be used by native XGBoost. The H2OFrame contains
numerical and enum columns alone. Note that H2O one-hot-encoding introduces a missing(NA)
... |
def list_pending_work_units(self, work_spec_name, start=0, limit=None):
"""Get a dictionary of in-progress work units for some work spec.
The dictionary is from work unit name to work unit definiton.
Units listed here should be worked on by some worker.
"""
return self.registry... | Get a dictionary of in-progress work units for some work spec.
The dictionary is from work unit name to work unit definiton.
Units listed here should be worked on by some worker. |
def complete_sum(self):
"""
Return an equivalent DNF expression that includes all prime
implicants.
"""
node = self.node.complete_sum()
if node is self.node:
return self
else:
return _expr(node) | Return an equivalent DNF expression that includes all prime
implicants. |
def _generate_destination_for_source(self, src_ase):
# type: (SyncCopy, blobxfer.models.azure.StorageEntity) ->
# blobxfer.models.azure.StorageEntity)
"""Generate entities for source path
:param SyncCopy self: this
:param blobxfer.models.azure.StorageEntity src_ase: source... | Generate entities for source path
:param SyncCopy self: this
:param blobxfer.models.azure.StorageEntity src_ase: source ase
:rtype: blobxfer.models.azure.StorageEntity
:return: destination storage entity |
def isModified(self):
"""Check if either the datastream content or profile fields have changed
and should be saved to Fedora.
:rtype: boolean
"""
# NOTE: only check content digest if locally cached content is set
# (content already pulled or new content set); otherwise t... | Check if either the datastream content or profile fields have changed
and should be saved to Fedora.
:rtype: boolean |
def set(self, id_, lineno, value='', fname=None, args=None):
""" Like the above, but issues no warning on duplicate macro
definitions.
"""
if fname is None:
if CURRENT_FILE:
fname = CURRENT_FILE[-1]
else: # If no files opened yet, use owns pro... | Like the above, but issues no warning on duplicate macro
definitions. |
def write_training_metrics(self):
"""
Write Training Metrics to CSV
"""
with open(self.path, 'w') as file:
writer = csv.writer(file)
writer.writerow(FIELD_NAMES)
for row in self.rows:
writer.writerow(row) | Write Training Metrics to CSV |
def load_config(path):
"""
Load device configuration from file path and return list with parsed lines.
:param path: Location of configuration file.
:type path: str
:rtype: list
"""
args = []
with open(path, 'r') as fp:
for line in fp.readlines():
if line.strip() and ... | Load device configuration from file path and return list with parsed lines.
:param path: Location of configuration file.
:type path: str
:rtype: list |
def decompile_pyc(bin_pyc, output=sys.stdout):
'''
decompile apython pyc or pyo binary file.
:param bin_pyc: input file objects
:param output: output file objects
'''
from turicreate.meta.asttools import python_source
bin = bin_pyc.read()
code = marshal.loads(bin[8:])... | decompile apython pyc or pyo binary file.
:param bin_pyc: input file objects
:param output: output file objects |
def memory_usage(self, index=True, deep=False):
"""
Return the memory usage of each column in bytes.
The memory usage can optionally include the contribution of
the index and elements of `object` dtype.
This value is displayed in `DataFrame.info` by default. This can be
... | Return the memory usage of each column in bytes.
The memory usage can optionally include the contribution of
the index and elements of `object` dtype.
This value is displayed in `DataFrame.info` by default. This can be
suppressed by setting ``pandas.options.display.memory_usage`` to Fa... |
def check(dependency=None, timeout=60):
"""Mark function as a check.
:param dependency: the check that this check depends on
:type dependency: function
:param timeout: maximum number of seconds the check can run
:type timeout: int
When a check depends on another, the former will only run if th... | Mark function as a check.
:param dependency: the check that this check depends on
:type dependency: function
:param timeout: maximum number of seconds the check can run
:type timeout: int
When a check depends on another, the former will only run if the latter passes.
Additionally, the dependen... |
def add_params(endpoint, params):
"""
Combine query endpoint and params.
Example::
>>> add_params("https://www.google.com/search", {"q": "iphone"})
https://www.google.com/search?q=iphone
"""
p = PreparedRequest()
p.prepare(url=endpoint, params=params)
if PY2: # pragma: no ... | Combine query endpoint and params.
Example::
>>> add_params("https://www.google.com/search", {"q": "iphone"})
https://www.google.com/search?q=iphone |
def ping(self):
"""sends a NOP packet and waits response; returns None"""
ret, data = self.sendmess(MSG_NOP, bytes())
if data or ret > 0:
raise ProtocolError('invalid reply to ping message')
if ret < 0:
raise OwnetError(-ret, self.errmess[-ret]) | sends a NOP packet and waits response; returns None |
def get_git_isolation():
"""Get Git isolation from the current context."""
ctx = click.get_current_context(silent=True)
if ctx and GIT_ISOLATION in ctx.meta:
return ctx.meta[GIT_ISOLATION] | Get Git isolation from the current context. |
def getPDFstr(s):
""" Return a PDF string depending on its coding.
Notes:
If only ascii then "(original)" is returned, else if only 8 bit chars
then "(original)" with interspersed octal strings \nnn is returned,
else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the
... | Return a PDF string depending on its coding.
Notes:
If only ascii then "(original)" is returned, else if only 8 bit chars
then "(original)" with interspersed octal strings \nnn is returned,
else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the
UTF-16BE encoding of ... |
def rm_file_or_dir(path, ignore_errors=True):
"""
Helper function to clean a certain filepath
Parameters
----------
path
Returns
-------
"""
if os.path.exists(path):
if os.path.isdir(path):
if os.path.islink(path):
os.unlink(path)
el... | Helper function to clean a certain filepath
Parameters
----------
path
Returns
------- |
def check_policies(self, account, account_policies, aws_policies):
"""Iterate through the policies of a specific account and create or update the policy if its missing or
does not match the policy documents from Git. Returns a dict of all the policies added to the account
(does not include updat... | Iterate through the policies of a specific account and create or update the policy if its missing or
does not match the policy documents from Git. Returns a dict of all the policies added to the account
(does not include updated policies)
Args:
account (:obj:`Account`): Account to c... |
def pypi_search(self):
"""
Search PyPI by metadata keyword
e.g. yolk -S name=yolk AND license=GPL
@param spec: Cheese Shop search spec
@type spec: list of strings
spec examples:
["name=yolk"]
["license=GPL"]
["name=yolk", "AND", "license=GP... | Search PyPI by metadata keyword
e.g. yolk -S name=yolk AND license=GPL
@param spec: Cheese Shop search spec
@type spec: list of strings
spec examples:
["name=yolk"]
["license=GPL"]
["name=yolk", "AND", "license=GPL"]
@returns: 0 on success or 1 if... |
def AddWarning(self, warning):
"""Adds an warning.
Args:
warning (ExtractionWarning): an extraction warning.
Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed.
"""
self._RaiseIfNotWritable()
self._storage_file.AddWarning(warning)
... | Adds an warning.
Args:
warning (ExtractionWarning): an extraction warning.
Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed. |
def get_user_groups(self, user_name):
"""Get a list of groups associated to a user.
:param user_name: name of user to list groups
:returns: list of groups
:raises: HTTPResponseError in case an HTTP error status was returned
"""
res = self._make_ocs_request(
... | Get a list of groups associated to a user.
:param user_name: name of user to list groups
:returns: list of groups
:raises: HTTPResponseError in case an HTTP error status was returned |
def match(self, s=''):
"""return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options.
"""
match = s.lower()
res = {}
for k in sorted(self)... | return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options. |
def for_entity(obj, check_support_attachments=False):
"""Return attachments on an entity."""
if check_support_attachments and not supports_attachments(obj):
return []
return getattr(obj, ATTRIBUTE) | Return attachments on an entity. |
def create(conversion_finder, parsed_att: Any, attribute_type: Type[Any], errors: Dict[Type, Exception] = None):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parsed_at... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parsed_att:
:param attribute_type:
:param conversion_finder:
:return: |
def get_vcsrc(self):
"""
Returns in-memory created module pointing at user's configuration
and extra code/commands. By default tries to create module from
:setting:`VCSRC_PATH`.
"""
try:
vimrc = create_module('vcsrc', settings.VCSRC_PATH)
except IOErro... | Returns in-memory created module pointing at user's configuration
and extra code/commands. By default tries to create module from
:setting:`VCSRC_PATH`. |
def timings(reps,func,*args,**kw):
"""timings(reps,func,*args,**kw) -> (t_total,t_per_call)
Execute a function reps times, return a tuple with the elapsed total CPU
time in seconds and the time per call. These are just the first two values
in timings_out()."""
return timings_out(reps,func,*args,**... | timings(reps,func,*args,**kw) -> (t_total,t_per_call)
Execute a function reps times, return a tuple with the elapsed total CPU
time in seconds and the time per call. These are just the first two values
in timings_out(). |
def _local_list_files(self, args):
'''
List files for a package file
'''
if len(args) < 2:
raise SPMInvocationError('A package filename must be specified')
pkg_file = args[1]
if not os.path.exists(pkg_file):
raise SPMPackageError('Package file {0}... | List files for a package file |
def create(self, metadata, publisher_account,
service_descriptors=None, providers=None,
use_secret_store=True):
"""
Register an asset in both the keeper's DIDRegistry (on-chain) and in the Metadata store (
Aquarius).
:param metadata: dict conforming to the ... | Register an asset in both the keeper's DIDRegistry (on-chain) and in the Metadata store (
Aquarius).
:param metadata: dict conforming to the Metadata accepted by Ocean Protocol.
:param publisher_account: Account of the publisher registering this asset
:param service_descriptors: list of... |
def main():
"""
NAME
core_depthplot.py
DESCRIPTION
plots various measurements versus core_depth or age. plots data flagged as 'FS-SS-C' as discrete samples.
SYNTAX
core_depthplot.py [command line options]
# or, for Anaconda users:
core_depthplot_anaconda [comma... | NAME
core_depthplot.py
DESCRIPTION
plots various measurements versus core_depth or age. plots data flagged as 'FS-SS-C' as discrete samples.
SYNTAX
core_depthplot.py [command line options]
# or, for Anaconda users:
core_depthplot_anaconda [command line options]
OP... |
def load_ns_sequence(eos_name):
"""
Load the data of an NS non-rotating equilibrium sequence
generated using the equation of state (EOS) chosen by the
user. [Only the 2H 2-piecewise polytropic EOS is currently
supported. This yields NSs with large radiss (15-16km).]
Parameters
-----------... | Load the data of an NS non-rotating equilibrium sequence
generated using the equation of state (EOS) chosen by the
user. [Only the 2H 2-piecewise polytropic EOS is currently
supported. This yields NSs with large radiss (15-16km).]
Parameters
-----------
eos_name: string
NS equation of... |
def _router_address(self, data):
"""only for IPv6 addresses"""
args = data.split()[1:]
try:
self._relay_attrs['ip_v6'].extend(args)
except KeyError:
self._relay_attrs['ip_v6'] = list(args) | only for IPv6 addresses |
def check_managed_changes(
name,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
template,
context,
defaults,
saltenv,
contents=None,
skip_verify=False,
keep_mode=False,
seuse... | Return a dictionary of what changes need to be made for a file
.. versionchanged:: Neon
selinux attributes added
CLI Example:
.. code-block:: bash
salt '*' file.check_managed_changes /etc/httpd/conf.d/httpd.conf salt://http/httpd.conf '{hash_type: 'md5', 'hsum': <md5sum>}' root, root, '... |
def beatExtraction(st_features, win_len, PLOT=False):
"""
This function extracts an estimate of the beat rate for a musical signal.
ARGUMENTS:
- st_features: a numpy array (n_feats x numOfShortTermWindows)
- win_len: window size in seconds
RETURNS:
- BPM: estimates o... | This function extracts an estimate of the beat rate for a musical signal.
ARGUMENTS:
- st_features: a numpy array (n_feats x numOfShortTermWindows)
- win_len: window size in seconds
RETURNS:
- BPM: estimates of beats per minute
- Ratio: a confidence measure |
def _get_code_dir(self, code_path):
"""
Method to get a path to a directory where the Lambda function code is available. This directory will
be mounted directly inside the Docker container.
This method handles a few different cases for ``code_path``:
- ``code_path``is a exis... | Method to get a path to a directory where the Lambda function code is available. This directory will
be mounted directly inside the Docker container.
This method handles a few different cases for ``code_path``:
- ``code_path``is a existent zip/jar file: Unzip in a temp directory and return ... |
def p_variable(self, p):
"""variable : LEFT_BRACE LITERAL EQUALS unbound_segments RIGHT_BRACE
| LEFT_BRACE LITERAL RIGHT_BRACE"""
p[0] = [_Segment(_BINDING, p[2])]
if len(p) > 4:
p[0].extend(p[4])
else:
p[0].append(_Segment(_TERMINAL, '*'))
... | variable : LEFT_BRACE LITERAL EQUALS unbound_segments RIGHT_BRACE
| LEFT_BRACE LITERAL RIGHT_BRACE |
def _get_blob(self):
"""read blob on access only because get_object is slow"""
if not self.__blob:
self.__blob = self.repo.get_object(self.id)
return self.__blob | read blob on access only because get_object is slow |
def _kl_independent(a, b, name="kl_independent"):
"""Batched KL divergence `KL(a || b)` for Independent distributions.
We can leverage the fact that
```
KL(Independent(a) || Independent(b)) = sum(KL(a || b))
```
where the sum is over the `reinterpreted_batch_ndims`.
Args:
a: Instance of `Independent... | Batched KL divergence `KL(a || b)` for Independent distributions.
We can leverage the fact that
```
KL(Independent(a) || Independent(b)) = sum(KL(a || b))
```
where the sum is over the `reinterpreted_batch_ndims`.
Args:
a: Instance of `Independent`.
b: Instance of `Independent`.
name: (optiona... |
def proxies(self, url):
"""
Get the transport proxy configuration
:param url: string
:return: Proxy configuration dictionary
:rtype: Dictionary
"""
netloc = urllib.parse.urlparse(url).netloc
proxies = {}
if settings.PROXIES and settings.PROXIES.ge... | Get the transport proxy configuration
:param url: string
:return: Proxy configuration dictionary
:rtype: Dictionary |
def partition_dumps(self):
"""Yeild a set of manifest object that parition the dumps.
Simply adds resources/files to a manifest until their are either the
the correct number of files or the size limit is exceeded, then yields
that manifest.
"""
manifest = self.manifest_c... | Yeild a set of manifest object that parition the dumps.
Simply adds resources/files to a manifest until their are either the
the correct number of files or the size limit is exceeded, then yields
that manifest. |
def model_post_save(sender, instance, created=False, **kwargs):
"""Signal emitted after any model is saved via Django ORM.
:param sender: Model class that was saved
:param instance: The actual instance that was saved
:param created: True if a new row was created
"""
if sender._meta.app_label =... | Signal emitted after any model is saved via Django ORM.
:param sender: Model class that was saved
:param instance: The actual instance that was saved
:param created: True if a new row was created |
async def take_control(self, password):
"""Take control of QTM.
:param password: Password as entered in QTM.
"""
cmd = "takecontrol %s" % password
return await asyncio.wait_for(
self._protocol.send_command(cmd), timeout=self._timeout
) | Take control of QTM.
:param password: Password as entered in QTM. |
def findGlyph(self, glyphName):
"""
Returns a ``list`` of the group or groups associated with
**glyphName**.
**glyphName** will be an :ref:`type-string`. If no group is found
to contain **glyphName** an empty ``list`` will be returned. ::
>>> font.groups.findGlyph("A... | Returns a ``list`` of the group or groups associated with
**glyphName**.
**glyphName** will be an :ref:`type-string`. If no group is found
to contain **glyphName** an empty ``list`` will be returned. ::
>>> font.groups.findGlyph("A")
["A_accented"] |
def xy_spectrail_arc_intersections(self, slitlet2d=None):
"""Compute intersection points of spectrum trails with arc lines.
The member list_arc_lines is updated with new keyword:keyval
values for each arc line.
Parameters
----------
slitlet2d : numpy array
S... | Compute intersection points of spectrum trails with arc lines.
The member list_arc_lines is updated with new keyword:keyval
values for each arc line.
Parameters
----------
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
... |
def css_property(self) -> str:
"""Generate a random snippet of CSS that assigns value to a property.
:return: CSS property.
:Examples:
'background-color: #f4d3a1'
"""
prop = self.random.choice(list(CSS_PROPERTIES.keys()))
val = CSS_PROPERTIES[prop]
... | Generate a random snippet of CSS that assigns value to a property.
:return: CSS property.
:Examples:
'background-color: #f4d3a1' |
def __driver_stub(self, text, state):
"""Display help messages or invoke the proper completer.
The interface of helper methods and completer methods are documented in
the helper() decorator method and the completer() decorator method,
respectively.
Arguments:
text: ... | Display help messages or invoke the proper completer.
The interface of helper methods and completer methods are documented in
the helper() decorator method and the completer() decorator method,
respectively.
Arguments:
text: A string, that is the current completion scope.
... |
def get_field_value_from_context(field_name, context_list):
"""
Helper to get field value from string path.
String '<context>' is used to go up on context stack. It just
can be used at the beginning of path: <context>.<context>.field_name_1
On the other hand, '<root>' is used to start lookup from fi... | Helper to get field value from string path.
String '<context>' is used to go up on context stack. It just
can be used at the beginning of path: <context>.<context>.field_name_1
On the other hand, '<root>' is used to start lookup from first item on context. |
def fillna_value(self, df, left, **concat_args):
"""
This method gives subclasses the opportunity to define how
join() fills missing values. Return value must be compatible with
DataFrame.fillna() value argument. Examples:
- return 0: replace missing values with zero
... | This method gives subclasses the opportunity to define how
join() fills missing values. Return value must be compatible with
DataFrame.fillna() value argument. Examples:
- return 0: replace missing values with zero
- return df.mean(): replace missing values with column mean
... |
async def get_connection(self, container):
'''
Get an exclusive connection, useful for blocked commands and transactions.
You must call release or shutdown (not recommanded) to return the connection after use.
:param container: routine container
:return... | Get an exclusive connection, useful for blocked commands and transactions.
You must call release or shutdown (not recommanded) to return the connection after use.
:param container: routine container
:returns: RedisClientBase object, with some commands same as RedisClie... |
def func_on_enter(func):
"""
Register the `func` as a callback reacting only to ENTER.
Note:
This function doesn't bind the key to the element, just creates sort of
filter, which ignores all other events.
"""
def function_after_enter_pressed(ev):
ev.stopPropagation()
... | Register the `func` as a callback reacting only to ENTER.
Note:
This function doesn't bind the key to the element, just creates sort of
filter, which ignores all other events. |
def remove_entry(self, offset, length):
# type: (int, int) -> None
'''
Given an offset and length, find and remove the entry in this block
that corresponds.
Parameters:
offset - The offset of the entry to look for.
length - The length of the entry to look for.
... | Given an offset and length, find and remove the entry in this block
that corresponds.
Parameters:
offset - The offset of the entry to look for.
length - The length of the entry to look for.
Returns:
Nothing. |
def check(self, dsm, independence_factor=5, **kwargs):
"""
Check least common mechanism.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
independence_factor (int): if the maximum dependencies for one
module is inferior or equal to the DSM si... | Check least common mechanism.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
independence_factor (int): if the maximum dependencies for one
module is inferior or equal to the DSM size divided by the
independence factor, then this criterion ... |
def modifyModlist(
old_entry: dict, new_entry: dict, ignore_attr_types: Optional[List[str]] = None,
ignore_oldexistent: bool = False) -> Dict[str, Tuple[str, List[bytes]]]:
"""
Build differential modify list for calling LDAPObject.modify()/modify_s()
:param old_entry:
Dictionary hol... | Build differential modify list for calling LDAPObject.modify()/modify_s()
:param old_entry:
Dictionary holding the old entry
:param new_entry:
Dictionary holding what the new entry should be
:param ignore_attr_types:
List of attribute type names to be ignored completely
:param i... |
def get_urlhash(self, url, fmt):
"""Returns the hash of the file of an internal url
"""
with self.open(os.path.basename(url)) as f:
return {'url': fmt(url), 'sha256': filehash(f, 'sha256')} | Returns the hash of the file of an internal url |
def app_authorize(self, account=None, flush=True, bailout=False):
"""
Like app_authenticate(), but uses the authorization password
of the account.
For the difference between authentication and authorization
please google for AAA.
:type account: Account
:param a... | Like app_authenticate(), but uses the authorization password
of the account.
For the difference between authentication and authorization
please google for AAA.
:type account: Account
:param account: An account object, like login().
:type flush: bool
:param flu... |
def add_months_to_date(months, date):
"""Add a number of months to a date"""
month = date.month
new_month = month + months
years = 0
while new_month < 1:
new_month += 12
years -= 1
while new_month > 12:
new_month -= 12
years += 1
# month = timestamp.month
... | Add a number of months to a date |
def url_to_filename(url: str, etag: str = None) -> str:
"""
Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period.
"""
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdiges... | Convert `url` into a hashed filename in a repeatable way.
If `etag` is specified, append its hash to the url's, delimited
by a period. |
def deploy(self, driver, location_id=config.DEFAULT_LOCATION_ID,
size=config.DEFAULT_SIZE):
"""Use driver to deploy node, with optional ability to specify
location id and size id.
First, obtain location object from driver. Next, get the
size. Then, get the image. Final... | Use driver to deploy node, with optional ability to specify
location id and size id.
First, obtain location object from driver. Next, get the
size. Then, get the image. Finally, deploy node, and return
NodeProxy. |
def event_stream(self, filters=None):
"""
:param filters: filters to apply on messages. See docker api.
:return: an iterable that contains events from docker. See the docker api for content.
"""
if filters is None:
filters = {}
return self._docker.events(decod... | :param filters: filters to apply on messages. See docker api.
:return: an iterable that contains events from docker. See the docker api for content. |
def compute():
"""Compute the polynomial."""
if what == "numpy":
y = eval(expr)
else:
y = ne.evaluate(expr)
return len(y) | Compute the polynomial. |
def create_diff_storage(self, target, variant):
"""Starts creating an empty differencing storage unit based on this
medium in the format and at the location defined by the @a target
argument.
The target medium must be in :py:attr:`MediumState.not_created`
state (i.e. mu... | Starts creating an empty differencing storage unit based on this
medium in the format and at the location defined by the @a target
argument.
The target medium must be in :py:attr:`MediumState.not_created`
state (i.e. must not have an existing storage unit). Upon successful
... |
def get_headers(self, container):
"""
Return the headers for the specified container.
"""
uri = "/%s" % utils.get_name(container)
resp, resp_body = self.api.method_head(uri)
return resp.headers | Return the headers for the specified container. |
def parse_object(lexer: Lexer, is_const: bool) -> ObjectValueNode:
"""ObjectValue[Const]"""
start = lexer.token
item = cast(Callable[[Lexer], Node], partial(parse_object_field, is_const=is_const))
return ObjectValueNode(
fields=any_nodes(lexer, TokenKind.BRACE_L, item, TokenKind.BRACE_R),
... | ObjectValue[Const] |
def initialize_socket(self):
"""initialize the socket"""
try:
_LOGGER.debug("Trying to open socket.")
self._socket = socket.socket(
socket.AF_INET, # IPv4
socket.SOCK_DGRAM # UDP
)
self._socket.bind(('', self._udp_port... | initialize the socket |
def ListTimeZones(self):
"""Lists the timezones."""
max_length = 0
for timezone_name in pytz.all_timezones:
if len(timezone_name) > max_length:
max_length = len(timezone_name)
utc_date_time = datetime.datetime.utcnow()
table_view = views.ViewsFactory.GetTableView(
self._views... | Lists the timezones. |
def nonNegativeDerivative(requestContext, seriesList, maxValue=None):
"""
Same as the derivative function above, but ignores datapoints that trend
down. Useful for counters that increase for a long time, then wrap or
reset. (Such as if a network interface is destroyed and recreated by
unloading and ... | Same as the derivative function above, but ignores datapoints that trend
down. Useful for counters that increase for a long time, then wrap or
reset. (Such as if a network interface is destroyed and recreated by
unloading and re-loading a kernel module, common with USB / WiFi cards.
Example::
... |
def shuffle(self, x, random=None):
"""x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""
if random is None:
random = self.... | x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random. |
def database_names(self, session=None):
"""**DEPRECATED**: Get a list of the names of all databases on the
connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.7
Deprecated. Use :... | **DEPRECATED**: Get a list of the names of all databases on the
connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.7
Deprecated. Use :meth:`list_database_names` instead.
.. ver... |
def db_to_specifier(db_string):
"""
Return the database specifier for a database string.
This accepts a database name or URL, and returns a database specifier in the
format accepted by ``specifier_to_db``. It is recommended that you consult
the documentation for that function for an explanation... | Return the database specifier for a database string.
This accepts a database name or URL, and returns a database specifier in the
format accepted by ``specifier_to_db``. It is recommended that you consult
the documentation for that function for an explanation of the format. |
def unitigs(args):
"""
%prog unitigs best.edges
Reads Celera Assembler's "best.edges" and extract all unitigs.
"""
p = OptionParser(unitigs.__doc__)
p.add_option("--maxerr", default=2, type="int", help="Maximum error rate")
opts, args = p.parse_args(args)
if len(args) != 1:
sys... | %prog unitigs best.edges
Reads Celera Assembler's "best.edges" and extract all unitigs. |
def getAccessURL(self, CorpNum, UserID):
""" νλΉ λ‘κ·ΈμΈ URL
args
CorpNum : νμ μ¬μ
μλ²νΈ
UserID : νμ νλΉμμ΄λ
return
30μ΄ λ³΄μ ν ν°μ ν¬ν¨ν url
raise
PopbillException
"""
result = self._httpget('/?TG=LOGIN', CorpNum... | νλΉ λ‘κ·ΈμΈ URL
args
CorpNum : νμ μ¬μ
μλ²νΈ
UserID : νμ νλΉμμ΄λ
return
30μ΄ λ³΄μ ν ν°μ ν¬ν¨ν url
raise
PopbillException |
def compare_packages(rpm_str_a, rpm_str_b, arch_provided=True):
"""Compare two RPM strings to determine which is newer
Parses version information out of RPM package strings of the form
returned by the ``rpm -q`` command and compares their versions to
determine which is newer. Provided strings *do not* ... | Compare two RPM strings to determine which is newer
Parses version information out of RPM package strings of the form
returned by the ``rpm -q`` command and compares their versions to
determine which is newer. Provided strings *do not* require an
architecture at the end, although if providing strings w... |
def normalize_pts(pts, ymax, scaler=2):
"""
scales all coordinates and flip y axis due to different
origin coordinates (top left vs. bottom left)
"""
return [(x * scaler, ymax - (y * scaler)) for x, y in pts] | scales all coordinates and flip y axis due to different
origin coordinates (top left vs. bottom left) |
def find(self, name, required):
"""
Finds all matching dependencies by their name.
:param name: the dependency name to locate.
:param required: true to raise an exception when no dependencies are found.
:return: a list of found dependencies
"""
if name == None:... | Finds all matching dependencies by their name.
:param name: the dependency name to locate.
:param required: true to raise an exception when no dependencies are found.
:return: a list of found dependencies |
def create_variable(self, varname, vtype=None):
"""Create a tk variable.
If the variable was created previously return that instance.
"""
var_types = ('string', 'int', 'boolean', 'double')
vname = varname
var = None
type_from_name = 'string' # default type
... | Create a tk variable.
If the variable was created previously return that instance. |
def subkeys(self, path):
"""
A generalized form that can return multiple subkeys.
"""
for _ in subpaths_for_path_range(path, hardening_chars="'pH"):
yield self.subkey_for_path(_) | A generalized form that can return multiple subkeys. |
def __deftype_impls( # pylint: disable=too-many-branches
ctx: ParserContext, form: ISeq
) -> Tuple[List[DefTypeBase], List[Method]]:
"""Roll up deftype* declared bases and method implementations."""
current_interface_sym: Optional[sym.Symbol] = None
current_interface: Optional[DefTypeBase] = None
i... | Roll up deftype* declared bases and method implementations. |
def raw_broadcast(self, destination, message, **kwargs):
"""Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param *... | Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
... |
def get_metric_names(self, agent_id, re=None, limit=5000):
"""
Requires: application ID
Optional: Regex to filter metric names, limit of results
Returns: A dictionary,
key: metric name,
value: list of fields available for a given metric
Me... | Requires: application ID
Optional: Regex to filter metric names, limit of results
Returns: A dictionary,
key: metric name,
value: list of fields available for a given metric
Method: Get
Restrictions: Rate limit to 1x per minute
Errors: 403... |
def numberofnetworks(self):
"""The number of distinct networks defined by the|Node| and
|Element| objects currently handled by the |HydPy| object."""
sels1 = selectiontools.Selections()
sels2 = selectiontools.Selections()
complete = selectiontools.Selection('complete',
... | The number of distinct networks defined by the|Node| and
|Element| objects currently handled by the |HydPy| object. |
def lock(self, name, ttl=None, lock_id=None):
"""
Create a named :py:class:`Lock` instance. The lock implements
an API similar to the standard library's ``threading.Lock``,
and can also be used as a context manager or decorator.
:param str name: The name of the lock.
:pa... | Create a named :py:class:`Lock` instance. The lock implements
an API similar to the standard library's ``threading.Lock``,
and can also be used as a context manager or decorator.
:param str name: The name of the lock.
:param int ttl: The time-to-live for the lock in milliseconds
... |
def get(self, request, bot_id, handler_id, id, format=None):
"""
Get url parameter by id
---
serializer: AbsParamSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(UrlParameterDetail, self).get(request, b... | Get url parameter by id
---
serializer: AbsParamSerializer
responseMessages:
- code: 401
message: Not authenticated |
def rule_command_cmdlist_interface_u_interface_fe_leaf_interface_fortygigabitethernet_leaf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa")
index_key = ET.SubElement(rule, "ind... | Auto Generated Code |
def get_remaining_time(program):
'''
Get the remaining time in seconds of a program that is currently on.
'''
now = datetime.datetime.now()
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could no... | Get the remaining time in seconds of a program that is currently on. |
def urlopen(self, method, url, redirect=True, **kw):
"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
u = parse_url(url)
if u.scheme == "http":
# For proxied HTTPS requests, httplib sets the necessary headers
# on the CONNECT to the proxy. For HTTP, we'... | Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.