code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def partial_imap_1to1(func, si_func):
""" a bit messy
DEPRICATE
"""
@functools.wraps(si_func)
def wrapper(input_):
if not util_iter.isiterable(input_):
return func(si_func(input_))
else:
return list(map(func, si_func(input_)))
set_funcname(wrapper, util_s... | a bit messy
DEPRICATE |
def parameterized_expectations(model, verbose=False, initial_dr=None,
pert_order=1, with_complementarities=True,
grid={}, distribution={},
maxit=100, tol=1e-8, inner_maxit=100,
direct=False):
... | Find global solution for ``model`` via parameterized expectations.
Controls must be expressed as a direct function of equilibrium objects.
Algorithm iterates over the expectations function in the arbitrage equation.
Parameters:
----------
model : NumericModel
``dtcscc`` model to be solved
... |
def hash(self, value):
"""
function hash() implement to acquire hash value that use simply method that weighted sum.
Parameters:
-----------
value: string
the value is param of need acquire hash
Returns:
--------
... | function hash() implement to acquire hash value that use simply method that weighted sum.
Parameters:
-----------
value: string
the value is param of need acquire hash
Returns:
--------
result
hash code for value |
def run(self, args, options):
"""
This function calls uploadchannel which performs all the run steps:
- Create ChannelNode
- Pupulate Tree with TopicNodes, ContentNodes, and associated File objects
- .
- ..
- ...
Args:
args (dict): r... | This function calls uploadchannel which performs all the run steps:
- Create ChannelNode
- Pupulate Tree with TopicNodes, ContentNodes, and associated File objects
- .
- ..
- ...
Args:
args (dict): ricecooker command line arguments
optio... |
def generate_output_network(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output RDAP network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bo... | The function for generating CLI output RDAP network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (d... |
def set_text(self, text=None):
"""stub"""
if text is None:
raise NullArgument()
if self.get_text_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_string(
text,
self.get_text_metadata()):
... | stub |
def get_course_current_grades(self, course_id):
"""
Returns a CurrentGradesByCourse object for all users in the specified course.
Args:
course_id (str): an edX course ids.
Returns:
CurrentGradesByCourse: object representing the student current grades
Au... | Returns a CurrentGradesByCourse object for all users in the specified course.
Args:
course_id (str): an edX course ids.
Returns:
CurrentGradesByCourse: object representing the student current grades
Authorization:
The authenticated user must have staff perm... |
def save_formset(self, request, form, formset, change):
"""
For each photo set it's author to currently authenticated user.
"""
instances = formset.save(commit=False)
for instance in instances:
if isinstance(instance, Photo):
instance.author = request.... | For each photo set it's author to currently authenticated user. |
def setdefault(self, key, value):
"""We may not always be connected to an app, but we still need
to provide a way to the base environment to set it's defaults.
"""
try:
super(FlaskConfigStorage, self).setdefault(key, value)
except RuntimeError:
self._defau... | We may not always be connected to an app, but we still need
to provide a way to the base environment to set it's defaults. |
def synchronize(self, verbose=False):
"""
Synchronizes the Repository information with the directory.
All registered but missing files and directories in the directory,
will be automatically removed from the Repository.
:parameters:
#. verbose (boolean): Whether to b... | Synchronizes the Repository information with the directory.
All registered but missing files and directories in the directory,
will be automatically removed from the Repository.
:parameters:
#. verbose (boolean): Whether to be warn and inform about any abnormalities. |
def _ctab(stream):
"""Process ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
"""
yield CtabBlockStart()
counts_line = stream.popleft()
counts_line_values = [counts_line[i:i + 3].strip() for i in range(0, ... | Process ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data. |
def image_show(id=None, name=None, profile=None): # pylint: disable=C0103
'''
Return details about a specific image (glance image-show)
CLI Example:
.. code-block:: bash
salt '*' glance.image_show
'''
g_client = _auth(profile)
ret = {}
if name:
for image in g_client.i... | Return details about a specific image (glance image-show)
CLI Example:
.. code-block:: bash
salt '*' glance.image_show |
def getChannel(self, channel_id, **kwargs):
"""
Load all information about a channel and return a custom Channel class.
Calls "getChannel" XML-RPC.
:param channel_id: ``int``, for example 12345, or ``str`` for name.
:returns: deferred that when fired returns a Channel (Munch, d... | Load all information about a channel and return a custom Channel class.
Calls "getChannel" XML-RPC.
:param channel_id: ``int``, for example 12345, or ``str`` for name.
:returns: deferred that when fired returns a Channel (Munch, dict-like)
object representing this Koji channe... |
def get_xy(self, xy, addr=True):
"""Get the agent with xy-coordinate in the grid. If *addr* is True,
returns only the agent's address.
If no such agent in the grid, returns None.
:raises:
:exc:`ValueError` if xy-coordinate is outside the environment's
grid.
... | Get the agent with xy-coordinate in the grid. If *addr* is True,
returns only the agent's address.
If no such agent in the grid, returns None.
:raises:
:exc:`ValueError` if xy-coordinate is outside the environment's
grid. |
def _serialize_datetime(value):
"""Serialize a DateTime object to its proper ISO-8601 representation."""
if not isinstance(value, (datetime, arrow.Arrow)):
raise ValueError(u'The received object was not a datetime: '
u'{} {}'.format(type(value), value))
return value.isoforma... | Serialize a DateTime object to its proper ISO-8601 representation. |
def hmget(key, *fields, **options):
'''
Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2
'''
host = options.get('host', None)
port = options.get('port', None)
... | Returns the values of all the given hash fields.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmget foo_hash bar_field1 bar_field2 |
def _lookup_abs(self, p, klass, create=1):
"""
Fast (?) lookup of a *normalized* absolute path.
This method is intended for use by internal lookups with
already-normalized path data. For general-purpose lookups,
use the FS.Entry(), FS.Dir() or FS.File() methods.
The ca... | Fast (?) lookup of a *normalized* absolute path.
This method is intended for use by internal lookups with
already-normalized path data. For general-purpose lookups,
use the FS.Entry(), FS.Dir() or FS.File() methods.
The caller is responsible for making sure we're passed a
norm... |
def dskx02(handle, dladsc, vertex, raydir):
"""
Determine the plate ID and body-fixed coordinates of the
intersection of a specified ray with the surface defined by a
type 2 DSK plate model.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskx02_c.html
:param handle: Handle of DSK ker... | Determine the plate ID and body-fixed coordinates of the
intersection of a specified ray with the surface defined by a
type 2 DSK plate model.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskx02_c.html
:param handle: Handle of DSK kernel containing plate model.
:type handle: int
:p... |
def get_layer_params(self, layer_name):
"""
Provides access to the parameters of the given layer.
Works arounds the non-availability of graph collections in
eager mode.
:layer_name: name of the layer for which parameters are
required, must be one of the string in the
... | Provides access to the parameters of the given layer.
Works arounds the non-availability of graph collections in
eager mode.
:layer_name: name of the layer for which parameters are
required, must be one of the string in the
list layer_names
:return: list of pa... |
def Collect(
self, knowledge_base, artifact_definition, searcher, file_system):
"""Collects values using a file artifact definition.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
artifact_definition (artifacts.ArtifactDefinition): artifact definition.
sea... | Collects values using a file artifact definition.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
artifact_definition (artifacts.ArtifactDefinition): artifact definition.
searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess
the file syste... |
def collect(self, order_ref):
"""Collects the result of a sign or auth order using the
``orderRef`` as reference.
RP should keep on calling collect every two seconds as long as status
indicates pending. RP must abort if status indicates failed. The user
identity is returned when... | Collects the result of a sign or auth order using the
``orderRef`` as reference.
RP should keep on calling collect every two seconds as long as status
indicates pending. RP must abort if status indicates failed. The user
identity is returned when complete.
Example collect resul... |
def winsorize(self,
min_percentile,
max_percentile,
mask=NotSpecified,
groupby=NotSpecified):
"""
Construct a new factor that winsorizes the result of this factor.
Winsorizing changes values ranked less than the minimum per... | Construct a new factor that winsorizes the result of this factor.
Winsorizing changes values ranked less than the minimum percentile to
the value at the minimum percentile. Similarly, values ranking above
the maximum percentile are changed to the value at the maximum
percentile.
... |
def fit(self, X, y, **fit_params):
"""See ``NeuralNet.fit``.
In contrast to ``NeuralNet.fit``, ``y`` is non-optional to
avoid mistakenly forgetting about ``y``. However, ``y`` can be
set to ``None`` in case it is derived dynamically from
``X``.
"""
# pylint: dis... | See ``NeuralNet.fit``.
In contrast to ``NeuralNet.fit``, ``y`` is non-optional to
avoid mistakenly forgetting about ``y``. However, ``y`` can be
set to ``None`` in case it is derived dynamically from
``X``. |
def add_step(self, setting, duration):
"""
Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None
"""
if len(self._prog_steps) < 10:
self._prog_steps... | Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None |
def download_file_job(entry, directory, checksums, filetype='genbank', symlink_path=None):
"""Generate a DownloadJob that actually triggers a file download."""
pattern = NgdConfig.get_fileending(filetype)
filename, expected_checksum = get_name_and_checksum(checksums, pattern)
base_url = convert_ftp_url(... | Generate a DownloadJob that actually triggers a file download. |
def asint(vari):
"""
Convert dtype of polynomial coefficients to float.
Example:
>>> poly = 1.5*cp.variable()+2.25
>>> print(poly)
1.5q0+2.25
>>> print(cp.asint(poly))
q0+2
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.k... | Convert dtype of polynomial coefficients to float.
Example:
>>> poly = 1.5*cp.variable()+2.25
>>> print(poly)
1.5q0+2.25
>>> print(cp.asint(poly))
q0+2 |
def workspaces_provider(context):
"""
create a vocab of all workspaces in this site
"""
catalog = api.portal.get_tool(name="portal_catalog")
workspaces = catalog(portal_type="ploneintranet.workspace.workspacefolder")
current = api.content.get_uuid(context)
terms = []
for ws in workspace... | create a vocab of all workspaces in this site |
def get_fields(model_class, field_name='', path=''):
""" Get fields and meta data from a model
:param model_class: A django model class
:param field_name: The field name to get sub fields from
:param path: path of our field in format
field_name__second_field_name__ect__
:returns: Returns fi... | Get fields and meta data from a model
:param model_class: A django model class
:param field_name: The field name to get sub fields from
:param path: path of our field in format
field_name__second_field_name__ect__
:returns: Returns fields and meta data about such fields
fields: Django m... |
def write_results(self, data, name=None):
"""
Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:para... | Write JSON to file with the specified name.
:param name: Path to the file to be written to. If no path is passed
a new JSON file "results.json" will be created in the
current working directory.
:param output: JSON object. |
def get_modules(modulename=None):
"""Return a list of modules and packages under modulename.
If modulename is not given, return a list of all top level modules
and packages.
"""
modulename = compat.ensure_not_unicode(modulename)
if not modulename:
try:
return ([modname for ... | Return a list of modules and packages under modulename.
If modulename is not given, return a list of all top level modules
and packages. |
def _bapp(self, sample, target_label, target_image):
"""
Main algorithm for Boundary Attack ++.
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param sample: input image. Without the batchsize dimension.
:par... | Main algorithm for Boundary Attack ++.
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param sample: input image. Without the batchsize dimension.
:param target_label: integer for targeted attack,
None for nont... |
def export(local_root, commit, target):
"""Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:pa... | Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param str commit: Git commit SHA to export.
:... |
def as_task(self, logger=None, **fields):
"""
Start a new L{eliot.Action} of this type as a task (i.e. top-level
action) with the given start fields.
See L{ActionType.__call__} for example of usage.
@param logger: A L{eliot.ILogger} provider to which the action's
me... | Start a new L{eliot.Action} of this type as a task (i.e. top-level
action) with the given start fields.
See L{ActionType.__call__} for example of usage.
@param logger: A L{eliot.ILogger} provider to which the action's
messages will be written, or C{None} to use the default one.
... |
def _process_config(self):
"""Traverses the config and adds master keys and regional clients as needed."""
self._user_agent_adding_config = botocore.config.Config(user_agent_extra=USER_AGENT_SUFFIX)
if self.config.region_names:
self.add_regional_clients_from_list(self.config.region_... | Traverses the config and adds master keys and regional clients as needed. |
def generate_data(nitem, nfeat=2, dim=10, labeldim=1, base='item'):
"""Returns a randomly generated h5f.Data instance.
- nitem is the number of items to generate.
- nfeat is the number of features to generate for each item.
- dim is the dimension of the features vectors.
- base is the items basenam... | Returns a randomly generated h5f.Data instance.
- nitem is the number of items to generate.
- nfeat is the number of features to generate for each item.
- dim is the dimension of the features vectors.
- base is the items basename
- labeldim is the dimension of the labels vectors. |
def emit(self, span_datas):
"""
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
"""
try:
# TODO: keep the stream alive.
... | :type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit |
def apply(self, X, ntree_limit=0):
"""Return the predicted leaf every tree for each sample.
Parameters
----------
X : array_like, shape=[n_samples, n_features]
Input features matrix.
ntree_limit : int
Limit number of trees in the prediction; defaults to ... | Return the predicted leaf every tree for each sample.
Parameters
----------
X : array_like, shape=[n_samples, n_features]
Input features matrix.
ntree_limit : int
Limit number of trees in the prediction; defaults to 0 (use all trees).
Returns
--... |
def get_public_ip(addresses, version=4):
"""Return either the devices public IPv4 or IPv6 address.
"""
for addr in addresses:
if addr['public'] and addr['address_family'] == version:
return addr.get('address')
return None | Return either the devices public IPv4 or IPv6 address. |
def _lmder1_freudenstein_roth():
"""Freudenstein and Roth function (lmder1 test #7)"""
def func(params, vec):
vec[0] = -13 + params[0] + ((5 - params[1]) * params[1] - 2) * params[1]
vec[1] = -29 + params[0] + ((1 + params[1]) * params[1] - 14) * params[1]
def jac(params, jac):
jac... | Freudenstein and Roth function (lmder1 test #7) |
def save_visible_toolbars(self):
"""Saves the name of the visible toolbars in the .ini file."""
toolbars = []
for toolbar in self.visible_toolbars:
toolbars.append(toolbar.objectName())
CONF.set('main', 'last_visible_toolbars', toolbars) | Saves the name of the visible toolbars in the .ini file. |
def tick(self, index, length):
"""
Add tick marks in order of axes by width
APIPARAM: chxtc <axis index>,<length of tick mark>
"""
assert int(length) <= 25, 'Width cannot be more than 25'
self.data['ticks'].append('%s,%d'%(index,length))
return self.parent | Add tick marks in order of axes by width
APIPARAM: chxtc <axis index>,<length of tick mark> |
def dcc(self, *args, **kwargs):
"""Create and associate a new DCCConnection object.
Use the returned object to listen for or connect to
a DCC peer.
"""
dcc = self.reactor.dcc(*args, **kwargs)
self.dcc_connections.append(dcc)
return dcc | Create and associate a new DCCConnection object.
Use the returned object to listen for or connect to
a DCC peer. |
def reset(self):
"""
Reset the videostream by restarting ffmpeg
"""
if self.ffmpeg_process is not None:
# Close the previous stream
try:
self.ffmpeg_process.send_signal(signal.SIGINT)
except OSError:
pass
comma... | Reset the videostream by restarting ffmpeg |
def com_google_fonts_check_has_ttfautohint_params(ttFont):
""" Font has ttfautohint params? """
from fontbakery.utils import get_name_entry_strings
def ttfautohint_version(value):
# example string:
#'Version 1.000; ttfautohint (v0.93) -l 8 -r 50 -G 200 -x 14 -w "G"
import re
results = re.search(r... | Font has ttfautohint params? |
def lock(self):
"""Lock specified (abstract) requirements into (concrete) candidates.
The locking procedure consists of four stages:
* Resolve versions and dependency graph (powered by ResolveLib).
* Walk the graph to determine "why" each candidate came to be, i.e.
what top-l... | Lock specified (abstract) requirements into (concrete) candidates.
The locking procedure consists of four stages:
* Resolve versions and dependency graph (powered by ResolveLib).
* Walk the graph to determine "why" each candidate came to be, i.e.
what top-level requirements result in... |
def from_kwargs(cls, **kwargs):
"""Initialise configuration from kwargs."""
config = cls()
for slot in cls.__slots__:
if slot.startswith('_'):
slot = slot[1:]
setattr(config, slot, kwargs.pop(slot, cls.get_default(slot)))
if kwargs:
r... | Initialise configuration from kwargs. |
def fullselection(self) -> selectiontools.Selection:
"""A |Selection| object containing all |Element| and |Node| objects
defined by |XMLInterface.selections| and |XMLInterface.devices|.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> ... | A |Selection| object containing all |Element| and |Node| objects
defined by |XMLInterface.selections| and |XMLInterface.devices|.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = H... |
def install_timers(config, context):
"""Create the timers as specified by the plugin configuration."""
timers = []
if config.get('capture_timeout_warnings'):
timeout_threshold = config.get('timeout_warning_threshold')
# Schedule the warning at the user specified threshold given in percent.
... | Create the timers as specified by the plugin configuration. |
def get_checksum(file):
"""
Get SHA256 hash from the contents of a given file
"""
with open(file, 'rb') as FH:
contents = FH.read()
return hashlib.sha256(contents).hexdigest() | Get SHA256 hash from the contents of a given file |
def synonym(name):
"""
Utility function mimicking the behavior of the old SA synonym function
with the new hybrid property semantics.
"""
return hybrid_property(lambda inst: getattr(inst, name),
lambda inst, value: setattr(inst, name, value),
exp... | Utility function mimicking the behavior of the old SA synonym function
with the new hybrid property semantics. |
def fontsize(self, fontsize=None):
'''
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
'''
if fontsize is not None:
self._canvas.fontsize = fontsize
else:
return self... | Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified) |
def source(self):
"""
Returns the single source name for a variant collection if it is unique,
otherwise raises an error.
"""
if len(self.sources) == 0:
raise ValueError("No source associated with %s" % self.__class__.__name__)
elif len(self.sources) > 1:
... | Returns the single source name for a variant collection if it is unique,
otherwise raises an error. |
def _set_line_speed(self, v, load=False):
"""
Setter method for line_speed, mapped from YANG variable /interface/management/line_speed (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_line_speed is considered as a private
method. Backends looking to popula... | Setter method for line_speed, mapped from YANG variable /interface/management/line_speed (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_line_speed is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj.... |
def _init_metadata(self):
"""stub"""
super(MultiLanguageMultipleChoiceQuestionFormRecord, self)._init_metadata()
self._choices_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
... | stub |
def user_agent(self):
"""Return the formatted user agent string."""
components = ["/".join(x) for x in self.user_agent_components.items()]
return " ".join(components) | Return the formatted user agent string. |
def createLinkToSelf(self, new_zone, callback=None, errback=None,
**kwargs):
"""
Create a new linked zone, linking to ourselves. All records in this
zone will then be available as "linked records" in the new zone.
:param str new_zone: the new zone name to link t... | Create a new linked zone, linking to ourselves. All records in this
zone will then be available as "linked records" in the new zone.
:param str new_zone: the new zone name to link to this one
:return: new Zone |
def feature_subset(self, indices):
""" Returns some subset of the features.
Parameters
----------
indices : :obj:`list` of :obj:`int`
indices of the features in the list
Returns
-------
:obj:`list` of :obj:`Feature`
"""
if isi... | Returns some subset of the features.
Parameters
----------
indices : :obj:`list` of :obj:`int`
indices of the features in the list
Returns
-------
:obj:`list` of :obj:`Feature` |
def write_surf_params_to_file(self):
"""Write the params to file that surftool_Free needs to generate the surface facets"""
inp_file = self.water_surface_file + '_params.txt'
lg.info('Writing Inputs to file : ' + inp_file)
if self.surf_state == 'flat': # this is the only one that curr... | Write the params to file that surftool_Free needs to generate the surface facets |
def restore(self):
"""
Unloads all modules that weren't loaded when save_modules was called.
"""
sys = set(self._sys_modules.keys())
for mod_name in sys.difference(self._saved_modules):
del self._sys_modules[mod_name] | Unloads all modules that weren't loaded when save_modules was called. |
def get_info_consistent(self, ndim):
"""
Returns the main meta-data information adapted to the supplied
image dimensionality.
It will try to resolve inconsistencies and other conflicts,
altering the information avilable int he most plausible way.
Parameters
----... | Returns the main meta-data information adapted to the supplied
image dimensionality.
It will try to resolve inconsistencies and other conflicts,
altering the information avilable int he most plausible way.
Parameters
----------
ndim : int
image's dimensional... |
def col_to_dt(df,col_name,set_format = None,infer_format = True, dest = False):
""" Coerces a column in a DataFrame to datetime
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to coerce
dest - bool, default False
Whether to apply the result... | Coerces a column in a DataFrame to datetime
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def _store(self, uid, content, data=None):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid)
if data:
gfs = gridfs.GridFS(self.db)
id = gfs.put(data, encoding='utf-8')
doc.update(data_id=id)
doc.update(content)
... | Store the given dict of content at uid. Nothing returned. |
def assignOrderNames(self):
"""
Assigns the order names for this tree based on the name of the
columns.
"""
try:
schema = self.tableType().schema()
except AttributeError:
return
for colname in self.columns():
... | Assigns the order names for this tree based on the name of the
columns. |
def _get_instance_key(self, host, namespace, wmi_class, other=None):
"""
Return an index key for a given instance. Useful for caching.
"""
if other:
return "{host}:{namespace}:{wmi_class}-{other}".format(
host=host, namespace=namespace, wmi_class=wmi_class, ot... | Return an index key for a given instance. Useful for caching. |
def kernel_id(self):
"""Get kernel id"""
if self.connection_file is not None:
json_file = osp.basename(self.connection_file)
return json_file.split('.json')[0] | Get kernel id |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data["properties"]
address_pools = []
for content in properties.get("loadBalancerBackendAddressPools", []):
resource = Resource.from_raw_data(content)
address_p... | Create a new model using raw API response. |
def parser_set(self, args):
"""Set config from an :py:class:`argparse.Namespace` object.
Call this method with the return value from
:py:meth:`~argparse.ArgumentParser.parse_args`.
:param argparse.Namespace args: The populated
:py:class:`argparse.Namespace` object.
... | Set config from an :py:class:`argparse.Namespace` object.
Call this method with the return value from
:py:meth:`~argparse.ArgumentParser.parse_args`.
:param argparse.Namespace args: The populated
:py:class:`argparse.Namespace` object. |
def update_tcs_table(self):
"""
Periodically update a table of info from the TCS.
Only works at GTC
"""
g = get_root(self).globals
if not g.cpars['tcs_on'] or not g.cpars['telins_name'].lower() == 'gtc':
self.after(60000, self.update_tcs_table)
re... | Periodically update a table of info from the TCS.
Only works at GTC |
def current_timestamp(self) -> datetime:
"""Get the current state timestamp."""
timestamp = DB.get_hash_value(self._key, 'current_timestamp')
return datetime_from_isoformat(timestamp) | Get the current state timestamp. |
def RV_2(self):
"""Instantaneous RV of star 2 with respect to system center-of-mass
"""
return -self.orbpop_long.RV * (self.orbpop_long.M1 /
(self.orbpop_long.M1 + self.orbpop_long.M2)) +\
self.orbpop_short.RV_com1 | Instantaneous RV of star 2 with respect to system center-of-mass |
def check_obfuscated_ip (self):
"""Warn if host of this URL is obfuscated IP address."""
# check if self.host can be an IP address
# check for obfuscated IP address
if iputil.is_obfuscated_ip(self.host):
ips = iputil.resolve_host(self.host)
if ips:
... | Warn if host of this URL is obfuscated IP address. |
def save_setting(self, setting_name, value):
"""Saves the setting value into the database."""
setting = self.get_setting(setting_name)
if setting is None:
setting = models.DashboardWidgetSettings.objects.create(
widget_name=self.get_name(),
setting_nam... | Saves the setting value into the database. |
def visibility(cls, orb, **kwargs):
"""Visibility from a topocentric frame
see :py:meth:`Propagator.iter() <beyond.propagators.base.Propagator.iter>`
for description of arguments handling.
Args:
orb (Orbit): Orbit to compute visibility from the station with
Keyword... | Visibility from a topocentric frame
see :py:meth:`Propagator.iter() <beyond.propagators.base.Propagator.iter>`
for description of arguments handling.
Args:
orb (Orbit): Orbit to compute visibility from the station with
Keyword Args:
start (Date): starting date ... |
def tmpdir(prefix='npythy_tempdir_', delete=True):
'''
tmpdir() creates a temporary directory and yields its path. At python exit, the directory and
all of its contents are recursively deleted (so long as the the normal python exit process is
allowed to call the atexit handlers).
tmpdir(prefix) ... | tmpdir() creates a temporary directory and yields its path. At python exit, the directory and
all of its contents are recursively deleted (so long as the the normal python exit process is
allowed to call the atexit handlers).
tmpdir(prefix) uses the given prefix in the tempfile.mkdtemp() call.
... |
def List(validator):
"""
Creates a validator that runs the given validator on every item in a list
or other collection. The validator can mutate the values.
Any raised errors will be collected into a single ``Invalid`` error. Their
paths will be replaced with the index of the item. Will raise an er... | Creates a validator that runs the given validator on every item in a list
or other collection. The validator can mutate the values.
Any raised errors will be collected into a single ``Invalid`` error. Their
paths will be replaced with the index of the item. Will raise an error if
the input value is not... |
def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_for... | Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions. |
def read(self, size):
"""Read raw bytes from the instrument.
:param size: amount of bytes to be sent to the instrument
:type size: integer
:return: received bytes
:return type: bytes
"""
raw_read = super(USBRawDevice, self).read
received = bytearray()
... | Read raw bytes from the instrument.
:param size: amount of bytes to be sent to the instrument
:type size: integer
:return: received bytes
:return type: bytes |
def get_parameters_at_instant(self, instant):
"""
Get the parameters of the legislation at a given instant
:param instant: string of the format 'YYYY-MM-DD' or `openfisca_core.periods.Instant` instance.
:returns: The parameters of the legislation at a given instant.
:rtype: :any... | Get the parameters of the legislation at a given instant
:param instant: string of the format 'YYYY-MM-DD' or `openfisca_core.periods.Instant` instance.
:returns: The parameters of the legislation at a given instant.
:rtype: :any:`ParameterNodeAtInstant` |
def download_file_from_google_drive(driveid, filename=None, destination=os.path.curdir):
""" Download script for google drive shared links
Thank you @turdus-merula and Andrew Hundt!
https://stackoverflow.com/a/39225039/623735
"""
if '&id=' in driveid:
# https://drive.google.com/uc?export=... | Download script for google drive shared links
Thank you @turdus-merula and Andrew Hundt!
https://stackoverflow.com/a/39225039/623735 |
def _dims_in_order(self, dimension_order):
'''
:param list dimension_order: A list of axes
:rtype: bool
:return: Returns True if the dimensions are in order U*, T, Z, Y, X,
False otherwise
'''
regx = regex.compile(r'^[^TZYX]*T?Z?Y?X?$')
dimension_... | :param list dimension_order: A list of axes
:rtype: bool
:return: Returns True if the dimensions are in order U*, T, Z, Y, X,
False otherwise |
def from_str(cls, string):
"""
Creates a literal from a string
Parameters
----------
string : str
If the string starts with '!', it's interpreted as a negated variable
Returns
-------
caspo.core.literal.Literal
Created object inst... | Creates a literal from a string
Parameters
----------
string : str
If the string starts with '!', it's interpreted as a negated variable
Returns
-------
caspo.core.literal.Literal
Created object instance |
def pci_lookup_name1(
access: (IN, ctypes.POINTER(pci_access)),
buf: (IN, ctypes.c_char_p),
size: (IN, ctypes.c_int),
flags: (IN, ctypes.c_int),
arg1: (IN, ctypes.c_int),
) -> ctypes.c_char_p:
"""
Conversion of PCI ID's to names (according to the pci.ids file).
char *pci_lookup_name(
... | Conversion of PCI ID's to names (according to the pci.ids file).
char *pci_lookup_name(
struct pci_access *a, char *buf, int size, int flags, ...
) PCI_ABI;
This is a variant of pci_lookup_name() that gets called with one argument.
It is required because ctypes doesn't support varadic function... |
def _handle_stream(self, msg):
""" Handle stdout, stderr, and stdin.
"""
self.log.debug("stream: %s", msg.get('content', ''))
if not self._hidden and self._is_from_this_session(msg):
# Most consoles treat tabs as being 8 space characters. Convert tabs
# to spaces ... | Handle stdout, stderr, and stdin. |
def get(self, *args, **kwargs):
"""
Returns a single instance matching this query, optionally with additional filter kwargs.
See :ref:`retrieving-objects-with-filters`
Returns a single object matching the QuerySet.
.. code-block:: python
user = User.get(id=1)
... | Returns a single instance matching this query, optionally with additional filter kwargs.
See :ref:`retrieving-objects-with-filters`
Returns a single object matching the QuerySet.
.. code-block:: python
user = User.get(id=1)
If no objects are matched, a :class:`~.DoesNotE... |
def CreateTypes(self, allTypes):
"""
Create pyVmomi types from vmodl.reflect.DynamicTypeManager.AllTypeInfo
"""
enumTypes, dataTypes, managedTypes = self._ConvertAllTypes(allTypes)
self._CreateAllTypes(enumTypes, dataTypes, managedTypes) | Create pyVmomi types from vmodl.reflect.DynamicTypeManager.AllTypeInfo |
def connect_cloudfront(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.fps.conne... | :type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.fps.connection.FPSConnection`
:return: A connection to FPS |
def early_stopping(stopping_rounds, first_metric_only=False, verbose=True):
"""Create a callback that activates early stopping.
Note
----
Activates early stopping.
The model will train until the validation score stops improving.
Validation score needs to improve at least every ``early_stopping_... | Create a callback that activates early stopping.
Note
----
Activates early stopping.
The model will train until the validation score stops improving.
Validation score needs to improve at least every ``early_stopping_rounds`` round(s)
to continue training.
Requires at least one validation da... |
def choose_colour(self, title="Select Colour", **kwargs):
"""
Show a Colour Chooser dialog
Usage: C{dialog.choose_colour(title="Select Colour")}
@param title: window title for the dialog
@return:
@rtype: C{DialogData(int, Optional[ColourData])}
"... | Show a Colour Chooser dialog
Usage: C{dialog.choose_colour(title="Select Colour")}
@param title: window title for the dialog
@return:
@rtype: C{DialogData(int, Optional[ColourData])} |
def _getitem(self, index):
"""Get a single non-slice index."""
row = self._records[index]
if row is not None:
pass
elif self.is_attached():
# need to handle negative indices manually
if index < 0:
index = len(self._records) + index
... | Get a single non-slice index. |
def find_disulfide_bridges(self, representative_only=True):
"""Run Biopython's disulfide bridge finder and store found bridges.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.annotations['SSBOND-biopython']``
Args:
representat... | Run Biopython's disulfide bridge finder and store found bridges.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.annotations['SSBOND-biopython']``
Args:
representative_only (bool): If analysis should only be run on the representative s... |
def Rect_to_wxRect(self, fr):
""" Return a zoomed wx.Rect for given fitz.Rect."""
r = (fr * self.zoom).irect # zoomed IRect
return wx.Rect(r.x0, r.y0, r.width, r.height) | Return a zoomed wx.Rect for given fitz.Rect. |
def get_following(self, auth_secret):
"""Get the following list of a logged-in user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the following list is successfully o... | Get the following list of a logged-in user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the following list is successfully obtained, False otherwise.
result
... |
def hide_routemap_holder_route_map_content_set_ip_interface_null0(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubEleme... | Auto Generated Code |
def _SmallestColSize(self, text):
"""Finds the largest indivisible word of a string.
...and thus the smallest possible column width that can contain that
word unsplit over rows.
Args:
text: A string of text potentially consisting of words.
Returns:
Integer size of the largest sing... | Finds the largest indivisible word of a string.
...and thus the smallest possible column width that can contain that
word unsplit over rows.
Args:
text: A string of text potentially consisting of words.
Returns:
Integer size of the largest single word in the text. |
def get_row_by_fsid(self, fs_id):
'''确认在Liststore中是否存在这条任务. 如果存在, 返回TreeModelRow,
否则就返回None'''
for row in self.liststore:
if row[FSID_COL] == fs_id:
return row
return None | 确认在Liststore中是否存在这条任务. 如果存在, 返回TreeModelRow,
否则就返回None |
def nside2pixarea(nside, degrees=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`."""
area = nside_to_pixel_area(nside)
if degrees:
return area.to(u.deg ** 2).value
else:
return area.to(u.sr).value | Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`. |
def sample_poly(self, poly, scalar=None, bias_range=1, poly_range=None,
ignored_terms=None, **parameters):
"""Scale and sample from the given binary polynomial.
If scalar is not given, problem is scaled based on bias and polynomial
ranges. See :meth:`.BinaryPolynomial.scale`... | Scale and sample from the given binary polynomial.
If scalar is not given, problem is scaled based on bias and polynomial
ranges. See :meth:`.BinaryPolynomial.scale` and
:meth:`.BinaryPolynomial.normalize`
Args:
poly (obj:`.BinaryPolynomial`): A binary polynomial.
... |
def timeout(timeout):
"""
A decorator to timeout a function. Decorated method calls are executed in a separate new thread
with a specified timeout.
Also check if a thread for the same function already exists before creating a new one.
Note: Compatible with Windows (thread based).
"""
def de... | A decorator to timeout a function. Decorated method calls are executed in a separate new thread
with a specified timeout.
Also check if a thread for the same function already exists before creating a new one.
Note: Compatible with Windows (thread based). |
def save(self):
"""
Deletes the selected files from storage
"""
storage = get_media_storage()
for storage_name in self.cleaned_data['selected_files']:
full_path = storage.path(storage_name)
try:
storage.delete(storage_name)
... | Deletes the selected files from storage |
def get_var(self, name, user=None):
"""
Retrieve a global or user variable
:param name: The name of the variable to retrieve
:type name: str
:param user: If retrieving a user variable, the user identifier
:type user: str or None
:rtype: str
:raises Us... | Retrieve a global or user variable
:param name: The name of the variable to retrieve
:type name: str
:param user: If retrieving a user variable, the user identifier
:type user: str or None
:rtype: str
:raises UserNotDefinedError: The specified user does not exist
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.