text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _decode_record(self, s, line=0):
'''Decode one record of HEX file.
@param s line with HEX record.
@param line line number (for error messages).
@raise EndOfFile if EOF record encountered.
'''
s = s.rstrip('\r\n')
if not s:
return ... | 0.001823 |
def search(cls,
query_string,
options=None,
enable_facet_discovery=False,
return_facets=None,
facet_options=None,
facet_refinements=None,
deadline=None,
**kwargs):
"""
Searches the ind... | 0.008925 |
def _cryptography_cipher(key, iv):
"""Build a cryptography TripleDES Cipher object.
:param bytes key: Encryption key
:param bytesiv iv: Initialization vector
:returns: TripleDES Cipher instance
:rtype: cryptography.hazmat.primitives.ciphers.Cipher
"""
return Cipher(
algorithm=algori... | 0.002451 |
def load_model(f, format=None, load_external_data=True): # type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto
'''
Loads a serialized ModelProto into memory
@params
f can be a file-like object (has "read" function) or a string containing a file name
format is for future use
@ret... | 0.004491 |
def get_storage_info(self, human=False):
"""
Get storage info
:param bool human: whether return human-readable size
:return: total and used storage
:rtype: dict
"""
res = self._req_get_storage_info()
if human:
res['total'] = humanize.naturals... | 0.004525 |
def reflect_static_member(cls, name):
"""Reflect 'name' using ONLY static reflection.
You most likely want to use ScopeStack.reflect instead.
Returns:
Type of 'name', or protocol.AnyType.
"""
for scope in reversed(cls.scopes):
try:
return... | 0.004065 |
def get_version(self, diff_to_increase_ratio):
"""Gets version
:param diff_to_increase_ratio: Ratio to convert number of changes into
:return: Version of this code, based on commits diffs
"""
diffs = self.get_diff_amounts()
version = Version()
for diff in diffs:... | 0.004831 |
def make_simple():
"""
Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error.
"""
authfile = config.get('coilmq', 'auth.simple.... | 0.003968 |
async def delete_sticker_from_set(self, sticker: base.String) -> base.Boolean:
"""
Use this method to delete a sticker from a set created by the bot.
The following methods and objects allow your bot to work in inline mode.
Source: https://core.telegram.org/bots/api#deletestickerfromset... | 0.00607 |
def from_stub(cls, data, udas=None):
""" Create a Task from an already deserialized dict. """
udas = udas or {}
fields = cls.FIELDS.copy()
fields.update(udas)
processed = {}
for k, v in six.iteritems(data):
processed[k] = cls._serialize(k, v, fields)
... | 0.005731 |
def etherleak(target, **kargs):
"""Exploit Etherleak flaw"""
return srp(Ether() / ARP(pdst=target),
prn=lambda s_r: conf.padding_layer in s_r[1] and hexstr(s_r[1][conf.padding_layer].load), # noqa: E501
filter="arp", **kargs) | 0.003788 |
def get_variables(expression, variables=None):
"""Returns the set of variable names in the given expression."""
if variables is None:
variables = set()
if hasattr(expression, 'variable_name') and expression.variable_name is not None:
variables.add(expression.variable_name)
if isinstance(... | 0.004405 |
def get_instances_by_name(name, sort_by_order=('cloud', 'name'), projects=None, raw=True, regions=None, gcp_credentials=None, clouds=SUPPORTED_CLOUDS):
"""Get intsances from GCP and AWS by name."""
matching_instances = all_clouds_get_instances_by_name(
name, projects, raw, credentials=gcp_credentials, c... | 0.006803 |
def drawCurve(self, p1, p2, p3):
"""Draw a curve between points using one control point.
"""
kappa = 0.55228474983
p1 = Point(p1)
p2 = Point(p2)
p3 = Point(p3)
k1 = p1 + (p2 - p1) * kappa
k2 = p3 + (p2 - p3) * kappa
return self.drawBezier(p1, k1, k... | 0.006135 |
def __valueKeyWithHeaderIndex(self, values):
"""
This is hellper function, so that we can mach decision values with row index
as represented in header index.
Args:
values (dict): Normaly this will have dict of header values and values from decision
Return:
>>> return()
{
values[headerName] : in... | 0.037736 |
def _calc_probability(self):
'''Determines the probability that each bee will be chosen during the
onlooker phase; also determines if a new best-performing bee is found
'''
self._logger.log('debug', 'Calculating bee probabilities')
self.__verify_ready()
self._total_score... | 0.002146 |
def extract_constant(code, symbol, default=-1):
"""Extract the constant value of 'symbol' from 'code'
If the name 'symbol' is bound to a constant value by the Python code
object 'code', return that value. If 'symbol' is bound to an expression,
return 'default'. Otherwise, return 'None'.
Return v... | 0.004638 |
def find_or_graft(self, board):
"""Build a tree with each level corresponding to a fixed position on
board. A path of tiles is stored for each board. If any two boards
have the same path, then they are the same board. If there is any
difference, a new branch will be created to store that... | 0.001494 |
def add_resource(self, descriptor):
"""https://github.com/frictionlessdata/datapackage-py#package
"""
self.__current_descriptor.setdefault('resources', [])
self.__current_descriptor['resources'].append(descriptor)
self.__build()
return self.__resources[-1] | 0.006579 |
def create_apply_graph(self, signature, input_tensors, name):
"""See `ModuleImpl.create_apply_graph`."""
signature_def = self._meta_graph.signature_def.get(signature)
meta_graph = meta_graph_pb2.MetaGraphDef()
meta_graph.CopyFrom(self._meta_graph)
apply_graph = tf_v1.get_default_graph()
infeed_m... | 0.004654 |
def fastp_read_n_plot(self):
""" Make the read N content plot for Fastp """
data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_n_content_data, 'Base Content Percent')
pconfig = {
'id': 'fastp-seq-content-n-plot',
'title': 'Fastp: Read N Content',
... | 0.004213 |
def add_parametric_object_params(prepend=False, hide_private=True):
"""
Add :class:`ParametricObject <cqparts.params.ParametricObject>` parameters
in a list to the *docstring*.
This is only intended to be used with *sphinx autodoc*.
In your *sphinx* ``config.py`` file::
from cqparts.utils... | 0.002552 |
def _chown_workdir(work_dir):
"""Ensure work directory files owned by original user.
Docker runs can leave root owned files making cleanup difficult.
Skips this if it fails, avoiding errors where we run remotely
and don't have docker locally.
"""
cmd = ("""docker run --rm -v %s:%s quay.io/bcbio... | 0.003752 |
def list_loadbalancers(self, datacenter_id, depth=1):
"""
Retrieves a list of load balancers in the data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param depth: The depth of the response data.
:type ... | 0.003868 |
async def set_config(self, on=None, tholddark=None, tholdoffset=None):
"""Change config of a CLIP LightLevel sensor."""
data = {
key: value for key, value in {
'on': on,
'tholddark': tholddark,
'tholdoffset': tholdoffset,
}.items() ... | 0.004329 |
def list_files(tag='', sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '' and 'ascii'.
If '' is specified, the primary dat... | 0.000635 |
def _parse_sheet(workbook, sheet):
"""
The universal spreadsheet parser. Parse chron or paleo tables of type ensemble/model/summary.
:param str name: Filename
:param obj workbook: Excel Workbook
:param dict sheet: Sheet path and naming info
:return dict dict: Table metadata and numeric data
... | 0.003519 |
def get_signatures_from_script(script):
"""Returns a list of signatures retrieved from the provided (partially)
signed multisig scriptSig.
:param script: The partially-signed multisig scriptSig.
:type script: ``bytes``
:returns: A list of retrieved signature from the provided scriptSig.
:rtype:... | 0.001031 |
def load_glb(self):
"""Loads a binary gltf file"""
with open(self.path, 'rb') as fd:
# Check header
magic = fd.read(4)
if magic != GLTF_MAGIC_HEADER:
raise ValueError("{} has incorrect header {} != {}".format(self.path, magic, GLTF_MAGIC_HEADER))
... | 0.00524 |
def readlines(self, sizehint = -1):
"""Return a list with all (following) lines. The sizehint parameter
is ignored in this implementation.
"""
result = []
while True:
line = self.readline()
if not line: break
result.append(line)
return ... | 0.015337 |
def randbytes(self):
""" -> #bytes result of bytes-encoded :func:gen_rand_str """
return gen_rand_str(
10, 30, use=self.random, keyspace=list(self.keyspace)
).encode("utf-8") | 0.009524 |
def pip(name):
'''Parse requirements file'''
with io.open(os.path.join('requirements', '{0}.pip'.format(name))) as f:
return f.readlines() | 0.006494 |
def iterate(self, params, repetition, iteration):
"""
Called once for each training iteration (== epoch here).
"""
print("\nStarting iteration",iteration)
print("Learning rate:", self.learningRate if self.lr_scheduler is None
else self.lr_scheduler.get_l... | 0.010248 |
def from_json(self, filename: str, silent: bool=False) -> None:
"""Load the configuration values from a JSON formatted file.
This allows configuration to be loaded as so
.. code-block:: python
app.config.from_json('config.json')
Arguments:
filename: The filena... | 0.005115 |
def on_sighup(self, signal_unused, frame_unused):
"""Reload the configuration
:param int signal_unused: Unused signal number
:param frame frame_unused: Unused frame the signal was caught in
"""
# Update HTTP configuration
for setting in self.http_config:
if ... | 0.00183 |
def from_flat_repr(self,fact_list,include_node_id=False,no_attributes=False,track_namespaces=True,namespace_mapping=None):
"""
Convert a flat representation of information (consisting of a fact list and a dictionary
mapping node ids to attributes into a dictionary representation information.
... | 0.007445 |
def _next_middleware(
self,
middlewares: Iterator[MIDDLEWARE_TYPE],
ctx: Context,
) -> NEXT_CALL_TYPE:
"""
生成 next_call 的调用
使用迭代器,这个方法每调用一次都会指向下一个中间件。
"""
@asyncio.coroutine
def next_call() -> NEXT_CALL_RES_TYPE:
"""
... | 0.006637 |
def _key(self):
"""A tuple key that uniquely describes this field.
Used to compute this instance's hashcode and evaluate equality.
Returns:
tuple: The contents of this
:class:`~google.cloud.bigquery.schema.SchemaField`.
"""
return (
se... | 0.004292 |
def get_initial_status_brok(self, extra=None):
"""
Get a brok with the group properties
`members` contains a list of uuid which we must provide the names. Thus we will replace
the default provided uuid with the members short name. The `extra` parameter, if present,
is containin... | 0.004278 |
def right_hand_side_as_function(self):
"""
Generates and returns the right hand side of the model as a callable function that takes two parameters:
values for variables and values for constants,
e.g. `f(values_for_variables=[1,2,3], values_for_constants=[3,4,5])
This function is... | 0.005298 |
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-bl... | 0.001961 |
def regex(val, schema, name = None): # pylint: disable-msg=W0613
"""
!~~regex(regex) or !~~regex regex
"""
if name is None:
name = schema
if not _regexs.has_key(name):
return False
try:
if _regexs[name](val):
return True
except TypeError:
pass
... | 0.014925 |
def auth_expired(self):
"""
Compare the expiration value of our current token including a CLOCK_SKEW.
:return: true if the token has expired
"""
if self._auth and self._expires:
now_with_skew = time.time() + AUTH_TOKEN_CLOCK_SKEW_MAX
return now_with_skew >... | 0.008475 |
def Read(
self,
Channel):
"""
Reads a CAN message from the receive queue of a PCAN Channel
Remarks:
The return value of this method is a 3-touple, where
the first value is the result (TPCANStatus) of the method.
The order of the values are:
... | 0.00722 |
def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_l... | 0.00177 |
def get_assessment_parts_by_genus_type(self, assessment_part_genus_type):
"""Gets an ``AssessmentPartList`` corresponding to the given assessment part genus ``Type`` which does not include assessment parts of types derived from the specified ``Type``.
arg: assessment_part_genus_type (osid.type.Type)... | 0.002833 |
def is_timeseries(nc, variable):
'''
Returns true if the variable is a time series feature type.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check
'''
# x, y, z, t(o)
# X(o)
dims = nc.variables[variable].dimensions
cmatrix = coord... | 0.001214 |
def read_credentials(fname):
"""
read a simple text file from a private location to get
username and password
"""
with open(fname, 'r') as f:
username = f.readline().strip('\n')
password = f.readline().strip('\n')
return username, password | 0.003584 |
def clear_decimal_values(self):
"""stub"""
if self._decimal_values_metadata['required'] or \
self._decimal_values_metadata['read_only']:
raise NoAccess()
self.my_osid_object_form._my_map['decimalValues'] = \
dict(self._decimal_values_metadata['default_obje... | 0.00597 |
def get_config(self, key, default=None):
''' Lookup a config field and return its value, first checking the
route.config, then route.app.config.'''
for conf in (self.config, self.app.conifg):
if key in conf: return conf[key]
return default | 0.010453 |
def plot(self, plot_intermediate_solutions=True,
plot_observed_data=True, plot_starting_trajectory=True, plot_optimal_trajectory=True,
filter_plots_function=None, legend=True,
kwargs_observed_data=None, kwargs_starting_trajectories=None, kwargs_optimal_trajectories=None,
... | 0.004399 |
async def prefetch(self, query, *subqueries):
"""Asynchronous version of the `prefetch()` from peewee.
:return: Query that has already cached data for subqueries
"""
query = self._swap_database(query)
subqueries = map(self._swap_database, subqueries)
return (await prefet... | 0.005831 |
def get_inflators_cn_to_cn(target_year):
'''
Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale.
'''
data_year = find_nearest_inferior(data_years, target_year)
data_year_cn_aggregates = get_cn_aggregates(data_year)['consoCN_COICOP_{}'.format(data_year)].to_dict()... | 0.006791 |
def edit_profile():
"""Updates a profile"""
if g.user is None:
abort(401)
form = dict(name=g.user.name, email=g.user.email)
if request.method == 'POST':
if 'delete' in request.form:
db_session.delete(g.user)
db_session.commit()
session['openid'] = None... | 0.001025 |
def thermodynamic_integration_log_evidence(betas, logls):
"""
Thermodynamic integration estimate of the evidence.
:param betas: The inverse temperatures to use for the quadrature.
:param logls: The mean log-likelihoods corresponding to ``betas`` to use for
computing the thermodynamic evidence... | 0.001828 |
def direct_to_template(
request, template, extra_context=None, mimetype=None, **kwargs):
"""
Render a given template with any extra URL parameters in the context as
``{{ params }}``.
"""
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, val... | 0.001631 |
def execute_script(self, string, args=None):
"""
Execute script passed in to function
@type string: str
@value string: Script to execute
@type args: dict
@value args: Dictionary representing command line args
@rtype: int
@rtype: ... | 0.004896 |
def rmdir(self, target_directory, dir_fd=None):
"""Remove a leaf Fake directory.
Args:
target_directory: (str) Name of directory to remove.
dir_fd: If not `None`, the file descriptor of a directory,
with `target_directory` being relative to this directory.
... | 0.002959 |
def ls_packages(self):
"""
List packages in this store.
"""
packages = []
pkgdir = os.path.join(self._path, self.PKG_DIR)
if not os.path.isdir(pkgdir):
return []
for team in sub_dirs(pkgdir):
for user in sub_dirs(self.team_path(team)):
... | 0.005863 |
def flush(self, timeout=None, callback=None):
"""Alias for self.client.flush"""
client, scope = self._stack[-1]
if client is not None:
return client.flush(timeout=timeout, callback=callback) | 0.00885 |
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the ... | 0.000722 |
def update_bin(self, bin_form):
"""Updates an existing bin.
arg: bin_form (osid.resource.BinForm): the form containing
the elements to be updated
raise: IllegalState - ``bin_form`` already used in an update
transaction
raise: InvalidArgument - the fo... | 0.004202 |
def stop_capture(self, adapter_number):
"""
Stops a packet capture.
:param adapter_number: adapter number
"""
try:
adapter = self._ethernet_adapters[adapter_number]
except IndexError:
raise QemuError('Adapter {adapter_number} does not exist on QE... | 0.007601 |
def disttar_suffix(env, sources):
"""tar archive suffix generator"""
env_dict = env.Dictionary()
if env_dict.has_key("DISTTAR_FORMAT") and env_dict["DISTTAR_FORMAT"] in ["gz", "bz2"]:
return ".tar." + env_dict["DISTTAR_FORMAT"]
else:
return ".tar" | 0.019231 |
def ls(types, as_json): # pylint: disable=invalid-name
"""List all available sensors"""
sensors = W1ThermSensor.get_available_sensors(types)
if as_json:
data = [
{"id": i, "hwid": s.id, "type": s.type_name}
for i, s in enumerate(sensors, 1)
]
click.echo(json... | 0.002475 |
async def read(self) -> bytes:
"""Read response payload."""
if self._body is None:
try:
self._body = await self.content.read()
for trace in self._traces:
await trace.send_response_chunk_received(self._body)
except BaseException:... | 0.004098 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AlphaSenderContext for this AlphaSenderInstance
:rtype: twilio.rest.messaging.v1.service.alpha_se... | 0.008157 |
def calibrate_signal(signal, resp, fs, frange):
"""Given original signal and recording, spits out a calibrated signal"""
# remove dc offset from recorded response (synthesized orignal shouldn't have one)
dc = np.mean(resp)
resp = resp - dc
npts = len(signal)
f0 = np.ceil(frange[0] / (float(fs) ... | 0.003906 |
def _handle(self, request: Request, response: Response) -> TypeGenerator[Any, None, None]:
"""
request 解析后的回调,调用中间件,并处理 headers, body 发送。
"""
# request.start_time = datetime.now().timestamp()
# 创建一个新的会话上下文
ctx = self._context(
cast(asyncio.AbstractEventLoop, s... | 0.002664 |
def convert(model, features, target):
"""Convert a Support Vector Regressor (SVR) model to the protobuf spec.
Parameters
----------
model: SVR
A trained SVR encoder model.
feature_names: [str]
Name of the input columns.
target: str
Name of the output column.
Return... | 0.001739 |
def modules(self):
"""A list of the modules, with 0 representing a bar and 1 representing a space.
>>> barcode = Code128("Hello!", charset='B')
>>> barcode.modules # doctest: +ELLIPSIS
[0, 0, 1, 0, 1, 1, 0, 1, ..., 0, 0, 0, 1, 0, 1, 0, 0]
:rtype: list[int]
"""
... | 0.00495 |
def get_solc_input(self):
"""Walks the contract directory and returns a Solidity input dict
Learn more about Solidity input JSON here: https://goo.gl/7zKBvj
Returns:
dict: A Solidity input JSON object as a dict
"""
def legal(r, file_name):
hidden = file... | 0.001783 |
def registergrant(source=None, setspec=None):
"""Harvest grants from OpenAIRE."""
with open(source, 'r') as fp:
data = json.load(fp)
register_grant(data) | 0.00578 |
def keyword(self) -> Tuple[Optional[str], str]:
"""Parse a YANG statement keyword.
Raises:
EndOfInput: If past the end of input.
UnexpectedInput: If no syntactically correct keyword is found.
"""
i1 = self.yang_identifier()
if self.peek() == ":":
... | 0.004608 |
def C_wedge_meter_Miller(D, H):
r'''Calculates the coefficient of discharge of an wedge flow meter
used for measuring flow rate of fluid, based on the geometry of the
differential pressure flow meter.
For half-inch lines:
.. math::
C = 0.7883 + 0.107(1 - \beta^2)
For ... | 0.007656 |
def _convert_url_to_downloadable(url):
"""Convert a url to the proper style depending on its website."""
if 'drive.google.com' in url:
# For future support of google drive
file_id = url.split('d/')[1].split('/')[0]
base_url = 'https://drive.google.com/uc?export=download&id='
out... | 0.001445 |
def create_csp_header(cspDict):
""" create csp header string """
policy = ['%s %s' % (k, v) for k, v in cspDict.items() if v != '']
return '; '.join(policy) | 0.025157 |
def translate(script, value=(0.0, 0.0, 0.0)):
"""An alternative translate implementation that uses a geometric function.
This is more accurate than the built-in version."""
# Convert value to list if it isn't already
if not isinstance(value, list):
value = list(value)
vert_function(script,
... | 0.008753 |
def _exec_cmd(self, command, **kwargs):
"""Create a new method as command has specific requirements.
There is a handful of the TMSH global commands supported,
so this method requires them as a parameter.
:raises: InvalidCommand
"""
kwargs['command'] = command
s... | 0.00243 |
def append_result(self, results, num_matches):
"""Real-time update of search results"""
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.text_col... | 0.001678 |
def _CheckForOutOfOrderStepAndMaybePurge(self, event):
"""Check for out-of-order event.step and discard expired events for tags.
Check if the event is out of order relative to the global most recent step.
If it is, purge outdated summaries for tags that the event contains.
Args:
event: The event... | 0.005208 |
def explain_instance(self,
data_row,
predict_fn,
labels=(1,),
top_labels=None,
num_features=10,
num_samples=5000,
distance_metric='euclidean',
... | 0.003103 |
def _getDict(j9Page):
"""Parses a Journal Title Abbreviations page
Note the pages are not well formatted html as the <DT> tags are not closes so html parses (Beautiful Soup) do not work. This is a simple parser that only works on the webpages and may fail if they are changed
For Backend
"""
slines... | 0.002257 |
def build_agency(pfeed):
"""
Given a ProtoFeed, return a DataFrame representing ``agency.txt``
"""
return pd.DataFrame({
'agency_name': pfeed.meta['agency_name'].iat[0],
'agency_url': pfeed.meta['agency_url'].iat[0],
'agency_timezone': pfeed.meta['agency_timezone'].iat[0],
}, index... | 0.003077 |
def apply_optimization(self, update_embedding_with, grad, **kwargs):
"""
Calculating (Obtaining) the learning rate (eta) and apply optimizations
on the embedding states by the specified method.
Parameters
----------
update_embedding_with : function
Function u... | 0.001767 |
def arcs(self):
"""Get information about the arcs available in the code.
Returns a sorted list of line number pairs. Line numbers have been
normalized to the first line of multiline statements.
"""
all_arcs = []
for l1, l2 in self.byte_parser._all_arcs():
f... | 0.004124 |
def save(self, *args, **kwargs):
"""
For new assets, creates a new slug.
For updates, deletes the old file from storage.
Calls super to actually save the object.
"""
if not self.pk and not self.slug:
self.slug = self.generate_slug()
if self.__origina... | 0.001612 |
def wipe_table(self, table: str) -> int:
"""Delete all records from a table. Use caution!"""
sql = "DELETE FROM " + self.delimit(table)
return self.db_exec(sql) | 0.01087 |
async def post(self, public_key):
"""Writes contents review
"""
if settings.SIGNATURE_VERIFICATION:
super().verify()
try:
body = json.loads(self.request.body)
except:
self.set_status(400)
self.write({"error":400, "reason":"Unexpected data format. JSON required"})
raise tornado.web.Finish
... | 0.039352 |
def select_locale_by_request(self, request, locales=()):
"""Choose an user's locales by request."""
default_locale = locales and locales[0] or self.cfg.default_locale
if len(locales) == 1 or 'ACCEPT-LANGUAGE' not in request.headers:
return default_locale
ulocales = [
... | 0.002663 |
def from_requirement(cls, provider, requirement, parent):
"""Build an instance from a requirement.
"""
candidates = provider.find_matches(requirement)
if not candidates:
raise NoVersionsAvailable(requirement, parent)
return cls(
candidates=candidates,
... | 0.005051 |
def create_csr(cls, name, common_name, public_key_algorithm='rsa',
signature_algorithm='rsa_sha_512', key_length=4096):
"""
Create a certificate signing request.
:param str name: name of TLS Server Credential
:param str rcommon_name: common name for certificate. ... | 0.004739 |
async def quit(self):
"""
Sends a SMTP 'QUIT' command. - Ends the session.
For further details, please check out `RFC 5321 § 4.1.1.10`_.
Returns:
(int, str): A (code, message) 2-tuple containing the server
response. If the connection is already closed when c... | 0.003456 |
def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None):
""" Retrieves the contents of a table.
Args:
table_name: the name of the table as a tuple of components.
start_index: the index of the row at which to start retrieval.
max_results: an optional maximum n... | 0.00681 |
def simple_peakfinder(x, y, delta):
'''Detect local maxima and minima in a vector
A point is considered a maximum peak if it has the maximal value, and was
preceded (to the left) by a value lower by `delta`.
Args
----
y: ndarray
array of values to find local maxima and minima in
de... | 0.001521 |
def rewrite_to_secure_url(url, secure_base=None):
"""
Rewrite URL to a Secure URL
@param url URL to be rewritten to a secure URL.
@param secure_base: Base URL of secure site (defaults to CFG_SITE_SECURE_URL).
"""
if secure_base is None:
secure_base = cfg.get('CFG_SITE_SECURE_URL')
u... | 0.003953 |
def plotly_app(context, name=None, slug=None, da=None, ratio=0.1, use_frameborder=False, initial_arguments=None):
'Insert a dash application using a html iframe'
fbs = '1' if use_frameborder else '0'
dstyle = """
position: relative;
padding-bottom: %s%%;
height: 0;
overflow:hidden;
"""... | 0.003289 |
def _process_compute(self, pipe_package):
"""
Since here, we are in process mode: you only have to use metas (objects_ids, states)
:param pipe_package:
:return:
"""
context = pipe_package.get_context()
step_key = pipe_package.get_step_key()
actions = []
... | 0.00519 |
def get_items(start_num, num_items):
"""
Generate a sequence of dynamo items
:param start_num: Start index
:type start_num: int
:param num_items: Number of items
:type num_items: int
:return: List of dictionaries
:rtype: list of dict
"""
result = []
for i in range(start_num,... | 0.002392 |
def aggregate(self, function, name=None):
"""Aggregates the contents of the window when the window is
triggered.
Upon a window trigger, the supplied function is passed a list containing
the contents of the window: ``function(items)``. The order of the window
items in t... | 0.007598 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.