code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_ipv6_neighbors_table(self):
"""
Get IPv6 neighbors table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float) in seconds
* state (string)
... | Get IPv6 neighbors table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float) in seconds
* state (string)
For example::
[
{
... |
def updateQTable( self, reward, current_state ):
"""Change q_table to reflect what we have learnt."""
# retrieve the old action value from the Q-table (indexed by the previous state and the previous action)
old_q = self.q_table[self.prev_s][self.prev_a]
# TODO: what sho... | Change q_table to reflect what we have learnt. |
def get_stack_data(self, frame, traceback, event_type):
"""Get the stack frames data at each of the hooks above (Ie. for each
line of the Python code)"""
heap_data = Heap(self.options)
stack_data = StackFrames(self.options)
stack_frames, cur_frame_ind = self.get_stack(frame, trac... | Get the stack frames data at each of the hooks above (Ie. for each
line of the Python code) |
def _ffi_module(self):
"""Load the native engine as a python module and register CFFI externs."""
native_bin_dir = os.path.dirname(self.binary)
logger.debug('loading native engine python module from: %s', native_bin_dir)
sys.path.insert(0, native_bin_dir)
return importlib.import_module(NATIVE_ENGINE... | Load the native engine as a python module and register CFFI externs. |
def filter_benchmarks(benchmarks, bench_funcs, base_ver):
"""Filters out benchmarks not supported by both Pythons.
Args:
benchmarks: a set() of benchmark names
bench_funcs: dict mapping benchmark names to functions
python: the interpereter commands (as lists)
Returns:
The f... | Filters out benchmarks not supported by both Pythons.
Args:
benchmarks: a set() of benchmark names
bench_funcs: dict mapping benchmark names to functions
python: the interpereter commands (as lists)
Returns:
The filtered set of benchmark names |
def _write_config_file(items, global_vars, template, project_name, out_dir,
remotes):
"""Write configuration file, adding required top level attributes.
"""
config_dir = utils.safe_makedir(os.path.join(out_dir, "config"))
out_config_file = os.path.join(config_dir, "%s.yaml" % proj... | Write configuration file, adding required top level attributes. |
def write(self, path, data, offset=0, timeout=0):
"""write data at path
path is a string, data binary; it is responsability of the caller
ensure proper encoding.
"""
# fixme: check of path type delayed to str2bytez
if not isinstance(data, (bytes, bytearray, )):
... | write data at path
path is a string, data binary; it is responsability of the caller
ensure proper encoding. |
def flatFieldFromCloseDistance(imgs, bg_imgs=None):
'''
Average multiple images of a homogeneous device
imaged directly in front the camera lens.
if [bg_imgs] are not given, background level is extracted
from 1% of the cumulative intensity distribution
of the averaged [imgs]
... | Average multiple images of a homogeneous device
imaged directly in front the camera lens.
if [bg_imgs] are not given, background level is extracted
from 1% of the cumulative intensity distribution
of the averaged [imgs]
This measurement method is referred as 'Method A' in
---
... |
def savez_two_column(matrix, row_offset, file_name, append=False):
"""Savez_compressed obj to file_name."""
logging.info("Saving obj to file in two column .npz format %s.", file_name)
tc = []
for u, items in enumerate(matrix):
user = row_offset + u
for item in items:
tc.append([user, item])
n... | Savez_compressed obj to file_name. |
def DbGetPropertyHist(self, argin):
""" Retrieve object property history
:param argin: Str[0] = Object name
Str[2] = Property name
:type: tango.DevVarStringArray
:return: Str[0] = Property name
Str[1] = date
Str[2] = Property value number (array case)
St... | Retrieve object property history
:param argin: Str[0] = Object name
Str[2] = Property name
:type: tango.DevVarStringArray
:return: Str[0] = Property name
Str[1] = date
Str[2] = Property value number (array case)
Str[3] = Property value 1
Str[n] = Propert... |
def delete_customer(self, handle):
"""Delete a customer."""
self.request(E.deleteCustomerRequest(E.handle(handle)))
return True | Delete a customer. |
async def send_webmention(self, entry, url):
""" send a webmention from an entry to a URL """
if (entry.url, url) in self._processed_mentions:
LOGGER.debug(
"Skipping already processed mention %s -> %s", entry.url, url)
self._processed_mentions.add((entry.url, url))
... | send a webmention from an entry to a URL |
def timed_cache(timeout, max_size=128):
"""
Time based decorator, implementing :class:`faste.caches.TimeoutCache`
:param int timeout: Cache key timeout
:param int max_size: (keyword) max size.
"""
def actual_decorator(func):
return _cached_func(func, caches.TimeoutCache, timeout, max_... | Time based decorator, implementing :class:`faste.caches.TimeoutCache`
:param int timeout: Cache key timeout
:param int max_size: (keyword) max size. |
def Morsi_Alexander(Re):
r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} & \mbox{if $Re < 0.1$}\\
\frac{22.73}{Re}+\frac{0.0903}{Re^2} + 3.69 & \mbox{if $0.1 < Re < 1$}\\
... | r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} & \mbox{if $Re < 0.1$}\\
\frac{22.73}{Re}+\frac{0.0903}{Re^2} + 3.69 & \mbox{if $0.1 < Re < 1$}\\
\frac{29.1667}{Re}-\frac{3.... |
def vinet_dPdV(v, v0, k0, k0p, precision=1.e-5):
"""
calculate dP/dV for numerical calculation of bulk modulus
according to test this differs from analytical result by 1.e-5
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference condit... | calculate dP/dV for numerical calculation of bulk modulus
according to test this differs from analytical result by 1.e-5
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at r... |
def _save_and_log_checkpoint(self, actor):
"""Save an actor checkpoint if necessary and log any errors.
Args:
actor: The actor to checkpoint.
Returns:
The result of the actor's user-defined `save_checkpoint` method.
"""
actor_id = self._worker.actor_id
... | Save an actor checkpoint if necessary and log any errors.
Args:
actor: The actor to checkpoint.
Returns:
The result of the actor's user-defined `save_checkpoint` method. |
def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs if p.key not in ('data')}
d['secret'] = 'not available'
if self.secret_password:
... | A dict that holds key/values for all of the properties in the
object.
:return: |
def _convert_series(self, metric, ts):
"""Convert an OC timeseries to a SD series."""
series = monitoring_v3.types.TimeSeries()
series.metric.type = self.get_metric_type(metric.descriptor)
for lk, lv in self.options.default_monitoring_labels.items():
series.metric.labels[lk.... | Convert an OC timeseries to a SD series. |
def get_object(cls, api_token, droplet_id):
"""Class method that will return a Droplet object by ID.
Args:
api_token (str): token
droplet_id (int): droplet id
"""
droplet = cls(token=api_token, id=droplet_id)
droplet.load()
return droplet | Class method that will return a Droplet object by ID.
Args:
api_token (str): token
droplet_id (int): droplet id |
def update(self):
'''
Update our object's data
'''
self._json = self._request(
method='GET',
url=self.API
)._json | Update our object's data |
def _process_gxd_genotype_view(self, limit=None):
"""
This table indicates the relationship between a genotype
and it's background strain. It leverages the Genotype class methods
to do this.
Makes these triples:
<MGI:genotypeid> GENO:has_reference_part <MGI:strainid>
... | This table indicates the relationship between a genotype
and it's background strain. It leverages the Genotype class methods
to do this.
Makes these triples:
<MGI:genotypeid> GENO:has_reference_part <MGI:strainid>
<MGI:strainid> a GENO:genomic_background
If the genotyp... |
def main(handwriting_datasets_file, analyze_features):
"""Start the creation of the wanted metric."""
# Load from pickled file
logging.info("Start loading data '%s' ...", handwriting_datasets_file)
loaded = pickle.load(open(handwriting_datasets_file))
raw_datasets = loaded['handwriting_datasets']
... | Start the creation of the wanted metric. |
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
port=None, fatal=True,
username="testuser1", password="changeme"):
"""Establish and return a pika amqp connection to the rabbitmq service
running on a rmq juju unit.
:param sentry_un... | Establish and return a pika amqp connection to the rabbitmq service
running on a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:param fatal: boolean, default to True (raises on connect er... |
def compute_statistic(self, layout):
"""
Compute & return statistics for this layer
"""
data = self.data
if not len(data):
return type(data)()
params = self.stat.setup_params(data)
data = self.stat.use_defaults(data)
data = self.stat.setup_dat... | Compute & return statistics for this layer |
def _get_localzone(_root='/'):
"""Tries to find the local timezone configuration.
This method prefers finding the timezone name and passing that to pytz,
over passing in the localtime file, as in the later case the zoneinfo
name is unknown.
The parameter _root makes the function look for files lik... | Tries to find the local timezone configuration.
This method prefers finding the timezone name and passing that to pytz,
over passing in the localtime file, as in the later case the zoneinfo
name is unknown.
The parameter _root makes the function look for files like /etc/localtime
beneath the _root... |
def data_to_tfrecord(images, labels, filename):
"""Save data into TFRecord."""
if os.path.isfile(filename):
print("%s exists" % filename)
return
print("Converting data into %s ..." % filename)
# cwd = os.getcwd()
writer = tf.python_io.TFRecordWriter(filename)
for index, img in en... | Save data into TFRecord. |
def reverse(
self,
query,
exactly_one=DEFAULT_SENTINEL,
timeout=DEFAULT_SENTINEL,
feature_code=None,
lang=None,
find_nearby_type='findNearbyPlaceName',
):
"""
Return an address by location point.
.. vers... | Return an address by location point.
.. versionadded:: 1.2.0
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longitude)``, or string as ``"%(latit... |
def ensure_json_content_type(req, app):
"""
ErrorMiddleware returns hard-coded content-type text/html.
Here we force it to be application/json.
"""
res = req.get_response(app, catch_exc_info=True)
res.content_type = 'application/json; charset=utf-8'
return res | ErrorMiddleware returns hard-coded content-type text/html.
Here we force it to be application/json. |
def get_plugins(package_name, paths=None):
"""Find packages that are plugins of the given package.
Args:
package_name (str): Name of the package.
paths (list of str): Paths to search for packages, defaults to
`config.packages_path`.
Returns:
list of str: The packages th... | Find packages that are plugins of the given package.
Args:
package_name (str): Name of the package.
paths (list of str): Paths to search for packages, defaults to
`config.packages_path`.
Returns:
list of str: The packages that are plugins of the given package. |
def get_state(self):
"""Get general information about the state of the class"""
return {"started": (True if self.background_process and
self.background_process.is_alive() else False),
"paused": self._pause.value,
"stopped": self._end.value,
... | Get general information about the state of the class |
def parse_nni_variable(code):
"""Parse `nni.variable` expression.
Return the name argument and AST node of annotated expression.
code: annotation string
"""
name, call = parse_annotation_function(code, 'variable')
assert len(call.args) == 1, 'nni.variable contains more than one arguments'
a... | Parse `nni.variable` expression.
Return the name argument and AST node of annotated expression.
code: annotation string |
def _get_env(self, key):
"""Wrapper around os.getenv() which replaces characters
in the original key. This allows env vars which have different keys
than the config object keys.
"""
if self._env_key_replacer is not None:
key = key.replace(*self._env_key_replacer)
... | Wrapper around os.getenv() which replaces characters
in the original key. This allows env vars which have different keys
than the config object keys. |
def _cast_to_type(self, value):
""" Convert the value to a datetime and raise error on failures"""
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
value = datetime.datetime(value.year, value.month, value.day)
return v... | Convert the value to a datetime and raise error on failures |
def _generate_barcode_ids(info_iter):
"""Create unique barcode IDs assigned to sequences
"""
bc_type = "SampleSheet"
barcodes = list(set([x[-1] for x in info_iter]))
barcodes.sort()
barcode_ids = {}
for i, bc in enumerate(barcodes):
barcode_ids[bc] = (bc_type, i+1)
return barcode... | Create unique barcode IDs assigned to sequences |
def safe_format_sh(s, **kwargs):
"""
:type s str
"""
to_replace = set(kwargs.keys()) & set(FORMAT_RE.findall(s))
for item in to_replace:
s = s.replace("{{" + item + "}}", kwargs[item])
return s | :type s str |
def hot_questions(self):
"""获取话题下热门的问题
:return: 话题下的热门动态中的问题,按热门度顺序返回生成器
:rtype: Question.Iterable
"""
from .question import Question
hot_questions_url = Topic_Hot_Questions_Url.format(self.id)
params = {'start': 0, '_xsrf': self.xsrf}
res = self._session... | 获取话题下热门的问题
:return: 话题下的热门动态中的问题,按热门度顺序返回生成器
:rtype: Question.Iterable |
def set_release_actions(self, actions):
"""Set the widget that gives users options about the release, e.g. importing references
:param actions: Release actions that define the sanity checks and cleanup actions
:type actions: :class:`jukeboxcore.release.ReleaseActions`
:returns: None
... | Set the widget that gives users options about the release, e.g. importing references
:param actions: Release actions that define the sanity checks and cleanup actions
:type actions: :class:`jukeboxcore.release.ReleaseActions`
:returns: None
:rtype: None
:raises: None |
def get_adjacent_pathways(self, pathway):
"""Get the pathways adjacent to this pathway in the network
Parameters
-----------
pathway : str
Returns
-----------
list(str), a list of pathways adjacent to the input pathway
"""
vertex_id = self.pathwa... | Get the pathways adjacent to this pathway in the network
Parameters
-----------
pathway : str
Returns
-----------
list(str), a list of pathways adjacent to the input pathway |
def remove_properties(self):
"""
Removes the property layer, if exists
"""
node_prop = self.node.find('properties')
if node_prop is not None:
self.node.remove(node_prop) | Removes the property layer, if exists |
def QA_fetch_get_future_transaction(code, start, end, retry=4, ip=None, port=None):
'期货历史成交分笔'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extensio... | 期货历史成交分笔 |
def ecs_idsKEGG(organism):
"""
Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism
:param organism: an organisms as listed in organismsKEGG()
:returns: a Pandas dataframe of with 'ec' and 'KEGGid'.
"""
kegg_ec=urlopen("http://rest.kegg.jp/link/"+organism+"/enzyme").read... | Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism
:param organism: an organisms as listed in organismsKEGG()
:returns: a Pandas dataframe of with 'ec' and 'KEGGid'. |
def save_collection(png_filename_base, numpy_data, start_layers_at=1):
"""
Export a numpy array to a set of png files, with each Z-index 2D
array as its own 2D file.
Arguments:
png_filename_base: A filename template, such as "my-image-*.png"
which will lead t... | Export a numpy array to a set of png files, with each Z-index 2D
array as its own 2D file.
Arguments:
png_filename_base: A filename template, such as "my-image-*.png"
which will lead to a collection of files named
"my-image-0.png", "my... |
def switch_to_window(self, window_name=None, title=None, url=None):
"""
WebDriver implements switching to other window only by it's name. With
wrapper there is also option to switch by title of window or URL. URL
can be also relative path.
"""
if window_name:
... | WebDriver implements switching to other window only by it's name. With
wrapper there is also option to switch by title of window or URL. URL
can be also relative path. |
def dfa_to_dot(dfa: dict, name: str, path: str = './'):
""" Generates a DOT file and a relative SVG image in **path**
folder of the input DFA using graphviz library.
:param dict dfa: DFA to export;
:param str name: name of the output file;
:param str path: path where to save the DOT/SVG files (defa... | Generates a DOT file and a relative SVG image in **path**
folder of the input DFA using graphviz library.
:param dict dfa: DFA to export;
:param str name: name of the output file;
:param str path: path where to save the DOT/SVG files (default:
working directory) |
def flattening(Pot,R,z):
"""
NAME:
flattening
PURPOSE:
calculate the potential flattening, defined as sqrt(fabs(z/R F_R/F_z))
INPUT:
Pot - Potential instance or list thereof
R - Galactocentric radius (can be Quantity)
z - hei... | NAME:
flattening
PURPOSE:
calculate the potential flattening, defined as sqrt(fabs(z/R F_R/F_z))
INPUT:
Pot - Potential instance or list thereof
R - Galactocentric radius (can be Quantity)
z - height (can be Quantity)
OUTPUT:
... |
def set_error(self, error_shortmsg: str, error_longmsg: str):
""" Set the stage to error and add a message """
LOG.error(f"Update session: error in stage {self._stage.name}: "
f"{error_shortmsg}: {error_longmsg}")
self._error = Value(error_shortmsg, error_longmsg)
self.... | Set the stage to error and add a message |
def get_points(self):
"""Returns a ketama compatible list of (position, nodename) tuples.
"""
return [(k, self.runtime._ring[k]) for k in self.runtime._keys] | Returns a ketama compatible list of (position, nodename) tuples. |
def get_column_type(column, column_values):
"""
Returns the type of the given column based on its row values on the given RunSetResult.
@param column: the column to return the correct ColumnType for
@param column_values: the column values to consider
@return: a tuple of a type object describing the ... | Returns the type of the given column based on its row values on the given RunSetResult.
@param column: the column to return the correct ColumnType for
@param column_values: the column values to consider
@return: a tuple of a type object describing the column - the concrete ColumnType is stored in the attrib... |
def _notifyDone(self):
'''
Allow any other editatoms waiting on me to complete to resume
'''
if self.notified:
return
self.doneevent.set()
for buid in self.mybldgbuids:
del self.allbldgbuids[buid]
self.notified = True | Allow any other editatoms waiting on me to complete to resume |
def pkill():
"""Kill all of FIO processes"""
if env():
return 1
cmd = ["ps -aux | grep fio | grep -v grep"]
status, _, _ = cij.ssh.command(cmd, shell=True, echo=False)
if not status:
status, _, _ = cij.ssh.command(["pkill -f fio"], shell=True)
if status:
return ... | Kill all of FIO processes |
def _read_syntax_quoted(ctx: ReaderContext) -> ReaderForm:
"""Read a syntax-quote and set the syntax-quoting state in the reader."""
start = ctx.reader.advance()
assert start == "`"
with ctx.syntax_quoted():
return _process_syntax_quoted_form(ctx, _read_next_consuming_comment(ctx)) | Read a syntax-quote and set the syntax-quoting state in the reader. |
def dump2sqlite(records, output_file):
"""Dumps tests results to database."""
results_keys = list(records.results[0].keys())
pad_data = []
for key in REQUIRED_KEYS:
if key not in results_keys:
results_keys.append(key)
pad_data.append("")
conn = sqlite3.connect(os.pa... | Dumps tests results to database. |
def land_address(self):
"""
:example 세종특별자치시 어진동 507
"""
pattern = self.random_element(self.land_address_formats)
return self.generator.parse(pattern) | :example 세종특별자치시 어진동 507 |
def get_long_description():
""" Read the long description. """
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as readme:
return readme.read()
return None | Read the long description. |
def handle_callback_exception(self, callback):
"""This method is called whenever a callback run by the `IOLoop`
throws an exception.
By default simply logs the exception as an error. Subclasses
may override this method to customize reporting of exceptions.
The exception itself... | This method is called whenever a callback run by the `IOLoop`
throws an exception.
By default simply logs the exception as an error. Subclasses
may override this method to customize reporting of exceptions.
The exception itself is not passed explicitly, but is available
in `sy... |
def time2isoz(t=None):
"""Return a string representing time in seconds since epoch, t.
If the function is called without an argument, it will use the current
time.
The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
representing Universal Time (UTC, aka GMT). An example of this form... | Return a string representing time in seconds since epoch, t.
If the function is called without an argument, it will use the current
time.
The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
representing Universal Time (UTC, aka GMT). An example of this format is:
1994-11-24 08:49:3... |
def move_if_not_on_dow(original, replacement, dow_not_orig, dow_replacement):
"""
Return a lambda function.
Lambda checks that either the original day does not fall on a given
weekday, or that the replacement day does fall on the expected weekday.
"""
return lambda x: (
(x.hdate.day == ... | Return a lambda function.
Lambda checks that either the original day does not fall on a given
weekday, or that the replacement day does fall on the expected weekday. |
def set_tenant(self, tenant, include_public=True):
"""
Main API method to current database schema,
but it does not actually modify the db connection.
"""
self.set_schema(tenant.schema_name, include_public)
self.tenant = tenant | Main API method to current database schema,
but it does not actually modify the db connection. |
def cli(env):
"""List object storage accounts."""
mgr = SoftLayer.ObjectStorageManager(env.client)
accounts = mgr.list_accounts()
table = formatting.Table(['id', 'name', 'apiType'])
table.sortby = 'id'
api_type = None
for account in accounts:
if 'vendorName' in account and account['... | List object storage accounts. |
async def get_top_clans(self):
'''Get a list of top clans, info is only brief,
call get_clan() on each of the ClanInfo objects
to get full clan info'''
url = self.BASE + '/top/clans'
data = await self.request(url)
return [ClanInfo(self, c) for c in data.get('clans')] | Get a list of top clans, info is only brief,
call get_clan() on each of the ClanInfo objects
to get full clan info |
def get_device(self, device_id, refresh=False):
"""Get a single device."""
if self._devices is None:
self.get_devices()
refresh = False
device = self._devices.get(device_id)
if device and refresh:
device.refresh()
return device | Get a single device. |
def format_location(ctx, text):
"""
Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary
"""
text = conversions.to_string(text, ctx)
return text.split(">")[-1].strip() | Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary |
def compute_average_regress(x, idx_chan):
"""Take the mean across channels and regress out the mean from each channel
Parameters
----------
x : ndarray
2d array with channels on one dimension
idx_chan:
which axis contains channels
Returns
-------
ndarray
same as... | Take the mean across channels and regress out the mean from each channel
Parameters
----------
x : ndarray
2d array with channels on one dimension
idx_chan:
which axis contains channels
Returns
-------
ndarray
same as x, but with the mean being regressed out |
def job(self):
"""REST binding for the job associated with the submitted build.
Returns:
Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted.
"""
if self._submitter and hasattr(self._submitter, '_job_access'):
... | REST binding for the job associated with the submitted build.
Returns:
Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted. |
def __deactivate_recipes(self, plugin, *args, **kwargs):
"""
Deactivates/unregisters all recipes of the current plugin, if this plugin gets deactivated.
"""
recipes = self.get()
for recipe in recipes.keys():
self.unregister(recipe) | Deactivates/unregisters all recipes of the current plugin, if this plugin gets deactivated. |
def other_Orange_tables(self):
'''
Returns the related tables as Orange example tables.
:rtype: list
'''
target_table = self.db.target_table
if not self.db.orng_tables:
return [self.convert_table(table, None) for table in self.db.tables if table != ta... | Returns the related tables as Orange example tables.
:rtype: list |
def nested_option(default=False):
""" Attaches the option ``nested`` with its *default* value to the
keyword arguments when the option does not exist. All positional
arguments and keyword arguments are forwarded unchanged.
"""
def decorator(method):
@wraps(method)
def wrapper(*args,... | Attaches the option ``nested`` with its *default* value to the
keyword arguments when the option does not exist. All positional
arguments and keyword arguments are forwarded unchanged. |
def _get_guidelines(self):
"""
Subclasses may override this method.
"""
return tuple([self._getitem__guidelines(i) for
i in range(self._len__guidelines())]) | Subclasses may override this method. |
def bounding_boxes(self, mode='fraction', output='dict'):
"""Get the bounding boxes of the labels on a page.
Parameters
----------
mode: 'fraction', 'actual'
If 'fraction', the bounding boxes are expressed as a fraction of the
height and width of the sheet. If 'a... | Get the bounding boxes of the labels on a page.
Parameters
----------
mode: 'fraction', 'actual'
If 'fraction', the bounding boxes are expressed as a fraction of the
height and width of the sheet. If 'actual', they are the actual
position of the labels in mil... |
def ifetch_single(iterable, key, default=EMPTY, getter=None):
"""
getter() g(item, key):pass
"""
def _getter(item):
if getter:
custom_getter = partial(getter, key=key)
return custom_getter(item)
else:
try:
attrgetter = operator.attrget... | getter() g(item, key):pass |
def concatenate(cls, *args):
"""Concatenates an arbitrary number of meshes.
Currently supports vertices, vertex colors, and faces.
"""
nargs = len(args)
if nargs == 1:
return args[0]
vs = [a.v for a in args if a.v is not None]
vcs = [a.vc for a in ar... | Concatenates an arbitrary number of meshes.
Currently supports vertices, vertex colors, and faces. |
def app(config, src, dst, features, reload, force):
"""Takes several files or directories as src and generates the code
in the given dst directory."""
config = Path(config)
if reload:
argv = sys.argv.copy()
argv.remove('--reload')
monitor(config.dirname(), src, dst, argv)
els... | Takes several files or directories as src and generates the code
in the given dst directory. |
def select(self):
'''If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot'''
if not hasattr(self._gdbframe, 'select'):
print ('Unabl... | If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot |
def get_distro_info(self, loglevel=logging.DEBUG):
"""Get information about which distro we are using, placing it in the environment object.
Fails if distro could not be determined.
Should be called with the container is started up, and uses as core info
as possible.
Note: if the install type is apt, it iss... | Get information about which distro we are using, placing it in the environment object.
Fails if distro could not be determined.
Should be called with the container is started up, and uses as core info
as possible.
Note: if the install type is apt, it issues the following:
- apt-get update
- apt-ge... |
def move(self, particle, u, v, w, modelTimestep, **kwargs):
""" I'm dead, so no behaviors should act on me """
# Kill the particle if it isn't settled and isn't already dead.
if not particle.settled and not particle.dead:
particle.die()
# Still save the temperature and sali... | I'm dead, so no behaviors should act on me |
def ifelse(self, yes, no):
"""
Equivalent to ``[y if t else n for t,y,n in zip(self,yes,no)]``.
Based on the booleans in the test vector, the output has the values of the
yes and no vectors interleaved (or merged together). All Frames must have
the same row count. Single colum... | Equivalent to ``[y if t else n for t,y,n in zip(self,yes,no)]``.
Based on the booleans in the test vector, the output has the values of the
yes and no vectors interleaved (or merged together). All Frames must have
the same row count. Single column frames are broadened to match wider
F... |
def get_by(cls, **kwargs):
'''
This method offers a simple query method for fetching entities of this
type via attribute numeric ranges (such columns must be ``indexed``),
or via ``unique`` columns.
Some examples::
user = User.get_by(email_address='user@domain.com')... | This method offers a simple query method for fetching entities of this
type via attribute numeric ranges (such columns must be ``indexed``),
or via ``unique`` columns.
Some examples::
user = User.get_by(email_address='user@domain.com')
# gets up to 25 users created in t... |
def run(files, temp_folder):
"Check frosted errors in the code base."
try:
import frosted # NOQA
except ImportError:
return NO_FROSTED_MSG
py_files = filter_python_files(files)
cmd = 'frosted {0}'.format(' '.join(py_files))
return bash(cmd).value() | Check frosted errors in the code base. |
def get_n_tail(tmax, tail_temps):
"""determines number of included tail checks in best fit segment"""
#print "tail_temps: {0}, tmax: {0}".format(tail_temps, tmax)
t_index = 0
adj_tmax = 0
if tmax < tail_temps[0]:
return 0
try:
t_index = list(tail_temps).index(tmax)
except: # ... | determines number of included tail checks in best fit segment |
def value(self, progress_indicator):
""" Interpolate linearly between start and end """
return interpolate.interpolate_linear_single(self.initial_value, self.final_value, progress_indicator) | Interpolate linearly between start and end |
def ordinal_float(dt):
"""Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1... | Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1, 2, 3, 4, 5, 6, 7)) # doctes... |
def make_taxonomy_dict(classification, parent=False):
"""
Takes a classification data frame returned by the API and parses it
into a dictionary mapping a tax_id to its children (or parent).
Restricted to tax_id's that are represented in the classification
results.
"""
tax_id_map = {}
i... | Takes a classification data frame returned by the API and parses it
into a dictionary mapping a tax_id to its children (or parent).
Restricted to tax_id's that are represented in the classification
results. |
def _decrypt_object(obj, **kwargs):
'''
Recursively try to decrypt any object. If the object is a six.string_types
(string or unicode), and it contains a valid NACLENC pretext, decrypt it,
otherwise keep going until a string is found.
'''
if salt.utils.stringio.is_readable(obj):
return _... | Recursively try to decrypt any object. If the object is a six.string_types
(string or unicode), and it contains a valid NACLENC pretext, decrypt it,
otherwise keep going until a string is found. |
def portable_b64encode(thing):
"""Wrap b64encode for Python 2 & 3"""
if is_py3():
try:
some_bits = bytes(thing, 'utf-8')
except TypeError:
some_bits = thing
return polite_string(b64encode(some_bits).decode('utf-8'))
return polite_string(b64encode(thing)) | Wrap b64encode for Python 2 & 3 |
def simplejson_datetime_serializer(obj):
"""
Designed to be passed as the default kwarg in simplejson.dumps. Serializes dates and datetimes to ISO strings.
"""
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError('Object of type %s with value of %s is not JSON ... | Designed to be passed as the default kwarg in simplejson.dumps. Serializes dates and datetimes to ISO strings. |
def push_back(self, value):
'''Appends a copy of *value* at the end of the :class:`Sequence`.'''
self.cache.push_back(self.value_pickler.dumps(value))
return self | Appends a copy of *value* at the end of the :class:`Sequence`. |
def _getAlias(self, auth_level_uri):
"""Return the alias for the specified auth level URI.
@raises KeyError: if no alias is defined
"""
for (alias, existing_uri) in self.auth_level_aliases.items():
if auth_level_uri == existing_uri:
return alias
rais... | Return the alias for the specified auth level URI.
@raises KeyError: if no alias is defined |
def _view_use_legacy_sql_getter(table):
"""bool: Specifies whether to execute the view with Legacy or Standard SQL.
This boolean specifies whether to execute the view with Legacy SQL
(:data:`True`) or Standard SQL (:data:`False`). The client side default is
:data:`False`. The server-side default is :da... | bool: Specifies whether to execute the view with Legacy or Standard SQL.
This boolean specifies whether to execute the view with Legacy SQL
(:data:`True`) or Standard SQL (:data:`False`). The client side default is
:data:`False`. The server-side default is :data:`True`. If this table is
not a view, :da... |
def _add_gmaf(self, variant_obj, gemini_variant):
"""Add the gmaf frequency
Args:
variant_obj (puzzle.models.Variant)
gemini_variant (GeminiQueryRow)
"""
max_af = gemini_variant['max_aaf_all']
if max_af:
max_af = float(max_af)... | Add the gmaf frequency
Args:
variant_obj (puzzle.models.Variant)
gemini_variant (GeminiQueryRow) |
def _ConvertBool(value, require_str):
"""Convert a boolean value.
Args:
value: A scalar value to convert.
require_str: If True, value must be a str.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
if require_str:
if value == 'true':
ret... | Convert a boolean value.
Args:
value: A scalar value to convert.
require_str: If True, value must be a str.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed. |
def example_reading_spec(self):
"""Data fields to store on disk and their decoders."""
# Subclasses can override and/or extend.
processed_reward_type = tf.float32
if self.is_processed_rewards_discrete:
processed_reward_type = tf.int64
data_fields = {
TIMESTEP_FIELD: tf.FixedLenFeatu... | Data fields to store on disk and their decoders. |
def _parse_indices(self):
"""Parse a sequence of Fortran vector indices as a list of tuples."""
v_name = self.prior_token
v_indices = []
while self.token in (',', '('):
v_indices.append(self._parse_index(v_name))
return v_indices | Parse a sequence of Fortran vector indices as a list of tuples. |
def warning(*tokens: Token, **kwargs: Any) -> None:
""" Print a warning message """
tokens = [brown, "Warning:"] + list(tokens) # type: ignore
kwargs["fileobj"] = sys.stderr
message(*tokens, **kwargs) | Print a warning message |
def filter_by_months_per_hour(self, months_per_hour):
"""Filter the Data Collection based on a list of months per hour (as strings).
Args:
months_per_hour: A list of tuples representing months per hour.
Each tuple should possess two values: the first is the month
... | Filter the Data Collection based on a list of months per hour (as strings).
Args:
months_per_hour: A list of tuples representing months per hour.
Each tuple should possess two values: the first is the month
and the second is the hour. (eg. (12, 23) = December at 11 PM)
... |
def imageurl(self):
""" Return the URL of a png image of the 2D structure """
if self._imageurl is None:
self._imageurl = 'http://www.chemspider.com/ImagesHandler.ashx?id=%s' % self.csid
return self._imageurl | Return the URL of a png image of the 2D structure |
def fit_deriv(x, amplitude, mean, stddev):
"""
GaussianAbsorption1D model function derivatives.
"""
import operator
return list(map(
operator.neg, Gaussian1D.fit_deriv(x, amplitude, mean, stddev))) | GaussianAbsorption1D model function derivatives. |
def set_object(self, name: str, pobj: ParameterObject) -> None:
"""Add or update an existing object."""
self.objects[zlib.crc32(name.encode())] = pobj | Add or update an existing object. |
def flatten_dict(i):
"""
Any list item is converted to @number=value
Any dict item is converted to #key=value
# is always added at the beginning
Input: {
dict - python dictionary
(prefix) - prefix (for recursion)
(prune_keys) - list of keys ... | Any list item is converted to @number=value
Any dict item is converted to #key=value
# is always added at the beginning
Input: {
dict - python dictionary
(prefix) - prefix (for recursion)
(prune_keys) - list of keys to prune (can have wildcards)
... |
def drop(self, table_name = 'dumptruck', if_exists = False, **kwargs):
'Drop a table.'
return self.execute(u'DROP TABLE %s %s;' % ('IF EXISTS' if if_exists else '', quote(table_name)), **kwargs) | Drop a table. |
def main (args):
"""Usage: echo_sedml input-filename output-filename
"""
if len(args) != 3:
print(main.__doc__)
sys.exit(1)
d = libsedml.readSedML(args[1]);
if ( d.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0):
print (d.getErrorLog().toString());
else:
libsedml.wri... | Usage: echo_sedml input-filename output-filename |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.