text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def build_day(self, dt):
"""
Build the page for the provided day.
"""
self.month = str(dt.month)
self.year = str(dt.year)
self.day = str(dt.day)
logger.debug("Building %s-%s-%s" % (self.year, self.month, self.day))
self.request = self.create_request(self.g... | 0.004808 |
def upload_to_mugshot(instance, filename):
"""
Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it
under unique hash for the image. This is for privacy reasons so others
can't just browse through the mugshot directory.
"""
extension = filename.split('.')[-1].lower()
s... | 0.004454 |
def fpopen(*args, **kwargs):
'''
Shortcut for fopen with extra uid, gid, and mode options.
Supported optional Keyword Arguments:
mode
Explicit mode to set. Mode is anything os.chmod would accept
as input for mode. Works only on unix/unix-like systems.
uid
The uid to set, i... | 0.000651 |
def errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
"""Add an error handler function to the Blueprint.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.errorhandler`. It applies
only to errors that originate in routes in t... | 0.002886 |
def get_reviews(self, publisher_name, extension_name, count=None, filter_options=None, before_date=None, after_date=None):
"""GetReviews.
[Preview API] Returns a list of reviews associated with an extension
:param str publisher_name: Name of the publisher who published the extension
:par... | 0.007022 |
def clean_old_jobs():
'''
Clean out the old jobs from the job cache
'''
if __opts__['keep_jobs'] != 0:
jid_root = _job_dir()
if not os.path.exists(jid_root):
return
# Keep track of any empty t_path dirs that need to be removed later
dirs_to_remove = set()
... | 0.001649 |
def std_coef_plot(self, num_of_features=None, server=False):
"""
Plot a GLM model"s standardized coefficient magnitudes.
:param num_of_features: the number of features shown in the plot.
:param server: ?
:returns: None.
"""
assert_is_type(num_of_features, None, ... | 0.004197 |
def _uniquewords(*args):
"""Dictionary of words to their indices. Helper function to `encode.`"""
words = {}
n = 0
for word in itertools.chain(*args):
if word not in words:
words[word] = n
n += 1
return words | 0.003717 |
def search(self, query, limit=15, offset=0, index=None):
"""
Query the search service.
:param query: The query.
:param limit: The maximal number of results to return (at most 500).
:param offset: Use to page through big search result sets.
:param index: Name of the index... | 0.002979 |
def _check_series_localize_timestamps(s, timezone):
"""
Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone.
If the input series is not a timestamp series, then the same series is returned. If the input
series is a timestamp series, then a converted series is... | 0.003315 |
def merge_boundboxes(*bb_list):
"""
Combine bounding boxes to result in a single BoundBox that encloses
all of them.
:param bb_list: List of bounding boxes
:type bb_list: :class:`list` of :class:`cadquery.BoundBox`
"""
# Verify types
if not all(isinstance(x, cadquery.BoundBox) for x in ... | 0.002593 |
def max_load(network, boundaries=[], filename=None, two_cb=False):
"""Plot maximum loading of each line.
Parameters
----------
network: PyPSA network container
Holds topology of grid including results from powerflow analysis
filename: str or None
Save figure in this direct... | 0.005069 |
def get_relationships_on_date(self, from_, to):
"""Gets a ``RelationshipList`` effective during the entire given date range inclusive but not confined to the date range.
arg: from (osid.calendaring.DateTime): starting date
arg: to (osid.calendaring.DateTime): ending date
return: (... | 0.004452 |
def marshall(self, registry):
"""Marshalls a full registry (various collectors)"""
blocks = []
for i in registry.get_all():
blocks.append(self.marshall_collector(i))
# Sort? used in tests
blocks = sorted(blocks)
# Needs EOF
blocks.append("")
... | 0.005333 |
def _get_action(self, action_meta):
'''
Parse action and turn into a calling point.
:param action_meta:
:return:
'''
conf = {
'fun': list(action_meta.keys())[0],
'arg': [],
'kwargs': {},
}
if not len(conf['fun'].split('.... | 0.002692 |
def validate(self, fn):
"""
Validate that the file has not expired based on the I{duration}.
@param fn: The file name.
@type fn: str
"""
if self.duration[1] < 1:
return
created = dt.fromtimestamp(os.path.getctime(fn))
d = {self.duration[0]: sel... | 0.004158 |
def parse_equality(cls, equality_string):
""" Parse some simple equality statements """
cls.register()
assert '=' in equality_string, "There must be an '=' sign in the equality"
[left_side, right_side] = equality_string.split('=', 1)
left_side_value = yaml.safe_load(left_side.st... | 0.007561 |
def remove_all(gset, elem):
"""Removes every occurrence of ``elem`` from ``gset``.
Returns the number of times ``elem`` was removed.
"""
n = 0
while True:
try:
remove_once(gset, elem)
n = n + 1
except RemoveError:
return n | 0.00339 |
def sos_zplane(sos,auto_scale=True,size=2,tol = 0.001):
"""
Create an z-plane pole-zero plot.
Create an z-plane pole-zero plot using the numerator
and denominator z-domain system function coefficient
ndarrays b and a respectively. Assume descending powers of z.
Parameters
--------... | 0.019211 |
def post(self, url, body="", headers={}, retry=True):
"""Execute an HTTP POST request and return a dict containing the
response and the response status code.
Keyword arguments:
url -- The path to execute the result against, not including the API
version or project ID, wit... | 0.003492 |
def write_packages(self, reqs_file):
"""
Dump the packages in the catalog in a requirements file
"""
write_file_lines(reqs_file, ('{}\n'.format(package) for package in self.packages)) | 0.013953 |
def topological_sorting(nodes, relations):
'''An implementation of Kahn's algorithm.
'''
ret = []
nodes = set(nodes) | _nodes(relations)
inc = _incoming(relations)
out = _outgoing(relations)
free = _free_nodes(nodes, inc)
while free:
n = free.pop()
ret.append(n)
... | 0.003175 |
def update_environment(self, environment, environment_ids):
"""
Method to update environment
:param environment_ids: Ids of Environment
"""
uri = 'api/v3/environment/%s/' % environment_ids
data = dict()
data['environments'] = list()
data['environments']... | 0.005013 |
def get_scheduler_location(self, topologyName, callback=None):
"""
Get scheduler location
"""
if callback:
self.scheduler_location_watchers[topologyName].append(callback)
else:
scheduler_location_path = self.get_scheduler_location_path(topologyName)
with open(scheduler_location_pat... | 0.008264 |
def files():
"""Load files."""
srcroot = dirname(dirname(__file__))
d = current_app.config['DATADIR']
if exists(d):
shutil.rmtree(d)
makedirs(d)
# Clear data
Part.query.delete()
MultipartObject.query.delete()
ObjectVersion.query.delete()
Bucket.query.delete()
FileIns... | 0.000678 |
def start_service(addr, n, authenticator):
""" Start a service """
s = Subscriber(addr, authenticator=authenticator)
def do_something(line):
pass
s.subscribe('test', do_something)
started = time.time()
for _ in range(n):
s.process()
s.socket.close()
duration = time.ti... | 0.002387 |
def date_to_long_form_string(dt, locale_ = 'en_US.utf8'):
'''dt should be a datetime.date object.'''
if locale_:
old_locale = locale.getlocale()
locale.setlocale(locale.LC_ALL, locale_)
v = dt.strftime("%A %B %d %Y")
if locale_:
locale.setlocale(locale.LC_ALL, old_locale)
ret... | 0.009231 |
def _list_request(self):
"""Returns a dictionary with JMX domain names as keys"""
try:
# https://jolokia.org/reference/html/protocol.html
#
# A maxDepth of 1 restricts the return value to a map with the JMX
# domains as keys. The values of the maps don't h... | 0.001543 |
def export_vms(
self,
vms_names=None,
standalone=False,
export_dir='.',
compress=False,
init_file_name='LagoInitFile',
out_format=YAMLOutFormatPlugin(),
collect_only=False,
with_threads=True,
):
"""
Export vm images disks and in... | 0.001867 |
def running_windows(iterable, size):
"""Generate n-size running windows.
Usage::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
"""
fifo = collections.deque(maxlen=size)
for i in iterable:
fifo.a... | 0.002584 |
def _check_children(self):
'''
Check all of the child processes are still running
'''
while self.up:
time.sleep(1)
for process in self._processes:
if process.is_alive() is True:
continue
log.debug('%s is dead. St... | 0.007353 |
def remove_from_group(self, group, user):
"""
Remove a user from a group
:type user: str
:param user: User's email
:type group: str
:param group: Group name
:rtype: dict
:return: an empty dictionary
"""
data = {'group': group, 'user': us... | 0.005305 |
def clean_unused_venvs(self, max_days_to_keep):
"""Compact usage stats and remove venvs.
This method loads the complete file usage in memory, for every venv compact all records in
one (the lastest), updates this info for every env deleted and, finally, write the entire
file to disk.
... | 0.005135 |
def get(self, name: str, config: dict = None) -> NodePool:
"""
Return node pool in input name and optional configuration.
:param name: name of configured pool
:param config: pool configuration with optional 'timeout' int, 'extended_timeout' int,
'preordered_nodes' array of s... | 0.005435 |
def get(self, request, path):
"""Return HTML (or other related content) for Meteor."""
if path == 'meteor_runtime_config.js':
config = {
'DDP_DEFAULT_CONNECTION_URL': request.build_absolute_uri('/'),
'PUBLIC_SETTINGS': self.meteor_settings.get('public', {}),
... | 0.001354 |
def _augment_sample_shape(partial_batch_dist,
full_sample_and_batch_shape,
validate_args=False):
"""Augment a sample shape to broadcast batch dimensions.
Computes an augmented sample shape, so that any batch dimensions not
part of the distribution `partial_batc... | 0.00457 |
def filter_inconsequential_mods(stmts_in, whitelist=None, **kwargs):
"""Filter out Modifications that modify inconsequential sites
Inconsequential here means that the site is not mentioned / tested
in any other statement. In some cases specific sites should be
preserved, for instance, to be used as rea... | 0.00039 |
def crypto_kx_seed_keypair(seed):
"""
Generate a keypair with a given seed.
This is functionally the same as crypto_box_seed_keypair, however
it uses the blake2b hash primitive instead of sha512.
It is included mainly for api consistency when using crypto_kx.
:param seed: random seed
:type s... | 0.000959 |
def update(self, settings):
"""Recursively merge the given settings into the current settings."""
self.settings.cache_clear()
self._settings = settings
log.info("Updated settings to %s", self._settings)
self._update_disabled_plugins() | 0.007299 |
def push(self,message,message_type):
"""
Send a reply message of the given type
Args:
- message: the message to publish
- message_type: the type of message being sent
"""
super(Producer,self).send(message,message_type) | 0.026316 |
def get_docker_io(self, container_id, all_stats):
"""Return the container IO usage using the Docker API (v1.0 or higher).
Input: id is the full container id
Output: a dict {'time_since_update': 3000, 'ior': 10, 'iow': 65}.
with:
time_since_update: number of seconds elapsed b... | 0.00373 |
def new_cbuf(self, input, null_if_empty=True):
"""
Converts the input into a raw C buffer
:param input: The input
:param null_if_empty: If the input is empty
:return: A tuple of buffer,length
"""
if not isinstance(input, bytes) and input:
input = input... | 0.003817 |
async def set_config(cls, name: str, value):
"""Set a configuration value in MAAS.
Consult your MAAS server for recognised settings. Alternatively, use
the pre-canned functions also defined on this object.
"""
return await cls._handler.set_config(name=[name], value=[value]) | 0.006349 |
def get_analysis(self):
""" Retrieve the detailed analysis for the track, if available.
Raises Exception if unable to create the detailed analysis. """
if self.analysis_url:
try:
# Try the existing analysis_url first. This expires shortly
# after ... | 0.004861 |
def auto_cleaned_path(instance, filename: str) -> str:
"""
Gets upload path in this format: {MODEL_NAME}/{SAFE_UPLOADED_FILENAME}{SUFFIX}.
:param instance: Instance of model or model class.
:param filename: Uploaded file name.
:return: Target upload path.
"""
stem, suffix = parse_filename(f... | 0.006525 |
def removeSegmentUpdate(self, updateInfo):
"""Remove a segment update (called when seg update expires or is processed)
Parameters:
--------------------------------------------------------------
updateInfo: (creationDate, SegmentUpdate)
"""
# An updateInfo contains (creationDate, SegmentUpd... | 0.001957 |
def render(template_name, template_vars={}, template_set='site', template_theme=None, template_extension='html', template_content=None):
"""Given a template path, a template name and template variables
will return rendered content using jinja2 library
:param template_path: Path to template directory
:param t... | 0.011008 |
def objective_value(self):
"""Returns the optimal objective value"""
if self._f is None:
raise RuntimeError("Problem has not been optimized yet")
if self.direction == "max":
return -self._f + self.offset
else:
return self._f + self.offset | 0.006536 |
def create_position_tear_sheet(returns, positions,
show_and_plot_top_pos=2, hide_positions=False,
return_fig=False, sector_mappings=None,
transactions=None, estimate_intraday='infer'):
"""
Generate a number of plots for... | 0.000258 |
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a... | 0.003145 |
def jtosparse(j):
"""
Generate sparse matrix coordinates from 3-D Jacobian.
"""
data = j.flatten().tolist()
nobs, nf, nargs = j.shape
indices = zip(*[(r, c) for n in xrange(nobs)
for r in xrange(n * nf, (n + 1) * nf)
for c in xrange(n * nargs, (n +... | 0.002457 |
def _iter_table_records(self):
"""
Generate a (tag, offset, length) 3-tuple for each of the tables in
this font file.
"""
count = self._table_count
bufr = self._stream.read(offset=12, length=count*16)
tmpl = '>4sLLL'
for i in range(count):
offs... | 0.004435 |
def set_user_attribute(self, username, attribute, value, raise_on_error=False):
"""Set an attribute on a user
:param username: The username on which to set the attribute
:param attribute: The name of the attribute to set
:param value: The value of the attribute to set
:return: T... | 0.003165 |
def value_count(x, value):
"""
Count occurrences of `value` in time series x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param value: the value to be counted
:type value: int or float
:return: the count
:rtype: int
"""
if not isinstance(x, (np.... | 0.002132 |
def tenants_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all tenants for your account.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.tenants_list
'''
result = {}
subconn = __utils__['azurearm.get_client']('subscription', **kwargs)
try:
tena... | 0.00314 |
def projects(self):
"""*All child projects of this taskpaper object*
**Usage:**
Given a taskpaper document object (`doc`), to get a list of the project objects found within the document use:
.. code-block:: python
docProjects = doc.projects
The sa... | 0.004808 |
def getLocalDeformationEnergy(self, bp, complexDna, freeDnaFrames=None, boundDnaFrames=None, helical=False,
unit='kT', which='all', outFile=None):
r"""Deformation energy of the input DNA using local elastic properties
The deformation energy of a base-step/s for probe D... | 0.004921 |
def get_remote_port(self, tlv_data):
"""Returns Remote Port from the TLV. """
ret, parsed_val = self._check_common_tlv_format(
tlv_data, "\n", "Port Description TLV")
if not ret:
return None
return parsed_val[1].strip() | 0.007273 |
def _start(self, start_message):
"""
Start this action given its start message.
@param WrittenMessage start_message: A start message that has the
same level as this action.
@raise InvalidStartMessage: If C{start_message} does not have a
C{ACTION_STATUS_FIELD} of... | 0.00375 |
def add_how(voevent, descriptions=None, references=None):
"""Add descriptions or references to the How section.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
descriptions(str): Description string, or list of description
strings.
references(:py:class:`voevent... | 0.003371 |
def _upload_part(api, session, url, upload, part_number, part, retry_count,
timeout):
"""
Used by the worker to upload a part to the storage service.
:param api: Api instance.
:param session: Storage service session.
:param url: Part url.
:param upload: Upload identifier.
:p... | 0.001335 |
def delete_index(self, refresh=False, ignore=None):
"""Removes the object from the index if `indexed=False`"""
es = connections.get_connection("default")
index = self.__class__.search_objects.mapping.index
doc_type = self.__class__.search_objects.mapping.doc_type
es.delete(index,... | 0.005348 |
def _set_tx_queue(self, v, load=False):
"""
Setter method for tx_queue, mapped from YANG variable /qos/tx_queue (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tx_queue is considered as a private
method. Backends looking to populate this variable should
... | 0.005851 |
def get_volume_list(self) -> list:
"""Get a list of docker volumes.
Only the manager nodes can retrieve all the volumes
Returns:
list, all the names of the volumes in swarm
"""
# Initialising empty list
volumes = []
# Raise an exception if we are n... | 0.003135 |
def add_layers(self, *layers):
""" Append given layers to this onion
:param layers: layer to add
:return: None
"""
for layer in layers:
if layer.name() in self.__layers.keys():
raise ValueError('Layer "%s" already exists' % layer.name())
self.__layers[layer.name()] = layer | 0.034014 |
def send(self, request, **kwargs):
"""Send a given PreparedRequest."""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify... | 0.002924 |
def slugable(self):
"""
A node is slugable in following cases:
1 - Node doesn't have children.
2 - Node has children but its page doesn't have a regex.
3 - Node has children, its page has regex but it doesn't show it.
4 - Node has children, its page shows his regex and no... | 0.005203 |
def make_reader_task(self, stream, callback):
"""
Create a reader executor task for a stream.
"""
return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback)) | 0.013043 |
def is_valid_assignment(self, mtf_dimension_name, mesh_dimension_name):
"""Whether this MTF dimension may be assigned to this mesh dimension.
Args:
mtf_dimension_name: string, the name of a Mesh TensorFlow dimension.
mesh_dimension_name: string, the name of a mesh dimension.
Returns:
A b... | 0.001661 |
def get_sequence(self):
"""Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
"""
if not self.address:
raise StellarAddressInvalidError('No address provided.')
address = self.horizon.... | 0.005195 |
def brand_monitor(self, query, exclude=[], domain_status=None, days_back=None, **kwargs):
"""Pass in one or more terms as a list or separated by the pipe character ( | )"""
return self._results('mark-alert', '/v1/mark-alert', query=delimited(query), exclude=delimited(exclude),
... | 0.017241 |
def snpeff(self):
"""
Annotation with snpEff
"""
# calculate time thread took to finish
# logging.info('Starting snpEff')
tstart = datetime.now()
se = snpeff.Snpeff(self.vcf_file)
std = se.run()
tend = datetime.now()
execution_time = ten... | 0.009091 |
def _related(self, concept):
"""
Returns related concepts for a concept.
"""
return concept.hypernyms() + \
concept.hyponyms() + \
concept.member_meronyms() + \
concept.substance_meronyms() + \
concept.part_meronyms() + \
... | 0.02087 |
def setBuffer(self, buffer_or_len):
"""
Replace buffer with a new one.
Allows resizing read buffer and replacing data sent.
Note: resizing is not allowed for isochronous buffer (use
setIsochronous).
Note: disallowed on control transfers (use setControl).
"""
... | 0.001533 |
def extra_dejson(self):
"""Returns the extra property by deserializing json."""
obj = {}
if self.extra:
try:
obj = json.loads(self.extra)
except Exception as e:
self.log.exception(e)
self.log.error("Failed parsing the json f... | 0.00813 |
def whois_list(request, format=None):
"""
Retrieve basic whois information related to a layer2 or layer3 network address.
"""
results = []
# layer3 results
for ip in Ip.objects.select_related().all():
interface = ip.interface
user = interface.device.node.user
device = int... | 0.001908 |
def remove_shared_folder(self, name):
"""Removes the global shared folder with the given name previously
created by :py:func:`create_shared_folder` from the collection of
shared folders and stops sharing it.
In the current implementation, this operation is not
implement... | 0.006441 |
def regularpage(foldername=None, pagename=None):
"""
Route not found by the other routes above. May point to a static template.
"""
if foldername is None and pagename is None:
raise ExperimentError('page_not_found')
if foldername is None and pagename is not None:
return render_templa... | 0.002513 |
def process_response(self, req, resp, resource):
"""Post-processing of the response (after routing).
Args:
req: Request object.
resp: Response object.
resource: Resource object to which the request was
routed. May be None if no route was found
... | 0.003697 |
def nunique(self, dropna=True):
"""
Return number of unique elements in the group.
"""
ids, _, _ = self.grouper.group_info
val = self.obj.get_values()
try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtypes
msg = '... | 0.001623 |
def add_object(self, obj):
"""Add object to local and app environment storage
:param obj: Instance of a .NET object
"""
if obj.top_level_object:
if isinstance(obj, DotNetNamespace):
self.namespaces[obj.name] = obj
self.objects[obj.id] = obj | 0.006472 |
def __from_xml(self, xmlnode):
"""Initialize `Register` from an XML node.
:Parameters:
- `xmlnode`: the jabber:x:register XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`"""
self.__logger.debug("Converting jabber:iq:register element from XML")
if xmln... | 0.005263 |
def update_saved_search(self, id, **kwargs): # noqa: E501
"""Update a specific saved search # 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.update_saved_searc... | 0.001799 |
def iteritems(self, indices=None):
'Iterate through items in the ``indices`` (defaults to all indices)'
if indices is None:
indices = force_list(self.indices.keys())
for x in self.itervalues(indices):
yield x | 0.007813 |
def parse_args():
"""
Parse the command line arguments
"""
parser = argparse.ArgumentParser(description = "Generate secrets for YubiKeys using YubiHSM",
add_help=True,
formatter_class = argparse.ArgumentDefaultsHelpFormatter,
... | 0.003298 |
def add_caveat(self, cav, key=None, loc=None):
'''Add a caveat to the macaroon.
It encrypts it using the given key pair
and by looking up the location using the given locator.
As a special case, if the caveat's Location field has the prefix
"local " the caveat is added as a clie... | 0.000742 |
def send_script_async(self, conn_id, data, progress_callback, callback):
"""Asynchronously send a a script to this IOTile device
Args:
conn_id (int): A unique identifer that will refer to this connection
data (bytes): the script to send to the device
progress_callbac... | 0.006017 |
def gen_cmakelists(project_name, project_language, min_cmake_version, default_build_type, relative_path, modules):
"""
Generate CMakeLists.txt.
"""
import os
s = []
s.append(autogenerated_notice())
s.append('\n# set minimum cmake version')
s.append('cmake_minimum_required(VERSION {0} ... | 0.003418 |
def gen_support_records(transaction_manager, min_support, **kwargs):
"""
Returns a generator of support records with given transactions.
Arguments:
transaction_manager -- Transactions as a TransactionManager instance.
min_support -- A minimum support (float).
Keyword arguments:
... | 0.000836 |
def deserialize(self, xml_input, *args, **kwargs):
"""
Convert XML to dict object
"""
return xmltodict.parse(xml_input, *args, **kwargs) | 0.011905 |
def sort_public_keys(pub_keys: List[bytes] or List[str]):
"""
:param pub_keys: a list of public keys in format of bytes.
:return: sorted public keys.
"""
for index, key in enumerate(pub_keys):
if isinstance(key, str):
pub_keys[index] = bytes.fromhex(ke... | 0.005141 |
async def server_reflexive_candidate(protocol, stun_server):
"""
Query STUN server to obtain a server-reflexive candidate.
"""
# lookup address
loop = asyncio.get_event_loop()
stun_server = (
await loop.run_in_executor(None, socket.gethostbyname, stun_server[0]),
stun_server[1])
... | 0.000932 |
def create_from(cls, another, **kwargs):
"""Create from another object of different type.
Another object must be from a derived class of SimpleObject (which
contains FIELDS)
"""
reused_fields = {}
for field, value in another.get_fields():
if field in cls.FIEL... | 0.004535 |
def configurationStore(self):
"""returns the ConfigurationStore object for this site"""
url = self._url + "/configstore"
return ConfigurationStore(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
... | 0.005305 |
def percussive(y, **kwargs):
'''Extract percussive elements from an audio time-series.
Parameters
----------
y : np.ndarray [shape=(n,)]
audio time series
kwargs : additional keyword arguments.
See `librosa.decompose.hpss` for details.
Returns
-------
y_percussive : np.... | 0.000871 |
def _clean_up_columns(
self):
"""clean up columns
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check subli... | 0.003322 |
def register_references(kb_app: kb,
sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docnames: List[str]):
""" Walk the registry and add sphinx directives """
references: ReferencesContainer = sphinx_app.env.references
for name, klas... | 0.00177 |
def run_hook(self,
app: FlaskUnchained,
bundles: List[Bundle],
_config_overrides: Optional[Dict[str, Any]] = None,
) -> None:
"""
For each bundle in ``unchained_config.BUNDLES``, iterate through that
bundle's class hierarchy, st... | 0.008953 |
def create_vnet(access_token, subscription_id, resource_group, name, location,
address_prefix='10.0.0.0/16', subnet_prefix='10.0.0.0/16', nsg_id=None):
'''Create a VNet with specified name and location. Optional subnet address prefix..
Args:
access_token (str): A valid Azure authenticat... | 0.003715 |
def apply(self, func, skills):
"""Run a function on all skills in parallel"""
def run_item(skill):
try:
func(skill)
return True
except MsmException as e:
LOG.error('Error running {} on {}: {}'.format(
func.__nam... | 0.004831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.