text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _normalize_utf8_keys(kwargs):
"""When kwargs are passed literally in a source file, their keys are ascii: normalize."""
if any(type(key) is binary_type for key in kwargs.keys()):
# This is to preserve the original dict type for kwargs.
dict_type = type(kwargs)
return dict_type([(text_type(k), v) for... | 0.01385 |
async def membership(client: Client, membership_signed_raw: str) -> ClientResponse:
"""
POST a Membership document
:param client: Client to connect to the api
:param membership_signed_raw: Membership signed raw document
:return:
"""
return await client.post(MODULE + '/membership', {'members... | 0.008043 |
def set_widgets(self):
"""Set widgets on the Hazard Layer From TOC tab."""
# The list is already populated in the previous step, but now we
# need to do it again in case we're back from the Keyword Wizard.
# First, preserve self.parent.layer before clearing the list
last_layer = ... | 0.001738 |
def _get_method_wrappers(cls):
"""
Find the appropriate operation-wrappers to use when defining flex/special
arithmetic, boolean, and comparison operations with the given class.
Parameters
----------
cls : class
Returns
-------
arith_flex : function or None
comp_flex : function... | 0.000469 |
def update(connection, force_download):
"""Update the database"""
manager.database.update(
connection=connection,
force_download=force_download
) | 0.00578 |
def one(self, command, params=None):
"""
Возвращает первую строку ответа, полученного через query
> db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID})
:param command: SQL запрос
:param params: Параметры для prepared statements
:rtype: dict
"""
... | 0.004454 |
def check_declared(self, node):
"""update the state of this Identifiers with the undeclared
and declared identifiers of the given node."""
for ident in node.undeclared_identifiers():
if ident != 'context' and\
ident not in self.declared.union(self.locally_dec... | 0.004301 |
def get_characteristic_subpattern(subpatterns):
"""Picks the most characteristic from a list of linear patterns
Current order used is:
names > common_names > common_chars
"""
if not isinstance(subpatterns, list):
return subpatterns
if len(subpatterns)==1:
return subpatterns[0]
... | 0.003378 |
def get_product_string(self):
""" Get the Product String from the HID device.
:return: The Product String
:rtype: unicode
"""
self._check_device_status()
str_p = ffi.new("wchar_t[]", 255)
rv = hidapi.hid_get_product_string(self._device, str_p, 255)
... | 0.003906 |
def timestamp(stamp, tolerance=150):
"""Validate timestamp specified by request.
See `validate.request` for additional info.
Args:
stamp: str. Time request was made as ISO 8601 timestamp.
tolerance: int. Number of seconds request remains valid from timestamp.
Returns
bool: Tru... | 0.001464 |
def to_dict(self, include_null=True):
"""
Convert to dict.
"""
if include_null:
return dict(self.items())
else:
return {
attr: value
for attr, value in self.__dict__.items()
if not attr.startswith("_sa_")
... | 0.006061 |
def limit_inference(iterator, size):
"""Limit inference amount.
Limit inference amount to help with performance issues with
exponentially exploding possible results.
:param iterator: Inference generator to limit
:type iterator: Iterator(NodeNG)
:param size: Maximum mount of nodes yielded plus... | 0.001623 |
def meld(*values):
"""Return the repeated value, or the first value if there's only one.
This is a convenience function, equivalent to calling
getvalue(repeated(x)) to get x.
This function skips over instances of None in values (None is not allowed
in repeated variables).
Examples:
me... | 0.001418 |
def decimal_to_dms(value, precision):
'''
Convert decimal position to degrees, minutes, seconds in a fromat supported by EXIF
'''
deg = math.floor(value)
min = math.floor((value - deg) * 60)
sec = math.floor((value - deg - min / 60) * 3600 * precision)
return ((deg, 1), (min, 1), (sec, prec... | 0.006116 |
def stop_charge(self):
"""Stop charging the Tesla Vehicle."""
if self.__charger_state:
data = self._controller.command(self._id, 'charge_stop',
wake_if_asleep=True)
if data and data['response']['result']:
self.__charger_... | 0.005195 |
def _compute_frequencies(self, word_sent):
"""
Compute the frequency of each of word.
Input:
word_sent, a list of sentences already tokenized.
Output:
freq, a dictionary where freq[w] is the frequency of w.
"""
freq = defaultdict(int)
for s in word_sent:
for word... | 0.012862 |
def search_by_category(self, category_id, limit=0, order_by=None, sort_order=None, filter=None):
"""
Search for series that belongs to a category id. Returns information about matching series in a DataFrame.
Parameters
----------
category_id : int
category id, e.g., ... | 0.007412 |
def symmetric_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8):
'''
perform symmetric EMA (exponential moving average)
smoothing and resampling to an even grid with n points.
Does not do extrapolation, so we assume
xolds[0] <= low && high <= xolds[-1]
Arg... | 0.006083 |
def readdir(path):
'''
.. versionadded:: 2014.1.0
Return a list containing the contents of a directory
CLI Example:
.. code-block:: bash
salt '*' file.readdir /path/to/dir/
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('Dir... | 0.001869 |
def to_bytes(value):
""" str to bytes (py3k) """
vtype = type(value)
if vtype == bytes or vtype == type(None):
return value
try:
return vtype.encode(value)
except UnicodeEncodeError:
pass
return value | 0.008 |
def validate_port_or_colon_separated_port_range(port_range):
"""Accepts a port number or a single-colon separated range."""
if port_range.count(':') > 1:
raise ValidationError(_("One colon allowed in port range"))
ports = port_range.split(':')
for port in ports:
validate_port_range(port) | 0.003125 |
def get_settings():
'''
Get all currently loaded settings.
'''
settings = {}
for config_file in config_files():
config_contents = load_config(config_file)
if config_contents is not None:
settings = deep_merge(settings, config_contents)
return settings | 0.0033 |
def set_text(self, point, text):
"""Set a text value in the screen canvas."""
if not self.option.legend:
return
if not isinstance(point, Point):
point = Point(point)
for offset, char in enumerate(str(text)):
self.screen.canvas[point.y][point.x + offs... | 0.006061 |
def daemon_factory(path):
"""Create a closure which creates a running daemon.
We need to create a closure that contains the correct path the daemon should
be started with. This is needed as the `Daemonize` library
requires a callable function for daemonization and doesn't accept any arguments.
This... | 0.004296 |
def send(*args, **kwargs):
"""
A basic interface around both queue and send_now. This honors a global
flag NOTIFICATION_QUEUE_ALL that helps determine whether all calls should
be queued or not. A per call ``queue`` or ``now`` keyword argument can be
used to always override the default global behavio... | 0.002677 |
def _read_compound_from_factsage_file_(file_name):
"""
Build a dictionary containing the factsage thermochemical data of a
compound by reading the data from a file.
:param file_name: Name of file to read the data from.
:returns: Dictionary containing compound data.
"""
with open(file_name... | 0.000232 |
def get_cachedir_bsig(self):
"""
Return the signature for a cached file, including
its children.
It adds the path of the cached file to the cache signature,
because multiple targets built by the same action will all
have the same build signature, and we have to different... | 0.002265 |
def draw(self, **kwargs):
"""
Called from the fit method, this method creates the canvas and
draws the distribution plot on it.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Prepare the data
bins = np.arange(self.N)
word... | 0.001952 |
def write_tsv(output_stream, *tup, **kwargs):
"""
Write argument list in `tup` out as a tab-separeated row to the stream.
"""
encoding = kwargs.get('encoding') or 'utf-8'
value = '\t'.join([s for s in tup]) + '\n'
output_stream.write(value.encode(encoding)) | 0.003559 |
def _render_before(self, element):
'''Render opening tag and inline content'''
start = ["%s<%s" % (self.spaces, element.tag)]
if element.id:
start.append(" id=%s" % self.element.attr_wrap(self.replace_inline_variables(element.id)))
if element.classes:
start.append... | 0.005025 |
def encoder_data(self, data):
"""
This method handles the incoming encoder data message and stores
the data in the digital response table.
:param data: Message data from Firmata
:return: No return value.
"""
prev_val = self.digital_response_table[data[self.RESPO... | 0.005792 |
def describe_db_subnet_groups(name=None, filters=None, jmespath='DBSubnetGroups',
region=None, key=None, keyid=None, profile=None):
'''
Return a detailed listing of some, or all, DB Subnet Groups visible in the
current scope. Arbitrary subelements or subsections of the returne... | 0.00348 |
def bot_item_drop_event(self, dropped_listwidget, event):
"""
Switches the team for the dropped agent to the other team
:param dropped_listwidget: The listwidget belonging to the new team for the agent
:param event: The QDropEvent containing the source
:return:
"""
... | 0.008518 |
def _copy_with_changed_callback(self, new_callback):
''' Dev API used to wrap the callback with decorators. '''
return TimeoutCallback(self._document, new_callback, self._timeout, self._id) | 0.014634 |
def consume(self, key, amount=1, rate=None, capacity=None, **kwargs):
"""Consume an amount for a given key.
Non-default rate/capacity can be given to override Throttler defaults.
Returns:
bool: whether the units could be consumed
"""
bucket = self.get_bucket(key, ra... | 0.005249 |
def cross(*sequences):
"""
From: http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-19-sect-9.html
"""
# visualize an odometer, with "wheels" displaying "digits"...:
wheels = map(iter, sequences)
digits = [it.next( ) for it in wheels]
while True:
yield t... | 0.023009 |
def setLoggerLevel(self, logger, level):
"""
Sets the level to log the inputed logger at.
:param logger | <str>
level | <int>
"""
if logger == 'root':
_log = logging.getLogger()
else:
_log = logging.getL... | 0.009381 |
def list_tables(self):
"""
Returns the existing tables.
Tables are returned in lexicographical order.
:rtype: ~collections.Iterable[.Table]
"""
# Server does not do pagination on listings of this resource.
# Return an iterator anyway for similarity with other AP... | 0.003135 |
def add_packages(packages):
"""Add external packages to the pyspark interpreter.
Set the PYSPARK_SUBMIT_ARGS properly.
Parameters
----------
packages: list of package names in string format
"""
#if the parameter is a string, convert to a single element list
if isinstance(packages,str)... | 0.013953 |
def polynet(num_classes=1000, pretrained='imagenet'):
"""PolyNet architecture from the paper
'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks'
https://arxiv.org/abs/1611.05725
"""
if pretrained:
settings = pretrained_settings['polynet'][pretrained]
assert num_classes... | 0.001134 |
def prob_lnm(m1, m2, s1z, s2z, **kwargs):
''' Return probability density for uniform in log
Parameters
----------
m1: array
Component masses 1
m2: array
Component masses 2
s1z: array
Aligned spin 1(Not in use currently)
s2z:
... | 0.001815 |
def filter_convolve(data, filters, filter_rot=False, method='scipy'):
r"""Filter convolve
This method convolves the input image with the wavelet filters
Parameters
----------
data : np.ndarray
Input data, 2D array
filters : np.ndarray
Wavelet filters, 3D array
filter_rot : ... | 0.000603 |
def set_conn(self, **kwargs):
""" takes a connection and creates the connection """
# log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3]))
log.setLevel(kwargs.get('log_level',self.log_level))
conn_name = kwargs.get("name")
if not conn_name:
raise Nam... | 0.00326 |
def get_steam_id(vanityurl, **kwargs):
"""
Get a players steam id from their steam name/vanity url
"""
params = {"vanityurl": vanityurl}
return make_request("ResolveVanityURL", params, version="v0001",
base="http://api.steampowered.com/ISteamUser/", **kwargs) | 0.006969 |
def create(self, list_id, data):
"""
Add a new member to the list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"status": string*, (Must be on... | 0.004658 |
def errorFunction(self, t, a):
"""
Using a hyperbolic arctan on the error slightly exaggerates
the actual error non-linearly. Return t - a to just use the difference.
t - target vector
a - activation vector
"""
def difference(v):
if not self.hyperbolic... | 0.018233 |
def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r'... | 0.000432 |
def compare_verbs(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as verbs
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
... | 0.004065 |
def katex_rendering_delimiters(app):
"""Delimiters for rendering KaTeX math.
If no delimiters are specified in katex_options, add the
katex_inline and katex_display delimiters. See also
https://khan.github.io/KaTeX/docs/autorender.html
"""
# Return if we have user defined rendering delimiters
... | 0.001078 |
def fetch(self, is_dl_forced=True):
"""
Fetches data from udp collaboration server,
see top level comments for class for more information
:return:
"""
username = config.get_config()['dbauth']['udp']['user']
password = config.get_config()['dbauth']['udp']['passwor... | 0.002561 |
def to_json_dict(self, filter_fcn=None):
"""Create a dict with Entity properties for json encoding.
It can be overridden by subclasses for each standard serialization
doesn't work. By default it call _to_json_dict on OneToOne fields
and build a list calling the same method on each OneToM... | 0.001048 |
def cc_from_arg_kinds(self, fp_args, ret_fp=None, sizes=None, sp_delta=None, func_ty=None):
"""
Get a SimCC (calling convention) that will extract floating-point/integral args correctly.
:param arch: The Archinfo arch for this CC
:param fp_args: A list, with one entry for eac... | 0.009393 |
def users(self):
"""
Gets the Users API client.
Returns:
Users:
"""
if not self.__users:
self.__users = Users(self.__connection)
return self.__users | 0.00905 |
def user_choice(prompt, choices=("yes", "no"), default=None):
"""
Prompts the user for confirmation. The default value, if any, is capitalized.
:param prompt: Information to display to the user.
:param choices: an iterable of possible choices.
:param default: default choice
:return: the user's... | 0.004392 |
def ImportConfig(filename, config):
"""Reads an old config file and imports keys and user accounts."""
sections_to_import = ["PrivateKeys"]
entries_to_import = [
"Client.executable_signing_public_key", "CA.certificate",
"Frontend.certificate"
]
options_imported = 0
old_config = grr_config.CONFIG... | 0.015248 |
def export_to_wif(self, compressed=None):
"""Export a key to WIF.
:param compressed: False if you want a standard WIF export (the most
standard option). True if you want the compressed form (Note that
not all clients will accept this form). Defaults to None, which
in... | 0.002146 |
def config_path(self, value):
"""Set config_path"""
self._config_path = value or ''
if not isinstance(self._config_path, str):
raise BadArgumentError("config_path must be string: {}".format(
self._config_path)) | 0.007634 |
def list(self, **params):
"""
Retrieve all lead unqualified reasons
Returns all lead unqualified reasons available to the user according to the parameters provided
:calls: ``get /lead_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of ... | 0.008292 |
def _bgzip_from_fastq(data):
"""Prepare a bgzipped file from a fastq input, potentially gzipped (or bgzipped already).
"""
in_file = data["in_file"]
if isinstance(in_file, (list, tuple)):
in_file = in_file[0]
needs_convert = dd.get_quality_format(data).lower() == "illumina"
# special cas... | 0.005288 |
def post_bug(self, bug):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#create-bug'''
assert type(bug) is DotDict
assert 'product' in bug
assert 'component' in bug
assert 'summary' in bug
if (not 'version' in bug): bug.version = 'other'
if (not ... | 0.019397 |
def stringify(req, resp):
"""
dumps all valid jsons
This is the latest after hook
"""
if isinstance(resp.body, dict):
try:
resp.body = json.dumps(resp.body)
except(nameError):
resp.status = falcon.HTTP_500 | 0.003774 |
def get_commands(self):
"""Gets command that have been run and have not been redacted.
"""
shutit_global.shutit_global_object.yield_to_draw()
s = ''
for c in self.build['shutit_command_history']:
if isinstance(c, str):
#Ignore commands with leading spaces
if c and c[0] != ' ':
s += c + '\n'
... | 0.039634 |
def args_ok(self, options, args):
"""Check for conflicts and problems in the options.
Returns True if everything is ok, or False if not.
"""
for i in ['erase', 'execute']:
for j in ['annotate', 'html', 'report', 'combine']:
if (i in options.actions) and (j i... | 0.002381 |
def quaternion_to_rotation_matrix(quaternion):
"""Compute the rotation matrix representated by the quaternion"""
c, x, y, z = quaternion
return np.array([
[c*c + x*x - y*y - z*z, 2*x*y - 2*c*z, 2*x*z + 2*c*y ],
[2*x*y + 2*c*z, c*c - x*x + y*y - z*z, 2*y*z - 2*c*x ... | 0.007212 |
def save(self, file_path, note_df):
'''
Save MIDI file.
Args:
file_path: File path of MIDI.
note_df: `pd.DataFrame` of note data.
'''
chord = pretty_midi.PrettyMIDI()
for program in note_df.program.drop_duplicates().v... | 0.00478 |
def write_metadata(self):
"""Write all ID3v2.4 tags to file from self.metadata"""
import mutagen
from mutagen import id3
id3 = id3.ID3(self.filename)
for tag in self.metadata.keys():
value = self.metadata[tag]
frame = mutagen.id3.Frames[tag](3, value)
... | 0.00703 |
def merge_directories(self, directory_digests):
"""Merges any number of directories.
:param directory_digests: Tuple of DirectoryDigests.
:return: A Digest.
"""
result = self._native.lib.merge_directories(
self._scheduler,
self._to_value(_DirectoryDigests(directory_digests)),
)
... | 0.002809 |
def venqueue(trg_queue, item_f, args, user=None, group=None, mode=None):
'''Enqueue the contents of a file, or file-like object, file-descriptor or
the contents of a file at an address (e.g. '/my/file') queue with
an argument list, venqueue is to enqueue what vprintf is to printf
If entropy is... | 0.001605 |
def buildprior(self, prior, mopt=None, extend=False):
" Extract the model's parameters from prior. "
newprior = {}
# allow for log-normal, etc priors
intercept, slope = gv.get_dictkeys(
prior, [self.intercept, self.slope]
)
newprior[intercept] = prior[inte... | 0.004158 |
def qos_queue_scheduler_strict_priority_dwrr_traffic_class0(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
queue = ET.SubElement(qos, "queue")
scheduler = ET.SubElement... | 0.006116 |
def _run_info_from_yaml(dirs, run_info_yaml, config, sample_names=None,
is_cwl=False, integrations=None):
"""Read run information from a passed YAML file.
"""
validate_yaml(run_info_yaml, run_info_yaml)
with open(run_info_yaml) as in_handle:
loaded = yaml.safe_load(in_han... | 0.003241 |
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary'... | 0.003731 |
def warmness(level=100, group=0):
""" Assumes level is out of 100 """
if level not in range(0,101):
raise Exception("Warmness must be value between 0 and 100")
b = int(floor(level / 10.0)) #lights have 10 levels of warmness
commands = list(coolest(group))
for i in range(0, b):
comman... | 0.010638 |
def mutualFundSymbolsDF(token='', version=''):
'''This call returns an array of mutual fund symbols that IEX Cloud supports for API calls.
https://iexcloud.io/docs/api/#mutual-fund-symbols
8am, 9am, 12pm, 1pm UTC daily
Args:
token (string); Access token
version (string); API version
... | 0.004141 |
def set_(device, minor, flag, state):
'''
Changes a flag on the partition with number <minor>.
A flag can be either "on" or "off" (make sure to use proper quoting, see
:ref:`YAML Idiosyncrasies <yaml-idiosyncrasies>`). Some or all of these
flags will be available, depending on what disk label you a... | 0.00077 |
def rtgen_family(self, value):
"""Family setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_ubyte(value or 0)) | 0.014599 |
def get_subs_dict(self, qnodes=None):
"""
Return substitution dict for replacements into the template
Subclasses may want to customize this method.
"""
#d = self.qparams.copy()
d = self.qparams
d.update(self.optimize_params(qnodes=qnodes))
# clean null val... | 0.008811 |
def add_group(self, name: str, **kwargs) -> None:
"""
Add a group to the inventory after initialization
"""
group = {
name: deserializer.inventory.InventoryElement.deserialize_group(
name=name, defaults=self.defaults, **kwargs
)
}
s... | 0.005814 |
def dump_all(data_list, stream=None, **kwargs):
"""
Serialize YAMLDict into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.dump_all(
data_list,
stream=stream,
Dumper=YAMLDictDumper,
**kwargs
) | 0.003484 |
def read_index(fn):
"""Reads index from file.
Args:
fn (str): the name of the file containing the index.
Returns:
pandas.DataFrame: the index of the file.
Before reading the index, we check the first couple of bytes to see if it
is a valid index file.
"""
index = None
... | 0.001608 |
def _safe_minmax(values):
"""Calculate min and max of array with guards for nan and inf."""
# Nan and inf guarded min and max
isfinite = np.isfinite(values)
if np.any(isfinite):
# Only use finite values
values = values[isfinite]
minval = np.min(values)
maxval = np.max(values)
... | 0.002899 |
def validate(self, request, data):
"""
Validate response from OpenID server.
Set identity in case of successfull validation.
"""
client = consumer.Consumer(request.session, None)
try:
resp = client.complete(data, request.session['openid_return_to'])
e... | 0.002153 |
def create_api_dict(bases, url, **kwargs):
"""Create an API dict
:param bases: configuration bases
:type bases: :class:`~pyextdirect.configuration.Base` or list of :class:`~pyextdirect.configuration.Base`
:param string url: URL where the router can be reached
:param \*\*kwargs: extra keyword argume... | 0.005029 |
def _Supercooled(T, P):
"""Guideline on thermodynamic properties of supercooled water
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Returns
-------
prop : dict
Dict with calculated properties of water. The available properties are:
... | 0.000181 |
def create_request_url(self, profile_type, steamID):
"""Create the url to submit to the Steam Community XML feed."""
regex = re.compile('^\d{17,}$')
if regex.match(steamID):
if profile_type == self.USER:
url = "http://steamcommunity.com/profiles/%s/?xml=1" % (steamID)... | 0.008097 |
def dump_system_json(self, filepath=None, modular=False, **kwargs):
"""
Dump a :class:`MolecularSystem` to a JSON dictionary.
The dumped JSON dictionary, with :class:`MolecularSystem`, can then be
loaded through a JSON loader and then through :func:`load_system()`
to retrieve a ... | 0.001049 |
def stack_eggs(eggs, meta='concatenate'):
'''
Takes a list of eggs, stacks them and reindexes the subject number
Parameters
----------
eggs : list of Egg data objects
A list of Eggs that you want to combine
meta : string
Determines how the meta data of each Egg combines. Default... | 0.005587 |
def add_backup_operation(self, backup, mode=None):
"""Add a backup operation to the version.
:param backup: To either add or skip the backup
:type backup: Boolean
:param mode: Name of the mode in which the operation is executed
For now, backups are mode-independent
... | 0.003711 |
def get_shutit_pexpect_session_from_id(self, shutit_pexpect_id):
"""Get the pexpect session from the given identifier.
"""
shutit_global.shutit_global_object.yield_to_draw()
for key in self.shutit_pexpect_sessions:
if self.shutit_pexpect_sessions[key].pexpect_session_id == shutit_pexpect_id:
return self.... | 0.026726 |
def _to_array(value):
"""As a convenience, turn Python lists and tuples into NumPy arrays."""
if isinstance(value, (tuple, list)):
return array(value)
elif isinstance(value, (float, int)):
return np.float64(value)
else:
return value | 0.003676 |
def exists(self, file_ref):
"""
Parameters
----------
file_ref: str
reference of file.
Available references: 'idf', 'epw', 'eio', 'eso', 'mtr', 'mtd', 'mdd', 'err', 'summary_table'
See EnergyPlus documentation for more information.
Returns
... | 0.007018 |
def get_top_stories(self):
"""
Get the item numbers for the current top stories.
Will raise an requests.HTTPError if we got a non-200 response back.
:return: A list with the top story item numbers.
"""
suburl = "v0/topstories.json"
try:
top_stories = s... | 0.00566 |
def iter_variants_by_names(self, names):
"""Iterates over the genotypes for variants using a list of names.
Args:
names (list): The list of names for variant extraction.
"""
if not self.is_parallel:
yield from super().iter_variants_by_names(names)
else:... | 0.002639 |
def parse_file(filename):
"""Parse the provided file, and return Code object."""
assert isinstance(filename, _str_type), "`filename` parameter should be a string, got %r" % type(filename)
with open(filename, "rt", encoding="utf-8") as f:
return Code(_tokenize(f.readline)) | 0.006849 |
def set_sp_template_updated(self, vlan_id, sp_template, device_id):
"""Sets update_on_ucs flag to True."""
entry = self.get_sp_template_vlan_entry(vlan_id,
sp_template,
device_id)
if entry:
... | 0.004435 |
def wallet_change_seed(self, wallet, seed):
"""
Changes seed for **wallet** to **seed**
.. enable_control required
:param wallet: Wallet to change seed for
:type wallet: str
:param seed: Seed to change wallet to
:type seed: str
:raises: :py:exc:`nano.r... | 0.004768 |
def size(self):
"""Total number of grid points."""
# Since np.prod(()) == 1.0 we need to handle that by ourselves
return (0 if self.shape == () else
int(np.prod(self.shape, dtype='int64'))) | 0.008734 |
def get_learning_rate(self, iter):
'''
Get learning rate with exponential decay based on current iteration.
Args:
iter (int): Current iteration (starting with 0).
Returns:
float: Learning rate
'''
lr = self.init_lr
for iter_step in self.i... | 0.004819 |
def control_loop():
'''Main loop, retrieving the schedule.
'''
set_service_status(Service.SCHEDULE, ServiceStatus.BUSY)
notify.notify('READY=1')
while not terminate():
notify.notify('WATCHDOG=1')
# Try getting an updated schedule
get_schedule()
session = get_session()... | 0.000805 |
def simulate_reads(self):
"""
Use the PacBio assembly FASTA files to generate simulated reads of appropriate forward and reverse lengths
at different depths of sequencing using randomreads.sh from the bbtools suite
"""
logging.info('Read simulation')
for sample in self.me... | 0.006369 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.