text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def make_hash_id():
"""
Compute the `datetime.now` based SHA-1 hash of a string.
:return: Returns the sha1 hash as a string.
:rtype: str
"""
today = datetime.datetime.now().strftime(DATETIME_FORMAT)
return hashlib.sha1(today.encode('utf-8')).hexdigest() | 0.003546 |
def register_instance(self, obj, prefix=''):
"""Create new subdispatcher and register all public object methods on
it.
To be used in conjunction with the :py:func:`public`
decorator (*not* :py:func:`RPCDispatcher.public`).
:param obj: The object whose public methods should be m... | 0.002755 |
def get_live_data_dir():
"""
pygeth needs a base directory to store it's chain data. By default this is
the directory that `geth` uses as it's `datadir`.
"""
if sys.platform == 'darwin':
data_dir = os.path.expanduser(os.path.join(
"~",
"Library",
"Ethereu... | 0.001075 |
def _badlink(info, base):
"""
Links are interpreted relative to the directory containing the link
"""
tip = _resolved(os.path.join(base, os.path.dirname(info.name)))
return _badpath(info.linkname, base=tip) | 0.004425 |
def set_checkpoint(self, checkpoint_trigger,
checkpoint_path, isOverWrite=True):
"""
Configure checkpoint settings.
:param checkpoint_trigger: the interval to write snapshots
:param checkpoint_path: the path to write snapshots into
:param isOverWrite: whe... | 0.006494 |
def updateCorpInfo(self, CorpNum, CorpInfo, UserID=None):
""" ๋ด๋น์ ์ ๋ณด ์์
args
CorpNum : ํ์ ์ฌ์
์๋ฒํธ
CorpInfo : ํ์ฌ ์ ๋ณด, Reference CorpInfo class
UserID : ํ์ ์์ด๋
return
์ฒ๋ฆฌ๊ฒฐ๊ณผ. consist of code and message
raise
... | 0.004246 |
def list_upcoming(cls):
"""
Returns a collection of upcoming tasks (tasks that have not yet been completed,
regardless of whether theyโre overdue) for the authenticated user
:return:
:rtype: list
"""
return fields.ListField(name=cls.ENDPOINT, init_class=cls).deco... | 0.006536 |
def writeFailure(failure, logger=None):
"""
Write a L{twisted.python.failure.Failure} to the log.
This is for situations where you got an unexpected exception and want to
log a traceback. For example, if you have C{Deferred} that might error,
you'll want to wrap it with a L{eliot.twisted.DeferredCo... | 0.001072 |
def GetHasherNamesFromString(cls, hasher_names_string):
"""Retrieves a list of a hasher names from a comma separated string.
Takes a string of comma separated hasher names transforms it to a list of
hasher names.
Args:
hasher_names_string (str): comma separated names of hashers to enable,
... | 0.00677 |
def _resolve_duplicates(self):
'''
Merge variables connected by identity operator to reduce the number of redundant variables
'''
self._initialize_graph_status_for_traversing()
# Traverse the graph from roots to leaves
for operator in self.topological_operator_iterator()... | 0.003944 |
def create_contact(self, *args, **kwargs):
"""Creates a contact"""
url = 'contacts.json'
contact_data = {
'active': True,
'helpdesk_agent': False,
'description': 'Freshdesk Contact'
}
contact_data.update(kwargs)
payload = {
... | 0.004762 |
def put_metadata(self, key, value, namespace='default'):
"""
Add metadata to the current active trace entity.
Metadata is not indexed but can be later retrieved
by BatchGetTraces API.
:param str namespace: optional. Default namespace is `default`.
It must be a string... | 0.003125 |
def load(
inputobj,
c="gold",
alpha=None,
wire=False,
bc=None,
texture=None,
smoothing=None,
threshold=None,
connectivity=False,
):
"""
Returns a ``vtkActor`` from reading a file, directory or ``vtkPolyData``.
:param c: color in RGB format, hex, symbol or name
:param... | 0.000525 |
def center_at(self, x, y):
"""Center the menu at x, y"""
self.x = x - (self.width / 2)
self.y = y - (self.height / 2) | 0.014085 |
def setDataFrame(self, dataFrame, copyDataFrame=False, filePath=None):
"""
Setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.D... | 0.003953 |
def markdown(text, renderer=None, **options):
"""
Parses the provided Markdown-formatted text into valid HTML, and returns
it as a :class:`flask.Markup` instance.
:param text: Markdown-formatted text to be rendered into HTML
:param renderer: A custom misaka renderer to be used instead of the defaul... | 0.003774 |
def call_moses_detokenizer(workspace_dir: str, input_fname: str, output_fname: str, lang_code: Optional[str] = None):
"""
Call Moses detokenizer.
:param workspace_dir: Workspace third-party directory where Moses
tokenizer is checked out.
:param input_fname: Path of tokenized i... | 0.002894 |
def add_signature(key, inputs, outputs):
"""Adds a signature to current graph.
Args:
key: Signature key as a string.
inputs: Signature inputs as a map from string to Tensor or SparseTensor.
outputs: Signature outputs as a map from string to Tensor or SparseTensor.
(Recall that a Variable is not a... | 0.008122 |
def version(*names, **kwargs):
'''
Common interface for obtaining the version of installed packages.
Accepts full or partial FMRI. If called using pkg_resource, full FMRI is required.
Partial FMRI is returned if the package is not installed.
CLI Example:
.. code-block:: bash
salt '*' ... | 0.002577 |
def bid(self, trade_id, bid, fast=False):
"""Make a bid.
:params trade_id: Trade id.
:params bid: Amount of credits You want to spend.
:params fast: True for fastest bidding (skips trade status & credits check).
"""
method = 'PUT'
url = 'trade/%s/bid' % trade_id
... | 0.004591 |
def bestfit(self):
"""
Returns a series with the bestfit values.
Example:
Series.bestfit()
Returns: series
The returned series contains a parameter
called 'formula' which includes the string representation
of the bestfit line.
"""
# statsmodel cannot be included on requirements.txt
# see https://g... | 0.057359 |
def set_fan_direction(self, direction):
"""
:param direction: a string one of ["forward", "reverse"]
:return: nothing
"""
desired_state = {"direction": direction}
response = self.api_interface.set_device_state(self, {
"desired_state": desired_state
})... | 0.005376 |
def get_arrays_from_file(params_file, params=None):
"""Reads the values of one or more parameters from an hdf file and
returns as a dictionary.
Parameters
----------
params_file : str
The hdf file that contains the values of the parameters.
params : {None, li... | 0.003228 |
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""... | 0.009119 |
def all_departed_units(self):
"""
Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasona... | 0.001793 |
def copy(self):
"""A shallow copy."""
# Could just ``return self.__class__(self)`` here instead, but the below is faster. It uses
# __new__ to create a copy instance while bypassing its __init__, which would result
# in copying this bidict's items into the copy instance one at a time. In... | 0.007813 |
def parse_child(self, node):
"""
Parses <Child>
@param node: Node containing the <Child> element
@type node: xml.etree.Element
"""
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('<Child> must specify a name.... | 0.003546 |
def bug_info(exc_type, exc_value, exc_trace):
"""Prints the traceback and invokes the ipython debugger on any exception
Only invokes ipydb if you are outside ipython or python interactive session.
So scripts must be called from OS shell in order for exceptions to ipy-shell-out.
Dependencies:
Nee... | 0.005028 |
def main(jlink_serial, device):
"""Main function.
Args:
jlink_serial (str): the J-Link serial number
device (str): the target CPU
Returns:
``None``
Raises:
JLinkException: on error
"""
buf = StringIO.StringIO()
jlink = pylink.JLink(log=buf.write, detailed_log=buf.w... | 0.002941 |
def reference_contexts_for_variants(
variants,
context_size,
transcript_id_whitelist=None):
"""
Extract a set of reference contexts for each variant in the collection.
Parameters
----------
variants : varcode.VariantCollection
context_size : int
Max of nucleotid... | 0.001074 |
def smart_device_selection(preferred_device_type=None):
"""Get a list of device environments that is suitable for use in MOT.
Basically this gets the total list of devices using all_devices() and applies a filter on it.
This filter does the following:
1) if the 'AMD Accelerated Par... | 0.007326 |
def encode(self, inputRow):
"""Encodes the given input row as a dict, with the
keys being the field names. This also adds in some meta fields:
'_category': The value from the category field (if any)
'_reset': True if the reset field was True (if any)
'_sequenceId': the value from the sequenceI... | 0.008839 |
def is_union(declaration):
"""
Returns True if declaration represents a C++ union
Args:
declaration (declaration_t): the declaration to be checked.
Returns:
bool: True if declaration represents a C++ union
"""
if not is_class(declaration):
return False
decl = class_... | 0.002375 |
def cov(self, x, y=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None):
"""Calculate the covariance matrix for x and y or more expressions, possibly on a grid defined by binby.
Either x and y are expressions, e.g:
>>> df.cov("x", "y")
Or only... | 0.002197 |
def make_single_template_plots(workflow, segs, data_read_name, analyzed_name,
params, out_dir, inj_file=None, exclude=None,
require=None, tags=None, params_str=None,
use_exact_inj_params=False):
"""Function for cre... | 0.003501 |
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
zoom parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another ... | 0.002868 |
async def peek(self):
"""
Look at a task without changing its state.
Always returns `True`.
"""
the_tuple = await self.queue.peek(self.tube, self.task_id)
self.update_from_tuple(the_tuple)
return True | 0.007722 |
def frombinary(self, s):
"""Decode the binary string into an in memory list.
S is a binary string."""
entrylen = struct.calcsize(self.ENTRYSTRUCT)
p = 0
while p<len(s):
(slen, dpos, dlen, ulen, flag, typcd) = struct.unpack(self.ENTRYSTRUCT,
... | 0.00765 |
def register_file(name, member, path, digest='', conn=None):
'''
Register a file in the package database
'''
close = False
if conn is None:
close = True
conn = init()
conn.execute('INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (
name,
'{0}/{1}'.... | 0.003273 |
def get_edges(self, indexed=None):
"""Edges of the mesh
Parameters
----------
indexed : str | None
If indexed is None, return (Nf, 3) array of vertex indices,
two per edge in the mesh.
If indexed is 'faces', then return (Nf, 3, 2) array of vertex... | 0.004381 |
def connect(self, *, db=None):
"""
A connected device can be switched to 'database mode' where the device will
not use the BACnet network but instead obtain its contents from a previously
stored database.
"""
if db:
self.poll(command="stop")
... | 0.012681 |
def download_cutout(self, reading, focus=None, needs_apcor=False):
"""
Downloads a cutout of the FITS image for a given source reading.
Args:
reading: ossos.astrom.SourceReading
The reading which will be the focus of the downloaded image.
focus: tuple(int, int)
... | 0.003346 |
def Lazarek_Black(m, D, mul, kl, Hvap, q=None, Te=None):
r'''Calculates heat transfer coefficient for film boiling of saturated
fluid in vertical tubes for either upward or downward flow. Correlation
is as shown in [1]_, and also reviewed in [2]_ and [3]_.
Either the heat flux or excess temperature... | 0.004977 |
def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None):
""" Return a new Retry object with incremented retry counters.
:param response: A response object, or None, if the server did not
return a response.
:type response: :class:`~urllib3.... | 0.00143 |
def last(col, ignorenulls=False):
"""Aggregate function: returns the last value in a group.
The function by default returns the last values it sees. It will return the last non-null
value it sees when ignoreNulls is set to true. If all values are null, then null is returned.
.. note:: The function is ... | 0.006908 |
def copy(cls, data):
"""Set the clipboard data ('Copy').
Parameters: data to set (string)
Optional: datatype if it's not a string
Returns: True / False on successful copy, Any exception raised (like
passes the NSPasteboardCommunicationError) should be caught
... | 0.001759 |
def get_service_name_resources(cls, service_name):
""" Get resource models by service name """
from django.apps import apps
resources = cls._registry[service_name]['resources'].keys()
return [apps.get_model(resource) for resource in resources] | 0.007246 |
def chk_qualifiers(self):
"""Check format of qualifier"""
if self.name == 'id2gos':
return
for ntd in self.associations:
# print(ntd)
qual = ntd.Qualifier
assert isinstance(qual, set), '{NAME}: QUALIFIER MUST BE A LIST: {NT}'.format(
... | 0.005988 |
def uuid(self):
""" Return UUID of logical volume
:return: str
"""
uuid_file = '/sys/block/%s/dm/uuid' % os.path.basename(os.path.realpath(self.volume_path()))
lv_uuid = open(uuid_file).read().strip()
if lv_uuid.startswith('LVM-') is True:
return lv_uuid[4:]
return lv_uuid | 0.037801 |
def _parse_expr(self):
"""
Generate sentence token trees from the current position to
the next closing parentheses / end of the list and return it
['1', '(', '2', '|', '3, ')'] -> ['1', [['2'], ['3']]]
['2', '|', '3'] -> [['2'], ['3']]
"""
# List of all gen... | 0.001147 |
def _setAxesNames(self, axisNames):
""" Sets the axesnames, combobox lables and updates the headers. Removes old values first.
The comboLables is the axes name + '-axis'
"""
for col, _ in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO):
self._setHeaderLabel(col, '')
... | 0.006897 |
def simple_round_factory(tol):
"""helper function for simple_round (a factory for simple_round functions)"""
def simple_round(*args, **kwds):
argstype = type(args)
_args = list(args)
_kwds = kwds.copy()
for i,j in enumerate(args): # args[0] is the class.
if isinstance... | 0.017673 |
async def send_cluster_commands(self, stack, raise_on_error=True, allow_redirections=True):
"""
Send a bunch of cluster commands to the redis cluster.
`allow_redirections` If the pipeline should follow `ASK` & `MOVED` responses
automatically. If set to false it will raise RedisClusterEx... | 0.006212 |
def mulmod(computation: BaseComputation) -> None:
"""
Modulo Multiplication
"""
left, right, mod = computation.stack_pop(num_items=3, type_hint=constants.UINT256)
if mod == 0:
result = 0
else:
result = (left * right) % mod
computation.stack_push(result) | 0.006711 |
def encode_async_options(async):
"""Encode Async options for JSON encoding."""
options = copy.deepcopy(async._options)
options['_type'] = reference_to_path(async.__class__)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = ... | 0.006158 |
def modify(self, pk=None, create_on_missing=False, **kwargs):
"""Modify an already existing object.
Fields in the resource's `identity` tuple can be used in lieu of a primary key for a lookup; in such a case,
only other fields are written.
To modify unique fields, you must use the prim... | 0.007373 |
def delegators_count(self, account):
"""
Get number of delegators for a specific representative **account**
.. version 8.0 required
:param account: Account to get number of delegators for
:type account: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.dele... | 0.004615 |
def delete(self, bucket=None, ignore=False):
"""https://github.com/frictionlessdata/tableschema-sql-py#storage
"""
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
elif bucket is None:
buckets = reversed(se... | 0.001899 |
async def tile(tile_number):
"""
Handles GET requests for a tile number.
:param int tile_number: Number of the tile between 0 and `max_tiles`^2.
:raises HTTPError: 404 if tile exceeds `max_tiles`^2.
"""
try:
tile = get_tile(tile_number)
except TileOutOfBoundsError:
abort(404... | 0.001575 |
def _try_coerce_args(self, values, other):
"""
Coerce values and other to int64, with null values converted to
iNaT. values is always ndarray-like, other may not be
Parameters
----------
values : ndarray-like
other : ndarray-like or scalar
Returns
... | 0.002125 |
def _extract_rpm_file(self, target_file, extract_path):
"""Extracts the rpm file.
:param target_file: the firmware file to be extracted from
:param extract_path: the path where extraction is supposed to happen
:raises: ImageExtractionFailed, if any issue with extraction
"""
if not os.path.exist... | 0.000805 |
def execute_command(self, *args, **options):
"Execute a command and return a parsed response"
pool = self.connection_pool
command_name = args[0]
connection = pool.get_connection(command_name, **options)
try:
connection.send_command(*args)
return self.parse... | 0.00266 |
def build_layout(self, dset_id: str):
"""
:param dset_id:
:return:
"""
all_fields = list(self.get_data(dset_id=dset_id).keys())
try:
field_reference = self.skd[dset_id].attrs('target')
except:
field_reference = all_fields[0]
field... | 0.000728 |
def _clear_namespace():
""" Clear names that are not part of the strict ES API
"""
ok_names = set(default_backend.__dict__)
ok_names.update(['gl2', 'glplus']) # don't remove the module
NS = globals()
for name in list(NS.keys()):
if name.lower().startswith('gl'):
if name not ... | 0.00277 |
def deriv(self, x: str, ctype: ContentType) -> SchemaPattern:
"""Return derivative of the receiver."""
return Alternative.combine(self.left.deriv(x, ctype),
self.right.deriv(x, ctype)) | 0.008511 |
def show_tricky_tasks(self, verbose=0):
"""
Print list of tricky tasks i.e. tasks that have been restarted or
launched more than once or tasks with corrections.
Args:
verbose: Verbosity level. If > 0, task history and corrections (if any) are printed.
"""
nid... | 0.004996 |
def ingest(self, token, endpoint=None, timeout=None, compress=None):
"""Obtain a datapoint and event ingest client."""
from . import ingest
if ingest.sf_pbuf:
client = ingest.ProtoBufSignalFxIngestClient
else:
_logger.warn('Protocol Buffers not installed properly;... | 0.00295 |
def update(self, dt=-1):
"""
Return type string, compatible with numpy.
"""
self.library.update.argtypes = [c_double]
self.library.update.restype = c_int
if dt == -1:
# use default timestep
dt = self.get_time_step()
result = wrap(self.libra... | 0.005618 |
def to_internal(self, attribute_profile, external_dict):
"""
Converts the external data from "type" to internal
:type attribute_profile: str
:type external_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: From which external type to convert (ex: oid... | 0.007374 |
def _perform_custom_queries(self, conn, custom_queries, tags, instance):
"""
Perform custom queries to collect additional metrics like number of result and duration of the query
"""
for query in custom_queries:
name = query.get("name")
if name is None:
... | 0.004388 |
def parse_stdout(self, filelike):
"""Parse the formulae from the content written by the script to standard out.
:param filelike: filelike object of stdout
:returns: an exit code in case of an error, None otherwise
"""
from aiida.orm import Dict
formulae = {}
con... | 0.004329 |
def _input_stmt(self, stmt: object) -> tuple:
"""
takes the input key from kwargs and processes it to aid in the generation of a model statement
:param stmt: str, list, or dict that contains the model information.
:return: tuple of strings one for the class statement one for the model st... | 0.003529 |
def path_from_uri(self, uri):
"""Make a safe path name from uri.
In the case that uri is already a local path then the
same path is returned.
"""
(scheme, netloc, path, params, query, frag) = urlparse(uri)
if (netloc == ''):
return(uri)
path = '/'.joi... | 0.013208 |
def get_nodes(self, request):
"""
Generates the nodelist
:param request:
:return: list of nodes
"""
nodes = []
language = get_language_from_request(request, check_path=True)
current_site = get_current_site(request)
page_site = self.instance.node... | 0.004105 |
def yield_amd_require_string_arguments(
node, pos,
reserved_module=reserved_module, wrapped=define_wrapped):
"""
This yields only strings within the lists provided in the argument
list at the specified position from a function call.
Originally, this was implemented for yield a list of m... | 0.001406 |
def infer_dict(node, context=None):
"""Try to infer a dict call to a Dict node.
The function treats the following cases:
* dict()
* dict(mapping)
* dict(iterable)
* dict(iterable, **kwargs)
* dict(mapping, **kwargs)
* dict(**kwargs)
If a case can't be infer... | 0.000775 |
def formataddr(pair, charset='utf-8'):
"""The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
returned unmodified.
O... | 0.001631 |
def __profile_file(self):
"""Method used to profile the given file line by line."""
self.line_profiler = pprofile.Profile()
self.line_profiler.runfile(
open(self.pyfile.path, "r"), {}, self.pyfile.path
) | 0.008097 |
def request(self, path, action, data=''):
"""To make a request to the API."""
# Check if the path includes URL or not.
head = self.base_url
if path.startswith(head):
path = path[len(head):]
path = quote_plus(path, safe='/')
if not path.startswith(self.api)... | 0.00054 |
def notify_launch(self, log_level='ERROR'):
"""logs launcher message before startup
Args:
log_level (str): level to notify at
"""
if not self.debug:
self.logger.log(
logging.getLevelName(log_level),
'LAUNCHING %s -- %s', self.PROG... | 0.00361 |
def create_asyncio_eventloop(loop=None):
"""
Returns an asyncio :class:`~prompt_toolkit.eventloop.EventLoop` instance
for usage in a :class:`~prompt_toolkit.interface.CommandLineInterface`. It
is a wrapper around an asyncio loop.
:param loop: The asyncio eventloop (or `None` if the default asynciol... | 0.004038 |
def to_json(self):
"""
Returns the JSON representation of the API key.
"""
result = super(ApiKey, self).to_json()
result.update({
'name': self.name,
'description': self.description,
'accessToken': self.access_token,
'environments':... | 0.005076 |
def key_event_to_name(event):
""" Converts a keystroke event into a corresponding key name.
"""
key_code = event.key()
modifiers = event.modifiers()
if modifiers & QtCore.Qt.KeypadModifier:
key = keypad_map.get(key_code)
else:
key = None
if key is None:
key = key_map.... | 0.008403 |
def tcase_exit(trun, tsuite, tcase):
"""..."""
#pylint: disable=locally-disabled, unused-argument
if trun["conf"]["VERBOSE"]:
cij.emph("rnr:tcase:exit { fname: %r }" % tcase["fname"])
rcode = 0
for hook in reversed(tcase["hooks"]["exit"]): # tcase EXIT-hooks
rcode = script_run(t... | 0.004158 |
def p_nonfluent_def(self, p):
'''nonfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY NON_FLUENT COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI
| IDENT COLON LCURLY NON_FLUENT COMMA type_spec COMMA DEFAULT ASSIGN_EQUAL range_const RCURLY SEMI'''
if len... | 0.010753 |
def map_query_string(self):
"""Maps the GET query string params the the query_key_mapper dict and
updates the request's GET QueryDict with the mapped keys.
"""
if (not self.query_key_mapper or
self.request.method == 'POST'):
# Nothing to map, don't do anything.
... | 0.005357 |
def disassociate_failure_node(self, parent, child):
"""Remove a failure node link.
The resulatant 2 nodes will both become root nodes.
=====API DOCS=====
Remove a failure node link.
:param parent: Primary key of parent node to disassociate failure node from.
:type paren... | 0.005848 |
def log_repo_action(func):
"""
Log all repo actions to .dgit/log.json
"""
def _inner(*args, **kwargs):
result = func(*args, **kwargs)
log_action(func, result, *args, **kwargs)
return result
_inner.__name__ = func.__name__
_inner.__doc__ = fun... | 0.020173 |
def _getitem(self, key):
"""Return specified page of series from cache or file."""
key = int(key)
if key < 0:
key %= self._len
if len(self._pages) == 1 and 0 < key < self._len:
index = self._pages[0].index
return self.parent.pages._getitem(index + key)... | 0.005682 |
def FindDevice(self, address):
'''Find a specific device by bluetooth address.
'''
for obj in mockobject.objects.keys():
if obj.startswith('/org/bluez/') and 'dev_' in obj:
o = mockobject.objects[obj]
if o.props[DEVICE_IFACE]['Address'] \
== dbus.String(ad... | 0.001969 |
def find_max_and_min_frequencies(name, mass_range_params, freqs):
"""
ADD DOCS
"""
cutoff_fns = pnutils.named_frequency_cutoffs
if name not in cutoff_fns.keys():
err_msg = "%s not recognized as a valid cutoff frequency choice." %name
err_msg += "Recognized choices: " + " ".join(cuto... | 0.004092 |
def write_hfb_template(m):
"""write a template file for an hfb (yuck!)
Parameters
----------
m : flopy.modflow.Modflow instance with an HFB file
Returns
-------
(tpl_filename, df) : (str, pandas.DataFrame)
the name of the template file and a dataframe with useful info.
... | 0.016629 |
def system_monitor_LineCard_threshold_down_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
LineCard = ET.SubElement(system_monitor, "L... | 0.004967 |
def get_children(self):
"""Gets the children of this composition.
return: (osid.repository.CompositionList) - the composition
children
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# ... | 0.005269 |
def ensure_overlap_ratio(self, required_ratio=0.5):
"""
Ensure that every adjacent pair of frequency bands meets the overlap
ratio criteria. This can be helpful in scenarios where a scale is
being used in an invertible transform, and something like the `constant
overlap add cons... | 0.001667 |
def build_default_simulation(self, tax_benefit_system, count = 1):
"""
Build a simulation where:
- There are ``count`` persons
- There are ``count`` instances of each group entity, containing one person
- Every person has, in each entity, the first rol... | 0.009309 |
def load_mnist_data(args):
'''
Load MNIST dataset
'''
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = (np.expand_dims(x_train, -1).astype(np.float) / 255.)[:args.num_train]
x_test = (np.expand_dims(x_test, -1).astype(np.float) / 255.)[:args.num_test]
y_train = keras.utils... | 0.004992 |
def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an optional argument to specify the name of a filter to use.
"""
if arg is not None:
return formatter(value, filter_name=arg)
return formatter(value) | 0.011152 |
def fq_merge(R1, R2):
"""
merge separate fastq files
"""
c = itertools.cycle([1, 2, 3, 4])
for r1, r2 in zip(R1, R2):
n = next(c)
if n == 1:
pair = [[], []]
pair[0].append(r1.strip())
pair[1].append(r2.strip())
if n == 4:
yield pair | 0.003165 |
def upload_files(self, owner, id, file, **kwargs):
"""
Upload files
Upload multiple files at once to a dataset via multipart request. This endpoint expects requests of type `multipart/form-data` and you can include one or more parts named `file`, each containing a different file to be uploaded.... | 0.003079 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.