code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_collation(self):
""" Reads :class:`Collation` object from stream """
buf = readall(self, Collation.wire_size)
return Collation.unpack(buf) | Reads :class:`Collation` object from stream |
def list_objects_v2(Bucket=None, Delimiter=None, EncodingType=None, MaxKeys=None, Prefix=None, ContinuationToken=None, FetchOwner=None, StartAfter=None, RequestPayer=None):
"""
Returns some or all (up to 1000) of the objects in a bucket. You can use the request parameters as selection criteria to return a subse... | Returns some or all (up to 1000) of the objects in a bucket. You can use the request parameters as selection criteria to return a subset of the objects in a bucket. Note: ListObjectsV2 is the revised List Objects API and we recommend you use this revised API for new application development.
See also: AWS API Docume... |
def enqueue(self, destination, frame):
"""
Store message (frame) for specified destinationination.
@param destination: The destinationination queue name for this message (frame).
@type destination: C{str}
@param frame: The message (frame) to send to specified destinationination... | Store message (frame) for specified destinationination.
@param destination: The destinationination queue name for this message (frame).
@type destination: C{str}
@param frame: The message (frame) to send to specified destinationination.
@type frame: C{stompclient.frame.Frame} |
def first_key(res):
"""
Returns the first result for the given command.
If more then 1 result is returned then a `RedisClusterException` is raised.
"""
if not isinstance(res, dict):
raise ValueError('Value should be of dict type')
if len(res.keys()) != 1:
raise RedisClusterExce... | Returns the first result for the given command.
If more then 1 result is returned then a `RedisClusterException` is raised. |
def bezier_radialrange(seg, origin, return_all_global_extrema=False):
"""returns the tuples (d_min, t_min) and (d_max, t_max) which minimize and
maximize, respectively, the distance d = |self.point(t)-origin|.
return_all_global_extrema: Multiple such t_min or t_max values can exist.
By default, this wi... | returns the tuples (d_min, t_min) and (d_max, t_max) which minimize and
maximize, respectively, the distance d = |self.point(t)-origin|.
return_all_global_extrema: Multiple such t_min or t_max values can exist.
By default, this will only return one. Set return_all_global_extrema=True
to return all such... |
async def log_out(self):
"""
Logs out Telegram and deletes the current ``*.session`` file.
Returns:
``True`` if the operation was successful.
"""
try:
await self(functions.auth.LogOutRequest())
except errors.RPCError:
return False
... | Logs out Telegram and deletes the current ``*.session`` file.
Returns:
``True`` if the operation was successful. |
def save(self, force=False, uuid=False, **kwargs):
"""
REPLACES the object in DB. This is forbidden with objects from find() methods unless force=True is given.
"""
if not self._initialized_with_doc and not force:
raise Exception("Cannot save a document not initialized fro... | REPLACES the object in DB. This is forbidden with objects from find() methods unless force=True is given. |
def check_unused(intersection, duplicates, intersections):
"""Check if a "valid" ``intersection`` is already in ``intersections``.
This assumes that
* ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0``
* At least one of the intersections in ``intersections`` is classified as
... | Check if a "valid" ``intersection`` is already in ``intersections``.
This assumes that
* ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0``
* At least one of the intersections in ``intersections`` is classified as
``COINCIDENT_UNUSED``.
Args:
intersection (.Intersec... |
def bed_occupied(self):
"""
bed_occupied: None -> boolean
Determines whether the bed is currently occupied by requesting
data from the remote XBee and comparing the analog value with
a threshold.
"""
# Receive samples from the remote device
self._set_sen... | bed_occupied: None -> boolean
Determines whether the bed is currently occupied by requesting
data from the remote XBee and comparing the analog value with
a threshold. |
def interact(self, display_banner=None):
"""Closely emulate the interactive Python console."""
# batch run -> do not interact
if self.exit_now:
return
if display_banner is None:
display_banner = self.display_banner
if isinstance(display_banner, ... | Closely emulate the interactive Python console. |
def acquire(self):
"""Acquire the lock."""
self.lease = self.client.lease(self.ttl)
base64_key = _encode(self.key)
base64_value = _encode(self._uuid)
txn = {
'compare': [{
'key': base64_key,
'result': 'EQUAL',
'target':... | Acquire the lock. |
def kind_as_string(self, add_colour=True):
'''Get the type of this context as an optionally coloured string.
@param add_colour If True, ANSI colour codes will be added.
@return A string describing the kind of execution context this is.
'''
with self._mutex:
if self.... | Get the type of this context as an optionally coloured string.
@param add_colour If True, ANSI colour codes will be added.
@return A string describing the kind of execution context this is. |
def _interpolate_meshes(self, data, n_neighbors=10, eps=0., power=1.,
reg=0.):
"""
Use IDW interpolation to fill in any masked pixels in the
low-resolution 2D mesh background and background RMS images.
This is required to use a regular-grid interpolator to ex... | Use IDW interpolation to fill in any masked pixels in the
low-resolution 2D mesh background and background RMS images.
This is required to use a regular-grid interpolator to expand
the low-resolution image to the full size image.
Parameters
----------
data : 1D `~numpy.... |
def grow_mask(anat, aseg, ants_segs=None, ww=7, zval=2.0, bw=4):
"""
Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/min... | Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/mindboggle/guts/segment.py#L1660 |
def calculate_cache_access(self):
"""Apply cache prediction to generate cache access behaviour."""
self.results = {'misses': self.predictor.get_misses(),
'hits': self.predictor.get_hits(),
'evicts': self.predictor.get_evicts(),
'ver... | Apply cache prediction to generate cache access behaviour. |
def replace_webhook(self, scaling_group, policy, webhook, name,
metadata=None):
"""
Replace an existing webhook. All of the attributes must be specified.
If you wish to delete any of the optional attributes, pass them in as
None.
"""
uri = "/%s/%s/policies/%s/... | Replace an existing webhook. All of the attributes must be specified.
If you wish to delete any of the optional attributes, pass them in as
None. |
def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False):
"""Install plugin from zipfile."""
logger.debug("%s is a file, attempting to load zip", pkgpath)
pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_")
try:
with zipfile.ZipFile(pkgpath) as pkgzip:
pk... | Install plugin from zipfile. |
def ensure_image(self):
"""
Ensure that config.image_url has been downloaded and unpacked.
"""
image_folder = self.get_image_folder()
if os.path.exists(image_folder):
print(
'OS image directory {} exists...not overwriting' .format(
... | Ensure that config.image_url has been downloaded and unpacked. |
def _watchdog_key(self):
"""
接受按键, 存入queue
"""
while True:
k = getch.getch()
self.key_queue.put(k) | 接受按键, 存入queue |
def save(self, png_file):
"""Save png to disk.
Parameters
----------
png_file : path to file
file to write to
Notes
-----
It relies on _repr_png_, so fix issues there.
"""
with open(png_file, 'wb') as f:
f.write(self._repr... | Save png to disk.
Parameters
----------
png_file : path to file
file to write to
Notes
-----
It relies on _repr_png_, so fix issues there. |
def copy(self):
'''Create a copy of the current instance.
:returns: A safely editable copy of the current sequence.
'''
# Significant performance improvements by skipping alphabet check
return type(self)(self.seq, self.material, run_checks=False) | Create a copy of the current instance.
:returns: A safely editable copy of the current sequence. |
def get_host_physnet(self, context):
"""Returns dictionary which contains physical topology information
for a given host_id
"""
host_id = utils.hostname(context.host)
cmd = ['show network physical-topology neighbors']
try:
response = self._run_eos_cmds(cmd)
... | Returns dictionary which contains physical topology information
for a given host_id |
def callback_handler(self):
"""RequestHandler for the OAuth 2.0 redirect callback.
Usage::
app = webapp.WSGIApplication([
('/index', MyIndexHandler),
...,
(decorator.callback_path, decorator.callback_handler())
])
Returns... | RequestHandler for the OAuth 2.0 redirect callback.
Usage::
app = webapp.WSGIApplication([
('/index', MyIndexHandler),
...,
(decorator.callback_path, decorator.callback_handler())
])
Returns:
A webapp.RequestHandler t... |
def chunk(self, size="150", axis=None, padding=None):
"""
Chunks records of a distributed array.
Chunking breaks arrays into subarrays, using an specified
size of chunks along each value dimension. Can alternatively
specify an average chunk byte size (in kilobytes) and the size ... | Chunks records of a distributed array.
Chunking breaks arrays into subarrays, using an specified
size of chunks along each value dimension. Can alternatively
specify an average chunk byte size (in kilobytes) and the size of
chunks (as ints) will be computed automatically.
Param... |
def post_mcore(state, last_instruction):
"""
Handle syscalls (import memory) and bail if we diverge
"""
global in_helper
# Synchronize qemu state to manticore's after a system call
if last_instruction.mnemonic.lower() == 'svc':
# Synchronize all writes that have happened
writes ... | Handle syscalls (import memory) and bail if we diverge |
def dump_document(cls, instance, fields_own=None, fields_to_many=None):
""" Get document for model_instance.
redefine dump rule for field x: def dump_document_x
:param django.db.models.Model instance: model instance
:param list<Field> or None fields: model_instance field to dump
... | Get document for model_instance.
redefine dump rule for field x: def dump_document_x
:param django.db.models.Model instance: model instance
:param list<Field> or None fields: model_instance field to dump
:return dict: document
Related documents are not included to current one.... |
def _query_account_key(cli_ctx, account_name):
"""Query the storage account key. This is used when the customer doesn't offer account key but name."""
rg, scf = _query_account_rg(cli_ctx, account_name)
t_storage_account_keys = get_sdk(
cli_ctx, CUSTOM_MGMT_STORAGE, 'models.storage_account_keys#Stora... | Query the storage account key. This is used when the customer doesn't offer account key but name. |
def get_cmdline_varargs(argv=None):
"""
Returns positional args specified directly after the scriptname
and before any args starting with '-' on the commandline.
"""
if argv is None:
argv = sys.argv
scriptname = argv[0]
if scriptname == '':
# python invoked by iteself
... | Returns positional args specified directly after the scriptname
and before any args starting with '-' on the commandline. |
def unique_addresses(data=None, file_path=None):
"""
The function to search an input string and/or file, extracting and
counting IPv4/IPv6 addresses/networks. Summarizes ports with sub-counts.
If both a string and file_path are provided, it will process them both.
Args:
data (:obj:`str`): T... | The function to search an input string and/or file, extracting and
counting IPv4/IPv6 addresses/networks. Summarizes ports with sub-counts.
If both a string and file_path are provided, it will process them both.
Args:
data (:obj:`str`): The data to process.
file_path (:obj:`str`): An option... |
def get_impl_ver():
"""Return implementation version."""
impl_ver = sysconfig.get_config_var("py_version_nodot")
if not impl_ver:
impl_ver = ''.join(map(str, sys.version_info[:2]))
return impl_ver | Return implementation version. |
def im():
""" Incoming message handler: forwarded by ForwardServerProvider """
req = jsonex_loads(request.get_data())
message = g.provider._receive_message(req['message'])
return {'message': message} | Incoming message handler: forwarded by ForwardServerProvider |
def get_index_from_filename(self, filename):
"""
Return the position index of a file in the tab bar of the editorstack
from its name.
"""
filenames = [d.filename for d in self.data]
return filenames.index(filename) | Return the position index of a file in the tab bar of the editorstack
from its name. |
def _has_commit(version, debug=False):
"""
Determine a version is a local git commit sha or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool
"""
if _has_tag(version, debug) or _has_branch(versi... | Determine a version is a local git commit sha or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool |
def nla_type(self, value):
"""Type setter."""
self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0)) | Type setter. |
def get(cls, resource_id, include_deactivated=False):
"""
Get a resource
:param resource_id: a resource's ID
:param include_deactivated: Include deactivated resources in response
:returns: Document instance
:raises: SocketError, CouchException
"""
resour... | Get a resource
:param resource_id: a resource's ID
:param include_deactivated: Include deactivated resources in response
:returns: Document instance
:raises: SocketError, CouchException |
def Fierz_to_Flavio_lep(C, ddll, parameters, norm_gf=True):
"""From semileptonic Fierz basis to Flavio semileptonic basis for Class V.
C should be the corresponding leptonic Fierz basis and
`ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc."""
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vu... | From semileptonic Fierz basis to Flavio semileptonic basis for Class V.
C should be the corresponding leptonic Fierz basis and
`ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc. |
def register(scanner_class, relevant_properties):
""" Registers a new generator class, specifying a set of
properties relevant to this scanner. Ctor for that class
should have one parameter: list of properties.
"""
assert issubclass(scanner_class, Scanner)
assert isinstance(relevant_pro... | Registers a new generator class, specifying a set of
properties relevant to this scanner. Ctor for that class
should have one parameter: list of properties. |
def delay(fn, opts, task, *args, **kwargs):
""" delay(t=5, stddev=0., pdf="gauss")
Wraps a bound method of a task and delays its execution by *t* seconds.
"""
if opts["stddev"] <= 0:
t = opts["t"]
elif opts["pdf"] == "gauss":
t = random.gauss(opts["t"], opts["stddev"])
elif opts[... | delay(t=5, stddev=0., pdf="gauss")
Wraps a bound method of a task and delays its execution by *t* seconds. |
def get_configs(self):
"""
It returns a name and a current value pairs of control files
which are categorised in the configs group.
"""
configs = {}
for name, default in self.configs.items():
cls = default.__class__
path = self.paths[name]
... | It returns a name and a current value pairs of control files
which are categorised in the configs group. |
def determine_version(self, request, *args, **kwargs):
"""
If versioning is being used, then determine any API version for the
incoming request. Returns a two-tuple of (version, versioning_scheme)
"""
if self.versioning_class is None:
return (None, None)
schem... | If versioning is being used, then determine any API version for the
incoming request. Returns a two-tuple of (version, versioning_scheme) |
def validate_variable_name(self, name):
"""
Validate variable name.
Arguments:
name (string): Property name.
Returns:
bool: ``True`` if variable name is valid.
"""
if not name:
raise SerializerError("Variable name is empty".format(nam... | Validate variable name.
Arguments:
name (string): Property name.
Returns:
bool: ``True`` if variable name is valid. |
def write_metrics_file(metrics: List[Dict[str, Any]], path: str):
"""
Write metrics data to tab-separated file.
:param metrics: metrics data.
:param path: Path to write to.
"""
with open(path, 'w') as metrics_out:
for checkpoint, metric_dict in enumerate(metrics, 1):
metrics... | Write metrics data to tab-separated file.
:param metrics: metrics data.
:param path: Path to write to. |
def join_conn_groups( conns, descs, mat_ids, concat = False ):
"""Join groups of the same element type."""
el = dict_from_keys_init( descs, list )
for ig, desc in enumerate( descs ):
el[desc].append( ig )
groups = [ii for ii in el.values() if ii]
## print el, groups
descs_out, conns_ou... | Join groups of the same element type. |
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message hand... | Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None |
def compilearg(self):
"""This method compiles the parameter into syntax that can be used on the shell, such as for example: --paramflag=value"""
if self.paramflag and self.paramflag[-1] == '=' or self.nospace:
sep = ''
elif self.paramflag:
sep = ' '
else:
... | This method compiles the parameter into syntax that can be used on the shell, such as for example: --paramflag=value |
def synchronize(self, pid, vendorSpecific=None):
"""See Also: synchronizeResponse() Args: pid: vendorSpecific:
Returns:
"""
response = self.synchronizeResponse(pid, vendorSpecific)
return self._read_boolean_response(response) | See Also: synchronizeResponse() Args: pid: vendorSpecific:
Returns: |
def Bipartite(graph, resolution_parameter_01,
resolution_parameter_0 = 0, resolution_parameter_1 = 0,
degree_as_node_size=False, types='type', **kwargs):
""" Create three layers for bipartite partitions.
This creates three layers for bipartite partition necessary for detecting
... | Create three layers for bipartite partitions.
This creates three layers for bipartite partition necessary for detecting
communities in bipartite networks. These three layers should be passed to
:func:`Optimiser.optimise_partition_multiplex` with
``layer_weights=[1,-1,-1]``.
Parameters
--------... |
def check_station_location_lat(self, ds):
"""
Checks station lat attributes are set
"""
gmin = self.std_check(ds, 'geospatial_lat_min')
gmax = self.std_check(ds, 'geospatial_lat_max')
msgs = []
count = 2
if not gmin:
count -= 1
msg... | Checks station lat attributes are set |
def initialize_gdt_x86(self, state, concrete_target):
"""
Create a GDT in the state memory and populate the segment registers.
:param state: state which will be modified
:param concrete_target: concrete target that will be used to read the fs register
:return: ... | Create a GDT in the state memory and populate the segment registers.
:param state: state which will be modified
:param concrete_target: concrete target that will be used to read the fs register
:return: the created GlobalDescriptorTable object |
def peek(library, session, address, width):
"""Read an 8, 16 or 32-bit value from the specified address.
Corresponds to viPeek* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address ... | Read an 8, 16 or 32-bit value from the specified address.
Corresponds to viPeek* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits... |
def _get_cpu_info_from_sysinfo_v2():
'''
Returns the CPU info gathered from sysinfo.
Returns {} if sysinfo is not found.
'''
try:
# Just return {} if there is no sysinfo
if not DataSource.has_sysinfo():
return {}
# If sysinfo fails return {}
returncode, output = DataSource.sysinfo_cpu()
if output == ... | Returns the CPU info gathered from sysinfo.
Returns {} if sysinfo is not found. |
def apply_selector(objs, selector):
'''Returns a list of objects which match the selector in any of objs.'''
out = []
for obj in objs:
timer.log('Applying selector: %s' % selector)
out += list(jsonselect.match(selector, objs))
timer.log('done applying selector')
return out | Returns a list of objects which match the selector in any of objs. |
async def set_codec(self, codectype=0x0040, bitrate=0x0003):
"""Set codec settings."""
act = self.service.action("X_SetCodec")
res = await act.async_call(CodecType=codectype, CodecBitrate=bitrate)
return res | Set codec settings. |
def _write_service_config(self):
"""
Will write the config out to disk.
"""
with open(self.config_path, 'w') as output:
output.write(json.dumps(self.data, sort_keys=True, indent=4)) | Will write the config out to disk. |
def _stringify_predicate_value(value):
"""Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'``
"""
if isi... | Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'`` |
def get_app_locations():
"""
Returns list of paths to tested apps
"""
return [os.path.dirname(os.path.normpath(import_module(app_name).__file__))
for app_name in PROJECT_APPS] | Returns list of paths to tested apps |
def get_vq_codebook(codebook_size, hidden_size):
"""Get lookup table for VQ bottleneck."""
with tf.variable_scope("vq", reuse=tf.AUTO_REUSE):
means = tf.get_variable(
name="means",
shape=[codebook_size, hidden_size],
initializer=tf.uniform_unit_scaling_initializer())
ema_count = tf.... | Get lookup table for VQ bottleneck. |
def set_change_request_state(change_id, state='approved'):
'''
Set the approval state of a change request/record
:param change_id: The ID of the change request, e.g. CHG123545
:type change_id: ``str``
:param state: The target state, e.g. approved
:type state: ``str``
CLI Example:
.... | Set the approval state of a change request/record
:param change_id: The ID of the change request, e.g. CHG123545
:type change_id: ``str``
:param state: The target state, e.g. approved
:type state: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.set_change_reques... |
def fix_variables(bqm, sampling_mode=True):
"""Determine assignments for some variables of a binary quadratic model.
Roof duality finds a lower bound for the minimum of a quadratic polynomial. It
can also find minimizing assignments for some of the polynomial's variables;
these fixed variables take the... | Determine assignments for some variables of a binary quadratic model.
Roof duality finds a lower bound for the minimum of a quadratic polynomial. It
can also find minimizing assignments for some of the polynomial's variables;
these fixed variables take the same values in all optimal solutions [BHT]_ [BH]_.... |
def append_request_id(req, resp, resource, params):
"""Append request id which got from response
header to resource.req_ids list.
"""
def get_headers(resp):
if hasattr(resp, 'headers'):
return resp.headers
if hasattr(resp, '_headers'):
return resp._headers
... | Append request id which got from response
header to resource.req_ids list. |
def create_xml_file_from_string(self, content, destination=None):
"""
Creates XML file from text.
:param content: C++ source code
:type content: str
:param destination: file name for xml file
:type destination: str
:rtype: returns file name of xml file
... | Creates XML file from text.
:param content: C++ source code
:type content: str
:param destination: file name for xml file
:type destination: str
:rtype: returns file name of xml file |
def ctrl(char):
"""
Calculate the control code for a given key. For example, this converts
"a" to 1 (which is the code for ctrl-a).
:param char: The key to convert to a control code.
:return: The control code as an integer or None if unknown.
"""
# Convert strin... | Calculate the control code for a given key. For example, this converts
"a" to 1 (which is the code for ctrl-a).
:param char: The key to convert to a control code.
:return: The control code as an integer or None if unknown. |
def OnInsertChartDialog(self, event):
"""Chart dialog event handler"""
key = self.grid.actions.cursor
cell_code = self.grid.code_array(key)
if cell_code is None:
cell_code = u""
chart_dialog = ChartDialog(self.grid.main_window, key, cell_code)
if chart_di... | Chart dialog event handler |
def DIPPR9H(ws, ks):
r'''Calculates thermal conductivity of a liquid mixture according to
mixing rules in [1]_ and also in [2]_.
.. math::
\lambda_m = \left( \sum_i w_i \lambda_i^{-2}\right)^{-1/2}
Parameters
----------
ws : float
Mass fractions of components
ks : float
... | r'''Calculates thermal conductivity of a liquid mixture according to
mixing rules in [1]_ and also in [2]_.
.. math::
\lambda_m = \left( \sum_i w_i \lambda_i^{-2}\right)^{-1/2}
Parameters
----------
ws : float
Mass fractions of components
ks : float
Liquid thermal condu... |
def get_output(self):
"""
Override standard get_output to return xml-file if xml-file is specified.
Otherwise, will return database.
"""
if self.__xml_output:
return self.__xml_output
elif self.get_database():
return self.get_database()
else:
raise ValueError, "no output xm... | Override standard get_output to return xml-file if xml-file is specified.
Otherwise, will return database. |
def brightness_temp(self, band, temp_scale='K'):
"""Calculate brightness temperature of Landsat 8
as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php
T = K2 / log((K1 / L) + 1)
and
L = ML * Q + AL
where:
T = At-satellite brightness temperature (degrees kelvin)
... | Calculate brightness temperature of Landsat 8
as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php
T = K2 / log((K1 / L) + 1)
and
L = ML * Q + AL
where:
T = At-satellite brightness temperature (degrees kelvin)
L = TOA spectral radiance (Watts / (m2 * srad * mm)... |
def create_business_rules(self):
"""Create business rules for hosts and services
:return: None
"""
self.hosts.create_business_rules(self.hosts, self.services,
self.hostgroups, self.servicegroups,
self.macr... | Create business rules for hosts and services
:return: None |
def data_flows(self, data_flows):
""" Setter for _data_flows field
See property
:param dict data_flows: Dictionary data_flows[data_flow_id] of :class:`rafcon.core.data_flow.DataFlow`
:raises exceptions.TypeError: if the data_flows parameter has the wrong type
:raises exceptions... | Setter for _data_flows field
See property
:param dict data_flows: Dictionary data_flows[data_flow_id] of :class:`rafcon.core.data_flow.DataFlow`
:raises exceptions.TypeError: if the data_flows parameter has the wrong type
:raises exceptions.AttributeError: if the keys of the data_flows... |
def get_artists(self, *args, **kwargs):
"""Convenience method for `get_music_library_information`
with ``search_type='artists'``. For details of other arguments,
see `that method
<#soco.music_library.MusicLibrary.get_music_library_information>`_.
"""
args = tuple(['artis... | Convenience method for `get_music_library_information`
with ``search_type='artists'``. For details of other arguments,
see `that method
<#soco.music_library.MusicLibrary.get_music_library_information>`_. |
def _iter_names(self):
"""
Generate a key/value pair for each name in this table. The key is a
(platform_id, name_id) 2-tuple and the value is the unicode text
corresponding to that key.
"""
table_format, count, strings_offset = self._table_header
table_bytes = se... | Generate a key/value pair for each name in this table. The key is a
(platform_id, name_id) 2-tuple and the value is the unicode text
corresponding to that key. |
def get_file_md5sum(path):
"""Calculate the MD5 hash for a file."""
with open(path, 'rb') as fh:
h = str(hashlib.md5(fh.read()).hexdigest())
return h | Calculate the MD5 hash for a file. |
def transform_sources(self, sources, with_string=False):
"""Get the defintions of needed strings and functions
after replacement.
"""
modules = {}
updater = partial(
self.replace_source, modules=modules, prefix='string_')
for filename in sources:
u... | Get the defintions of needed strings and functions
after replacement. |
def render_content(self):
"""Render the panel's content."""
if not self.has_content:
return ""
template = self.template
if isinstance(self.template, str):
template = self.app.ps.jinja2.env.get_template(self.template)
context = self.render_vars()
co... | Render the panel's content. |
def notify3_d_event(self, type_p, data):
"""Notifies framebuffer about 3D backend event.
in type_p of type int
event type. Currently only VBOX3D_NOTIFY_EVENT_TYPE_VISIBLE_3DDATA is supported.
in data of type str
event-specific data, depends on the supplied event type
... | Notifies framebuffer about 3D backend event.
in type_p of type int
event type. Currently only VBOX3D_NOTIFY_EVENT_TYPE_VISIBLE_3DDATA is supported.
in data of type str
event-specific data, depends on the supplied event type |
def save(self, *args, **kwargs):
"""
Custom save method
"""
# change status to scheduled if necessary
if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled'):
self.status = OUTWARD_STATUS.get('scheduled')
# call super.save()
super(... | Custom save method |
def _to_camel_case(string):
"""Return a camel cased version of the input string.
Args:
string (str): A snake cased string.
Returns:
str: A camel cased string.
"""
components = string.split('_')
return '%s%s' % (
components[0],
... | Return a camel cased version of the input string.
Args:
string (str): A snake cased string.
Returns:
str: A camel cased string. |
def createStaticLibBuilder(env):
"""This is a utility function that creates the StaticLibrary
Builder in an Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
static_lib = env['BUILDERS']['StaticLibrary']
except KeyError:
action... | This is a utility function that creates the StaticLibrary
Builder in an Environment if it is not there already.
If it is already there, we return the existing one. |
def fit(R):
''' Fit skew - lognormal to the rate samples achived from a prior analysis
Parameters
----------
R: array
Rate samples
Returns
-------
ff[0]: float
The skewness
ff[1]: float
The mean
ff[2]: float
... | Fit skew - lognormal to the rate samples achived from a prior analysis
Parameters
----------
R: array
Rate samples
Returns
-------
ff[0]: float
The skewness
ff[1]: float
The mean
ff[2]: float
The standard devi... |
def validate_yubikey_otp_short(self, params):
"""
Validate YubiKey OTP using YubiHSM internal database.
"""
from_key = params["otp"][0]
if not re.match(ykotp_valid_input, from_key):
self.log_error("IN: %s, Invalid OTP" % (from_key))
return "ERR Invalid OTP"
try:
res = pyh... | Validate YubiKey OTP using YubiHSM internal database. |
def unload(self, source: Source) -> None:
"""
Unloads a registered source, causing all of its associated bugs, tools,
and blueprints to also be unloaded. If the given source is not loaded,
this function will do nothing.
"""
logger.info('unloading source: %s', source.name)... | Unloads a registered source, causing all of its associated bugs, tools,
and blueprints to also be unloaded. If the given source is not loaded,
this function will do nothing. |
def smart_open_write(path=None, mode='wb', encoding=None):
"""Open a file for writing or return ``stdout``.
Adapted from StackOverflow user "Wolph"
(http://stackoverflow.com/a/17603000).
"""
if path is not None:
# open a file
fh = io.open(path, mode=mode, encoding=encoding)
else... | Open a file for writing or return ``stdout``.
Adapted from StackOverflow user "Wolph"
(http://stackoverflow.com/a/17603000). |
def parse_name(cls, name):
""" Parses a name into a dictionary of identified subsections with accompanying information to
correctly identify and replace if necessary
:param name: str, string to be parsed
:return: dict, dictionary with relevant parsed information
"""
... | Parses a name into a dictionary of identified subsections with accompanying information to
correctly identify and replace if necessary
:param name: str, string to be parsed
:return: dict, dictionary with relevant parsed information |
def observe(self, ob):
"""
Add the Observe option.
:param ob: observe count
"""
option = Option()
option.number = defines.OptionRegistry.OBSERVE.number
option.value = ob
self.del_option_by_number(defines.OptionRegistry.OBSERVE.number)
self.add_opt... | Add the Observe option.
:param ob: observe count |
def set(self, num):
"""
Sets the current value equal to num
"""
self._value = str(round(float(num), self.nplaces))
self._variable.set(self._value) | Sets the current value equal to num |
def message(self, message, source, point, ln, target):
"""Creates the --target Coconut error message."""
if target is not None:
message += " (enable --target " + target + " to dismiss)"
return super(CoconutTargetError, self).message(message, source, point, ln) | Creates the --target Coconut error message. |
def _encode(cls, data, charsets):
"""Encode the data using the character sets in charsets.
:param data: Data to be encoded.
:param charsets: Sequence of charsets that are used to encode the barcode.
Must be the exact amount of symbols needed to encode the data.
... | Encode the data using the character sets in charsets.
:param data: Data to be encoded.
:param charsets: Sequence of charsets that are used to encode the barcode.
Must be the exact amount of symbols needed to encode the data.
:return: List of the symbol values representi... |
def read_environment_file(envfile=None):
"""
Read a .env file into os.environ.
If not given a path to a envfile path, does filthy magic stack backtracking
to find manage.py and then find the envfile.
"""
if envfile is None:
frame = sys._getframe()
envfile = os.path.join(os.path.... | Read a .env file into os.environ.
If not given a path to a envfile path, does filthy magic stack backtracking
to find manage.py and then find the envfile. |
def get_profile_data(self, auth_response):
""" Retrieve profile data from provider """
res = auth_response
token = res.get('access_token')
me = res.get('user')
if not me.get('id'):
raise x.UserException('Instagram must return a user id')
data = dict(
... | Retrieve profile data from provider |
def check_background(qpi):
"""Check QPimage background data
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
for imdat in [qpi._amp, qpi._pha]:
try:
fit, attrs = imdat.get_bg(key="fit", ret_attrs=Tr... | Check QPimage background data
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails |
def authorized_http(client_id, client_secret, apps, file=None):
"""
Start an authorized HTTP session.
Try fetching valid user credentials from storage. If nothing has been
stored, or if the stored credentials are invalid, complete the OAuth2 flow
to obtain new credentials.
"""
if not os.pat... | Start an authorized HTTP session.
Try fetching valid user credentials from storage. If nothing has been
stored, or if the stored credentials are invalid, complete the OAuth2 flow
to obtain new credentials. |
def fourier_sinusoidal_residual(fourierparams, times, mags, errs):
'''
This returns the residual between the model mags and the actual mags.
Parameters
----------
fourierparams : list
This MUST be a list of the following form like so::
[period,
epoch,
... | This returns the residual between the model mags and the actual mags.
Parameters
----------
fourierparams : list
This MUST be a list of the following form like so::
[period,
epoch,
[amplitude_1, amplitude_2, amplitude_3, ..., amplitude_X],
[phase... |
def perform(self):
"""
Performs a simple HTTP request against the configured url and returns
true if the response has a 2xx code.
The url can be configured to use https via the "https" boolean flag
in the config, as well as a custom HTTP method via the "method" key.
The... | Performs a simple HTTP request against the configured url and returns
true if the response has a 2xx code.
The url can be configured to use https via the "https" boolean flag
in the config, as well as a custom HTTP method via the "method" key.
The default is to not use https and the GE... |
def concat_excel_reports(addresses, output_file_name, endpoint, report_type,
retry, api_key, api_secret, files_path):
"""Creates an Excel file made up of combining the Value Report or Rental Report Excel
output for the provided addresses.
Args:
addresses: A list of (addr... | Creates an Excel file made up of combining the Value Report or Rental Report Excel
output for the provided addresses.
Args:
addresses: A list of (address, zipcode) tuples
output_file_name: A file name for the Excel output
endpoint: One of 'value_report' or 'rental_report'
rep... |
def train(self, sentences, nr_iter=5):
"""Train a model from sentences.
:param sentences: A list of sentences, each of which is a list of (token, tag) tuples.
:param nr_iter: Number of training iterations.
"""
self._make_tagdict(sentences)
self.perceptron.classes = self.... | Train a model from sentences.
:param sentences: A list of sentences, each of which is a list of (token, tag) tuples.
:param nr_iter: Number of training iterations. |
def handleFlow(self):
#TODO replace sorting loops with sorted function
self.targets = {}
self.api = []
#flow = []
addrs = []
internals = []
for instr in self.bb_insns:
if isinstance(instr, CallInsn):
... | for f in flow:
print f
for pp in self.bb_insns:
print pp |
def detach(self, connection_info):
"""Detach a volume from a guest
"""
fcp = connection_info['zvm_fcp']
fcp = fcp.lower()
target_wwpn = connection_info['target_wwpn']
target_lun = connection_info['target_lun']
assigner_id = connection_info['assigner_id']
a... | Detach a volume from a guest |
async def send_audio(self, chat_id: typing.Union[base.Integer, base.String],
audio: typing.Union[base.InputFile, base.String],
caption: typing.Union[base.String, None] = None,
parse_mode: typing.Union[base.String, None] = None,
... | Use this method to send audio files, if you want Telegram clients to display them in the music player.
Your audio must be in the .mp3 format.
For sending voice messages, use the sendVoice method instead.
Source: https://core.telegram.org/bots/api#sendaudio
:param chat_id: Unique ident... |
def serve_forever(self, poll_interval=0.5):
""" Wait for incomming requests. """
self.serial_port.timeout = poll_interval
while not self._shutdown_request:
try:
self.serve_once()
except (CRCError, struct.error) as e:
log.error('Can\'t hand... | Wait for incomming requests. |
def view_call(method_name, *args, **kwargs):
"""
Creates an effect that will drop the current effect value,
call the view's method with specified name
with the specified arguments and keywords.
@param method_name: the name of method belonging to the view.
@type method_name: str
"""
def ... | Creates an effect that will drop the current effect value,
call the view's method with specified name
with the specified arguments and keywords.
@param method_name: the name of method belonging to the view.
@type method_name: str |
def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None):
"""
Print a tree of nodes. This is like render_tree, except it prints
lines directly instead of creating a string representation in memory,
so that huge trees can be printed.
:Parameters:
- `root` - the ... | Print a tree of nodes. This is like render_tree, except it prints
lines directly instead of creating a string representation in memory,
so that huge trees can be printed.
:Parameters:
- `root` - the root node of the tree
- `child_func` - the function called to get the children of a n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.