text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def song(netease, name, id):
"""Download a song by name or id."""
if name:
netease.download_song_by_search(name)
if id:
netease.download_song_by_id(id, 'song'+str(id)) | 0.005102 |
def get_merged_filenode_list(nodes, filter_media_types=None, exclude_media_types=None, filter=None, ordering=None, processors=None, max_depth=None, max_nodes=None):
"""
Almost the same as :func:`get_nested_filenode_list`, but returns a flat (one-dimensional) list.
Using the same QuerySet as in the example f... | 0.008037 |
def handle_or_else(self, orelse, test):
"""Handle the orelse part of an if or try node.
Args:
orelse(list[Node])
test(Node)
Returns:
The last nodes of the orelse branch.
"""
if isinstance(orelse[0], ast.If):
control_flow_node = se... | 0.002356 |
def imprint(self, path=None):
"""Write the determined version, if any, to ``self.version_file`` or
the path passed as an argument.
"""
if self.version is not None:
with open(path or self.version_file, 'w') as h:
h.write(self.version + '\n')
else:
... | 0.004938 |
def _emplace_pmrna(mrnas, parent, strict=False):
"""Retrieve the primary mRNA and discard all others."""
mrnas.sort(key=lambda m: (m.cdslen, m.get_attribute('ID')))
pmrna = mrnas.pop()
if strict:
parent.children = [pmrna]
else:
parent.children = [c for c in parent.children if c not i... | 0.003049 |
def atanh(x):
""" atanh(x)
Hyperbolic arc tan function.
"""
_math = infer_math(x)
if _math is math:
return _math.atanh(x)
else:
return _math.arctanh(x) | 0.005236 |
def visit_Call(self, node):
"""
Transform call site to have normal function call.
Examples
--------
For methods:
>> a = [1, 2, 3]
>> a.append(1)
Becomes
>> __list__.append(a, 1)
For functions:
>> __builtin__.dict.fromkeys([1, ... | 0.000593 |
def _parse_return_code_powershell(string):
'''
return from the input string the return code of the powershell command
'''
regex = re.search(r'ReturnValue\s*: (\d*)', string)
if not regex:
return (False, 'Could not parse PowerShell return code.')
else:
return int(regex.group(1)) | 0.003135 |
def error_msg_wx(msg, parent=None):
"""
Signal an error condition -- in a GUI, popup a error dialog
"""
dialog =wx.MessageDialog(parent = parent,
message = msg,
caption = 'Matplotlib backend_wx error',
style=wx.OK | ... | 0.023077 |
def _example_plate_stock(quote_ctx):
"""
获取板块下的股票列表,输出 市场,股票每手,股票名称,所属市场,子类型,股票类型
"""
ret_status, ret_data = quote_ctx.get_plate_stock("SH.BK0531")
if ret_status != ft.RET_OK:
print(ret_data)
exit()
print("plate_stock")
print(ret_data) | 0.003584 |
def obo(self):
"""str: the synonym type serialized in obo format.
"""
return ' '.join(['synonymtypedef:', self.name,
'"{}"'.format(self.desc),
self.scope or '']).strip() | 0.00823 |
def generate_matching_datasets(self, data_slug):
"""Return datasets that match data_slug (hub_slug)."""
matching_datasets = Dataset.objects.filter(
hub_slug=data_slug
).order_by('-date_uploaded')
if len(matching_datasets) > 0:
return matching_datasets
els... | 0.00578 |
def whois(self, record):
"""
Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str
"""
if PyFunceble.CONFIGURATION["debug"] and PyFunceble.CONFIGURATION["logs"]:
# The debug and the logs subsystem are activated.
if... | 0.002496 |
def add_argument(self, parser, set_default=False):
"""Add this :class:`Setting` to the ``parser``.
The operation is carried out only if :attr:`flags` or
:attr:`nargs` and :attr:`name` are defined.
"""
default = self.default if set_default else None
kwargs = dict(
... | 0.001871 |
def hset(self, key, field, value):
"""Set the string value of a hash field."""
return self.execute(b'HSET', key, field, value) | 0.014085 |
def build_graph(self, regularizers=()):
'''Connect the layers in this network to form a computation graph.
Parameters
----------
regularizers : list of :class:`theanets.regularizers.Regularizer`
A list of the regularizers to apply while building the computation
g... | 0.002324 |
def after_this_request(func: Callable) -> Callable:
"""Schedule the func to be called after the current request.
This is useful in situations whereby you want an after request
function for a specific route or circumstance only, for example,
.. code-block:: python
def index():
@aft... | 0.001764 |
def adjust_locations(ast_node, first_lineno, first_offset):
"""
Adjust the locations of the ast nodes, offsetting them
to the new lineno and column offset
"""
line_delta = first_lineno - 1
def _fix(node):
if 'lineno' in node._attributes:
lineno = node.lineno
col... | 0.00155 |
def _is_len_call(node):
"""Checks if node is len(SOMETHING)."""
return (
isinstance(node, astroid.Call)
and isinstance(node.func, astroid.Name)
and node.func.name == "len"
) | 0.004785 |
def tarjan_iter(g):
""" Returns the strongly connected components of the graph @g
in a topological order.
@g is the graph represented as a dictionary
{ <vertex> : <successors of vertex> }.
This function does not recurse. It returns an iterator. ... | 0.019078 |
def _sendMessage(self, msg):
"""
Collapse and send msg to the master
"""
if not msg:
return
msg = self._collapseMsg(msg)
self.sendStatus(msg) | 0.00995 |
def _get_timestamp_cached(dirname_full, remove):
"""
Get the timestamp from the cache or fill the cache
Much quicker than reading the same files over and over
"""
if dirname_full not in TIMESTAMP_CACHE:
mtime = _get_timestamp(dirname_full, remove)
TIMESTAMP_CACHE[dirname_full] = mtim... | 0.002762 |
def check_cv(cv=3, y=None, classifier=False):
"""Dask aware version of ``sklearn.model_selection.check_cv``
Same as the scikit-learn version, but works if ``y`` is a dask object.
"""
if cv is None:
cv = 3
# If ``cv`` is not an integer, the scikit-learn implementation doesn't
# touch th... | 0.00129 |
def parse_deckspawn_metainfo(protobuf: bytes, version: int) -> dict:
'''Decode deck_spawn tx op_return protobuf message and validate it,
Raise error if deck_spawn metainfo incomplete or version mistmatch.'''
deck = DeckSpawnProto()
deck.ParseFromString(protobuf)
error = {"error": "Deck ({deck})... | 0.002525 |
def get_by_resource(self, resource_uri):
"""
Gets all the labels for the specified resource
Args:
resource_uri: The resource URI
Returns:
dict: Resource Labels
"""
uri = self.URI + self.RESOURCES_PATH + '/' + resource_uri
return self._cli... | 0.005848 |
def update_json_file(filename, items):
"""Updates the json `filename` with a given dict.
:param filename: path to json file (e.g. /etc/glance/policy.json)
:param items: dict of items to update
"""
if not items:
return
with open(filename) as fd:
policy = json.load(fd)
# Comp... | 0.001456 |
def K_separator_Watkins(x, rhol, rhog, horizontal=False, method='spline'):
r'''Calculates the Sounders-Brown `K` factor as used in determining maximum
allowable gas velocity in a two-phase separator in either a horizontal or
vertical orientation. This function approximates a graph published in [1]_
to... | 0.00711 |
def more_master_mem_overhead(self, mem_increase_mb=1000):
"""
Method to increase the amount of memory overheaded asked for the master node.
Return: new master memory overhead if success, 0 if it cannot be increased.
"""
old_master_mem_overhead = self.master_mem_overhead
n... | 0.006154 |
def _compute_style_of_faulting_term(self, C, rup):
"""
Returns the style of faulting factor, depending on the mechanism (rake)
and top of rupture depth (equations (4) and (5), pages 145 - 146)
"""
frv, fnm = self._get_fault_type_dummy_variables(rup.rake)
if frv > 0.:
... | 0.003396 |
def rmswidth(self, floor=0):
"""Calculate :ref:`pysynphot-formula-rmswidth`.
Parameters
----------
floor : float
Throughput values equal or below this threshold are not
included in the calculation. By default (0), all points
are included.
Ret... | 0.002039 |
def keys(self):
"""Return a list of all resource names of this widget."""
keys = ttk.Label.keys(self)
keys.extend(["link", "normal_color", "hover_color", "clicked_color"])
return keys | 0.009302 |
def parse_union_type_extension(lexer: Lexer) -> UnionTypeExtensionNode:
"""UnionTypeExtension"""
start = lexer.token
expect_keyword(lexer, "extend")
expect_keyword(lexer, "union")
name = parse_name(lexer)
directives = parse_directives(lexer, True)
types = parse_union_member_types(lexer)
... | 0.002004 |
def parser_setup():
"""Create ArgumentParser object to parse command line arguments.
Returns:
parser (object): containing ArgumentParser data and methods.
Raises:
SystemExit: if the user enters invalid args.
"""
parser = argparse.ArgumentParser(description="Control AWS instances fr... | 0.000186 |
def get_group(path, follow_symlinks=True):
'''
Return the group that owns a given file
Under Windows, this will return the user (owner) of the file.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
conf... | 0.000649 |
def message(self, value):
"""Attempt to deconstruct error message to retrieve further
error data.
"""
try:
import ast
value = ast.literal_eval(value)
except (SyntaxError, TypeError, ValueError):
pass
try:
value = value.get('... | 0.002535 |
def transform(params):
"""
Transforms an heterogeneous map of params into a CloudStack
ready mapping of parameter to values.
It handles lists and dicts.
>>> p = {"a": 1, "b": "foo", "c": ["eggs", "spam"], "d": {"key": "value"}}
>>> transform(p)
>>> print(p)
{'a': '1', 'b': 'foo', 'c': ... | 0.000721 |
def get_paths(self, key):
''' Retrieve a set of environment paths from the config
Parameters:
key (str):
The section name to grab from the environment
Returns:
self.environ[newkey] (OrderedDict):
An ordered dict containing all of the path... | 0.00299 |
def order_series_by(series, order_series):
"""
Orders one series according to another series, or a list of other
series. If a list of other series are specified, ordering is done hierarchically
like when a list of columns is supplied to `.sort_values()`.
Args:
series (:obj:`pandas.Series`):... | 0.002358 |
def update_folder_name(self, name, update_folder_data=True):
""" Change this folder name
:param str name: new name to change to
:param bool update_folder_data: whether or not to re-fetch the data
:return: Updated or Not
:rtype: bool
"""
if self.root:
... | 0.00173 |
def url_concat(url, args):
"""Concatenate url and argument dictionary regardless of whether
url has existing query parameters.
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
"""
if not args: return url
if url[-1] not in ('?', '&'):
url += ... | 0.005155 |
def exit(self):
"""Call this to exit cleanly."""
# First detach all servo's, otherwise it somehow doesn't want to close...
if hasattr(self, 'digital'):
for pin in self.digital:
if pin.mode == SERVO:
pin.mode = OUTPUT
if hasattr(self, 'sp'):... | 0.008621 |
def getTransitionProbabilities(s, x, F, a):
"""Calculate the transition probabilities for the given state and action.
Parameters
----------
s : float
The probability of a population remaining in its current abundance
class
x : int
The population abundance class
F : i... | 0.003012 |
def users_autocomplete(self, name=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users#autocomplete-users"
api_path = "/api/v2/users/autocomplete.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update(kwargs["query"])
del kwargs["qu... | 0.00625 |
def xminvsks(self, **kwargs):
"""
Plot xmin versus the ks value for derived alpha. This plot can be used
as a diagnostic of whether you have derived the 'best' fit: if there are
multiple local minima, your data set may be well suited to a broken
powerlaw or a different function.... | 0.014041 |
def on_audio_adapter_change(self, audio_adapter):
"""Triggerd when settings of the audio adapter of the
associated virtual machine have changed.
in audio_adapter of type :class:`IAudioAdapter`
raises :class:`VBoxErrorInvalidVmState`
Session state prevents operation.
... | 0.008915 |
def _redundancy_routers_for_floatingip(
self, context, router_id, redundancy_router_ids=None,
ha_settings_db=None):
"""To be called in update_floatingip() to get the
redundant router ids.
"""
if ha_settings_db is None:
ha_settings_db = self._get_ha... | 0.00274 |
def _set_cluster(self, v, load=False):
"""
Setter method for cluster, mapped from YANG variable /cluster (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_cluster is considered as a private
method. Backends looking to populate this variable should
do so via ... | 0.00331 |
def offset_byte_in_data(target_data, offset, target_byte_pos, readable = False, wraparound = False):
"""
Offset a given byte in the provided data payload (kind of rot(x))
readable will return a human-readable representation of the byte+offset
wraparound will wrap around 255 to 0 (ex: 257 = 2... | 0.005882 |
def _slr_build_parser_table(productionset):
"""SLR method to build parser table"""
result = ParserTable()
statesset = build_states_sets(productionset)
for itemindex, itemset in enumerate(statesset):
LOG.debug("_slr_build_parser_table: Evaluating itemset:" + str(itemset))
for symbol in pr... | 0.00692 |
def pattern_to_regex(cls, *args, **kw):
"""
Warn about deprecation.
"""
cls._deprecated()
return super(GitIgnorePattern, cls).pattern_to_regex(*args, **kw) | 0.042424 |
def percentile_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=1024, percentile_limits="minmax", selection=False, delay=False):
"""Calculate the percentile given by percentage, possibly on a grid defined by binby.
NOTE: this value is approximated by... | 0.003878 |
def call(self, verb, servicePath, data=None, headers=None, forceText=False, sendJson=True):
"""Call the Nutch Server, do some error checking, and return the response.
:param verb: One of nutch.RequestVerbs
:param servicePath: path component of URL to append to endpoint, e.g. '/config'
:... | 0.00499 |
def setSingleStep(self, singleStep):
"""setter to _singleStep. converts negativ values to positiv ones.
Args:
singleStep (int): new _singleStep value. converts negativ values to positiv ones.
Raises:
TypeError: If the given argument is not an integer.
Returns:
... | 0.004902 |
def _convert_to_dict(stdout):
"""Wrapper function for parsing hpssacli/ssacli command.
This function gets the output from hpssacli/ssacli command
and calls the recursive function _get_dict to return
the complete dictionary containing the RAID information.
"""
lines = stdout.split("\n")
lin... | 0.002404 |
def get_events(self, start_time, end_time, ignore_cancelled = True, get_recurring_events_as_instances = True, restrict_to_calendars = []):
'''A wrapper for events().list. Returns the events from the calendar within the specified times. Some of the interesting fields are:
description, end, htmlLi... | 0.013482 |
def create(self, client_id, title, unsubscribe_page, confirmed_opt_in,
confirmation_success_page, unsubscribe_setting="AllClientLists"):
"""Creates a new list for a client."""
body = {
"Title": title,
"UnsubscribePage": unsubscribe_page,
"ConfirmedOptIn... | 0.006547 |
def join(self, right_table, on=None, right_prefix='R.', outer=False):
"""
Inner-joins another DataTable to this one using `on` (iterable of join
keys). If two tables share columns other than the join keys, appends
right_prefix to the right table's column name. If `on` is not
prov... | 0.002451 |
def date_tuple(ovls):
"""
We should have a list of overlays from which to extract day month
year.
"""
day = month = year = 0
for o in ovls:
if 'day' in o.props:
day = o.value
if 'month' in o.props:
month = o.value
if 'year' in o.props:
... | 0.001838 |
def _set_fc_speed_cfg(self, v, load=False):
"""
Setter method for fc_speed_cfg, mapped from YANG variable /interface/fc_port/fc_speed_cfg (fc-speed-cfg-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fc_speed_cfg is considered as a private
method. Backends look... | 0.004373 |
def normalize_param(self, slf, args, kwargs):
"""this is where all the magic happens, this will try and find the param and
put its value in kwargs if it has a default and stuff"""
if self.is_kwarg:
kwargs = self.normalize_kwarg(slf.request, kwargs)
else:
args = se... | 0.007732 |
def geodetic2ecef(lat: float, lon: float, alt: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
point transformation from Geodetic of specified ellipsoid (default WGS-84) to ECEF
Parameters
----------
lat : float or numpy.ndarray of float
... | 0.001819 |
def setup_placeholders(self):
"""
Creates the TensorFlow placeholders, variables, ops and functions for this model.
NOTE: Does not add the internal state placeholders and initialization values to the model yet as that requires
the model's Network (if any) to be generated first.
"... | 0.004471 |
def refactor_with_2to3(source_text, fixer_names, filename=''):
"""Use lib2to3 to refactor the source.
Return the refactored source code.
"""
from lib2to3.refactor import RefactoringTool
fixers = ['lib2to3.fixes.fix_' + name for name in fixer_names]
tool = RefactoringTool(fixer_names=fixers, ex... | 0.001608 |
def grounded_monomer_patterns(model, agent, ignore_activities=False):
"""Get monomer patterns for the agent accounting for grounding information.
Parameters
----------
model : pysb.core.Model
The model to search for MonomerPatterns matching the given Agent.
agent : indra.statements.Agent
... | 0.00067 |
def apply_vcc(self, vcc, distribution_skip=False,
**kwargs):
"""
Applies "velocity contrast curve" to population.
That is, the constraint that comes from not seeing two sets
of spectral lines in a high resolution spectrum.
Only works if population has ``dmag``... | 0.005291 |
def serialise(self, obj):
"""
Take an object from the project or the runner and serialise it into a
dictionary.
Parameters
----------
obj : object
An object to serialise.
Returns
-------
object
A serialised version of the ... | 0.002339 |
def default(self, statement: Statement) -> Optional[bool]:
"""Executed when the command given isn't a recognized command implemented by a do_* method.
:param statement: Statement object with parsed input
"""
if self.default_to_shell:
if 'shell' not in self.exclude_from_histo... | 0.005137 |
def _generate_union_serializer(self, union):
"""Emits the serialize method for the serialization object for the given union."""
union_name = fmt_class_prefix(union)
with self.block_func(
func='serialize',
args=fmt_func_args_declaration([('valueObj',
... | 0.00157 |
def load_file(self, filename):
"""Load xml into treeview"""
self.tree_editor.load_file(filename)
self.project_name.configure(text=filename)
self.currentfile = filename
self.is_changed = False | 0.008621 |
def daemonize():
"""
Forks and daemonizes the current process. Does not automatically track
the process id; to do this, use :class:`Exscript.util.pidutil`.
"""
sys.stdout.flush()
sys.stderr.flush()
# UNIX double-fork magic. We need to fork before any threads are
# created.
pid = os.... | 0.0016 |
def _write_cache(self, lines, append=False):
"""Write virtualenv metadata to cache."""
mode = 'at' if append else 'wt'
with open(self.filepath, mode, encoding='utf8') as fh:
fh.writelines(line + '\n' for line in lines) | 0.007874 |
def getsourcefallback(cls):
""" Fallback for getting the source of interactively defined classes (typically in ipython)
This is basically just a patched version of the inspect module, in which
we get the code by calling inspect.findsource on an *instancemethod* of
a class for which inspect.findsource f... | 0.003562 |
def getattr(self, tid, fh=None):
"""
File attributes.
Parameters
----------
tid : str
Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator.
fh : int
File descriptor. Unnecessary, therefore ignored.
... | 0.010395 |
def vector_drive(self, vx, vy, vw, tm_diff):
"""Call this from your :func:`PhysicsEngine.update_sim` function.
Will update the robot's position on the simulation field.
This moves the robot using a velocity vector relative to the robot
instead of by speed/rotation sp... | 0.004171 |
def truthtable2expr(tt, conj=False):
"""Convert a truth table into an expression."""
if conj:
outer, inner = (And, Or)
nums = tt.pcdata.iter_zeros()
else:
outer, inner = (Or, And)
nums = tt.pcdata.iter_ones()
inputs = [exprvar(v.names, v.indices) for v in tt.inputs]
t... | 0.002309 |
def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any],
logger: Logger) -> Dict[str, Any]:
"""
Simply inspects the required type to find the names and types of its constructor arguments.
Then relies ... | 0.0086 |
def get_alignment_df_from_file(alignment_file, a_seq_id=None, b_seq_id=None):
"""Get a Pandas DataFrame of the Needle alignment results. Contains all positions of the sequences.
Args:
alignment_file:
a_seq_id: Optional specification of the ID of the reference sequence
b_seq_id: Optional... | 0.002871 |
def Hf_g(CASRN, AvailableMethods=False, Method=None):
r'''This function handles the retrieval of a chemical's gas heat of
formation. Lookup is based on CASRNs. Will automatically select a data
source to use if no Method is provided; returns None if the data is not
available.
Prefered sources are 'A... | 0.001131 |
def toString(self, obj):
"""
Convert the given L{Identifier} to a string.
"""
return Box(shareID=obj.shareID.encode('utf-8'),
localpart=obj.localpart.encode('utf-8'),
domain=obj.domain.encode('utf-8')).serialize() | 0.007067 |
def _set_mac_move_action(self, v, load=False):
"""
Setter method for mac_move_action, mapped from YANG variable /mac_address_table/mac_move/mac_move_action (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_move_action is considered as a private
method... | 0.004427 |
def get_exclusions(self):
"""
Return a collections.Sized collections.Container of paths to be
excluded for single_version_externally_managed installations.
"""
all_packages = (
pkg
for ns_pkg in self._get_SVEM_NSPs()
for pkg in self._all_packag... | 0.004193 |
def _extract_mnist_labels(filename, num_labels):
"""Extract labels from an MNIST file into integers.
Args:
filename: The path to an MNIST labels file.
num_labels: The number of labels in the file.
Returns:
A int64 numpy array of shape [num_labels]
"""
with gzip.open(filename) as bytestream:
... | 0.008753 |
def ok_for_running(self, cmd_obj, name, cmd_hash):
'''We separate some of the common debugger command checks here:
whether it makes sense to run the command in this execution state,
if the command has the right number of arguments and so on.
'''
if hasattr(cmd_obj, 'execution_set... | 0.003846 |
def _find_dirs(metadata):
'''
Looks for all the directories in the S3 bucket cache metadata.
Supports trailing '/' keys (as created by S3 console) as well as
directories discovered in the path of file keys.
'''
ret = []
found = {}
for bucket_dict in metadata:
for bucket_name, ... | 0.000934 |
def replace_node_status(self, name, body, **kwargs):
"""
replace status of the specified Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_node_status(name, body, async_req=True)... | 0.003947 |
def custom_render_template(template_name_or_list, **context):
"""
Try to render templates in the custom folder first,
if no custom templates, try the theme's default ones.
"""
response_str = render_template(
functools.reduce(lambda x, y: x + [os.path.join('custom', y), y],
... | 0.001887 |
def get(self, path):
""" Get a transform from the cache that maps along *path*, which must
be a list of Transforms to apply in reverse order (last transform is
applied first).
Accessed items have their age reset to 0.
"""
key = tuple(map(id, path))
item = self._c... | 0.005128 |
def install_config_kibana(self):
"""
install and config kibana
:return:
"""
if self.prompt_check("Download and install kibana"):
self.kibana_install()
if self.prompt_check("Configure and autostart kibana"):
self.kibana_config() | 0.006667 |
def _mod_bufsize_linux(iface, *args, **kwargs):
'''
Modify network interface buffer sizes using ethtool
'''
ret = {'result': False,
'comment': 'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'}
cmd = '/sbin/ethtool -G ' + iface
if not kwargs:
return ret
if ... | 0.002198 |
def pack_header_for_user(
self, user,
override_access_lifespan=None, override_refresh_lifespan=None,
**custom_claims
):
"""
Encodes a jwt token and packages it into a header dict for a given user
:param: user: The user to package the ... | 0.001883 |
def get_file_object(username, password, utc_start=None, utc_stop=None):
"""Make the connection. Return a file-like object."""
if not utc_start:
utc_start = datetime.now()
if not utc_stop:
utc_stop = utc_start + timedelta(days=1)
logging.info("Downloading schedules for username [%s] in... | 0.003623 |
def _flush_queue(self, q, ignore_priority=False):
"""
:param q: PriorityQueue instance holding GarbageCollector entries
:param ignore_priority: If True - all GarbageCollector entries should be resubmitted
If False - only those entries whose waiting time has expired will be resubm... | 0.005312 |
def manage_options(self):
"""
Create a parser given the command-line arguments, creates a parser
Return True if the programme must exit.
"""
self.parser = self.create_parser()
self.options, self.args = self.parser.parse_args(self.argv)
self.do_imports()
... | 0.006243 |
def optimize_updates(params, gradients, config=None, shapes=None):
"""
General optimization function for Theano.
Parameters:
params - parameters
gradients - gradients
config - training config
Returns:
Theano updates
:type config: deepy.TrainerConfig or dict
"""
... | 0.002284 |
def inheritdocstring(name, bases, attrs):
"""
Use as metaclass to inherit class and method docstrings from parent.
Adapted from http://stackoverflow.com/questions/13937500/inherit-a-parent-class-docstring-as-doc-attribute
Use this on classes defined in solver-specific interfaces to inherit docstrings fr... | 0.002703 |
def build_ports_dict(nsg, direction_key, ip_protocol):
""" Build entire ports array filled with True (Allow), False (Deny) and None(default - Deny)
based on the provided Network Security Group object, direction and protocol.
"""
rules = nsg['properties']['securityRules']
rule... | 0.004684 |
def qos_queue_scheduler_strict_priority_dwrr_traffic_class1(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 doc_from_xml(document_element_name, inner_xml):
'''Wraps the specified xml in an xml root element with default azure
namespaces'''
xml = ''.join(['<', document_element_name,
' xmlns:i="http://www.w3.org/2001/XMLSchema-instance"',
' xmlns="http://sc... | 0.006522 |
def create_index_tuple(group_ids):
"""An helper function to create index tuples for fast lookup in HDF5Pump"""
max_group_id = np.max(group_ids)
start_idx_arr = np.full(max_group_id + 1, 0)
n_items_arr = np.full(max_group_id + 1, 0)
current_group_id = group_ids[0]
current_idx = 0
item_count... | 0.001258 |
def text2wngram(text, output_file, n=3, chars=63636363, words=9090909, compress=False, verbosity=2):
"""
List of every word n-gram which occurred in the text, along with its number of occurrences.
The maximum numbers of charactors and words that can be stored in the buffer are given by the chars and... | 0.009259 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.