code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def adjust_prior(self, index, prior):
""" Adjusts priors for the latent variables
Parameters
----------
index : int or list[int]
Which latent variable index/indices to be altered
prior : Prior object
Which prior distribution? E.g. Normal(0,1)
Re... | Adjusts priors for the latent variables
Parameters
----------
index : int or list[int]
Which latent variable index/indices to be altered
prior : Prior object
Which prior distribution? E.g. Normal(0,1)
Returns
----------
None (changes pri... |
def resize_volume(self, volumeObj, sizeInGb, bsize=1000):
"""
Resize a volume to new GB size, must be larger than original.
:param volumeObj: ScaleIO Volume Object
:param sizeInGb: New size in GB (have to be larger than original)
:param bsize: 1000
:return: POST request r... | Resize a volume to new GB size, must be larger than original.
:param volumeObj: ScaleIO Volume Object
:param sizeInGb: New size in GB (have to be larger than original)
:param bsize: 1000
:return: POST request response
:rtype: Requests POST response object |
def run_on(*, event: str):
"""A decorator to store and link a callback to an event."""
def decorator(callback):
@functools.wraps(callback)
def decorator_wrapper():
RTMClient.on(event=event, callback=callback)
return decorator_wrapper()
retur... | A decorator to store and link a callback to an event. |
def _get_parser(extra_args):
"""Return ArgumentParser with any extra arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
dirs = appdirs.AppDirs('hangups', 'hangups')
default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.tx... | Return ArgumentParser with any extra arguments. |
def get_codemirror_parameters(self, name):
"""
Return CodeMirror parameters for given configuration name.
This is a reduced configuration from internal parameters.
Arguments:
name (string): Config name from available ones in
``settings.CODEMIRROR_SETTINGS``.... | Return CodeMirror parameters for given configuration name.
This is a reduced configuration from internal parameters.
Arguments:
name (string): Config name from available ones in
``settings.CODEMIRROR_SETTINGS``.
Returns:
dict: Parameters. |
def show_driver(devname):
'''
Queries the specified network device for associated driver information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_driver <devname>
'''
try:
module = ethtool.get_module(devname)
except IOError:
log.error('Driver informatio... | Queries the specified network device for associated driver information
CLI Example:
.. code-block:: bash
salt '*' ethtool.show_driver <devname> |
def unorm(data, ord=None, axis=None, keepdims=False):
"""Matrix or vector norm that preserves units
This is a wrapper around np.linalg.norm that preserves units. See
the documentation for that function for descriptions of the keyword
arguments.
Examples
--------
>>> from unyt import km
... | Matrix or vector norm that preserves units
This is a wrapper around np.linalg.norm that preserves units. See
the documentation for that function for descriptions of the keyword
arguments.
Examples
--------
>>> from unyt import km
>>> data = [1, 2, 3]*km
>>> print(unorm(data))
3.741... |
def prepare_adiabatic_limit(slh, k=None):
"""Prepare the adiabatic elimination on an SLH object
Args:
slh: The SLH object to take the limit for
k: The scaling parameter $k \rightarrow \infty$. The default is a
positive symbol 'k'
Returns:
tuple: The objects ``Y, A, B, F... | Prepare the adiabatic elimination on an SLH object
Args:
slh: The SLH object to take the limit for
k: The scaling parameter $k \rightarrow \infty$. The default is a
positive symbol 'k'
Returns:
tuple: The objects ``Y, A, B, F, G, N``
necessary to compute the limitin... |
def request(self, url, method = u"get", data = None, headers = None, **kwargs):
"""
public method for doing the live request
"""
url, method, data, headers, kwargs = self._pre_request(url,
method=method,
... | public method for doing the live request |
def _parse_typed_parameter_typed_value(values):
'''
Creates Arguments in a TypedParametervalue.
'''
type_, value = _expand_one_key_dictionary(values)
_current_parameter_value.type = type_
if _is_simple_type(value):
arg = Argument(value)
_current_parameter_value.add_argument(arg)... | Creates Arguments in a TypedParametervalue. |
def msg(cls, error=None, debug=True, trace=True):
"""
prints the error message
:param error: the error message
:param debug: only prints it if debug is set to true
:param trace: if true prints the trace
:return:
"""
if debug and error is not None:
... | prints the error message
:param error: the error message
:param debug: only prints it if debug is set to true
:param trace: if true prints the trace
:return: |
def src2ast(src: str) -> Expression:
"""Return ast.Expression created from source code given in `src`."""
try:
return ast.parse(src, mode='eval')
except SyntaxError:
raise ValueError("Not a valid expression.") from None | Return ast.Expression created from source code given in `src`. |
def take_snapshot(obj, store=True, **kw):
"""Takes a snapshot of the passed in object
:param obj: Content object
:returns: New snapshot
"""
logger.debug("📷 Take new snapshot for {}".format(repr(obj)))
# get the object data
snapshot = get_object_data(obj)
# get the metadata
metada... | Takes a snapshot of the passed in object
:param obj: Content object
:returns: New snapshot |
async def _set_rev_reg(self, rr_id: str, rr_size: int) -> None:
"""
Move precomputed revocation registry data from hopper into place within tails directory.
:param rr_id: revocation registry identifier
:param rr_size: revocation registry size, in case creation required
"""
... | Move precomputed revocation registry data from hopper into place within tails directory.
:param rr_id: revocation registry identifier
:param rr_size: revocation registry size, in case creation required |
def do_state_tomography(preparation_program, nsamples, cxn, qubits=None, use_run=False):
"""
Method to perform both a QPU and QVM state tomography, and use the latter as
as reference to calculate the fidelity of the former.
:param Program preparation_program: Program to execute.
:param int nsamples... | Method to perform both a QPU and QVM state tomography, and use the latter as
as reference to calculate the fidelity of the former.
:param Program preparation_program: Program to execute.
:param int nsamples: Number of samples to take for the program.
:param QVMConnection|QPUConnection cxn: Connection o... |
def fix_chrome_mac_platform(platform):
"""
Chrome on Mac OS adds minor version number and uses underscores instead
of dots. E.g. platform for Firefox will be: 'Intel Mac OS X 10.11'
but for Chrome it will be 'Intel Mac OS X 10_11_6'.
:param platform: - string like "Macintosh; Intel Mac OS X 10.8"
... | Chrome on Mac OS adds minor version number and uses underscores instead
of dots. E.g. platform for Firefox will be: 'Intel Mac OS X 10.11'
but for Chrome it will be 'Intel Mac OS X 10_11_6'.
:param platform: - string like "Macintosh; Intel Mac OS X 10.8"
:return: platform with version number including ... |
def sub_template(template,template_tag,substitution):
'''make a substitution for a template_tag in a template
'''
template = template.replace(template_tag,substitution)
return template | make a substitution for a template_tag in a template |
def BuildCampaignOperations(batch_job_helper,
budget_operations, number_of_campaigns=1):
"""Builds the operations needed to create a new Campaign.
Note: When the Campaigns are created, they will have a different Id than those
generated here as a temporary Id. This is just used to iden... | Builds the operations needed to create a new Campaign.
Note: When the Campaigns are created, they will have a different Id than those
generated here as a temporary Id. This is just used to identify them in the
BatchJobService.
Args:
batch_job_helper: a BatchJobHelper instance.
budget_operations: a lis... |
def get_interface_detail_output_interface_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
... | Auto Generated Code |
def expand_path(path):
"""Expands directories and globs in given path."""
paths = []
path = os.path.expanduser(path)
path = os.path.expandvars(path)
if os.path.isdir(path):
for (dir, dirs, files) in os.walk(path):
for file in files:
paths.append(os.path.join(di... | Expands directories and globs in given path. |
def render(self, *args, **kwargs):
'''
Creates a <title> tag if not present and renders the DOCTYPE and tag tree.
'''
r = []
#Validates the tag tree and adds the doctype if one was set
if self.doctype:
r.append(self.doctype)
r.append('\n')
r.append(super(document, self).render(*... | Creates a <title> tag if not present and renders the DOCTYPE and tag tree. |
def callback(self, provider):
"""
Handles 3rd party callback and processes it's data
"""
provider = self.get_provider(provider)
try:
return provider.authorized_handler(self.login)(provider=provider)
except OAuthException as ex:
logging.error("Data:... | Handles 3rd party callback and processes it's data |
def get(self, sid):
"""
Constructs a SigningKeyContext
:param sid: The sid
:returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext
:rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext
"""
return SigningKeyContext(self._version, accou... | Constructs a SigningKeyContext
:param sid: The sid
:returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext
:rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext |
def extract_concepts(self, sentences=None, ids=None,
composite_phrase=4, filename=None,
file_format='sldi', allow_acronym_variants=False,
word_sense_disambiguation=False, allow_large_n=False,
strict_model=False, relaxed_... | extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMap.
Supported Options:
Composite Phrase -Q
Word Sense Disambiguation -y
use strict model -A
use rela... |
def update_data(self):
"""This is a method that will be called every time a packet is opened
from the roaster."""
time_elapsed = datetime.datetime.now() - self.start_time
crntTemp = self.roaster.current_temp
targetTemp = self.roaster.target_temp
heaterLevel = self.roaster... | This is a method that will be called every time a packet is opened
from the roaster. |
def _as_published_topic(self):
"""This stream as a PublishedTopic if it is published otherwise None
"""
oop = self.get_operator_output_port()
if not hasattr(oop, 'export'):
return
export = oop.export
if export['type'] != 'properties':
return
... | This stream as a PublishedTopic if it is published otherwise None |
def _vmomentsurfaceIntegrand(vz,vR,vT,R,z,df,sigmaR1,gamma,sigmaz1,n,m,o): #pragma: no cover because this is too slow; a warning is shown
"""Internal function that is the integrand for the vmomentsurface mass integration"""
return vR**n*vT**m*vz**o*df(R,vR*sigmaR1,vT*sigmaR1*gamma,z,vz*sigmaz1,
... | Internal function that is the integrand for the vmomentsurface mass integration |
def main():
"""Measure capnp serialization performance of Random
"""
r = Random(42)
# Measure serialization
startSerializationTime = time.time()
for i in xrange(_SERIALIZATION_LOOPS):
# NOTE pycapnp's builder.from_dict (used in nupic.bindings) leaks
# memory if called on the same builder more than... | Measure capnp serialization performance of Random |
def delete(queue, items):
'''
Delete an item or items from a queue
'''
with _conn(commit=True) as cur:
if isinstance(items, dict):
cmd = str("""DELETE FROM {0} WHERE data = '{1}'""").format( # future lint: disable=blacklisted-function
queue,
salt.util... | Delete an item or items from a queue |
def load_config():
"""Load configuration file containing API KEY and other settings.
:rtype: str
"""
configfile = get_configfile()
if not os.path.exists(configfile):
data = {
'apikey': 'GET KEY AT: https://www.filemail.com/apidoc/ApiKey.aspx'
}
save_config... | Load configuration file containing API KEY and other settings.
:rtype: str |
def insertFromMimeData(self, source):
"""
Inserts the information from the inputed source.
:param source | <QMimeData>
"""
lines = projex.text.nativestring(source.text()).splitlines()
for i in range(1, len(lines)):
if not lines[i].startsw... | Inserts the information from the inputed source.
:param source | <QMimeData> |
def _get_mapping_for_table(self, table):
""" Returns the first mapping for a table name """
for mapping in self.mappings.values():
if mapping["table"] == table:
return mapping | Returns the first mapping for a table name |
def __focus(self, item):
"""Called when focus item has changed"""
cols = self.__get_display_columns()
for col in cols:
self.__event_info =(col,item)
self.event_generate('<<TreeviewInplaceEdit>>')
if col in self._inplace_widgets:
w = self._inpla... | Called when focus item has changed |
def print_(*objects, **kwargs):
"""print_(*objects, sep=None, end=None, file=None, flush=False)
Args:
objects (object): zero or more objects to print
sep (str): Object separator to use, defaults to ``" "``
end (str): Trailing string to use, defaults to ``"\\n"``.
If end is `... | print_(*objects, sep=None, end=None, file=None, flush=False)
Args:
objects (object): zero or more objects to print
sep (str): Object separator to use, defaults to ``" "``
end (str): Trailing string to use, defaults to ``"\\n"``.
If end is ``"\\n"`` then `os.linesep` is used.
... |
def _merge_outfile_fname(out_file, bam_files, work_dir, batch):
"""Derive correct name of BAM file based on batching.
"""
if out_file is None:
out_file = os.path.join(work_dir, os.path.basename(sorted(bam_files)[0]))
if batch is not None:
base, ext = os.path.splitext(out_file)
ou... | Derive correct name of BAM file based on batching. |
def extractValue(self, model, item):
"""
Get the path referenced by this column's attribute.
@param model: Either a TabularDataModel or a ScrollableView, depending
on what this column is part of.
@param item: A port item instance (as defined by L{xmantissa.port}).
@rty... | Get the path referenced by this column's attribute.
@param model: Either a TabularDataModel or a ScrollableView, depending
on what this column is part of.
@param item: A port item instance (as defined by L{xmantissa.port}).
@rtype: C{unicode} |
def Refresh():
"""looks up symbols within the inferior and caches their names / values.
If debugging information is only partial, this method does its best to
find as much information as it can, validation can be done using
IsSymbolFileSane.
"""
try:
GdbCache.DICT = gdb.lookup_type('PyDic... | looks up symbols within the inferior and caches their names / values.
If debugging information is only partial, this method does its best to
find as much information as it can, validation can be done using
IsSymbolFileSane. |
def __mark(self, element, mark_set):
"""
Marks an element
:param element: The element to mark
:param mark_set: The set corresponding to the mark
:return: True if the element was known
"""
try:
# The given element can be of a different type than the or... | Marks an element
:param element: The element to mark
:param mark_set: The set corresponding to the mark
:return: True if the element was known |
def data_transforms_mnist(args, mnist_mean=None, mnist_std=None):
""" data_transforms for mnist dataset
"""
if mnist_mean is None:
mnist_mean = [0.5]
if mnist_std is None:
mnist_std = [0.5]
train_transform = transforms.Compose(
[
transforms.RandomCrop(28, paddin... | data_transforms for mnist dataset |
def sign_statement(self, statement, node_name, key_file, node_id, id_attr):
"""
Sign an XML statement.
:param statement: The statement to be signed
:param node_name: string like 'urn:oasis:names:...:Assertion'
:param key_file: The file where the key can be found
:param n... | Sign an XML statement.
:param statement: The statement to be signed
:param node_name: string like 'urn:oasis:names:...:Assertion'
:param key_file: The file where the key can be found
:param node_id:
:param id_attr: The attribute name for the identifier, normally one of
... |
def get_core_name_without_suffix(file_path):
# type: (AnyStr) -> AnyStr
"""Return core file name without suffix.
Examples:
>>> FileClass.get_core_name_without_suffix(r'/home/zhulj/1990.01.30/test.01.tif')
'test.01'
>>> FileClass.get_core_name_without_suffix(r... | Return core file name without suffix.
Examples:
>>> FileClass.get_core_name_without_suffix(r'/home/zhulj/1990.01.30/test.01.tif')
'test.01'
>>> FileClass.get_core_name_without_suffix(r'C:\zhulj\igsnrr\lreis.txt')
'lreis'
>>> FileClass.get_core_name_wi... |
def concatenate(ctx, *text):
"""
Joins text strings into one text string
"""
result = ''
for arg in text:
result += conversions.to_string(arg, ctx)
return result | Joins text strings into one text string |
def encode_string(data, encoding='hex'):
'''
Encode string
:param data: string to encode
:param encoding: encoding to use (default: 'hex')
:return: encoded string
'''
if six.PY2:
return data.encode(encoding)
else:
if isinstance(data, str):
data = bytes(data, ... | Encode string
:param data: string to encode
:param encoding: encoding to use (default: 'hex')
:return: encoded string |
def find(self, nameFilter=None, typeFilter=None, bindingModeFilter=None, boundFilter=None):
"""
Gets the list of services that the Watson IoT Platform can connect to.
The list can include a mixture of services that are either bound or unbound.
Parameters:
-... | Gets the list of services that the Watson IoT Platform can connect to.
The list can include a mixture of services that are either bound or unbound.
Parameters:
- nameFilter(string) - Filter the results by the specified name
- typeFilter(string) - Filter the res... |
def create(cls, cash_register_id, tab_uuid, description,
monetary_account_id=None, ean_code=None,
avatar_attachment_uuid=None, tab_attachment=None, quantity=None,
amount=None, custom_headers=None):
"""
Create a new TabItem for a given Tab.
:type user... | Create a new TabItem for a given Tab.
:type user_id: int
:type monetary_account_id: int
:type cash_register_id: int
:type tab_uuid: str
:param description: The TabItem's brief description. Can't be empty and
must be no longer than 100 characters
:type description... |
def hazeDriver():
"""
Process the command line arguments and run the appropriate haze subcommand.
We want to be able to do git-style handoffs to subcommands where if we
do `haze aws foo bar` and the executable haze-aws-foo exists, we'll call
it with the argument bar.
We deliberately don't do anything with... | Process the command line arguments and run the appropriate haze subcommand.
We want to be able to do git-style handoffs to subcommands where if we
do `haze aws foo bar` and the executable haze-aws-foo exists, we'll call
it with the argument bar.
We deliberately don't do anything with the arguments other than ... |
def bump_version(version, bump='patch'):
"""patch: patch, minor, major"""
try:
parts = map(int, version.split('.'))
except ValueError:
fail('Current version is not numeric')
if bump == 'patch':
parts[2] += 1
elif bump == 'minor':
parts[1] += 1
parts[2] = 0
... | patch: patch, minor, major |
def get_glibc_version():
"""
Returns:
Version as a pair of ints (major, minor) or None
"""
# TODO: Look into a nicer way to get the version
try:
out = subprocess.Popen(['ldd', '--version'],
stdout=subprocess.PIPE).communicate()[0]
except OSError:
... | Returns:
Version as a pair of ints (major, minor) or None |
def refresh(self, module=None):
"""Recompute the salience values of the Activations on the Agenda
and then reorder the agenda.
The Python equivalent of the CLIPS refresh-agenda command.
If no Module is specified, the current one is used.
"""
module = module._mdl if modu... | Recompute the salience values of the Activations on the Agenda
and then reorder the agenda.
The Python equivalent of the CLIPS refresh-agenda command.
If no Module is specified, the current one is used. |
def commit_manually(using=None):
"""
Decorator that activates manual transaction control. It just disables
automatic transaction control and doesn't do any commit/rollback of its
own -- it's up to the user to call the commit and rollback functions
themselves.
"""
def entering(using):
... | Decorator that activates manual transaction control. It just disables
automatic transaction control and doesn't do any commit/rollback of its
own -- it's up to the user to call the commit and rollback functions
themselves. |
def UpdateStatus(self, is_complete):
'''Mock method to update the transfer status.
If is_complete is False, this marks the transfer is active; otherwise it
marks the transfer as complete. It is an error to call this method after
calling it with is_complete as True.
In both cases, it updates the nu... | Mock method to update the transfer status.
If is_complete is False, this marks the transfer is active; otherwise it
marks the transfer as complete. It is an error to call this method after
calling it with is_complete as True.
In both cases, it updates the number of bytes transferred to be the current
... |
def alter_object(self, obj):
"""
Alters all the attributes in an individual object.
If it returns False, the object will not be saved
"""
for attname, field, replacer in self.replacers:
currentval = getattr(obj, attname)
replacement = replacer(self, obj, ... | Alters all the attributes in an individual object.
If it returns False, the object will not be saved |
def check(self):
"""Add platform specific checks"""
if not self.is_valid:
raise PolyaxonDeploymentConfigError(
'Deployment type `{}` not supported'.format(self.deployment_type))
check = False
if self.is_kubernetes:
check = self.check_for_kubernetes... | Add platform specific checks |
def invalidate(self, name):
# type: (str) -> None
"""
Invalidates the given component
:param name: Name of the component to invalidate
:raise ValueError: Invalid component name
"""
with self.__instances_lock:
try:
stored_instance = sel... | Invalidates the given component
:param name: Name of the component to invalidate
:raise ValueError: Invalid component name |
def gather(self, cmd):
"""
Runs a command and returns rc,stdout,stderr as a tuple.
If called while the `Dir` context manager is in effect, guarantees that the
process is executed in that directory, even if it is no longer the current
directory of the process (i.e. it is thread-s... | Runs a command and returns rc,stdout,stderr as a tuple.
If called while the `Dir` context manager is in effect, guarantees that the
process is executed in that directory, even if it is no longer the current
directory of the process (i.e. it is thread-safe).
:param cmd: The command and ... |
def identifyApplication(self, unProcessId, pchAppKey):
"""
Identifies a running application. OpenVR can't always tell which process started in response
to a URL. This function allows a URL handler (or the process itself) to identify the app key
for the now running application. Passing a... | Identifies a running application. OpenVR can't always tell which process started in response
to a URL. This function allows a URL handler (or the process itself) to identify the app key
for the now running application. Passing a process ID of 0 identifies the calling process.
The application m... |
def _create_filter(self):
"""Create a filter of all of the dependency products that we have selected."""
self._product_filter = {}
for chip in itertools.chain(iter(self._family.targets(self._tile.short_name)),
iter([self._family.platform_independent_target()... | Create a filter of all of the dependency products that we have selected. |
def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
writer.WriteVarBytes(self.Script)
writer.WriteVarBytes(self.ParameterList)
writer.WriteByte(self.ReturnType) | Serialize full object.
Args:
writer (neo.IO.BinaryWriter): |
def _generate_typevars(self):
# type: () -> None
"""
Creates type variables that are used by the type signatures for
_process_custom_annotations.
"""
self.emit("T = TypeVar('T', bound=bb.AnnotationType)")
self.emit("U = TypeVar('U')")
self.import_tracker._... | Creates type variables that are used by the type signatures for
_process_custom_annotations. |
def run_samtools(align_bams, items, ref_file, assoc_files, region=None,
out_file=None):
"""Detect SNPs and indels with samtools mpileup and bcftools.
"""
return shared_variantcall(_call_variants_samtools, "samtools", align_bams, ref_file,
items, assoc_files, re... | Detect SNPs and indels with samtools mpileup and bcftools. |
def project_decrease_permissions(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /project-xxxx/decreasePermissions API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2FdecreasePermissions... | Invokes the /project-xxxx/decreasePermissions API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2FdecreasePermissions |
def _add_reference(self, obj, ident=0):
"""
Adds a read reference to the marshaler storage
:param obj: Reference to add
:param ident: Log indentation level
"""
log_debug(
"## New reference handle 0x{0:X}: {1} -> {2}".format(
len(self.reference... | Adds a read reference to the marshaler storage
:param obj: Reference to add
:param ident: Log indentation level |
def _process_message(self, message: amqp.Message) -> None:
"""Processes the message received from the queue."""
if self.shutdown_pending.is_set():
return
try:
if isinstance(message.body, bytes):
message.body = message.body.decode()
description... | Processes the message received from the queue. |
def change_wavelength(self, wavelength):
'''
Changes the wavelength of the structure.
This will affect the mode solver and potentially
the refractive indices used (provided functions
were provided as refractive indices).
Args:
wavelength (float): The new wav... | Changes the wavelength of the structure.
This will affect the mode solver and potentially
the refractive indices used (provided functions
were provided as refractive indices).
Args:
wavelength (float): The new wavelength. |
def set_perms(path,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Set permissions for the given path
Args:
path (str):
The full path to the directory.
grant_perms (dict):
A dictionary ... | Set permissions for the given path
Args:
path (str):
The full path to the directory.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the... |
def group_by_month(self):
"""Return a dictionary of this collection's values grouped by each month.
Key values are between 1-12.
"""
data_by_month = OrderedDict()
for d in xrange(1, 13):
data_by_month[d] = []
for v, dt in zip(self._values, self.datetimes):
... | Return a dictionary of this collection's values grouped by each month.
Key values are between 1-12. |
def require_iterable_of(objs, types, name=None, type_name=None, truncate_at=80):
"""
Raise an exception if objs is not an iterable with each element an instance
of one of the specified types.
See `require_instance` for descriptions of the other parameters.
"""
# Fast pass for common case where ... | Raise an exception if objs is not an iterable with each element an instance
of one of the specified types.
See `require_instance` for descriptions of the other parameters. |
def delete_attachment(self, attachment):
"""Delete attachment from the AR or Analysis
The attachment will be only deleted if it is not further referenced by
another AR/Analysis.
"""
# Get the holding parent of this attachment
parent = None
if attachment.getLinke... | Delete attachment from the AR or Analysis
The attachment will be only deleted if it is not further referenced by
another AR/Analysis. |
def change_port_speed(self, instance_id, public, speed):
"""Allows you to change the port speed of a virtual server's NICs.
Example::
#change the Public interface to 10Mbps on instance 12345
result = mgr.change_port_speed(instance_id=12345,
... | Allows you to change the port speed of a virtual server's NICs.
Example::
#change the Public interface to 10Mbps on instance 12345
result = mgr.change_port_speed(instance_id=12345,
public=True, speed=10)
# result will be True or an Ex... |
def _add_fold_decoration(self, block, region):
"""
Add fold decorations (boxes arround a folded block in the editor
widget).
"""
deco = TextDecoration(block)
deco.signals.clicked.connect(self._on_fold_deco_clicked)
deco.tooltip = region.text(max_lines=25)
... | Add fold decorations (boxes arround a folded block in the editor
widget). |
def zoom_to(self, zoomlevel, no_reset=False):
"""Set zoom level in a channel.
This only changes the relevant settings; The image is not modified.
Also see :meth:`scale_to`.
.. note::
In addition to the given zoom level, other zoom settings are
defined for the ch... | Set zoom level in a channel.
This only changes the relevant settings; The image is not modified.
Also see :meth:`scale_to`.
.. note::
In addition to the given zoom level, other zoom settings are
defined for the channel in preferences.
Parameters
-------... |
def import_device(self, directory):
"""Imports a device from the given directory. You export the device
by using device.export()
There are two special cases: user and meta devices.
If the device name is meta, import_device will not do anything.
If the device name is "user", impo... | Imports a device from the given directory. You export the device
by using device.export()
There are two special cases: user and meta devices.
If the device name is meta, import_device will not do anything.
If the device name is "user", import_device will overwrite the user device
... |
def deployed_devices(self):
"""
:returns: Version deployed_devices of preview
:rtype: twilio.rest.preview.deployed_devices.DeployedDevices
"""
if self._deployed_devices is None:
self._deployed_devices = DeployedDevices(self)
return self._deployed_devices | :returns: Version deployed_devices of preview
:rtype: twilio.rest.preview.deployed_devices.DeployedDevices |
def get_distribution(self, name):
"""
Looks for a named distribution on the path.
This function only returns the first result found, as no more than one
value is expected. If nothing is found, ``None`` is returned.
:rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribu... | Looks for a named distribution on the path.
This function only returns the first result found, as no more than one
value is expected. If nothing is found, ``None`` is returned.
:rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`
or ``None`` |
def get_root_modules():
"""
Returns a list containing the names of all the modules available in the
folders of the pythonpath.
"""
ip = get_ipython()
if 'rootmodules' in ip.db:
return ip.db['rootmodules']
t = time()
store = False
modules = list(sys.builtin_module_names)
... | Returns a list containing the names of all the modules available in the
folders of the pythonpath. |
def match_criterion(self, tag):
'''Override. Determine if a tag has the desired name and kind attribute
value.
Args:
tag: A BeautifulSoup Tag.
Returns:
True if tag has the desired name and kind, otherwise False.
'''
return tag.name == self.refere... | Override. Determine if a tag has the desired name and kind attribute
value.
Args:
tag: A BeautifulSoup Tag.
Returns:
True if tag has the desired name and kind, otherwise False. |
def dbRestore(self, db_value, context=None):
"""
Converts a stored database value to Python.
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant>
"""
if db_value is not None:
return yaml.load(projex.text.nativestring(db_value))... | Converts a stored database value to Python.
:param py_value: <variant>
:param context: <orb.Context>
:return: <variant> |
def _append_value(self, v_values, next_value, v_idx=None, n_vals=1):
"""Update a list of parsed values with a new value."""
for _ in range(n_vals):
if v_idx:
try:
v_i = next(v_idx)
except StopIteration:
# Repeating comma... | Update a list of parsed values with a new value. |
def _get_queue(self):
"""Gets the actual location of the queue, or None.
"""
if self._queue is None:
self._links = []
queue, depth = self._resolve_queue(self.queue, links=self._links)
if queue is None and depth > 0:
raise QueueLinkBroken
... | Gets the actual location of the queue, or None. |
def _expectation(p, rbf_kern, feat1, lin_kern, feat2, nghp=None):
"""
Compute the expectation:
expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n)
- K_lin_{.,.} :: RBF kernel
- K_rbf_{.,.} :: Linear kernel
Different Z1 and Z2 are handled if p is diagonal and K_lin and K_rbf have disjoint... | Compute the expectation:
expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n)
- K_lin_{.,.} :: RBF kernel
- K_rbf_{.,.} :: Linear kernel
Different Z1 and Z2 are handled if p is diagonal and K_lin and K_rbf have disjoint
active_dims, in which case the joint expectations simplify into a product... |
def getNameFromPath(filePath):
"""
Returns the filename of the specified path without its extensions.
This is usually how we derive the default name for a given object.
"""
if len(filePath) == 0:
raise ValueError("Cannot have empty path for name")
fileName = os.path.split(os.path.normpat... | Returns the filename of the specified path without its extensions.
This is usually how we derive the default name for a given object. |
def _execute(self, *args):
""" Execute a given taskwarrior command with arguments
Returns a 2-tuple of stdout and stderr (respectively).
"""
command = (
[
'task',
'rc:%s' % self.config_filename,
]
+ self.get_configurat... | Execute a given taskwarrior command with arguments
Returns a 2-tuple of stdout and stderr (respectively). |
def set_ylabel(self, s, delay_draw=False):
"set plot ylabel"
self.conf.relabel(ylabel=s, delay_draw=delay_draw) | set plot ylabel |
def autoconfig_url_from_preferences():
"""
Get the PAC ``AutoConfigURL`` value from the macOS System Preferences.
This setting is visible as the "URL" field in
System Preferences > Network > Advanced... > Proxies > Automatic Proxy Configuration.
:return: The value from the registry, or None i... | Get the PAC ``AutoConfigURL`` value from the macOS System Preferences.
This setting is visible as the "URL" field in
System Preferences > Network > Advanced... > Proxies > Automatic Proxy Configuration.
:return: The value from the registry, or None if the value isn't configured or available.
N... |
def getPositionFromState(pState):
"""Return the position of a particle given its state dict.
Parameters:
--------------------------------------------------------------
retval: dict() of particle position, keys are the variable names,
values are their positions
"""
result =... | Return the position of a particle given its state dict.
Parameters:
--------------------------------------------------------------
retval: dict() of particle position, keys are the variable names,
values are their positions |
def _normalised_numpy(self):
"""Normalised data points using numpy."""
dx = (self.screen.width / float(len(self.points)))
oy = (self.screen.height)
points = np.array(self.points) - self.minimum
points = points * 4.0 / self.extents * self.size.y
for x, y in enumerate(point... | Normalised data points using numpy. |
def instantiateSong(fileName):
"""Create an AudioSegment with the data from the given file"""
ext = detectFormat(fileName)
if(ext == "mp3"):
return pd.AudioSegment.from_mp3(fileName)
elif(ext == "wav"):
return pd.AudioSegment.from_wav(fileName)
elif(ext == "ogg"):
return pd.A... | Create an AudioSegment with the data from the given file |
def CheckFile(self, path):
"""Validates the definition in a file.
Args:
path (str): path of the definition file.
Returns:
bool: True if the file contains valid definitions.
"""
print('Checking: {0:s}'.format(path))
definitions_registry = registry.DataTypeDefinitionsRegistry()
... | Validates the definition in a file.
Args:
path (str): path of the definition file.
Returns:
bool: True if the file contains valid definitions. |
def county_state_alerts(self, county, state):
"""Given a county and state, return alerts"""
samecode = self.geo.lookup_samecode(county, state)
return self.samecode_alerts(samecode) | Given a county and state, return alerts |
def return_letters_from_string(text):
"""Get letters from string only."""
out = ""
for letter in text:
if letter.isalpha():
out += letter
return out | Get letters from string only. |
def cubic_lattice( a, b, c, spacing ):
"""
Generate a cubic lattice.
Args:
a (Int): Number of lattice repeat units along x.
b (Int): Number of lattice repeat units along y.
c (Int): Number of lattice repeat units along z.
spacing (Float): Distance bet... | Generate a cubic lattice.
Args:
a (Int): Number of lattice repeat units along x.
b (Int): Number of lattice repeat units along y.
c (Int): Number of lattice repeat units along z.
spacing (Float): Distance between lattice sites.
Returns:
(Lattice)... |
async def stream(
self, version="1.1", keep_alive=False, keep_alive_timeout=None
):
"""Streams headers, runs the `streaming_fn` callback that writes
content to the response body, then finalizes the response body.
"""
headers = self.get_headers(
version,
... | Streams headers, runs the `streaming_fn` callback that writes
content to the response body, then finalizes the response body. |
def _viewport_default(self):
""" Trait initialiser """
viewport = Viewport(component=self.canvas, enable_zoom=True)
viewport.tools.append(ViewportPanTool(viewport))
return viewport | Trait initialiser |
def command(name):
"""Create a command, using the wrapped function as the handler.
Args
----
name : str
Name given to the created Command instance.
Returns
-------
Command
A new instance of Command, with handler set to the wrapped function.
"""
# TODO(nick): It wou... | Create a command, using the wrapped function as the handler.
Args
----
name : str
Name given to the created Command instance.
Returns
-------
Command
A new instance of Command, with handler set to the wrapped function. |
def _port_action_vlan(self, port, segment, func, vni):
"""Verify configuration and then process event."""
# Verify segment.
if not self._is_valid_segment(segment):
return
device_id = self._get_port_uuid(port)
if nexus_help.is_baremetal(port):
host_id = ... | Verify configuration and then process event. |
def channel_is_settled(
self,
participant1: Address,
participant2: Address,
block_identifier: BlockSpecification,
channel_identifier: ChannelID,
) -> bool:
""" Returns true if the channel is in a settled state, false otherwise. """
try:
... | Returns true if the channel is in a settled state, false otherwise. |
def info(self, **kwargs):
"""
Get the basic information for an account.
Call this method first, before calling other Account methods.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('info')
kwargs.update({... | Get the basic information for an account.
Call this method first, before calling other Account methods.
Returns:
A dict respresentation of the JSON returned from the API. |
def command(cls, command, stdin=None, shell=False):
""" Runs specified command.
The command can be fed with data on stdin with parameter ``stdin``.
The command can also be treated as a shell command with parameter ``shell``.
Please refer to subprocess.Popen on how does this stuff work
... | Runs specified command.
The command can be fed with data on stdin with parameter ``stdin``.
The command can also be treated as a shell command with parameter ``shell``.
Please refer to subprocess.Popen on how does this stuff work
:returns: Run() instance with resulting data |
def set_memcached_backend(self, config):
"""
Select the most suitable Memcached backend based on the config and
on what's installed
"""
# This is the preferred backend as it is the fastest and most fully
# featured, so we use this by default
config['BACKEND'] = 'd... | Select the most suitable Memcached backend based on the config and
on what's installed |
def view_umatrix(self, figsize=None, colormap=cm.Spectral_r,
colorbar=False, bestmatches=False, bestmatchcolors=None,
labels=None, zoom=None, filename=None):
"""Plot the U-matrix of the trained map.
:param figsize: Optional parameter to specify the size of the ... | Plot the U-matrix of the trained map.
:param figsize: Optional parameter to specify the size of the figure.
:type figsize: (int, int)
:param colormap: Optional parameter to specify the color map to be
used.
:type colormap: matplotlib.colors.Colormap
:par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.