code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _from_string(cls, serialized):
"""
Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKe... | Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKeyError: Should be raised if `serialized` is not a valid... |
def cli_main(pid, include_greenlet, debugger, verbose):
'''Print stack of python process.
$ pystack <pid>
'''
try:
print_stack(pid, include_greenlet, debugger, verbose)
except DebuggerNotFound as e:
click.echo('DebuggerNotFound: %s' % e.args[0], err=True)
click.get_current_c... | Print stack of python process.
$ pystack <pid> |
def get_palette(num_colors=256):
"""generates the colormap for visualizing the segmentation mask
Args:
num_colors (int): the number of colors to generate in the output palette
Returns:
string: the supplied extension, if assertion is successful.
"""
p... | generates the colormap for visualizing the segmentation mask
Args:
num_colors (int): the number of colors to generate in the output palette
Returns:
string: the supplied extension, if assertion is successful. |
def show_error_dialog(self, message, details=None):
"""
Convenience method for showing an error dialog.
"""
dlg = Gtk.MessageDialog(type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
message_format=message)
if details is not None:
... | Convenience method for showing an error dialog. |
def form_valid_bridge(self, form, field, model, related_field, error_message):
"""
call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: na... | call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: name of the related_name of the brigde (type: string)
@error_message: list of message errors ... |
def vapour_density(Temperature, element, isotope=None):
r"""This function returns the density in a rubidium or cesium
vapour in kg/m^-3. It receives as input the temperature in Kelvins, the
name of the element, and optionally the isotope. If no isotope is
specified, the density of a vapour with the natu... | r"""This function returns the density in a rubidium or cesium
vapour in kg/m^-3. It receives as input the temperature in Kelvins, the
name of the element, and optionally the isotope. If no isotope is
specified, the density of a vapour with the natural abundances will
be returned.
This is calculated... |
def humanize_api_path(api_path):
"""
Converts an API path to a humaized string, for example:
# >>> In [2]: humanize_api_path('/api/vlan/{id}')
# >>> Out[2]: u'ApiVlanId'
Parameters
----------
api_path : str
An API path string.
Returns
-------
str - humazined f... | Converts an API path to a humaized string, for example:
# >>> In [2]: humanize_api_path('/api/vlan/{id}')
# >>> Out[2]: u'ApiVlanId'
Parameters
----------
api_path : str
An API path string.
Returns
-------
str - humazined form. |
def _parse_requirements_file(requirements_file):
'''
Parse requirements.txt and return list suitable for
passing to ``install_requires`` parameter in ``setup()``.
'''
parsed_requirements = []
with open(requirements_file) as rfh:
for line in rfh.readlines():
line = line.strip(... | Parse requirements.txt and return list suitable for
passing to ``install_requires`` parameter in ``setup()``. |
def _f90repr(self, value):
"""Convert primitive Python types to equivalent Fortran strings."""
if isinstance(value, bool):
return self._f90bool(value)
elif isinstance(value, numbers.Integral):
return self._f90int(value)
elif isinstance(value, numbers.Real):
... | Convert primitive Python types to equivalent Fortran strings. |
def skips(self, ticket):
"""
Skips for ticket See Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__.
"""
return self._get(self._build_url(self.endpoint.skips(id=ticket))) | Skips for ticket See Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__. |
def _process_phendesc(self, limit):
"""
The description of the resulting phenotypes
with the genotype+environment
:param limit:
:return:
"""
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
model = Model(g... | The description of the resulting phenotypes
with the genotype+environment
:param limit:
:return: |
def extract(self, obj, bypass_ref=False):
"""
Extract parent of obj, according to current token.
:param obj: the object source
:param bypass_ref: not used
"""
for i in range(0, self.stages):
try:
obj = obj.parent_obj
except Attribu... | Extract parent of obj, according to current token.
:param obj: the object source
:param bypass_ref: not used |
def delete_entity_signal_handler(sender, instance, **kwargs):
"""
Defines a signal handler for syncing an individual entity. Called when
an entity is saved or deleted.
"""
if instance.__class__ in entity_registry.entity_registry:
Entity.all_objects.delete_for_obj(instance) | Defines a signal handler for syncing an individual entity. Called when
an entity is saved or deleted. |
def validate_set_ops(df, other):
"""
Helper function to ensure that DataFrames are valid for set operations.
Columns must be the same name in the same order, and indices must be of the
same dimension with the same names.
"""
if df.columns.values.tolist() != other.columns.values.tolist():
... | Helper function to ensure that DataFrames are valid for set operations.
Columns must be the same name in the same order, and indices must be of the
same dimension with the same names. |
def from_int(value: int) -> ulid.ULID:
"""
Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~int` value.
:param value: 128 bit integer
:type value: :class:`~int`
:return: ULID from integer value
:rtype: :class:`~ulid.ulid.ULID`
:raises ValueError: when the value is not ... | Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~int` value.
:param value: 128 bit integer
:type value: :class:`~int`
:return: ULID from integer value
:rtype: :class:`~ulid.ulid.ULID`
:raises ValueError: when the value is not a 128 bit integer |
def get_heteroatoms(self, elements=None):
"""
Identify non-H, non-C atoms in the MoleculeGraph, returning a list of
their node indices.
:param elements: List of elements to identify (if only certain
functional groups are of interest).
:return: set of ints representin... | Identify non-H, non-C atoms in the MoleculeGraph, returning a list of
their node indices.
:param elements: List of elements to identify (if only certain
functional groups are of interest).
:return: set of ints representing node indices |
def schema2jsonschema(self, schema):
"""Return the JSON Schema Object for a given marshmallow
:class:`Schema <marshmallow.Schema>` instance. Schema may optionally
provide the ``title`` and ``description`` class Meta options.
https://github.com/OAI/OpenAPI-Specification/blob/master/versi... | Return the JSON Schema Object for a given marshmallow
:class:`Schema <marshmallow.Schema>` instance. Schema may optionally
provide the ``title`` and ``description`` class Meta options.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject
Example: ::
... |
def deploy_windows(host,
port=445,
timeout=900,
username='Administrator',
password=None,
name=None,
sock_dir=None,
conf_file=None,
start_action=None,
... | Copy the install files to a remote Windows box, and execute them |
def add_dos(self, label, dos):
"""
Adds a dos for plotting.
Args:
label:
label for the DOS. Must be unique.
dos:
PhononDos object
"""
densities = dos.get_smeared_densities(self.sigma) if self.sigma \
else dos.d... | Adds a dos for plotting.
Args:
label:
label for the DOS. Must be unique.
dos:
PhononDos object |
def find_comment_markers(cellsource):
"""Look through the cell source for comments which affect nbval's behaviour
Yield an iterable of ``(MARKER_TYPE, True)``.
"""
found = {}
for line in cellsource.splitlines():
line = line.strip()
if line.startswith('#'):
# print("Found... | Look through the cell source for comments which affect nbval's behaviour
Yield an iterable of ``(MARKER_TYPE, True)``. |
def _update_indexes_for_deleted_object(collection, obj):
"""If an object is deleted, it should no longer be
indexed so this removes the object from all indexes
on the given collection."""
for index in _db[collection].indexes.values():
_remove_from_index(index, obj) | If an object is deleted, it should no longer be
indexed so this removes the object from all indexes
on the given collection. |
def calc_tools_spacing(tools_layout):
"""
Return a spacing (int) or None if we don't have the appropriate metrics
to calculate the spacing.
We're trying to adapt the spacing below the tools_layout spacing so that
the main_widget has the same vertical position as the editor widgets
(which... | Return a spacing (int) or None if we don't have the appropriate metrics
to calculate the spacing.
We're trying to adapt the spacing below the tools_layout spacing so that
the main_widget has the same vertical position as the editor widgets
(which have tabs above).
The required spacing is
... |
def set_val(self, nval):
"""
Sets new attribute's value.
@param nval: replaces current value by nval.
@type nval: int
@raise IOError: if corresponding file in /proc/sys cannot be written.
"""
file_obj = file(os.path.join(self._base, self._attr), 'w')
try:... | Sets new attribute's value.
@param nval: replaces current value by nval.
@type nval: int
@raise IOError: if corresponding file in /proc/sys cannot be written. |
def _get_or_create_user(self, force_populate=False):
"""
Loads the User model object from the database or creates it if it
doesn't exist. Also populates the fields, subject to
AUTH_LDAP_ALWAYS_UPDATE_USER.
"""
save_user = False
username = self.backend.ldap_to_dja... | Loads the User model object from the database or creates it if it
doesn't exist. Also populates the fields, subject to
AUTH_LDAP_ALWAYS_UPDATE_USER. |
def cmd(send, *_):
"""Returns the Discordian date.
Syntax: {command}
"""
try:
output = subprocess.check_output(['ddate'], universal_newlines=True)
except subprocess.CalledProcessError:
output = 'Today is the day you install ddate!'
for line in output.splitlines():
send(... | Returns the Discordian date.
Syntax: {command} |
def measure_bw(type_, total_size, threads_per_core, max_threads_per_core, cores_per_socket,
sockets):
"""*size* is given in kilo bytes"""
groups = []
for s in range(sockets):
groups += [
'-w',
'S' + str(s) + ':' + str(total_size) + 'kB:' +
str(threa... | *size* is given in kilo bytes |
def _read_para_seq(self, code, cbit, clen, *, desc, length, version):
"""Read HIP SEQ parameter.
Structure of HIP SEQ parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
... | Read HIP SEQ parameter.
Structure of HIP SEQ parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ... |
def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
word = split(word) # detect any non-delimited compounds
compound = True if re.search(r'-| |\.', word) else False
syllabify = _syllabify_compound if compound else _syllabify
syll, rules = syllabify(word)
yield syll... | Syllabify the given word, whether simplex or complex. |
def clear_boxes(self):
"""
Clear all boxes
"""
self.tmin_box.Clear()
self.tmin_box.SetStringSelection("")
if self.current_fit:
self.tmin_box.SetItems(self.T_list)
self.tmin_box.SetSelection(-1)
self.tmax_box.Clear()
self.tmax_box.S... | Clear all boxes |
def clean(self, suffixes=None):
"""
Remove all persistence-related files from the directory.
"""
if suffixes is None:
suffixes = [DONE_SUFFIX, LOCK_SUFFIX, PART_SUFFIX]
for suffix in suffixes:
listing = self.working_context.get_listing(suffix)
... | Remove all persistence-related files from the directory. |
def getmembers(_object, _predicate):
"""This is an implementation of inspect.getmembers, as in some versions
of python it may be buggy.
See issue at http://bugs.python.org/issue1785"""
# This should be:
#return inspect.getmembers(_object, _predicate)
# ... and it is re-implemented as:
obser... | This is an implementation of inspect.getmembers, as in some versions
of python it may be buggy.
See issue at http://bugs.python.org/issue1785 |
def attrs(
maybe_cls=None, type=None, context=None, translate=None, **attrs_kwargs
):
"""Wrap an attr enabled class."""
if isinstance(type, (list, tuple, set)):
types = list(type)
else:
types = [type] if type is not None else []
context = context or {}
translate = translate or {}... | Wrap an attr enabled class. |
def _create_dct_matrix(self):
"""
Create the not-quite-DCT matrix as used by Sphinx,
and store it in ```self.s2dct```.
"""
self.s2dct = numpy.zeros((self.mfcc_size, self.filter_bank_size))
for i in range(0, self.mfcc_size):
freq = numpy.pi * float(i) / self.fi... | Create the not-quite-DCT matrix as used by Sphinx,
and store it in ```self.s2dct```. |
def lookup_table(values, key=None, keyval=None, unique=False, use_lists=False):
"""
Builds a dict-based lookup table (index) elegantly.
Supports building normal and unique lookup tables. For example:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0]) == {
.... | Builds a dict-based lookup table (index) elegantly.
Supports building normal and unique lookup tables. For example:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0]) == {
... 'b': {'bar', 'baz'},
... 'f': {'foo'},
... 'q': {'quux', 'qux'}
.... |
def selected_unit(self):
"""Obtain the unit selected by user.
:returns: Metadata of the selected unit.
:rtype: dict, None
"""
item = self.lstUnits.currentItem()
try:
return definition(item.data(QtCore.Qt.UserRole))
except (AttributeError, NameError):
... | Obtain the unit selected by user.
:returns: Metadata of the selected unit.
:rtype: dict, None |
def path(self):
"""str: URL path for the model's APIs."""
return "/projects/%s/datasets/%s/models/%s" % (
self._proto.project_id,
self._proto.dataset_id,
self._proto.model_id,
) | str: URL path for the model's APIs. |
def trim_Ns(self):
'''Removes any leading or trailing N or n characters from the sequence'''
# get index of first base that is not an N
i = 0
while i < len(self) and self.seq[i] in 'nN':
i += 1
# strip off start of sequence and quality
self.seq = self.seq[i:]... | Removes any leading or trailing N or n characters from the sequence |
def type_suffix(self):
"""This is used in compose ID."""
if not self.type or self.type.lower() == 'ga':
return ''
return '-%s' % self.type.lower() | This is used in compose ID. |
def update_changes(changes,newtext,change):
"decide whether to compact the newest change into the old last; return new change list. assumes changes is safe to mutate.\
note: newtext MUST be the result of applying change to changes, and is only passed to save doing the computation again."
# the criteria for a n... | decide whether to compact the newest change into the old last; return new change list. assumes changes is safe to mutate.\
note: newtext MUST be the result of applying change to changes, and is only passed to save doing the computation again. |
def get_snmp_information(self):
"""Return the SNMP configuration."""
snmp_information = {}
snmp_config = junos_views.junos_snmp_config_table(self.device)
snmp_config.get()
snmp_items = snmp_config.items()
if not snmp_items:
return snmp_information
s... | Return the SNMP configuration. |
def _pkcs1imify(self, data):
"""
turn a 20-byte SHA1 hash into a blob of data as large as the key's N,
using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre.
"""
size = len(util.deflate_long(self.n, 0))
filler = max_byte * (size - len(SHA1_DIGESTINFO) - len(data) -... | turn a 20-byte SHA1 hash into a blob of data as large as the key's N,
using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. |
def _ps(self, sys_output):
''' a helper method for parsing docker ps output '''
import re
gap_pattern = re.compile('\t|\s{2,}')
container_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
... | a helper method for parsing docker ps output |
def on_resize(self, event):
"""Resize handler
Parameters
----------
event : instance of Event
The event.
"""
if self._aspect is None:
return
w, h = self._canvas.size
aspect = self._aspect / (w / h)
self.scale = (self.scale[... | Resize handler
Parameters
----------
event : instance of Event
The event. |
def populator(self, sample):
"""
Populates objects with the necessary attributes
:param sample: sample object
"""
from accessoryFunctions.accessoryFunctions import GenObject
if sample.general.bestassemblyfile != 'NA':
profile = ''
setattr(sample, s... | Populates objects with the necessary attributes
:param sample: sample object |
def _prt_qualifiers(associations, prt=sys.stdout):
"""Print Qualifiers found in the annotations.
QUALIFIERS:
1,462 colocalizes_with
1,454 contributes_to
1,157 not
13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not gafs)
... | Print Qualifiers found in the annotations.
QUALIFIERS:
1,462 colocalizes_with
1,454 contributes_to
1,157 not
13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not gafs)
4 not contributes_to (TBD: CHK - Seen in... |
def already_downloaded(track, title, filename):
"""
Returns True if the file has already been downloaded
"""
global arguments
already_downloaded = False
if os.path.isfile(filename):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) \
... | Returns True if the file has already been downloaded |
def initrepo(repopath, bare, shared):
""" Initialize an activegit repo.
Default makes base shared repo that should be cloned for users """
ag = activegit.ActiveGit(repopath, bare=bare, shared=shared) | Initialize an activegit repo.
Default makes base shared repo that should be cloned for users |
def objective_value(self):
"""Returns the optimal objective value"""
if self._f is None:
raise RuntimeError("Problem has not been optimized yet")
if self.direction == "max":
return -self._f + self.offset
else:
return self._f + self.offset | Returns the optimal objective value |
def _show_tables(self, *args):
""" print the existing tables within the 'doc' schema """
v = self.connection.lowest_server_version
schema_name = \
"table_schema" if v >= TABLE_SCHEMA_MIN_VERSION else "schema_name"
table_filter = \
" AND table_type = 'BASE TABLE'" ... | print the existing tables within the 'doc' schema |
def remove_action_callback(self, *event):
"""Callback method for remove action
The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality
of maybe active a entry widget. If a entry widget is active the remove callback return with None.
... | Callback method for remove action
The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality
of maybe active a entry widget. If a entry widget is active the remove callback return with None. |
def _set_seo_models(self, value):
"""Gets the actual models to be used."""
seo_models = []
for model_name in value:
if "." in model_name:
app_label, model_name = model_name.split(".", 1)
model = apps.get_model(app_label, model_name)
if ... | Gets the actual models to be used. |
def get_lastfunction_header(self, header, default_return_value=None):
"""Returns a specific header from the last API call
This will return None if the header is not present
:param header: (required) The name of the header you want to get
the value of
Most useful ... | Returns a specific header from the last API call
This will return None if the header is not present
:param header: (required) The name of the header you want to get
the value of
Most useful for the following header information:
x-rate-limit-limit,
... |
def recv(self):
"""
Receive a value from the channel.
Receiving will always block if no value is available.
If the channel is already closed,
:class:`goless.ChannelClosed` will be raised.
If the channel closes during a blocking ``recv``,
:class:`goless.ChannelClos... | Receive a value from the channel.
Receiving will always block if no value is available.
If the channel is already closed,
:class:`goless.ChannelClosed` will be raised.
If the channel closes during a blocking ``recv``,
:class:`goless.ChannelClosed` will be raised. (#TODO) |
def wer_201_2018():
r"""Werthmüller 201 pt Hankel filter, 2018.
Designed with the empymod add-on ``fdesign``, see
https://github.com/empymod/article-fdesign.
License: `Apache License, Version 2.0,
<http://www.apache.org/licenses/LICENSE-2.0>`_.
"""
dlf = DigitalFilter('Werthmüller 201', ... | r"""Werthmüller 201 pt Hankel filter, 2018.
Designed with the empymod add-on ``fdesign``, see
https://github.com/empymod/article-fdesign.
License: `Apache License, Version 2.0,
<http://www.apache.org/licenses/LICENSE-2.0>`_. |
async def add_reactions(self):
"""Adds the reactions buttons to the current message"""
self.statuslog.info("Loading buttons")
for e in ("⏯", "⏮", "⏹", "⏭", "🔀", "🔉", "🔊"):
try:
if self.embed is not None:
await client.add_reaction(self.embed.sent... | Adds the reactions buttons to the current message |
def cleanup(api_instance=None):
""" Remove completed jobs from the cluster """
api = api_instance or get_api()
r = api.list_job_for_all_namespaces()
delete_opts = kubernetes.client.V1DeleteOptions(
propagation_policy="Background")
for job in r.items:
if job.status.succeeded == jo... | Remove completed jobs from the cluster |
def shot_add_asset(self, *args, **kwargs):
"""Add more assets to the shot.
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_shot:
return
dialog = AssetAdderDialog(shot=self.cur_shot)
dialog.exec_()
assets = dialog.assets
... | Add more assets to the shot.
:returns: None
:rtype: None
:raises: None |
def run_migrations():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
with engine.connect() as connection:
context.configure(
connection=connection,
target_metadata=Model.metadata)
... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. |
def _transientSchedule(self, when, now):
"""
If this service's store is attached to its parent, ask the parent to
schedule this substore to tick at the given time.
@param when: The time at which to tick.
@type when: L{epsilon.extime.Time}
@param now: Present for signatu... | If this service's store is attached to its parent, ask the parent to
schedule this substore to tick at the given time.
@param when: The time at which to tick.
@type when: L{epsilon.extime.Time}
@param now: Present for signature compatibility with
L{_SiteScheduler._transient... |
def fit_from_image(self, data, voxelsize, seeds, unique_cls):
"""
This Method allows computes feature vector and train model.
:cls: list of index number of requested classes in seeds
"""
fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls)
self... | This Method allows computes feature vector and train model.
:cls: list of index number of requested classes in seeds |
def update_gates(self, gate_update_metadata, project, gate_step_id):
"""UpdateGates.
[Preview API] Updates the gate for a deployment.
:param :class:`<GateUpdateMetadata> <azure.devops.v5_0.release.models.GateUpdateMetadata>` gate_update_metadata: Metadata to patch the Release Gates.
:par... | UpdateGates.
[Preview API] Updates the gate for a deployment.
:param :class:`<GateUpdateMetadata> <azure.devops.v5_0.release.models.GateUpdateMetadata>` gate_update_metadata: Metadata to patch the Release Gates.
:param str project: Project ID or project name
:param int gate_step_id: Gate... |
def barrier(events, sid, kind='neighbour'):
"""
act as a multiprocessing barrier
"""
events[sid].set()
# only wait for the neighbours
if kind=='neighbour':
if sid > 0:
logging.debug("{0} is waiting for {1}".format(sid, sid - 1))
events[sid - 1].wait()
if s... | act as a multiprocessing barrier |
def clear_halt(self, ep):
r""" Clear the halt/stall condition for the endpoint ep."""
if isinstance(ep, Endpoint):
ep = ep.bEndpointAddress
self._ctx.managed_open()
self._ctx.backend.clear_halt(self._ctx.handle, ep) | r""" Clear the halt/stall condition for the endpoint ep. |
def train(args):
"""Training helper."""
if not args.model.lower() in ['cbow', 'skipgram']:
logging.error('Unsupported model %s.', args.model)
sys.exit(1)
if args.data.lower() == 'toy':
data = mx.gluon.data.SimpleDataset(nlp.data.Text8(segment='train')[:2])
data, vocab, idx_t... | Training helper. |
def IterReferenceInstancePaths(self, InstanceName, ResultClass=None,
Role=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCo... | Retrieve the instance paths of the association instances that reference
a source instance, using the Python :term:`py:generator` idiom to
return the result.
*New in pywbem 0.10 as experimental and finalized in 0.12.*
This method uses the corresponding pull operations if supported by th... |
def _reload_maybe(self):
"""
Reload the config if the config\
model has been updated. This is called\
once on every request by the middleware.\
Should not be called directly.
"""
ConfigModel = apps.get_model('djconfig.Config')
data = dict(
Con... | Reload the config if the config\
model has been updated. This is called\
once on every request by the middleware.\
Should not be called directly. |
def display_system(sys, style='vdw'):
'''Display the system *sys* with the default viewer.
'''
v = QtViewer()
#v.add_post_processing(FXAAEffect)
v.add_post_processing(SSAOEffect)
if style == 'vdw':
sr = v.add_renderer(AtomRenderer, sys.r_array, sys.type_array,
... | Display the system *sys* with the default viewer. |
def get_template_names(self):
"""Return a list (or tuple) of template names to search for when
rendering an instance of this class. The list should be ordered
with most specific names first, since the first template found to
exist will be used for rendering."""
site = self._conte... | Return a list (or tuple) of template names to search for when
rendering an instance of this class. The list should be ordered
with most specific names first, since the first template found to
exist will be used for rendering. |
def update(self, w, offset=0):
"""Compute gradient and Hessian matrix with respect to `w`."""
time = self.time
x = self.x
exp_xw = numpy.exp(offset + numpy.dot(x, w))
n_samples, n_features = x.shape
gradient = numpy.zeros((1, n_features), dtype=float)
hessian = n... | Compute gradient and Hessian matrix with respect to `w`. |
def partial_derivative(f, x, n, nargs, delta=DELTA):
"""
Calculate partial derivative using central finite difference approximation.
:param f: function
:param x: sequence of arguments
:param n: index of argument derivateve is with respect to
:param nargs: number of arguments
:param ... | Calculate partial derivative using central finite difference approximation.
:param f: function
:param x: sequence of arguments
:param n: index of argument derivateve is with respect to
:param nargs: number of arguments
:param delta: optional step size, default is :math:`\\epsilon^{1/3}` where... |
def B3(formula):
"""
Rewrite formula eval result into Boolean3
:param formula:
:return: Boolean3
"""
if isinstance(formula, true) or formula is True or formula == Boolean3.Top.name or formula == Boolean3.Top.value:
return Boolean3.Top
if isinstance(formula, false) or formula is False... | Rewrite formula eval result into Boolean3
:param formula:
:return: Boolean3 |
def run(self, func=None):
''' Run the app '''
args = self.parser.parse_args()
if self.__add_vq is not None and self.__config_logging:
self.__config_logging(args)
if self.__show_version_func and args.version and callable(self.__show_version_func):
self.__show_versi... | Run the app |
def migrate(self) -> None:
""" Migrate
Perform a database migration, upgrading to the latest schema level.
"""
assert self.ormSessionCreator, "ormSessionCreator is not defined"
connection = self._dbEngine.connect()
isDbInitialised = self._dbEngine.dialect.has_table(
... | Migrate
Perform a database migration, upgrading to the latest schema level. |
def get_calendar_event(self, calendar_event):
"""
Return single Calendar Event by id
:calls: `GET /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.show>`_
:param calendar_event: The object or ID of the calenda... | Return single Calendar Event by id
:calls: `GET /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.show>`_
:param calendar_event: The object or ID of the calendar event.
:type calendar_event: :class:`canvasapi.calendar_... |
def _initialize(self,
provide_data: List[mx.io.DataDesc],
provide_label: List[mx.io.DataDesc],
default_bucket_key: Tuple[int, int]):
"""
Initializes model components, creates training symbol and module, and binds it.
"""
source ... | Initializes model components, creates training symbol and module, and binds it. |
def history_mean(self, nb=5):
"""Return the mean on the <nb> values in the history.
"""
_, v = zip(*self._history)
return sum(v[-nb:]) / float(v[-1] - v[-nb]) | Return the mean on the <nb> values in the history. |
def load(cls, partname, content_type, blob, package):
"""
Called by ``docx.opc.package.PartFactory`` to load an image part from
a package being opened by ``Document(...)`` call.
"""
return cls(partname, content_type, blob) | Called by ``docx.opc.package.PartFactory`` to load an image part from
a package being opened by ``Document(...)`` call. |
def reward_bonus(self, assignment_id, amount, reason):
"""Reward the Turker for a specified assignment with a bonus."""
try:
return self.mturkservice.grant_bonus(assignment_id, amount, reason)
except MTurkServiceException as ex:
logger.exception(str(ex)) | Reward the Turker for a specified assignment with a bonus. |
def snapshot_agent(self):
'''Gives snapshot of everything related to the agent'''
protocols = [i.get_agent_side() for i in self._protocols.values()]
return (self.agent, protocols, ) | Gives snapshot of everything related to the agent |
def iscontinuous(self):
"""Checks if a path is continuous with respect to its
parameterization."""
return all(self[i].end == self[i+1].start for i in range(len(self) - 1)) | Checks if a path is continuous with respect to its
parameterization. |
def get_covers(work, args):
""" Get missing covers. """
with contextlib.ExitStack() as cm:
if args.filename == EMBEDDED_ALBUM_ART_SYMBOL:
tmp_prefix = "%s_" % (os.path.splitext(os.path.basename(inspect.getfile(inspect.currentframe())))[0])
tmp_dir = cm.enter_context(tempfile.TemporaryDirectory(pref... | Get missing covers. |
def _to_DOM(self):
"""
Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object
"""
root_node = ET.Element("location")
name_node = ET.SubElement(root_node, "name")
name_node.text = self._name
... | Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object |
def fast_sync_import(working_dir, import_url, public_keys=config.FAST_SYNC_PUBLIC_KEYS, num_required=len(config.FAST_SYNC_PUBLIC_KEYS), verbose=False):
"""
Fast sync import.
Verify the given fast-sync file from @import_path using @public_key, and then
uncompress it into @working_dir.
Verify that a... | Fast sync import.
Verify the given fast-sync file from @import_path using @public_key, and then
uncompress it into @working_dir.
Verify that at least `num_required` public keys in `public_keys` signed.
NOTE: `public_keys` needs to be in the same order as the private keys that signed. |
def create_asset_timeline(self, asset_list):
"""
Returns a ``dict`` of the timeline for the requested assets. The key is
a datetime object (down to the millisecond) of ANY time where at least
one of the requested assets was loaded. The value is a ``list`` of ALL
assets that were ... | Returns a ``dict`` of the timeline for the requested assets. The key is
a datetime object (down to the millisecond) of ANY time where at least
one of the requested assets was loaded. The value is a ``list`` of ALL
assets that were loading at that time.
:param asset_list: ``list`` of the... |
def get_stories(self, *args, **kwargs):
"""
Returns a full StoryDataWrapper object for this creator.
/creators/{creatorId}/stories
:returns: StoriesDataWrapper -- A new request to API. Contains full results set.
"""
from .story import Story, StoryDataWrapper
re... | Returns a full StoryDataWrapper object for this creator.
/creators/{creatorId}/stories
:returns: StoriesDataWrapper -- A new request to API. Contains full results set. |
def create_autoscale_rule(subscription_id, resource_group, vmss_name, metric_name, operator,
threshold, direction, change_count, time_grain='PT1M',
time_window='PT5M', cool_down='PT1M'):
'''Create a new autoscale rule - pass the output in a list to create_autoscal... | Create a new autoscale rule - pass the output in a list to create_autoscale_setting().
Args:
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vmss_name (str): Name of scale set to apply scale events to.
metric_name (str): Name of metric ... |
def _validate_resources(self):
"""Validate the resources defined in the options."""
resources = self.options.resources
for key in ['num_machines', 'num_mpiprocs_per_machine', 'tot_num_mpiprocs']:
if key in resources and resources[key] != 1:
raise exceptions.FeatureNo... | Validate the resources defined in the options. |
def load_environment(global_conf, app_conf):
"""Configure the Pylons environment via the ``pylons.config``
object
"""
# Pylons paths
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
paths = dict(root=root,
controllers=os.path.join(root, 'controllers'),
... | Configure the Pylons environment via the ``pylons.config``
object |
def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Kraus', da... | Transform a QuantumChannel to the Kraus representation. |
def getConfiguration(self):
"""
Get the current configuration number for this device.
"""
configuration = c_int()
mayRaiseUSBError(libusb1.libusb_get_configuration(
self.__handle, byref(configuration),
))
return configuration.value | Get the current configuration number for this device. |
def tabulate_state_transitions(x, states, pos=None):
"""Construct a dataframe where each row provides information about a state transition.
Parameters
----------
x : array_like, int
1-dimensional array of state values.
states : set
Set of states of interest. Any state value not in t... | Construct a dataframe where each row provides information about a state transition.
Parameters
----------
x : array_like, int
1-dimensional array of state values.
states : set
Set of states of interest. Any state value not in this set will be ignored.
pos : array_like, int, optional... |
def address(self, value):
"""
Setter for **self.__address** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"addre... | Setter for **self.__address** attribute.
:param value: Attribute value.
:type value: unicode |
def contains(self, key):
'''Returns whether the object is in this datastore.'''
for store in self._stores:
if store.contains(key):
return True
return False | Returns whether the object is in this datastore. |
def clone(gandi, name, vhost, directory, origin):
"""Clone a remote vhost in a local git repository."""
if vhost != 'default':
directory = vhost
else:
directory = name if not directory else directory
return gandi.paas.clone(name, vhost, directory, origin) | Clone a remote vhost in a local git repository. |
def standardize_role(role):
"""Convert role text into standardized form."""
role = role.lower()
if any(c in role for c in {'synthesis', 'give', 'yield', 'afford', 'product', 'preparation of'}):
return 'product'
return role | Convert role text into standardized form. |
def _update_options(model, connection=None):
"""Updates the table options for the given model if necessary.
:param model: The model to update.
:param connection: Name of the connection to use
:return: `True`, if the options were modified in Cassandra,
`False` otherwise.
:rtype: bool
""... | Updates the table options for the given model if necessary.
:param model: The model to update.
:param connection: Name of the connection to use
:return: `True`, if the options were modified in Cassandra,
`False` otherwise.
:rtype: bool |
def super_mro(self):
"""Get the MRO which will be used to lookup attributes in this super."""
if not isinstance(self.mro_pointer, scoped_nodes.ClassDef):
raise exceptions.SuperError(
"The first argument to super must be a subtype of "
"type, not {mro_pointer}.... | Get the MRO which will be used to lookup attributes in this super. |
def serialize(self):
"""A module may have some properties that are not defined in the class properties list.
Serializing a module is the same as serializing an Item but we also also include all the
existing properties that are not defined in the properties or running_properties
class lis... | A module may have some properties that are not defined in the class properties list.
Serializing a module is the same as serializing an Item but we also also include all the
existing properties that are not defined in the properties or running_properties
class list.
We must also exclude... |
async def build_pool_upgrade_request(submitter_did: str,
name: str,
version: str,
action: str,
_sha256: str,
_timeout: Optional[int],
... | Builds a POOL_UPGRADE request. Request to upgrade the Pool (sent by Trustee).
It upgrades the specified Nodes (either all nodes in the Pool, or some specific ones).
:param submitter_did: DID of the submitter stored in secured Wallet.
:param name: Human-readable name for the upgrade.
:param version: The... |
def clone_workspace(self) -> None:
""" Pose a dialog to name and clone a workspace. """
def clone_clicked(text):
if text:
command = Workspace.CloneWorkspaceCommand(self, text)
command.perform()
self.document_controller.push_undo_command(comman... | Pose a dialog to name and clone a workspace. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.