code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _lt(field, value, document):
"""
Returns True if the value of a document field is less than a given value
"""
try:
return document.get(field, None) < value
except TypeError: # pragma: no cover Python < 3.0
return False | Returns True if the value of a document field is less than a given value |
def data_lookup_method(fields_list, mongo_db_obj, hist, record,
lookup_type):
"""
Method to lookup the replacement value given a single input value from
the same field.
:param dict fields_list: Fields configurations
:param MongoClient mongo_db_obj: Mon... | Method to lookup the replacement value given a single input value from
the same field.
:param dict fields_list: Fields configurations
:param MongoClient mongo_db_obj: MongoDB collection object
:param dict hist: existing input of history values object
:param dict record: values t... |
def get_settings(self, section=None, defaults=None):
"""
Gets a named section from the configuration source.
:param section: a :class:`str` representing the section you want to
retrieve from the configuration source. If ``None`` this will
fallback to the :attr:`plaster.P... | Gets a named section from the configuration source.
:param section: a :class:`str` representing the section you want to
retrieve from the configuration source. If ``None`` this will
fallback to the :attr:`plaster.PlasterURL.fragment`.
:param defaults: a :class:`dict` that will g... |
def nt_commonpath(paths): # pylint: disable=too-many-locals
"""Given a sequence of NT path names,
return the longest common sub-path."""
from ntpath import splitdrive
if not paths:
raise ValueError('commonpath() arg is an empty sequence')
check_arg_types('commonpath', *paths)
if ... | Given a sequence of NT path names,
return the longest common sub-path. |
def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng):
""" Run a single trial of k-medoids clustering
on dataset X, and given number of clusters
"""
membs = np.empty(shape=X.shape[0], dtype=int)
centers = kmeans._kmeans_init(X, n_clusters, method='', rng=rng)
sse_last = 9999.9
... | Run a single trial of k-medoids clustering
on dataset X, and given number of clusters |
def seqids(args):
"""
%prog seqids bedfile
Print out all seqids on one line. Useful for graphics.karyotype.
"""
p = OptionParser(seqids.__doc__)
p.add_option("--maxn", default=100, type="int",
help="Maximum number of seqids")
p.add_option("--prefix", help="Seqids must start... | %prog seqids bedfile
Print out all seqids on one line. Useful for graphics.karyotype. |
def references(self, criteria, publications='publications', column_name='publication_shortname', fetch=False):
"""
Do a reverse lookup on the **publications** table. Will return every entry that matches that reference.
Parameters
----------
criteria: int or str
The i... | Do a reverse lookup on the **publications** table. Will return every entry that matches that reference.
Parameters
----------
criteria: int or str
The id from the PUBLICATIONS table whose data across all tables is to be printed.
publications: str
Name of the publ... |
def _session():
'''
Return the boto3 session to use for the KMS client.
If aws_kms:profile_name is set in the salt configuration, use that profile.
Otherwise, fall back on the default aws profile.
We use the boto3 profile system to avoid having to duplicate
individual boto3 configuration setti... | Return the boto3 session to use for the KMS client.
If aws_kms:profile_name is set in the salt configuration, use that profile.
Otherwise, fall back on the default aws profile.
We use the boto3 profile system to avoid having to duplicate
individual boto3 configuration settings in salt configuration. |
def framesToFrameRanges(frames, zfill=0):
"""
Converts a sequence of frames to a series of padded
frame range strings.
Args:
frames (collections.Iterable): sequence of frames to process
zfill (int): width for zero padding
Yields:
str:
... | Converts a sequence of frames to a series of padded
frame range strings.
Args:
frames (collections.Iterable): sequence of frames to process
zfill (int): width for zero padding
Yields:
str: |
def remove_comments_and_docstrings(source):
"""
Returns *source* minus comments and docstrings.
.. note:: Uses Python's built-in tokenize module to great effect.
Example::
def noop(): # This is a comment
'''
Does nothing.
'''
pass # Don't do any... | Returns *source* minus comments and docstrings.
.. note:: Uses Python's built-in tokenize module to great effect.
Example::
def noop(): # This is a comment
'''
Does nothing.
'''
pass # Don't do anything
Will become::
def noop():
... |
def priority_run_or_raise(self, hosts, function, attempts=1):
"""
Like priority_run(), but if a host is already in the queue, the
existing host is moved to the top of the queue instead of enqueuing
the new one.
:type hosts: string|list(string)|Host|list(Host)
:param hos... | Like priority_run(), but if a host is already in the queue, the
existing host is moved to the top of the queue instead of enqueuing
the new one.
:type hosts: string|list(string)|Host|list(Host)
:param hosts: A hostname or Host object, or a list of them.
:type function: functio... |
def pil_image(self):
"""A :class:`PIL.Image.Image` instance containing the image data."""
if not self._pil_image:
if self._format == "SVG":
raise VectorImageError("can't rasterise vector images")
self._pil_image = PIL.Image.open(StringIO(self.contents))
re... | A :class:`PIL.Image.Image` instance containing the image data. |
def unique_list_dicts(dlist, key):
"""Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list:
"""
return list(dict((val[key], val) for val in dlist).values()) | Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list: |
def _put_or_post_multipart(self, method, url, data):
"""
encodes the data as a multipart form and PUTs or POSTs to the url
the response is parsed as JSON and the returns the resulting data structure
"""
fields = []
files = []
for key, value in data.items():
... | encodes the data as a multipart form and PUTs or POSTs to the url
the response is parsed as JSON and the returns the resulting data structure |
def get_planes(im, squeeze=True):
r"""
Extracts three planar images from the volumetric image, one for each
principle axis. The planes are taken from the middle of the domain.
Parameters
----------
im : ND-array
The volumetric image from which the 3 planar images are to be obtained
... | r"""
Extracts three planar images from the volumetric image, one for each
principle axis. The planes are taken from the middle of the domain.
Parameters
----------
im : ND-array
The volumetric image from which the 3 planar images are to be obtained
squeeze : boolean, optional
... |
def pathparse(value, sep=os.pathsep, os_sep=os.sep):
'''
Get enviroment PATH directories as list.
This function cares about spliting, escapes and normalization of paths
across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defau... | Get enviroment PATH directories as list.
This function cares about spliting, escapes and normalization of paths
across OSes.
:param value: path string, as given by os.environ['PATH']
:type value: str
:param sep: PATH separator, defaults to os.pathsep
:type sep: str
:param os_sep: OS filesy... |
def Matches(self, file_entry):
"""Compares the file entry against the filter.
Args:
file_entry (dfvfs.FileEntry): file entry to compare.
Returns:
bool: True if the file entry matches the filter, False if not or
None if the filter does not apply.
"""
if not self._date_time_ran... | Compares the file entry against the filter.
Args:
file_entry (dfvfs.FileEntry): file entry to compare.
Returns:
bool: True if the file entry matches the filter, False if not or
None if the filter does not apply. |
def get_device_model(self) -> str:
'''Show device model.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'getprop', 'ro.product.model')
return output.strip() | Show device model. |
def from_element(cls, element):
"""Set the resource properties from a ``<res>`` element.
Args:
element (~xml.etree.ElementTree.Element): The ``<res>``
element
"""
def _int_helper(name):
"""Try to convert the name attribute to an int, or None."""
... | Set the resource properties from a ``<res>`` element.
Args:
element (~xml.etree.ElementTree.Element): The ``<res>``
element |
def find_files(root, pattern):
"""Find all files matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of file paths relative to root
"""
results = []
for base, dirs, files in os.walk(root):
matched = fnmatch.filter(files, pattern)
re... | Find all files matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of file paths relative to root |
def GetAvailableClaimTotal(self):
"""
Gets the total amount of Gas that this wallet is able to claim at a given moment.
Returns:
Fixed8: the amount of Gas available to claim as a Fixed8 number.
"""
coinrefs = [coin.Reference for coin in self.GetUnclaimedCoins()]
... | Gets the total amount of Gas that this wallet is able to claim at a given moment.
Returns:
Fixed8: the amount of Gas available to claim as a Fixed8 number. |
def update(self, campaign_id, budget, nick=None):
'''xxxxx.xxxxx.campaign.budget.update
===================================
更新一个推广计划的日限额'''
request = TOPRequest('xxxxx.xxxxx.campaign.budget.update')
request['campaign_id'] = campaign_id
request['budget'] = budget
i... | xxxxx.xxxxx.campaign.budget.update
===================================
更新一个推广计划的日限额 |
def convert_date_to_iso(value):
"""Convert a date-value to the ISO date standard."""
date_formats = ["%d %b %Y", "%Y/%m/%d"]
for dformat in date_formats:
try:
date = datetime.strptime(value, dformat)
return date.strftime("%Y-%m-%d")
except ValueError:
pass... | Convert a date-value to the ISO date standard. |
def rotate(self, angle, axis, point=None, radians=False):
"""Rotates `Atom` by `angle`.
Parameters
----------
angle : float
Angle that `Atom` will be rotated.
axis : 3D Vector (tuple, list, numpy.array)
Axis about which the `Atom` will be rotated.
... | Rotates `Atom` by `angle`.
Parameters
----------
angle : float
Angle that `Atom` will be rotated.
axis : 3D Vector (tuple, list, numpy.array)
Axis about which the `Atom` will be rotated.
point : 3D Vector (tuple, list, numpy.array), optional
P... |
def threshold_monitor_hidden_threshold_monitor_security_pause(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_m... | Auto Generated Code |
def create_instance(self, port):
"""Enqueue instance create"""
instance_type = self.get_instance_type(port)
if not instance_type:
return
i_res = MechResource(port['device_id'], instance_type, a_const.CREATE)
self.provision_queue.put(i_res) | Enqueue instance create |
def _flatten_list(self, data):
'Flattens nested lists into strings.'
if data is None:
return ''
if isinstance(data, types.StringTypes):
return data
elif isinstance(data, (list, tuple)):
return '\n'.join(self._flatten_list(x) for x in data) | Flattens nested lists into strings. |
def get_geophysical_variables(ds):
'''
Returns a list of variable names for the variables detected as geophysical
variables.
:param netCDF4.Dataset nc: An open netCDF dataset
'''
parameters = []
for variable in ds.variables:
if is_geophysical(ds, variable):
parameters.a... | Returns a list of variable names for the variables detected as geophysical
variables.
:param netCDF4.Dataset nc: An open netCDF dataset |
def find_sparse_mode(self, core, additional, scaling, weights={}):
"""Find a sparse mode containing reactions of the core subset.
Return an iterator of the support of a sparse mode that contains as
many reactions from core as possible, and as few reactions from
additional as possible (a... | Find a sparse mode containing reactions of the core subset.
Return an iterator of the support of a sparse mode that contains as
many reactions from core as possible, and as few reactions from
additional as possible (approximately). A dictionary of weights can be
supplied which gives fur... |
def build_task(self, name):
""" Builds a task by name, resolving any dependencies on the way """
try:
self._gettask(name).value = (
self._gettask(name).task.resolve_and_build())
except TaskExecutionException as e:
perror(e.header, indent="+0")
... | Builds a task by name, resolving any dependencies on the way |
def on_backward_begin(self, last_loss:Rank0Tensor, **kwargs:Any) -> Rank0Tensor:
"Scale gradients up by `self.loss_scale` to prevent underflow."
#To avoid gradient underflow, we scale the gradients
ret_loss = last_loss * self.loss_scale
return {'last_loss': ret_loss} | Scale gradients up by `self.loss_scale` to prevent underflow. |
def CreateFromDocument(xml_text, default_namespace=None, location_base=None):
"""Parse the given XML and use the document element to create a Python instance.
@param xml_text An XML document. This should be data (Python 2
str or Python 3 bytes), or a text (Python 2 unicode or Python 3
str) in the L{py... | Parse the given XML and use the document element to create a Python instance.
@param xml_text An XML document. This should be data (Python 2
str or Python 3 bytes), or a text (Python 2 unicode or Python 3
str) in the L{pyxb._InputEncoding} encoding.
@keyword default_namespace The L{pyxb.Namespace} in... |
def within(self, x, ctrs, kdtree=None):
"""Check which balls `x` falls within. Uses a K-D Tree to
perform the search if provided."""
if kdtree is None:
# If no K-D Tree is provided, execute a brute-force
# search over all balls.
idxs = np.where(lalg.norm(ctrs... | Check which balls `x` falls within. Uses a K-D Tree to
perform the search if provided. |
def minute_frame_to_session_frame(minute_frame, calendar):
"""
Resample a DataFrame with minute data into the frame expected by a
BcolzDailyBarWriter.
Parameters
----------
minute_frame : pd.DataFrame
A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`,
and `d... | Resample a DataFrame with minute data into the frame expected by a
BcolzDailyBarWriter.
Parameters
----------
minute_frame : pd.DataFrame
A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`,
and `dt` (minute dts)
calendar : trading_calendars.trading_calendar.Tradin... |
def get_all_snapshots(self):
"""
This method returns a list of all Snapshots.
"""
data = self.get_data("snapshots/")
return [
Snapshot(token=self.token, **snapshot)
for snapshot in data['snapshots']
] | This method returns a list of all Snapshots. |
def actions_for_project(self, project):
"""Compile & Run the experiment with -O3 enabled."""
project.cflags = ["-O3", "-fno-omit-frame-pointer"]
project.runtime_extension = time.RunWithTime(
run.RuntimeExtension(project, self))
return self.default_runtime_actions(project) | Compile & Run the experiment with -O3 enabled. |
def update(self, *args, **kwargs):
"""This funcion updates a checkout of source code."""
self._call_helper("Updating", self.real.update, *args, **kwargs) | This funcion updates a checkout of source code. |
def makeEndOfPrdvFunc(self,EndOfPrdvP):
'''
Construct the end-of-period value function for this period, storing it
as an attribute of self for use by other methods.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal value of assets co... | Construct the end-of-period value function for this period, storing it
as an attribute of self for use by other methods.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal value of assets corresponding to the
asset values in self.aLvlNow ... |
def _plot_posterior_op(
values,
var_name,
selection,
ax,
bw,
linewidth,
bins,
kind,
point_estimate,
round_to,
credible_interval,
ref_val,
rope,
ax_labelsize,
xt_labelsize,
**kwargs
): # noqa: D202
"""Artist to draw posterior."""
def format_as_per... | Artist to draw posterior. |
def memoize(func=None, maxlen=None):
"""Cache a function's return value each time it is called.
This function serves as a function decorator to provide a caching of
evaluated fitness values. If called later with the same arguments,
the cached value is returned instead of being re-evaluated.
... | Cache a function's return value each time it is called.
This function serves as a function decorator to provide a caching of
evaluated fitness values. If called later with the same arguments,
the cached value is returned instead of being re-evaluated.
This decorator assumes that candidates ar... |
def _mpv_coax_proptype(value, proptype=str):
"""Intelligently coax the given python value into something that can be understood as a proptype property."""
if type(value) is bytes:
return value;
elif type(value) is bool:
return b'yes' if value else b'no'
elif proptype in (str, int, float)... | Intelligently coax the given python value into something that can be understood as a proptype property. |
def _parse_team_data(self, team_data):
"""
Parses a value for every attribute.
This function looks through every attribute and retrieves the value
according to the parsing scheme and index of the attribute from the
passed HTML data. Once the value is retrieved, the attribute's v... | Parses a value for every attribute.
This function looks through every attribute and retrieves the value
according to the parsing scheme and index of the attribute from the
passed HTML data. Once the value is retrieved, the attribute's value is
updated with the returned result.
... |
def CreateLink(target_path, link_path, override=True):
'''
Create a symbolic link at `link_path` pointing to `target_path`.
:param unicode target_path:
Link target
:param unicode link_path:
Fullpath to link name
:param bool override:
If True and `link_path` already exists ... | Create a symbolic link at `link_path` pointing to `target_path`.
:param unicode target_path:
Link target
:param unicode link_path:
Fullpath to link name
:param bool override:
If True and `link_path` already exists as a link, that link is overridden. |
def fftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True):
r"""
Return the phase of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
... | r"""
Return the phase of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
... |
def count(expr):
"""
Value counts
:param expr:
:return:
"""
if isinstance(expr, SequenceExpr):
unique_input = _extract_unique_input(expr)
if unique_input:
return nunique(unique_input).rename('count')
else:
return Count(_value_type=types.int64, _i... | Value counts
:param expr:
:return: |
def return_abs_path(directory, path):
"""
Unfortunately, Python is not smart enough to return an absolute
path with tilde expansion, so I writing functionality to do this
:param directory:
:param path:
:return:
"""
if directory is None or path is None:
return
directory = os.... | Unfortunately, Python is not smart enough to return an absolute
path with tilde expansion, so I writing functionality to do this
:param directory:
:param path:
:return: |
def main():
"""
Run the main CLI program.
Initializes the stack, parses command line arguments, and fires requested
logic.
"""
plugins = DefaultPluginManager()
plugins.load_plugins()
parser, _ = create_argparser()
# add the updater protocol options to the CLI:
for kls in update... | Run the main CLI program.
Initializes the stack, parses command line arguments, and fires requested
logic. |
def parametrize_grid(self, debug=False):
""" Performs Parametrization of grid equipment:
i) Sets voltage level of MV grid,
ii) Operation voltage level and transformer of HV/MV station,
iii) Default branch types (normal, aggregated, settlement)
Args
... | Performs Parametrization of grid equipment:
i) Sets voltage level of MV grid,
ii) Operation voltage level and transformer of HV/MV station,
iii) Default branch types (normal, aggregated, settlement)
Args
----
debug: bool, defaults to False
... |
def _correct_qualimap_genome_results(samples):
""" fixing java.lang.Double.parseDouble error on entries like "6,082.49"
"""
for s in samples:
if verify_file(s.qualimap_genome_results_fpath):
correction_is_needed = False
with open(s.qualimap_genome_results_fpath, 'r') as f:
... | fixing java.lang.Double.parseDouble error on entries like "6,082.49" |
def com_google_fonts_check_italic_angle(ttFont, style):
"""Checking post.italicAngle value."""
failed = False
value = ttFont["post"].italicAngle
# Checking that italicAngle <= 0
if value > 0:
failed = True
yield FAIL, Message("positive",
("The value of post.italicAngle is posi... | Checking post.italicAngle value. |
def get(self, name: str) -> Union[None, str, List[str]]:
"""
获取 header
"""
if name in self._headers:
return self._headers[name]
return None | 获取 header |
def produce_context(namespace, context_id, max_delay=None):
"""Produce event context."""
try:
context_obj = get_context(namespace, context_id)
logger.info("Found context '%s:%s'", namespace, context_id)
except ContextError:
logger.info("Context '%s:%s' not found", namespace, context_... | Produce event context. |
def numberOfConnectedProximalSynapses(self, cells=None):
"""
Returns the number of proximal connected synapses on these cells.
Parameters:
----------------------------
@param cells (iterable)
Indices of the cells. If None return count for all cells.
"""
if cells is None:
... | Returns the number of proximal connected synapses on these cells.
Parameters:
----------------------------
@param cells (iterable)
Indices of the cells. If None return count for all cells. |
def _ShouldPrintError(category, confidence, linenum):
"""If confidence >= verbose, category passes filter and is not suppressed."""
# There are three ways we might decide not to print an error message:
# a "NOLINT(category)" comment appears in the source,
# the verbosity level isn't high enough, or the filters... | If confidence >= verbose, category passes filter and is not suppressed. |
def on_service_departure(self, svc_ref):
"""
Called when a service has been unregistered from the framework
:param svc_ref: A service reference
"""
with self._lock:
if svc_ref is self.reference:
# Injected service going away...
service... | Called when a service has been unregistered from the framework
:param svc_ref: A service reference |
def _(pymux, variables):
" Go to previous active window. "
w = pymux.arrangement.get_previous_active_window()
if w:
pymux.arrangement.set_active_window(w) | Go to previous active window. |
def CRPS(label, pred):
""" Custom evaluation metric on CRPS.
"""
for i in range(pred.shape[0]):
for j in range(pred.shape[1] - 1):
if pred[i, j] > pred[i, j + 1]:
pred[i, j + 1] = pred[i, j]
return np.sum(np.square(label - pred)) / label.size | Custom evaluation metric on CRPS. |
def update(self,*flags):
"""Update Flags registry with a list of :class:`Flag` instances."""
super(Flags,self).update([(flag.name,flag) for flag in flags]) | Update Flags registry with a list of :class:`Flag` instances. |
def get_configuration(self):
"""Returns a mapping of UID -> configuration
"""
mapping = {}
settings = self.get_settings()
for record in self.context.getAnalyses():
uid = record.get("service_uid")
setting = settings.get(uid, {})
config = {
... | Returns a mapping of UID -> configuration |
def decorator(wrapped_decorator):
"""Converts a function into a decorator that optionally accepts keyword
arguments in its declaration.
Example usage:
@utils.decorator
def decorator(func, args, kwds, op1=None):
... apply op1 ...
return func(*args, **kwds)
# Form (1), vanilla
@decorat... | Converts a function into a decorator that optionally accepts keyword
arguments in its declaration.
Example usage:
@utils.decorator
def decorator(func, args, kwds, op1=None):
... apply op1 ...
return func(*args, **kwds)
# Form (1), vanilla
@decorator
foo(...)
...
# Form (... |
def parse_variable_definition(lexer: Lexer) -> VariableDefinitionNode:
"""VariableDefinition: Variable: Type DefaultValue? Directives[Const]?"""
start = lexer.token
return VariableDefinitionNode(
variable=parse_variable(lexer),
type=expect_token(lexer, TokenKind.COLON) and parse_type_referen... | VariableDefinition: Variable: Type DefaultValue? Directives[Const]? |
def distroinfo(cargs, version=__version__):
"""
distroinfo Command-Line Interface
"""
code = 1
args = docopt(__doc__, argv=cargs)
try:
if args['--version']:
if not version:
version = 'N/A'
print(version)
code = 0
elif args['fet... | distroinfo Command-Line Interface |
def _normalize_server_settings(**settings):
'''
Convert setting values that has been improperly converted to a dict back to a string.
'''
ret = dict()
settings = salt.utils.args.clean_kwargs(**settings)
for setting in settings:
if isinstance(settings[setting], dict):
value_f... | Convert setting values that has been improperly converted to a dict back to a string. |
def returnOrderBook(self, currencyPair='all', depth='50'):
"""Returns the order book for a given market, as well as a sequence
number for use with the Push API and an indicator specifying whether
the market is frozen. You may set currencyPair to "all" to get the
order books of all market... | Returns the order book for a given market, as well as a sequence
number for use with the Push API and an indicator specifying whether
the market is frozen. You may set currencyPair to "all" to get the
order books of all markets. |
def input_dim(self):
"""
Extracts the input dimension of the domain.
"""
n_cont = len(self.get_continuous_dims())
n_disc = len(self.get_discrete_dims())
return n_cont + n_disc | Extracts the input dimension of the domain. |
def AddEventAttribute(self, attribute_name, attribute_value):
"""Adds an attribute that will be set on all events produced.
Setting attributes using this method will cause events produced via this
mediator to have an attribute with the provided name set with the
provided value.
Args:
attribu... | Adds an attribute that will be set on all events produced.
Setting attributes using this method will cause events produced via this
mediator to have an attribute with the provided name set with the
provided value.
Args:
attribute_name (str): name of the attribute to add.
attribute_value (s... |
def compute_json(self, build_context):
"""Compute and store a JSON serialization of this target for caching
purposes.
The serialization includes:
- The build flavor
- The builder name
- Target tags
- Hashes of target dependencies & buildenv
- Processed... | Compute and store a JSON serialization of this target for caching
purposes.
The serialization includes:
- The build flavor
- The builder name
- Target tags
- Hashes of target dependencies & buildenv
- Processed props (where target props are replaced with their... |
def get_bandstructure(self):
"""
returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter
"""
return LobsterBandStructureSymmLine(kpoints=self.kpoints_array, eigenvals=self.eigenvals, lattice=self.lattice,
efe... | returns a LobsterBandStructureSymmLine object which can be plotted with a normal BSPlotter |
def pauli_expansion(
val: Any,
*,
default: Union[value.LinearDict[str], TDefault]
= RaiseTypeErrorIfNotProvided,
atol: float = 1e-9
) -> Union[value.LinearDict[str], TDefault]:
"""Returns coefficients of the expansion of val in the Pauli basis.
Args:
val: The value whose Pauli e... | Returns coefficients of the expansion of val in the Pauli basis.
Args:
val: The value whose Pauli expansion is to returned.
default: Determines what happens when `val` does not have methods that
allow Pauli expansion to be obtained (see below). If set, the value
is returned ... |
def get_value(self):
"""Gets the value of a select or input element
@rtype: str
@return: The value of the element
@raise: ValueError if element is not of type input or select, or has multiple selected options
"""
def get_element_value():
if self.tag_name() ==... | Gets the value of a select or input element
@rtype: str
@return: The value of the element
@raise: ValueError if element is not of type input or select, or has multiple selected options |
def to_header(self):
"""Convert the stored values into a WWW-Authenticate header."""
d = dict(self)
auth_type = d.pop("__auth_type__", None) or "basic"
return "%s %s" % (
auth_type.title(),
", ".join(
[
"%s=%s"
... | Convert the stored values into a WWW-Authenticate header. |
def _analyze_single(self, reference, result):
'''Report mistmatches and indels for a single (aligned) reference and
result.'''
# TODO: Recalculate coverage based on reference (e.g. sequencing result
# longer than template
reference_str = str(reference)
result_str = str(re... | Report mistmatches and indels for a single (aligned) reference and
result. |
def _fill_from_config(self, config):
"""
Fill this instance from given dictionary.
The method only uses keys which corresponds to properties
this class, throws exception on unknown property name.
:param conf: dictionary of parameters
:return: a new instance of this clas... | Fill this instance from given dictionary.
The method only uses keys which corresponds to properties
this class, throws exception on unknown property name.
:param conf: dictionary of parameters
:return: a new instance of this class filled with values from given dictionary
:raise... |
def sources(self):
"""A tuple containing the names of the Class sources for this Slot.
The Python equivalent of the CLIPS slot-sources function.
"""
data = clips.data.DataObject(self._env)
lib.EnvSlotSources(self._env, self._cls, self._name, data.byref)
return tuple(d... | A tuple containing the names of the Class sources for this Slot.
The Python equivalent of the CLIPS slot-sources function. |
def s(self, *args, **kwargs) -> Partial[Stepwise]:
"""
Create an unbound prototype of this class, partially applying arguments
.. code:: python
@stepwise
def control(pool: Pool, interval):
return 10
pipeline = control.s(interval=20) >> pool
... | Create an unbound prototype of this class, partially applying arguments
.. code:: python
@stepwise
def control(pool: Pool, interval):
return 10
pipeline = control.s(interval=20) >> pool
:note: The partial rules are sealed, and :py:meth:`~.UnboundSt... |
def getdateByTimezone(cDateUTC, timezone=None):
'''
Esse método trata a data recebida de acordo com o timezone do
usuário. O seu retorno é dividido em duas partes:
1) A data em si;
2) As horas;
:param cDateUTC: string contendo as informações da data
:param timezone: timezone do usuári... | Esse método trata a data recebida de acordo com o timezone do
usuário. O seu retorno é dividido em duas partes:
1) A data em si;
2) As horas;
:param cDateUTC: string contendo as informações da data
:param timezone: timezone do usuário do sistema
:return: data e hora convertidos para a time... |
def change_dir():
"""Change the local directory if the HADOOPY_CHDIR environmental variable is provided"""
try:
d = os.environ['HADOOPY_CHDIR']
sys.stderr.write('HADOOPY: Trying to chdir to [%s]\n' % d)
except KeyError:
pass
else:
try:
os.chdir(d)
exce... | Change the local directory if the HADOOPY_CHDIR environmental variable is provided |
def plot_energy(time, H, T, U):
"""Plot kinetic and potential energy of system over time"""
# Normalize energy to initial KE
T0 = T[0]
H = H / T0
T = T / T0
U = U / T0
# Plot
fig, ax = plt.subplots(figsize=[16,8])
ax.set_title('System Energy vs. Time')
ax.set_xlabel('Time in... | Plot kinetic and potential energy of system over time |
def to_json(self):
"""Serializes all states into json form.
Returns:
all states in json-compatible map.
"""
cursor = self._get_cursor()
cursor_object = False
if cursor and isinstance(cursor, datastore_query.Cursor):
cursor = cursor.to_websafe_string()
cursor_object = True
... | Serializes all states into json form.
Returns:
all states in json-compatible map. |
def get_kabsch_rotation(Q, P):
"""Calculate the optimal rotation from ``P`` unto ``Q``.
Using the Kabsch algorithm the optimal rotation matrix
for the rotation of ``other`` unto ``self`` is calculated.
The algorithm is described very well in
`wikipedia <http://en.wikipedia.org/wiki/Kabsch_algorithm... | Calculate the optimal rotation from ``P`` unto ``Q``.
Using the Kabsch algorithm the optimal rotation matrix
for the rotation of ``other`` unto ``self`` is calculated.
The algorithm is described very well in
`wikipedia <http://en.wikipedia.org/wiki/Kabsch_algorithm>`_.
Args:
other (Cartesi... |
def get_params(self, param=""):
""" pretty prints params if called as a function """
fullcurdir = os.path.realpath(os.path.curdir)
if not param:
for index, (key, value) in enumerate(self.paramsdict.items()):
if isinstance(value, str):
value = value... | pretty prints params if called as a function |
def remember_encrypted_identity(self, subject, encrypted):
"""
Base64-encodes the specified serialized byte array and sets that
base64-encoded String as the cookie value.
The ``subject`` instance is expected to be a ``WebSubject`` instance
with a web_registry handle so that an H... | Base64-encodes the specified serialized byte array and sets that
base64-encoded String as the cookie value.
The ``subject`` instance is expected to be a ``WebSubject`` instance
with a web_registry handle so that an HTTP cookie may be set on an
outgoing response. If it is not a ``WebSub... |
def from_string(bnf: str, entry=None, *optional_inherit) -> Grammar:
"""
Create a Grammar from a string
"""
inherit = [Grammar] + list(optional_inherit)
scope = {'grammar': bnf, 'entry': entry}
return build_grammar(tuple(inherit), scope) | Create a Grammar from a string |
def users_update(self, user_id, **kwargs):
"""Update an existing user."""
return self.__call_api_post('users.update', userId=user_id, data=kwargs) | Update an existing user. |
def as_yml(self):
"""
Return yml compatible version of self
"""
return YmlFileEvent(name=str(self.name),
subfolder=str(self.subfolder)) | Return yml compatible version of self |
def build_permission_name(model_class, prefix):
""" Build permission name for model_class (like 'app.add_model'). """
model_name = model_class._meta.object_name.lower()
app_label = model_class._meta.app_label
action_name = prefix
perm = '%s.%s_%s' % (app_label, action_name, model_name)
return pe... | Build permission name for model_class (like 'app.add_model'). |
def create_attach_volumes(name, kwargs, call=None):
'''
.. versionadded:: 2017.7.0
Create and attach multiple volumes to a node. The 'volumes' and 'node'
arguments are required, where 'node' is a libcloud node, and 'volumes'
is a list of maps, where each map contains:
size
The size of ... | .. versionadded:: 2017.7.0
Create and attach multiple volumes to a node. The 'volumes' and 'node'
arguments are required, where 'node' is a libcloud node, and 'volumes'
is a list of maps, where each map contains:
size
The size of the new disk in GB. Required.
type
The disk type, e... |
def axes(self):
"""Dimensions in which an actual resizing is performed."""
return tuple(i for i in range(self.domain.ndim)
if self.domain.shape[i] != self.range.shape[i]) | Dimensions in which an actual resizing is performed. |
def get_point(theta_ik, theta_jk, Pi, Pj):
""" Calculate coordinates of point Pk given two points Pi, Pj and inner angles. :param theta_ik: Inner angle at Pi to Pk.
:param theta_jk: Inner angle at Pj to Pk.
:param Pi: Coordinates of point Pi.
:param Pj: Coordinates of point Pj.
:return: Coordinate... | Calculate coordinates of point Pk given two points Pi, Pj and inner angles. :param theta_ik: Inner angle at Pi to Pk.
:param theta_jk: Inner angle at Pj to Pk.
:param Pi: Coordinates of point Pi.
:param Pj: Coordinates of point Pj.
:return: Coordinate of point Pk. |
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
''' run a command on the remote host '''
bufsize = 4096
try:
chan = self.ssh.get_transport().open_session()
except Exception, e:
msg = "Failed to open session"
if ... | run a command on the remote host |
def run_evaluation(self, stream_name: str) -> None:
"""
Run the main loop with the given stream in the prediction mode.
:param stream_name: name of the stream to be evaluated
"""
def prediction():
logging.info('Running prediction')
self._run_zeroth_epoch(... | Run the main loop with the given stream in the prediction mode.
:param stream_name: name of the stream to be evaluated |
def joliet_vd_factory(joliet, sys_ident, vol_ident, set_size, seqnum,
log_block_size, vol_set_ident, pub_ident_str,
preparer_ident_str, app_ident_str, copyright_file,
abstract_file, bibli_file, vol_expire_date, app_use, xa):
# type: (int, bytes, byte... | An internal function to create an Joliet Volume Descriptor.
Parameters:
joliet - The joliet version to use, one of 1, 2, or 3.
sys_ident - The system identification string to use on the new ISO.
vol_ident - The volume identification string to use on the new ISO.
set_size - The size of the set o... |
def generate(cls, size, string, filetype="JPEG"):
"""
Generates a squared avatar with random background color.
:param size: size of the avatar, in pixels
:param string: string to be used to print text and seed the random
:param filetype: the file format of the ima... | Generates a squared avatar with random background color.
:param size: size of the avatar, in pixels
:param string: string to be used to print text and seed the random
:param filetype: the file format of the image (i.e. JPEG, PNG) |
def partition_version_classifiers(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]:
"""Find version number classifiers in given list and partition them into 2 groups."""
versions_min, ve... | Find version number classifiers in given list and partition them into 2 groups. |
def _create_source(self, src):
"""Create a pyLikelihood Source object from a
`~fermipy.roi_model.Model` object."""
if src['SpatialType'] == 'SkyDirFunction':
pylike_src = pyLike.PointSource(self.like.logLike.observation())
pylike_src.setDir(src.skydir.ra.deg, src.skydir.... | Create a pyLikelihood Source object from a
`~fermipy.roi_model.Model` object. |
def register_job(self, job_details):
"""Register a job in this `JobArchive` """
# check to see if the job already exists
try:
job_details_old = self.get_details(job_details.jobname,
job_details.jobkey)
if job_details_old.stat... | Register a job in this `JobArchive` |
def update_vpnservice(self, vpnservice, body=None):
"""Updates a VPN service."""
return self.put(self.vpnservice_path % (vpnservice), body=body) | Updates a VPN service. |
def nat_gateways(self):
"""Instance depends on the API version:
* 2019-02-01: :class:`NatGatewaysOperations<azure.mgmt.network.v2019_02_01.operations.NatGatewaysOperations>`
"""
api_version = self._get_api_version('nat_gateways')
if api_version == '2019-02-01':
fr... | Instance depends on the API version:
* 2019-02-01: :class:`NatGatewaysOperations<azure.mgmt.network.v2019_02_01.operations.NatGatewaysOperations>` |
def conflicts_with(self, other):
"""Returns True if this requirement conflicts with another `Requirement`
or `VersionedObject`."""
if isinstance(other, Requirement):
if (self.name_ != other.name_) or (self.range is None) \
or (other.range is None):
... | Returns True if this requirement conflicts with another `Requirement`
or `VersionedObject`. |
def make_regular_points_with_no_res(bounds, nb_points=10000):
"""
Return a regular grid of points within `bounds` with the specified
number of points (or a close approximate value).
Parameters
----------
bounds : 4-floats tuple
The bbox of the grid, as xmin, ymin, xmax, ymax.
nb_poi... | Return a regular grid of points within `bounds` with the specified
number of points (or a close approximate value).
Parameters
----------
bounds : 4-floats tuple
The bbox of the grid, as xmin, ymin, xmax, ymax.
nb_points : int, optionnal
The desired number of points (default: 10000)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.