text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_dotted(self, key):
"""
obj = qs.get_dotted('foo.bar.baz')
is equivelent to:
obj = qs.foo.bar.baz
"""
parts = key.split('.')
cobj = self
for attr in parts:
cobj = getattr(cobj, attr)
return cobj | 0.006515 |
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
... | 0.00713 |
def __read_byte_offset(decl, attrs):
"""Using duck typing to set the offset instead of in constructor"""
offset = attrs.get(XML_AN_OFFSET, 0)
# Make sure the size is in bytes instead of bits
decl.byte_offset = int(offset) / 8 | 0.007782 |
def print_summary(self, verbose=False, no_color=False):
'Prints a summary of the validation process so far.'
types = {0: 'Unknown',
1: 'Extension/Multi-Extension',
2: 'Full Theme',
3: 'Dictionary',
4: 'Language Pack',
... | 0.000718 |
def _dictionary(self):
# type: () -> Dict[str, Any]
"""A dictionary representing the loaded configuration.
"""
# NOTE: Dictionaries are not populated if not loaded. So, conditionals
# are not needed here.
retval = {}
for variant in self._override_order:
... | 0.007732 |
def overlay_gateway_activate(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
name_key.text ... | 0.006085 |
def _encode_path(path_items):
"""Take an iterable of ``(path_operation, coordinates)`` tuples
in the same format as from :meth:`Context.copy_path`
and return a ``(path, data)`` tuple of cdata object.
The first cdata object is a ``cairo_path_t *`` pointer
that can be used as long as both objects liv... | 0.000748 |
def user_transactions(self, offset=0, limit=100, descending=True,
base=None, quote=None):
"""
Returns descending list of transactions. Every transaction (dictionary)
contains::
{u'usd': u'-39.25',
u'datetime': u'2013-03-26 18:49:13',
... | 0.003769 |
def publish(self, message_type=ON_SEND, client_id=None, client_storage=None,
*args, **kwargs):
"""
Publishes a message
"""
self.publisher.publish(
message_type, client_id, client_storage, *args, **kwargs) | 0.011364 |
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
figure = self.get_root()
assert isinstance(figure, Figure), ('You cannot render this Element '
'if it is not in a Figure.')
header = self._template.module.__dict... | 0.001947 |
def install_mathjax(tag='v1.1', replace=False):
"""Download and install MathJax for offline use.
This will install mathjax to the 'static' dir in the IPython notebook
package, so it will fail if the caller does not have write access
to that location.
MathJax is a ~15MB download, and ~150MB... | 0.006645 |
def copyHiddenToContext(self):
"""
Uses key to identify the hidden layer associated with each
layer in the self.contextLayers dictionary.
"""
for item in list(self.contextLayers.items()):
if self.verbosity > 2: print('Hidden layer: ', self.getLayer(item[0]).activatio... | 0.015625 |
def on_stop(self):
"""
stop subscriber
"""
LOGGER.debug("zeromq.Subscriber.on_stop")
self.running = False
while self.is_started:
time.sleep(0.1)
self.zmqsocket.close()
self.zmqcontext.destroy() | 0.007435 |
def gaussian(h, Xi, x):
"""
Gaussian Kernel for continuous variables
Parameters
----------
h : 1-D ndarray, shape (K,)
The bandwidths used to estimate the value of the kernel function.
Xi : 1-D ndarray, shape (K,)
The value of the training set.
x : 1-D ndarray, shape (K,)
... | 0.001634 |
def graceful(cls):
""" A decorator to protect against message structure changes.
Many of our processors expect messages to be in a certain format. If the
format changes, they may start to fail and raise exceptions. This decorator
is in place to catch and log those exceptions and to gracefully return
... | 0.00299 |
def imagetransformer_b12l_4h_b128_h512_uncond_dr01_im():
"""TPU related imagenet model."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.learning_rate_w... | 0.025 |
def service(
state, host,
*args, **kwargs
):
'''
Manage the state of services. This command checks for the presence of all the
init systems pyinfra can handle and executes the relevant operation. See init
system sepcific operation for arguments.
'''
if host.fact.which('systemctl'):
... | 0.003628 |
def add_dynamic_gateway(self, networks):
"""
A dynamic gateway object creates a router object that is
attached to a DHCP interface. You can associate networks with
this gateway address to identify networks for routing on this
interface.
::
route = en... | 0.006342 |
def free_symbols(self):
"""Set of free SymPy symbols contained within the expression."""
if self._free_symbols is None:
if len(self._vals) == 0:
self._free_symbols = self.operand.free_symbols
else:
dummy_map = {}
for sym in self._va... | 0.002395 |
def as_object(obj):
"""Return a JSON serializable type for ``o``.
Args:
obj (:py:class:`object`): the object to be serialized.
Raises:
:py:class:`AttributeError`:
when ``o`` is not a Python object.
Returns:
(dict): JSON serializable type for the given object.
"... | 0.002215 |
def parse_arg(arg: str) -> typing.Tuple[str, typing.Any]:
"""
Parse CLI argument in format ``key=value`` to ``(key, value)``
:param arg: CLI argument string
:return: tuple (key, value)
:raise: yaml.ParserError: on yaml parse error
"""
assert '=' in arg, 'Unrecognized argument `{}`. [name]=[... | 0.004425 |
def _update_keywords(self, **update_props):
""" Update operation for ISO type-specific Keywords metadata: Theme or Place """
tree_to_update = update_props['tree_to_update']
prop = update_props['prop']
values = update_props['values']
keywords = []
if prop in KEYWORD_PRO... | 0.00353 |
def read_node(self, name, **kwargs): # noqa: E501
"""read_node # noqa: E501
read the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_node(name, async_re... | 0.001711 |
def get_all_active(self):
"""
Get all of the active messages ordered by the active_datetime.
"""
now = timezone.now()
return self.select_related().filter(active_datetime__lte=now,
inactive_datetime__gte=now).order_by('active_datetime'... | 0.012461 |
def send_keys(self, keyserver, *keyids):
"""Send keys to a keyserver."""
result = self._result_map['list'](self)
log.debug('send_keys: %r', keyids)
data = _util._make_binary_stream("", self._encoding)
args = ['--keyserver', keyserver, '--send-keys']
args.extend(keyids)
... | 0.004202 |
def delete(self, list_id, webhook_id):
"""
Delete a specific webhook in a list.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str`
"""
self.list_id... | 0.006508 |
def toCSV(pdl,out=None,write_field_names=True):
"""Conversion from the PyDbLite Base instance pdl to the file object out
open for writing in binary mode
If out is not specified, the field name is the same as the PyDbLite
file with extension .csv
If write_field_names is True, field names are wri... | 0.010512 |
def web_agent(self, reactor, socks_endpoint, pool=None):
"""
:param socks_endpoint: create one with
:meth:`txtorcon.TorConfig.create_socks_endpoint`. Can be a
Deferred.
:param pool: passed on to the Agent (as ``pool=``)
"""
# local import because there is... | 0.003096 |
def gmres(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None,
M=None, callback=None, residuals=None, orthog='householder',
**kwargs):
"""Generalized Minimum Residual Method (GMRES).
GMRES iteratively refines the initial solution guess to the
system Ax = b
Parameters
... | 0.000232 |
def sg_arg_def(**kwargs):
r"""Defines command line options
Args:
**kwargs:
key: A name for the option.
value : Default value or a tuple of (default value, description).
Returns:
None
For example,
```
# Either of the following two lines will define `--n_epoch` comm... | 0.002172 |
def connect(self, fn):
"""SQLite connect method initialize db"""
self.conn = sqlite3.connect(fn)
cur = self.get_cursor()
cur.execute('PRAGMA page_size=4096')
cur.execute('PRAGMA FOREIGN_KEYS=ON')
cur.execute('PRAGMA cache_size=10000')
cur.execute('PRAGMA journal_m... | 0.006024 |
def _ivy_jvm_options(self, repo):
"""Get the JVM options for ivy authentication, if needed."""
# Get authentication for the publish repo if needed.
if not repo.get('auth'):
# No need to copy here, as this list isn't modified by the caller.
return self._jvm_options
# Create a copy of the opt... | 0.008917 |
def create_authorization(self, scopes=github.GithubObject.NotSet, note=github.GithubObject.NotSet, note_url=github.GithubObject.NotSet, client_id=github.GithubObject.NotSet, client_secret=github.GithubObject.NotSet, onetime_password=None):
"""
:calls: `POST /authorizations <http://developer.github.com/v... | 0.004758 |
def set_debug(self, debug=1):
"""
Set the debug level.
:type debug: int
:param debug: The debug level.
"""
self._check_if_ready()
self.debug = debug
self.main_loop.debug = debug | 0.00823 |
def cfmakeraw(tflags):
"""Given a list returned by :py:func:`termios.tcgetattr`, return a list
modified in a manner similar to the `cfmakeraw()` C library function, but
additionally disabling local echo."""
# BSD: https://github.com/freebsd/freebsd/blob/master/lib/libc/gen/termios.c#L162
# Linux: ht... | 0.006083 |
def _proc_error(ifn: str, e: Exception) -> None:
""" Report an error
:param ifn: Input file name
:param e: Exception to report
"""
type_, value_, traceback_ = sys.exc_info()
traceback.print_tb(traceback_, file=sys.stderr)
print(file=sys.stderr)
print("****... | 0.005063 |
def get_hash(self):
"""Generate and return the dict index hash of the given queue item.
Note:
Cookies should not be included in the hash calculation because
otherwise requests are crawled multiple times with e.g. different
session keys, causing infinite crawling recu... | 0.003311 |
def norm(self, coords: Vector3Like, frac_coords: bool = True) -> float:
"""
Compute the norm of vector(s).
Args:
coords:
Array-like object with the coordinates.
frac_coords:
Boolean stating whether the vector corresponds to fractional or
... | 0.003968 |
def get(self, sid):
"""
Constructs a MessageContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.message.MessageContext
:rtype: twilio.rest.api.v2010.account.message.MessageContext
"""
return MessageContext(s... | 0.007752 |
def show(self, baseAppInstance):
"""Allows to show the widget as root window"""
self.from_dict_to_fields(self.configDict)
super(ProjectConfigurationDialog, self).show(baseAppInstance) | 0.009662 |
def get_or_create(self, qualifier, new_parameter, **kwargs):
"""
Get a :class:`Parameter` from the ParameterSet, if it does not exist,
create and attach it.
Note: running this on a ParameterSet that is NOT a
:class:`phoebe.frontend.bundle.Bundle`,
will NOT add the Parame... | 0.002046 |
def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID conversion.
Parameters
----------
mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
class instance representing MIB browsing functionality.
Returns
-------
: :py... | 0.000412 |
def _main_loop(self):
'''
Continuous loop that reads from a kafka topic and tries to validate
incoming messages
'''
self.logger.debug("Processing messages")
old_time = 0
while True:
self._process_messages()
if self.settings['STATS_DUMP'] !=... | 0.004594 |
def readTuple(self, stream):
"""Read symbol from stream. Returns symbol, length.
"""
length, symbol = self.decodePeek(stream.peek(self.maxLength))
stream.pos += length
return length, symbol | 0.008734 |
def call(self, method, args={}, retry=False, retry_policy=None,
ticket=None, **props):
"""Send message to the same actor and return :class:`AsyncResult`."""
ticket = ticket or uuid()
reply_q = self.get_reply_queue(ticket)
self.cast(method, args, declare=[reply_q], reply_to=t... | 0.007874 |
def preserve_builtin_query_params(url, request=None):
"""
Given an incoming request, and an outgoing URL representation,
append the value of any built-in query parameters.
"""
if request is None:
return url
overrides = [
api_settings.URL_FORMAT_OVERRIDE,
]
for param in ... | 0.002053 |
def two_lorentzian(freq, freq0_1, freq0_2, area1, area2, hwhm1, hwhm2, phase1,
phase2, offset, drift):
"""
A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and pha... | 0.007463 |
def get_permission(context, method, *args, **kwargs):
""" This will return a boolean indicating if the considered permission is granted for the passed
user.
Usage::
{% get_permission 'can_access_moderation_panel' request.user as var %}
"""
request = context.get('request', None)
pe... | 0.005708 |
def input(self, *args, **kwargs):
"""
Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors
"""
errors = []
if args and self.arg_names:
args = list(args)
# Replace args inline that have... | 0.001873 |
def find(max_depth=3):
"""Returns the path of a Pipfile in parent directories."""
i = 0
for c, d, f in walk_up(os.getcwd()):
i += 1
if i < max_depth:
if 'Pipfile':
p = os.path.join(c, 'Pipfile')
if os.path.isfile(p)... | 0.004975 |
def _makewindows(self, indices, window):
"""
Make masks used by windowing functions
Given a list of indices specifying window centers,
and a window size, construct a list of index arrays,
one per window, that index into the target array
Parameters
----------
... | 0.004216 |
def _do_names(names, fun, path=None):
'''
Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
ret = {}
hosts = find_guests(names, path=path)
if not hosts:
re... | 0.00112 |
def copy_ifcfg_file(source_interface, dest_interface):
"""Copies an existing ifcfg network script to another
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises TypeError, OSError
"""
log = logging.getLogger(mod_logger + '.copy_ifcfg_file'... | 0.002702 |
def script_current_send(self, seq, force_mavlink1=False):
'''
This message informs about the currently active SCRIPT.
seq : Active Sequence (uint16_t)
'''
return self.send(self.script_current_encode(seq), force_mavli... | 0.00885 |
def draw(self, **kwargs):
"""
Renders the rfecv curve.
"""
# Compute the curves
x = self.n_feature_subsets_
means = self.cv_scores_.mean(axis=1)
sigmas = self.cv_scores_.std(axis=1)
# Plot one standard deviation above and below the mean
self.ax.f... | 0.004082 |
def _model(self, beta):
""" Creates the structure of the model (model matrices, etc)
Parameters
----------
beta : np.array
Contains untransformed starting values for the latent variables
Returns
----------
lambda : n... | 0.007493 |
def load(self, filething):
"""load(filething)
Load file information from a filename.
Args:
filething (filething)
Raises:
mutagen.MutagenError
"""
fileobj = filething.fileobj
try:
self.info = self._Info(fileobj)
s... | 0.003436 |
def commit_config(self, message=""):
"""Implementation of NAPALM method commit_config."""
if message:
raise NotImplementedError(
"Commit message not implemented for this platform"
)
commands = [
"copy startup-config flash:rollback-0",
... | 0.003899 |
async def _run(self):
"""后台任务更新时间戳和重置序号"""
tick_gen = _task_idle_ticks(0.5*self._shard_ttl)
self._is_running = True
self._ready_event.clear()
while True:
try:
await self._lease_shard()
break
except grpc.RpcError as... | 0.004219 |
async def async_run_command(self, command, retry=False):
"""Run commands through an SSH connection.
Connect to the SSH server if not currently connected, otherwise
use the existing connection.
"""
if not self.is_connected:
await self.async_connect()
try:
... | 0.002006 |
def is_response_correct(self, response):
"""returns True if response evaluates to an Item Answer that is 100 percent correct"""
for answer in self.my_osid_object.get_answers():
if self._is_match(response, answer):
return True
return False | 0.010345 |
def hierarchy_cycles(rdf, fix=False):
"""Check if the graph contains skos:broader cycles and optionally break these.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing any skos:broader that overlaps
with skos:broaderTransitive.
"""
top_concepts = so... | 0.002212 |
def __create_log_props(cls, log_props, _getdict, _setdict): # @NoSelf
"""Creates all the logical property.
The list of names of properties to be created is passed
with frozenset log_props. The getter/setter information is
taken from _{get,set}dict.
This method resolves also wi... | 0.00239 |
def _param32(ins):
""" Pushes 32bit param into the stack
"""
output = _32bit_oper(ins.quad[1])
output.append('push de')
output.append('push hl')
return output | 0.005495 |
def clone(self):
"""
Do not initialize again since everything is ready to launch app.
:return: Initialized monitor instance
"""
return Monitor(org=self.org, app=self.app, env=self.env) | 0.008929 |
def DSP_callback_tic(self):
"""
Add new tic time to the DSP_tic list. Will not be called if
Tcapture = 0.
"""
if self.Tcapture > 0:
self.DSP_tic.append(time.time()-self.start_time) | 0.012097 |
def build_genome_alignment_from_file(ga_path, ref_spec, idx_path=None,
verbose=False):
"""
build a genome alignment by loading from a single MAF file.
:param ga_path: the path to the file to load.
:param ref_spec: which species in the MAF file is the reference?
:param id... | 0.008203 |
def sortshaw(s, datablock):
"""
sorts data block in to ARM1,ARM2 NRM,TRM,ARM1,ARM2=[],[],[],[]
stick first zero field stuff into first_Z
"""
for rec in datablock:
methcodes = rec["magic_method_codes"].split(":")
step = float(rec["treatment_ac_field"])
str = float(rec["meas... | 0.000982 |
def calcELAxi(R,vR,vT,pot,vc=1.,ro=1.):
"""
NAME:
calcELAxi
PURPOSE:
calculate the energy and angular momentum
INPUT:
R - Galactocentric radius (/ro)
vR - radial part of the velocity (/vc)
vT - azimuthal part of the velocity (/vc)
vc - circular velocity
r... | 0.017578 |
def get_identities(self, item):
""" Return the identities from an item """
# All identities are in the post stream
# The first post is the question. Next replies
posts = item['data']['post_stream']['posts']
for post in posts:
user = self.get_sh_identity(post)
... | 0.005935 |
def cleanPolyline(elem, options):
"""
Scour the polyline points attribute
"""
pts = parseListOfPoints(elem.getAttribute('points'))
elem.setAttribute('points', scourCoordinates(pts, options, True)) | 0.004566 |
def update(self, name, rssi):
"""Update the device name and/or RSSI.
During an ongoing scan, multiple records from the same device can be
received during the scan. Each time that happens this method is
called to update the :attr:`name` and/or :attr:`rssi` attributes.
"""
... | 0.010101 |
def run_in_terminal(self, func, render_cli_done=False, cooked_mode=True):
"""
Run function on the terminal above the prompt.
What this does is first hiding the prompt, then running this callable
(which can safely output to the terminal), and then again rendering the
prompt which... | 0.001376 |
def normalize(self, **kwargs):
"""
Adjust the offsetvector so that a particular instrument has
the desired offset. All other instruments have their
offsets adjusted so that the relative offsets are
preserved. The instrument to noramlize, and the offset one
wishes it to have, are provided as a key-word arg... | 0.026294 |
def create_snapshot(kwargs=None, call=None, wait_to_finish=False):
'''
Create a snapshot.
volume_id
The ID of the Volume from which to create a snapshot.
description
The optional description of the snapshot.
CLI Exampe:
.. code-block:: bash
salt-cloud -f create_snaps... | 0.001971 |
def import_cls(cls_name):
"""Import class by its fully qualified name.
In terms of current example it is just a small helper function. Please,
don't use it in production approaches.
"""
path_components = cls_name.split('.')
module = __import__('.'.join(path_components[:-1]),
... | 0.002119 |
def getEdges(npArr):
"""get np array of bin edges"""
edges = np.concatenate(([0], npArr[:,0] + npArr[:,2]))
return np.array([Decimal(str(i)) for i in edges]) | 0.03681 |
def from_characteristic_rate(cls, min_mag, b_val, char_mag, char_rate,
bin_width):
"""
Define Youngs and Coppersmith 1985 MFD by constraing cumulative a
value from characteristic rate.
The cumulative a value is obtained by making use of the property that
... | 0.001216 |
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ValueError, AttributeError):
raise ImportError('Cla... | 0.002174 |
def create_negotiate_message(self, domain_name=None, workstation=None):
"""
Create an NTLM NEGOTIATE_MESSAGE
:param domain_name: The domain name of the user account we are authenticating with, default is None
:param worksation: The workstation we are using to authenticate with, default ... | 0.008757 |
def subvolume_find_new(name, last_gen):
'''
List the recently modified files in a subvolume
name
Name of the subvolume
last_gen
Last transid marker from where to compare
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_find_new /var/volumes/tmp 1024
''... | 0.002597 |
def ve_interfaces(self, **kwargs):
"""list[dict]: A list of dictionary items describing the operational
state of ve interfaces along with the ip address associations.
Args:
rbridge_id (str): rbridge-id for device.
callback (function): A function executed upon completion ... | 0.000963 |
def sg_symbol_from_int_number(int_number, hexagonal=True):
"""
Obtains a SpaceGroup name from its international number.
Args:
int_number (int): International number.
hexagonal (bool): For rhombohedral groups, whether to return the
hexagonal setting (default) or rhombohedral sett... | 0.00122 |
def scrape_wikinews(conn, project, articleset, query):
"""
Scrape wikinews articles from the given query
@param conn: The AmcatAPI object
@param articleset: The target articleset ID
@param category: The wikinews category name
"""
url = "http://en.wikinews.org/w/index.php?search={}&limit=50".... | 0.002878 |
def removeRow(self, triggered):
"""Removes a row to the model.
This method is also a slot.
Args:
triggered (bool): If the corresponding button was
activated, the selected row will be removed
from the model.
"""
if triggered:
... | 0.003565 |
def move_tab(self, index_from, index_to):
"""
Move tab.
(tabs themselves have already been moved by the history.tabwidget)
"""
filename = self.filenames.pop(index_from)
editor = self.editors.pop(index_from)
self.filenames.insert(index_to, filename)
self.... | 0.005682 |
def resize(self, size, interp='bilinear'):
"""Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str... | 0.003974 |
def scan_to_table(input_table, genome, scoring, pwmfile=None, ncpus=None):
"""Scan regions in input table with motifs.
Parameters
----------
input_table : str
Filename of input table. Can be either a text-separated tab file or a
feather file.
genome : str
Genome name. C... | 0.005398 |
def query( self ):
"""
Returns the query this widget is representing from the tree widget.
:return <Query> || <QueryCompound> || None
"""
if ( not self.uiQueryCHK.isChecked() ):
return None
# build a query if not searching all
... | 0.016032 |
def on(self):
"""
Turn all the output devices on.
"""
for device in self:
if isinstance(device, (OutputDevice, CompositeOutputDevice)):
device.on() | 0.009662 |
def load(custom_url=None, pkg_type=None, serve_local=None, version='4.9.2'):
"""Load CKEditor resource from CDN or local.
:param custom_url: The custom resource url to use, build your CKEditor
on `CKEditor builder <https://ckeditor.com/cke4/builder>`_.
:param pkg_type: The type of C... | 0.003086 |
def login():
" View function which handles an authentication request. "
form = LoginForm(request.form)
# make sure data are valid, but doesn't validate password is right
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
# we use werzeug to validate ... | 0.002924 |
def count(index,h):
'''
Gives count of the documents stored in Elasticsearch. If index option is
provided, it will provide document count of that index.
'''
try:
response = base.es.cat.count(index,h=h)
table = base.draw_table(response)
except Exception as e:
click.echo(e)... | 0.008427 |
def print_splits(cliques, next_cliques):
"""Print shifts for new forks."""
splits = 0
for i, clique in enumerate(cliques):
parent, _ = clique
# If this fork continues
if parent in next_cliques:
# If there is a new fork, print a split
if len(next_cliques[paren... | 0.002387 |
def _next_file(self):
"""Find next filename.
self._filenames may need to be expanded via listbucket.
Returns:
None if no more file is left. Filename otherwise.
"""
while True:
if self._bucket_iter:
try:
return self._bucket_iter.next().filename
except StopItera... | 0.013889 |
def _get_children(self, index):
"""
Извлекает всех потомков вершины с номером index
"""
if self.dict_storage:
return list(self.graph[index].values())
else:
return [elem for elem in self.graph[index] if elem != Trie.NO_NODE] | 0.006969 |
def propagate_timezone_option(self):
"""Set our timezone value and give it too to unset satellites
:return: None
"""
if self.use_timezone:
# first apply myself
os.environ['TZ'] = self.use_timezone
time.tzset()
tab = [self.schedulers, self... | 0.005236 |
def download_to_file(self, file):
"""
Download and store the file of the sample.
:param file: A file-like object to store the file.
"""
con = ConnectionManager().get_connection(self._connection_alias)
return con.download_to_file(self.file, file, append_base_url=False) | 0.006309 |
def fftlog(fEM, time, freq, ftarg):
r"""Fourier Transform using FFTLog.
FFTLog is the logarithmic analogue to the Fast Fourier Transform FFT.
FFTLog was presented in Appendix B of [Hami00]_ and published at
<http://casa.colorado.edu/~ajsh/FFTLog>.
This function uses a simplified version of ``pyfft... | 0.000242 |
def load_template_source(self, *ka):
"""
Backward compatible method for Django < 2.0.
"""
template_name = ka[0]
for origin in self.get_template_sources(template_name):
try:
return self.get_contents(origin), origin.name
except TemplateDoesNo... | 0.005025 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.