text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _resolve(self, path, method, urlargs=None):
'''Resolve a path and return a ``(handler, urlargs)`` tuple or
``None`` if the path could not be resolved.
'''
match = self.route.match(path)
if match is None:
if not self.route.is_leaf: # no match
retur... | 0.001986 |
def _debug_string(self, debug, data):
"""
Annotate a frames data, if debug is True.
"""
if not debug:
return data
if self.command in [
SLOT.CONFIG,
SLOT.CONFIG2,
SLOT.UPDATE1,
SLOT.UPDATE2,
SLOT.SWAP,
... | 0.006296 |
def collect_data(bids_dir, participant_label, task=None, echo=None,
bids_validate=True):
"""
Uses pybids to retrieve the input data for a given participant
>>> bids_root, _ = collect_data(str(datadir / 'ds054'), '100185',
... bids_validate=False)
>>> bids... | 0.001065 |
def get_alt_az(utc_time, lon, lat):
"""Return sun altitude and azimuth from *utc_time*, *lon*, and *lat*.
lon,lat in degrees
What is the unit of the returned angles and heights!? FIXME!
"""
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
ra_, dec = sun_ra_dec(utc_time)
h__ = _local_hour_ang... | 0.001698 |
def compare_list_iter(propval_a, propval_b, fs_a=None, fs_b=None,
options=None):
"""Generator for comparing 'simple' lists when they are encountered. This
does not currently recurse further. Arguments are as per other
``compare_``\ *X* functions.
"""
if fs_a is None:
... | 0.000729 |
def event(self, event): # pylint: disable-msg=R0201
"""Handle a stream event.
Called when connection state is changed.
Should not be called with self.lock acquired!
"""
event.stream = self
logger.debug(u"Stream event: {0}".format(event))
self.settings["event_que... | 0.008427 |
def get_all(self, key, fallback=None):
"""returns all header values for given key"""
if key in self.headers:
value = self.headers[key]
else:
value = fallback or []
return value | 0.008621 |
def ServiceWorker_deliverPushMessage(self, origin, registrationId, data):
"""
Function path: ServiceWorker.deliverPushMessage
Domain: ServiceWorker
Method name: deliverPushMessage
Parameters:
Required arguments:
'origin' (type: string) -> No description
'registrationId' (type: string) -> N... | 0.043566 |
def simulate(protocol_file,
propagate_logs=False,
log_level='warning') -> List[Mapping[str, Any]]:
"""
Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other... | 0.000294 |
def request_timestamp(self):
"""
The timestamp of the request in ISO8601 YYYYMMDD'T'HHMMSS'Z' format.
If this is not available in the query parameters or headers, or the
value is not a valid format for AWS SigV4, an AttributeError exception
is raised.
"""
amz_dat... | 0.002214 |
def sourceDirValidationError(dirname, component_name):
''' validate source directory names in components '''
if dirname == component_name:
return 'Module %s public include directory %s should not contain source files' % (component_name, dirname)
elif dirname.lower() in ('source', 'src') and dirname ... | 0.005225 |
def complete(self):
"""
Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the
sample.general.bestassemblyfile != 'NA'
"""
# Boolean to store the completeness of the analyses
allcomplete = True
# Clear the list of samp... | 0.003676 |
def setProperty(self, name, value):
'''
Sets one of the supported property values of the speech engine listed
above. If a value is invalid, attempts to clip it / coerce so it is
valid before giving up and firing an exception.
@param name: Property name
@type name: str
... | 0.00225 |
def eval_basis(self, x, regularize=True):
"""
basis_mat = C.eval_basis(x)
Evaluates self's basis functions on x and returns them stacked
in a matrix. basis_mat[i,j] gives basis function i (formed by
multiplying basis functions) evaluated at x[j,:].
"""
# Make obj... | 0.003311 |
def batchInsert(self, itemType, itemAttributes, dataRows):
"""
Create multiple items in the store without loading
corresponding Python objects into memory.
the items' C{stored} callback will not be called.
Example::
myData = [(37, u"Fred", u"Wichita"),
... | 0.00163 |
def remove_data(self, request, pk=None):
"""Remove data from collection."""
collection = self.get_object()
if 'ids' not in request.data:
return Response({"error": "`ids`parameter is required"}, status=status.HTTP_400_BAD_REQUEST)
for data_id in request.data['ids']:
... | 0.007853 |
def diff_time(t1, t2):
"""
Calculates datetime.timedelta between two datetime.time values.
:param t1: First time
:type t1: datetime.time
:param t2: Second time
:type t2: datetime.time
:return: Differences between t1 and t2 or None when t1 or t2 is None
:rtype: datetime.timedelta/None
... | 0.001167 |
def _desy_bookkeeping2marc(self, key, value):
"""Populate the ``595_D`` MARC field.
Also populates the ``035`` MARC field through side effects.
"""
if 'identifier' not in value:
return {
'a': value.get('expert'),
'd': value.get('date'),
's': value.get('status... | 0.002299 |
def load_udata_commands(self, ctx):
'''
Load udata commands from:
- `udata.commands.*` module
- known internal modules with commands
- plugins exporting a `udata.commands` entrypoint
'''
if self._udata_commands_loaded:
return
# Load all comman... | 0.001646 |
def check_vip_ip(self, ip, id_evip):
"""
Get a Ipv4 or Ipv6 for Vip request
:param ip: IPv4 or Ipv6. 'xxx.xxx.xxx.xxx or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'
:return: Dictionary with the following structure:
::
{'ip': {'ip': < ip - octs for ipv4, blocks for ip... | 0.004344 |
def list(self, kind, tag_slug, cur_p=''):
'''
根据 cat_handler.py 中的 def view_cat_new(self, cat_slug, cur_p = '')
'''
# 下面用来使用关键字过滤信息,如果网站信息量不是很大不要开启
# Todo:
# if self.get_current_user():
# redisvr.sadd(config.redis_kw + self.userinfo.user_name, tag_slug)
... | 0.002952 |
def _compute_needed_metrics(self, instance, available_metrics):
""" Compare the available metrics for one MOR we have computed and intersect them
with the set of metrics we want to report
"""
i_key = self._instance_key(instance)
if self.in_compatibility_mode(instance):
... | 0.004673 |
def is_namespace_valid( namespace_id ):
"""
Is a namespace ID valid?
>>> is_namespace_valid('abcd')
True
>>> is_namespace_valid('+abcd')
False
>>> is_namespace_valid('abc.def')
False
>>> is_namespace_valid('.abcd')
False
>>> is_namespace_valid('abcdabcdabcdabcdabcd')
Fal... | 0.011111 |
def _send_response(
self, environ, start_response, root_res, success_code, error_list
):
"""Send WSGI response (single or multistatus).
- If error_list is None or [], then <success_code> is send as response.
- If error_list contains a single error with a URL that matches root_res,
... | 0.005754 |
def edges(s, edges, alpha=1.0, weighted=False, directed=False):
""" Visualization of the edges in a network.
"""
p = s._ctx.BezierPath()
if directed and s.stroke:
pd = s._ctx.BezierPath()
if weighted and s.fill:
pw = [s._ctx.BezierPath() for i in range(11)... | 0.023434 |
def create_directory(self, filename):
"""Create a subdirectory in the temporary directory."""
path = os.path.join(self.path, filename)
makedirs(path)
return path | 0.010363 |
def _analyze_states(state: GlobalState) -> List[Issue]:
"""
:param state: the current state
:return: returns the issues for that corresponding state
"""
call = get_call_from_state(state)
if call is None:
return []
issues = [] # type: List[Issue]
if call.type is not "DELEGATECAL... | 0.001449 |
def analyze(self,A):
"""
Analyzes structure of A.
Parameters
----------
A : matrix
For symmetric systems, should contain only lower diagonal part.
"""
A = coo_matrix(A)
self.mumps.set_shape(A.shape[0])
self.mumps.set... | 0.016317 |
def get_gene_goterms(self, gene, ancestors=False):
"""Return all GO terms a particular gene is annotated with.
Parameters
----------
gene: str
The gene symbol of the gene.
ancestors: bool, optional
If set to True, also return all ancestor GO terms.
... | 0.002026 |
def get_size(self, value=None):
"""Return the size in bytes.
Args:
value (bytes): In structs, the user can assign other value instead
of this class' instance. Here, in such cases, ``self`` is a
class attribute of the struct.
Returns:
int:... | 0.003759 |
def args_options():
""" Generates an arugment parser.
:returns:
Parser object
"""
parser = argparse.ArgumentParser(prog='landsat',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent(DESCRIP... | 0.005229 |
def diff_a_thing(thing, opt):
"""Handle the diff action for a single thing. It may be a Vault backend
implementation or it may be a Vault data resource"""
changed = thing.diff()
if changed == ADD:
print("%s %s" % (maybe_colored("+", "green", opt), str(thing)))
elif changed == DEL:
pr... | 0.0013 |
def to_dict(self):
"""Dump progress to a dictionary.
:return: Progress dictionary
:rtype: :class:`~python:dict`
"""
result = super(Progress, self).to_dict()
label = LABELS['last_progress_change'][self.progress_type]
result[label] = to_iso8601_datetime(self.last... | 0.003281 |
def ApplicationReceiving(self, app, streams):
"""Called when the list of streams with data ready to be read changes."""
# we should only proceed if we are in TCP mode
if stype != socket.SOCK_STREAM:
return
# handle all streams
for stream in streams:
# re... | 0.002747 |
def as_pyemu_matrix(self,typ=Matrix):
"""
Create a pyemu.Matrix from the Ensemble.
Parameters
----------
typ : pyemu.Matrix or derived type
the type of matrix to return
Returns
-------
pyemu.Matrix : pyemu.Matrix
"""
... | 0.010823 |
def overlay(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and overlay each group
Groups data by supplied dimension(s) overlaying the groups
along the dimension(s).
Args:
dimensions: Dimension(s) of dimensions to group by
Returns:
N... | 0.002558 |
def whisper(self, user, message):
"""
This seems super gimmicky, but so far this is the only way
way I've seen to do this (at least through IRC). It's definitely
not documented.
"""
if user[0] == '#':
LOGGER.warning(f"Whisper is for users only.")
else... | 0.005249 |
def bm3_k(p, v0, k0, k0p):
"""
calculate bulk modulus, wrapper for cal_k_bm3
cannot handle uncertainties
:param p: pressure
:param v0: volume at reference conditions
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at different conditions
:... | 0.002475 |
def stop(self):
"""
Stops the `git push` thread and commits all streamed files (Git.store_file and Git.stream_file), followed
by a final git push.
You can not start the process again.
"""
self.active_thread = False
if self.thread_push_instance and self.t... | 0.003036 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'customizations') and self.customizations is not None:
_dict['customizations'] = [
x._to_dict() for x in self.customizations
]
return _dict | 0.006349 |
def ds2n(self):
"""Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
"""
idx = [(x[0] + 0, x[1] + 2) for x in self.df.index]
values = self.s2n.values - self.s2n.loc[idx].values
return Table(df=pd.Series(values, index=self.df.... | 0.008242 |
def wvcal_spectrum(sp, fxpeaks, poly_degree_wfit, wv_master,
wv_ini_search=None, wv_end_search=None,
wvmin_useful=None, wvmax_useful=None,
geometry=None, debugplot=0):
"""Execute wavelength calibration of a spectrum using fixed line peaks.
Parameters
... | 0.000244 |
def scalar_stats(data, functions=('min', 'max', 'mean', 'std')):
'''Calculate the stats from the given numpy functions
Parameters:
data: array of data points to be used for the stats
Options:
functions: tuple of numpy stat functions to apply on data
Returns:
Dictionary with th... | 0.001957 |
def setup(self, port):
"""Connects to an Arduino UNO on serial port `port`.
@throw RuntimeError can't connect to Arduino
"""
port = str(port)
# timeout is used by all I/O operations
self._serial = serial.Serial(port, 115200, timeout=2)
time.sleep(2) # time to Ar... | 0.002688 |
def set_dashboard_tags(self, id, **kwargs): # noqa: E501
"""Set all tags associated with a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.... | 0.002144 |
def __get_empty_config(self):
"""
Returns the config file contents as a string. The config file is generated and then deleted.
"""
self._generate_config()
path = self._get_config_path()
with open(path, 'r') as readable:
contents = readable.read()
os.re... | 0.008475 |
def get(self, tags):
"""Find an adequate value for this field from a dict of tags."""
# Try to find our name
value = tags.get(self.name, '')
for name in self.alternate_tags:
# Iterate of alternates until a non-empty value is found
value = value or tags.get(name, ... | 0.004566 |
def load_descendant_articles_for_section(
context, section, featured_in_homepage=None, featured_in_section=None,
featured_in_latest=None, count=5):
"""
Returns all descendant articles (filtered using the parameters)
If the `locale_code` in the context is not the main language, it will
re... | 0.000568 |
def get(self, **kwargs):
"""
Performs the query and returns a single object matching the given
keyword arguments.
"""
clone = self.filter(**kwargs)
num = len(clone)
if num == 1:
return clone._result_cache[0]
if not num:
raise Task.D... | 0.00318 |
def run(config, clear_opt=False):
"""Find an image and download it."""
flickr = flickrapi.FlickrAPI(config.get('walls', 'api_key'),
config.get('walls', 'api_secret'))
width = config.getint('walls', 'width')
height = config.getint('walls', 'height')
# Clear out the d... | 0.000941 |
def disapproveworker(ctx, workers, account):
""" Disapprove worker(es)
"""
print_tx(ctx.bitshares.disapproveworker(workers, account=account)) | 0.006536 |
def gotoPrevious(self):
"""
Goes to the previous panel tab.
"""
index = self._currentPanel.currentIndex() - 1
if index < 0:
index = self._currentPanel.count() - 1
self._currentPanel.setCurrentIndex(index) | 0.010989 |
def _service_by_name(name):
'''
Return the service info for a service by label, filename or path
'''
services = _available_services()
name = name.lower()
if name in services:
# Match on label
return services[name]
for service in six.itervalues(services):
if service[... | 0.001709 |
def is_toml_file(filename, show_warnings = False):
"""Check configuration file type is TOML
Return a boolean indicating wheather the file is TOML format or not
"""
if is_yaml_file(filename):
return(False)
try:
config_dict = load_config(filename, file_type = "toml")
is_toml = ... | 0.015789 |
def interpolate(self, tres="<default>", fres="<default>", logf=False,
outseg=None):
"""Interpolate this `QGram` over a regularly-gridded spectrogram
Parameters
----------
tres : `float`, optional
desired time resolution (seconds) of output `Spectrogram`,
... | 0.00066 |
def get_arctic_version(self, symbol, as_of=None):
"""
Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str`... | 0.006803 |
def start_pipeline(self, args=None, multi=False):
"""
Initialize setup. Do some setup, like tee output, print some diagnostics, create temp files.
You provide only the output directory (used for pipeline stats, log, and status flag files).
"""
# Perhaps this could all just be put... | 0.006264 |
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/... | 0.001894 |
def _convert(reddit_session, data):
"""Return a Redditor object from the data."""
retval = Redditor(reddit_session, data['name'], fetch=False)
retval.id = data['id'].split('_')[1] # pylint: disable=C0103,W0201
return retval | 0.007813 |
def example_transform(v, row, row_n, i_s, i_d, header_s, header_d,scratch, errors, accumulator):
""" An example column transform.
This is an example of a column transform with all of the arguments listed. An real transform
can omit any ( or all ) of these, and can supply them in any order; the calling code... | 0.007457 |
def calculate_distribution(network_agents=None,
agent_type=None):
'''
Calculate the threshold values (thresholds for a uniform distribution)
of an agent distribution given the weights of each agent type.
The input has this form: ::
[
{'agent_type': 'a... | 0.000766 |
def cee_map_priority_table_map_cos6_pgid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name_key.text = kwargs.pop... | 0.004894 |
def get_role_arn(role_name, env, region):
"""Get role ARN given role name.
Args:
role_name (str): Role name to lookup
env (str): Environment in which to lookup
region (str): Region
Returns:
ARN if role found
"""
session = boto3.Session(profile_name=env, region_name... | 0.001712 |
def get_cover(song, size=250):
"""Download the cover art."""
try:
data = mus.search_releases(artist=song["artist"],
release=song["album"],
limit=1)
release_id = data["release-list"][0]["release-group"]["id"]
print(f"al... | 0.00155 |
def add_variable(self, name, expression, overwrite=True, unique=True):
"""Add a variable to to a DataFrame.
A variable may refer to other variables, and virtual columns and expression may refer to variables.
Example
>>> df.add_variable('center', 0)
>>> df.add_virtual_column('x... | 0.005488 |
def configure_deletefor(self, ns, definition):
"""
Register a delete-for relation endpoint.
The definition's func should be a delete function, which must:
- accept kwargs for path data
- return truthy/falsey
:param ns: the namespace
:param definition: the endpoi... | 0.003607 |
def delete_orderrun(backend, orderrun_id):
"""
Delete the orderrun specified by the argument.
"""
click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green')
check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip())) | 0.010345 |
def checkplot_infokey_worker(task):
'''This gets the required keys from the requested file.
Parameters
----------
task : tuple
Task is a two element tuple::
- task[0] is the dict to work on
- task[1] is a list of lists of str indicating all the key address to
extrac... | 0.001381 |
def transform(self, X):
"""Transform your data to zero mean unit variance."""
if not self.is_fit:
raise ValueError("The scaler has not been fit yet.")
return (X-self.mean) / (self.std + 10e-7) | 0.008772 |
def __generate_study_name(self):
"""
When a study name is not given, generate one with the format of " author - site name - year "
:return str study_name: generated study name
"""
study_name = ""
_exist = False
try:
if self.noaa_data_sorted["Top"]["Stu... | 0.003597 |
def dwrap(kx,nc):
'''compute a wrapped distance'''
q1 = np.mod(kx, nc)
q2 = np.minimum(q1, nc-q1)
return q2 | 0.01626 |
def _attachToObject(self, anchorObj, relationName) :
"dummy fct for compatibility reasons, a RabaListPupa is attached by default"
#MutableSequence.__getattribute__(self, "develop")()
self.develop()
self._attachToObject(anchorObj, relationName) | 0.031873 |
def install_caller_instruction(self, token_type="Unrestricted",
transaction_id=None):
"""
Set us up as a caller
This will install a new caller_token into the FPS section.
This should really only be called to regenerate the caller token.
"""
... | 0.003359 |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidListView, self).init_widget()
d = self.declaration
self.set_arrangement(d.arrangement) | 0.009756 |
def get_encrypted_pin(self, clear_pin, card_number):
"""
Get PIN block in ISO 0 format, encrypted with the terminal key
"""
if not self.terminal_key:
print('Terminal key is not set')
return ''
if self.pinblock_format == '01':
try:
... | 0.004225 |
async def revoke_credential(self):
"""
Revokes a credential.
:return: None
Example:
credential.revoke_credential()
"""
if not hasattr(IssuerCredential.revoke_credential, "cb"):
self.logger.debug("vcx_issuer_revoke_credential: Creating callback"... | 0.006329 |
def add(self, index):
"""Calculate time elapsed from the point previously called
this method or this object is created to this is called.
Args:
index (int): Index to be displayed, and be used to take intervals.
"""
if (index - self.flush_at) < self.interval:
... | 0.002384 |
def from_dataframe(df,
source_col='source',
target_col='target',
interaction_col='interaction',
name='From DataFrame',
edge_attr_cols=[]):
"""
Utility to convert Pandas DataFrame object into Cytoscape.js JSON
:pa... | 0.000674 |
def set_event_tags(self, id, **kwargs): # noqa: E501
"""Set all tags associated with a specific event # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set_even... | 0.002191 |
def main(argv):
"""
Main mon
:param argv: console arguments
:return:
"""
input_file = ""
output_file = ""
monitor = None
formula = None
trace = None
iformula = None
itrace = None
isys = None
online = False
fuzzer = False
l2m = False
debug = False
r... | 0.003415 |
def put(self, item, block=True, timeout=None, chill=True):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds a... | 0.001153 |
def _initialize_master_working_set():
"""
Prepare the master working set and make the ``require()``
API available.
This function has explicit effects on the global state
of pkg_resources. It is intended to be invoked once at
the initialization of this module.
Invocation by other packages i... | 0.001838 |
def set_provenance(self, provenance_id):
"""stub"""
if not self.my_osid_object_form._is_valid_string(
provenance_id, self.get_provenance_metadata()):
raise InvalidArgument('provenanceId')
self.my_osid_object_form._my_map['provenanceId'] = provenance_id | 0.006579 |
def save_hdf(self, filename, path='', overwrite=False, append=False):
"""Saves object data to HDF file (only works if MCMC is run)
Samples are saved to /samples location under given path,
and object properties are also attached, so suitable for
re-loading via :func:`StarModel.load_hdf`.... | 0.003472 |
def run(self):
"""
Write the input/data files and run LAMMPS.
"""
lammps_cmd = self.lammps_bin + ['-in', self.input_filename]
print("Running: {}".format(" ".join(lammps_cmd)))
p = Popen(lammps_cmd, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = p.communicate()
... | 0.005814 |
def award_points(target, key, reason="", source=None):
"""
Awards target the point value for key. If key is an integer then it's a
one off assignment and should be interpreted as the actual point value.
"""
point_value, points = get_points(key)
if not ALLOW_NEGATIVE_TOTALS:
total = poi... | 0.000556 |
def normalize(self):
"""
Returns a new table with values ranging from -1 to 1, reaching at least
one of these, unless there's no data.
"""
max_abs = max(self.table, key=abs)
if max_abs == 0:
raise ValueError("Can't normalize zeros")
return self / max_abs | 0.006944 |
def encode(msg, strict=False, logger=None, timezone_offset=None):
"""
Encodes and returns the L{msg<Envelope>} as an AMF stream.
@param strict: Enforce strict encoding. Default is C{False}. Specifically
header/body lengths will be written correctly, instead of the default 0.
Default is `Fal... | 0.002488 |
def list_xz (archive, compression, cmd, verbosity, interactive):
"""List a XZ archive."""
cmdlist = [cmd]
cmdlist.append('-l')
if verbosity > 1:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | 0.008475 |
def reformat_cmd(self, text):
""" reformat the text to be stripped of noise """
# remove az if there
text = text.replace('az', '')
# disregard defaulting symbols
if text and SELECT_SYMBOL['scope'] == text[0:2]:
text = text.replace(SELECT_SYMBOL['scope'], "")
... | 0.004577 |
def _configure(configuration_details):
"""Adds alias to shell config."""
path = Path(configuration_details.path).expanduser()
with path.open('a') as shell_config:
shell_config.write(u'\n')
shell_config.write(configuration_details.content)
shell_config.write(u'\n') | 0.003333 |
def error(self, msg, file=None):
"""
Outputs the error msg to the file if specified, or to the
io_manager's stderr if available, or to sys.stderr.
"""
self.error_encountered = True
file.write(self.error_prefix)
file.write(msg)
file.write('\n')
file... | 0.006098 |
def make_model(self):
"""Return the assembled HTML content as a string.
Returns
-------
str
The assembled HTML as a string.
"""
stmts_formatted = []
stmt_rows = group_and_sort_statements(self.statements,
s... | 0.002376 |
def str_to_inet(address):
"""Convert an a string IP address to a inet struct
Args:
address (str): String representation of address
Returns:
inet: Inet network address
"""
# First try ipv4 and then ipv6
try:
return socket.inet_pton(socket.AF_INET, address)... | 0.002481 |
async def send_from_directory(
directory: FilePath,
file_name: str,
*,
mimetype: Optional[str]=None,
as_attachment: bool=False,
attachment_filename: Optional[str]=None,
add_etags: bool=True,
cache_timeout: Optional[int]=None,
conditional: bool=True... | 0.013636 |
def clear_avatar(self):
"""Clears the asset.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.clear_av... | 0.005545 |
def password_validator(self, form, field):
"""Ensure that passwords have at least 6 characters with one lowercase letter, one uppercase letter and one number.
Override this method to customize the password validator.
"""
# Convert string to list of characters
password = list(fi... | 0.008395 |
def btox(data, sep=''):
"""Return the hex encoding of a blob (string)."""
# translate the blob into hex
hex_str = binascii.hexlify(data)
# inject the separator if it was given
if sep:
hex_str = sep.join(hex_str[i:i+2] for i in range(0, len(hex_str), 2))
# return the result
return h... | 0.003067 |
def compile_results(self):
"""Compile all results for the current test
"""
self._init_dataframes()
self.total_transactions = len(self.main_results['raw'])
self._init_dates() | 0.009346 |
def post_series_publish(self, id, **data):
"""
POST /series/:id/publish/
Publishes a repeating event series and all of its occurrences that are not already canceled or deleted. Once a date is cancelled it can still be uncancelled and can be viewed by the public. A deleted date cannot be undelete... | 0.004669 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.