text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def path_only_contains_dirs(self, path):
"""Return boolean on whether a path only contains directories."""
pathlistdir = os.listdir(path)
if pathlistdir == []:
return True
if any(os.path.isfile(os.path.join(path, i)) for i in pathlistdir):
return False
ret... | 0.007481 |
def get_file_meta(filepath):
"""
Get meta-information about a file.
Parameters
----------
filepath : str
Returns
-------
meta : dict
"""
meta = {}
meta['filepath'] = os.path.abspath(filepath)
meta['creation_datetime'] = get_creation_datetime(filepath)
meta['last_acc... | 0.001316 |
def json_changebase(obj, changer):
"""
Given a primitive compound Python object (i.e. a dict,
string, int, or list) and a changer function that takes
a primitive Python object as an argument, apply the
changer function to the object and each sub-component.
Return the newly-reencoded object.
... | 0.001395 |
def reconnect(self):
"""Reconnect to rabbitmq server"""
import pika
import pika.exceptions
self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))
self.channel = self.connection.channel()
try:
self.channel.queue_declare(self.name)
... | 0.008 |
def get_task(self, id):
"""
Returns the task with the given id.
:type id:integer
:param id: The id of a task.
:rtype: Task
:returns: The task with the given id.
"""
tasks = [task for task in self.get_tasks() if task.id == id]
return tasks[0] if le... | 0.005831 |
def square_and_sum(a, s):
"""
Writes np.sum(a**2,axis=0) into s
"""
cmin, cmax = thread_partition_array(a)
map_noreturn(asqs, [(a, s, cmin[i], cmax[i]) for i in xrange(len(cmax))])
return a | 0.004695 |
def _update_indexes_for_mutated_object(collection, obj):
"""If an object is updated, this will simply remove
it and re-add it to the indexes defined on the
collection."""
for index in _db[collection].indexes.values():
_remove_from_index(index, obj)
_add_to_index(index, obj) | 0.003268 |
def do_put(endpoint, body, access_token):
'''Do an HTTP PUT request and return JSON.
Args:
endpoint (str): Azure Resource Manager management endpoint.
body (str): JSON body of information to put.
access_token (str): A valid Azure authentication token.
Returns:
HTTP response... | 0.003697 |
def GetLinkedFileEntry(self):
"""Retrieves the linked file entry, e.g. for a symbolic link.
Returns:
APFSFileEntry: linked file entry or None if not available.
"""
link = self._GetLink()
if not link:
return None
# TODO: is there a way to determine the identifier here?
link_iden... | 0.002703 |
def get(self, name):
"""Returns the specific IP interface properties
The Ipinterface resource returns the following:
* name (str): The name of the interface
* address (str): The IP address of the interface in the form
of A.B.C.D/E
* mtu (int): The co... | 0.00183 |
def list_tasks(collector):
"""List the available_tasks"""
print("Usage: aws_syncr <environment> <task>")
print("")
print("Available environments to choose from are")
print("-----------------------------------------")
print("")
for environment in os.listdir(collector.configuration_folder):
... | 0.002806 |
def encipher(self,message):
"""Encipher string using M209 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example (continuing from the example above)::
ciphertext = m.encipher(plaintext)
:param string: The str... | 0.020455 |
def add_content(self, content, mime_type=None):
"""Add content to the email
:param contents: Content to be added to the email
:type contents: Content
:param mime_type: Override the mime type
:type mime_type: MimeType, str
"""
if isinstance(content, str):
... | 0.002554 |
def GetCustomerIDs(client):
"""Retrieves all CustomerIds in the account hierarchy.
Note that your configuration file must specify a client_customer_id belonging
to an AdWords manager account.
Args:
client: an AdWordsClient instance.
Raises:
Exception: if no CustomerIds could be found.
Returns:
... | 0.009785 |
def _escape_str_id(id_str):
"""make a single string id SBML compliant"""
for c in ("'", '"'):
if id_str.startswith(c) and id_str.endswith(c) \
and id_str.count(c) == 2:
id_str = id_str.strip(c)
for char, escaped_char in _renames:
id_str = id_str.replace(char, esca... | 0.002882 |
def t_quotedvar_DOLLAR_OPEN_CURLY_BRACES(t):
r'\$\{'
if re.match(r'[A-Za-z_]', peek(t.lexer)):
t.lexer.begin('varname')
else:
t.lexer.begin('php')
return t | 0.005348 |
def make_python_patterns(additional_keywords=[], additional_builtins=[]):
"""Strongly inspired from idlelib.ColorDelegator.make_pat"""
kw = r"\b" + any("keyword", kwlist + additional_keywords) + r"\b"
kw_namespace = r"\b" + any("namespace", kw_namespace_list) + r"\b"
word_operators = r"\b" + any("operat... | 0.000452 |
def _score_step(step):
"""Count the mapped two-qubit gates, less the number of added SWAPs."""
# Each added swap will add 3 ops to gates_mapped, so subtract 3.
return len([g for g in step['gates_mapped']
if len(g.qargs) == 2]) - 3 * step['swaps_added'] | 0.003559 |
def _rr_new(self, rr_version, rr_name, rr_symlink_target, rr_relocated_child,
rr_relocated, rr_relocated_parent, file_mode):
# type: (str, bytes, bytes, bool, bool, bool, int) -> None
'''
Internal method to add Rock Ridge to a Directory Record.
Parameters:
rr_ve... | 0.003119 |
def set_body_s(self, stream):
"""Set customized body stream.
Note: the body stream can only be changed before the stream
is consumed.
:param stream: InMemStream/PipeStream for body
:except TChannelError:
Raise TChannelError if the stream is being sent when you try
... | 0.003413 |
def add_membership(self, email, role, **attrs):
"""
Add a Membership to the project and returns a
:class:`Membership` resource.
:param email: email for :class:`Membership`
:param role: role for :class:`Membership`
:param attrs: role for :class:`Membership`
:param... | 0.004149 |
def connect(self, From, to,
protocolName, clientFactory,
chooser):
"""
Issue an INBOUND command, creating a virtual connection to the peer,
given identifying information about the endpoint to connect to, and a
protocol factory.
@param clientFactor... | 0.002319 |
def TimestampToRDFDatetime(timestamp):
"""Converts MySQL `TIMESTAMP(6)` columns to datetime objects."""
# TODO(hanuszczak): `timestamp` should be of MySQL type `Decimal`. However,
# it is unclear where this type is actually defined and how to import it in
# order to have a type assertion.
if timestamp is None... | 0.015556 |
def convert_video(fieldfile, force=False):
"""
Converts a given video file into all defined formats.
"""
instance = fieldfile.instance
field = fieldfile.field
filename = os.path.basename(fieldfile.path)
source_path = fieldfile.path
encoding_backend = get_backend()
for options in s... | 0.000552 |
def _get_relative_path(self):
"""Returns the path with the query parameters escaped and appended."""
param_string = self._get_query_string()
if self.path is None:
path = '/'
else:
path = self.path
if param_string:
return '?'.join([path, param_string])
else:
return path | 0.015773 |
def delete(self, record_id):
"""
Deletes a record by its id
>>> record = airtable.match('Employee Id', 'DD13332454')
>>> airtable.delete(record['id'])
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Deleted Re... | 0.004684 |
def get_assessment_part_ids_by_banks(self, bank_ids):
"""Gets the list of ``AssessmentPart Ids`` corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.id.IdList) - list of assessment part ``Ids``
raise: NullArgument - ``bank_ids`` i... | 0.003663 |
def activate_status_output_overall_error_msg(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
activate_status = ET.Element("activate_status")
config = activate_status
output = ET.SubElement(activate_status, "output")
overall_error_msg = ET... | 0.003876 |
def expect(self, f, *args):
"""Like 'accept' but throws a parse error if 'f' doesn't match."""
match = self.accept(f, *args)
if match:
return match
try:
func_name = f.func_name
except AttributeError:
func_name = "<unnamed grammar function>"
... | 0.003802 |
def capitalize_unicode_name(s):
"""
Turns a string such as 'capital delta' into the shortened,
capitalized version, in this case simply 'Delta'. Used as a
transform in sanitize_identifier.
"""
index = s.find('capital')
if index == -1: return s
tail = s[index:].replace('capital', '').stri... | 0.005141 |
async def processClaims(self, allClaims: Dict[ID, Claims]):
"""
Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition.
"""
res = []
for schemaId, (claim_signature, claim_attributes) in allClaims.items():
... | 0.006993 |
def replace_cells(self, key, sorted_row_idxs):
"""Replaces cells in current selection so that they are sorted"""
row, col, tab = key
new_keys = {}
del_keys = []
selection = self.grid.actions.get_selection()
for __row, __col, __tab in self.grid.code_array:
... | 0.002375 |
def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True):
"""
Parses the given text and yields tokens which represent words within
the given text. Tokens are assumed to be divided by any form of
whitespace character.
"""
if ngrams is None:
ngrams = 1
... | 0.00235 |
def load_data_file(fname, directory=None, force_download=False):
"""Get a standard vispy demo data file
Parameters
----------
fname : str
The filename on the remote ``demo-data`` repository to download,
e.g. ``'molecular_viewer/micelle.npy'``. These correspond to paths
on ``http... | 0.000543 |
def all_complexes(network, state):
"""Return a generator for all complexes of the network.
.. note::
Includes reducible, zero-|big_phi| complexes (which are not, strictly
speaking, complexes at all).
Args:
network (Network): The |Network| of interest.
state (tuple[int]): Th... | 0.001695 |
def update_vnic_template(self, host_id, vlan_id, physnet,
vnic_template_path, vnic_template):
"""Updates VNIC Template with the vlan_id."""
ucsm_ip = self.get_ucsm_ip_for_host(host_id)
if not ucsm_ip:
LOG.info('UCS Manager network driver does not have UCSM IP '
... | 0.005523 |
def _flat_map(self, f: Callable):
''' **f** must return the same stack type as **self.value** has.
Iterates over the effects, sequences the inner instance
successively to the top and joins with the outer instance.
Example:
List(Right(Just(1))) => List(Right(Just(List(Right(Just(5... | 0.00431 |
def get_docs(r_session, url, encoder=None, headers=None, **params):
"""
Provides a helper for functions that require GET or POST requests
with a JSON, text, or raw response containing documents.
:param r_session: Authentication session from the client
:param str url: URL containing the endpoint
... | 0.000888 |
def _redraw(self):
"""
Forgets the current layout and redraws with the most recent information
:return: None
"""
for row in self._rows:
for widget in row:
widget.grid_forget()
offset = 0 if not self.headers else 1
for i, row in enumer... | 0.004619 |
def send_message(self, recipient, subject, message, from_sr=None,
captcha=None, **kwargs):
"""Send a message to a redditor or a subreddit's moderators (mod mail).
:param recipient: A Redditor or Subreddit instance to send a message
to. A string can also be used in which... | 0.001696 |
def step(self, disable_interrupts=True, start=0, end=0):
"""
perform an instruction level step. This function preserves the previous
interrupt mask state
"""
# Was 'if self.get_state() != TARGET_HALTED:'
# but now value of dhcsr is saved
dhcsr = self.read_memory(... | 0.006496 |
def highlight(code, lexer, formatter, outfile=None):
"""
Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.
If ``outfile`` is given and a valid file object (an object
with a ``write`` method), the result will be written to it, otherwise
it is returned as a string.
"""
... | 0.002674 |
def get_incidents(self, offset=0, limit=None, include_resolved=False, **kwargs):
"""Retrieve all (v2) incidents.
"""
resp = self._get(
self._u(self._INCIDENT_ENDPOINT_SUFFIX),
params={
'offset': offset,
'limit': limit,
'incl... | 0.006494 |
def init_logging(log_level):
"""
Initialise the logging by adding an observer to the global log publisher.
:param str log_level: The minimum log level to log messages for.
"""
log_level_filter = LogLevelFilterPredicate(
LogLevel.levelWithName(log_level))
log_level_filter.setLogLevelForN... | 0.001832 |
def boot(name, flavor_id=0, image_id=0, profile=None, timeout=300, **kwargs):
'''
Boot (create) a new instance
name
Name of the new instance (must be first)
flavor_id
Unique integer ID for the flavor
image_id
Unique integer ID for the image
timeout
How long to... | 0.001156 |
def cross_list_section(self, id, new_course_id):
"""
Cross-list a Section.
Move the Section to another course. The new course may be in a different account (department),
but must belong to the same root account (institution).
"""
path = {}
data = {}
... | 0.005855 |
def Run(self):
"""
Renames all TV files from the constructor given file list.
It follows a number of key steps:
1) Extract a list of unique show titles from file name and lookup
actual show names from database or TV guide.
2) Update each file with showID and showName.
3) Get epi... | 0.009747 |
def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn,
customer_gateway_name=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid VPN connection type, a static IP address and a customer
gateway’s Border Ga... | 0.002028 |
def step(self, batch_size, ignore_stale_grad=False):
"""Makes one step of parameter update. Should be called after
`autograd.backward()` and outside of `record()` scope.
For normal parameter updates, `step()` should be used, which internally calls
`allreduce_grads()` and then `update()`... | 0.006897 |
def _get_response(self, timeout=1.0, eor=('\n', '\n- ')):
""" Reads a response from the drive.
Reads the response returned by the drive with an optional
timeout. All carriage returns and linefeeds are kept.
Parameters
----------
timeout : number, optional
Op... | 0.000752 |
def find_promulgation_date(line):
"""
>>> find_promulgation_date("Loi nº 2010-383 du 16 avril 2010 autorisant l'approbation de l'accord entre...")
'2010-04-16'
"""
line = line.split(' du ')[1]
return format_date(re.search(r"(\d\d? \w\w\w+ \d\d\d\d)", line).group(1)) | 0.006873 |
def _supplementary_files_download_worker(*args):
"""A worker to download supplementary files.
To be used with multiprocessing.
"""
gsm = args[0][0]
download_sra = args[0][1]
email = args[0][2]
dirpath = args[0][3]
sra_kwargs = args[0][4]
return (gsm.get_accession(), gsm.download_sup... | 0.002299 |
def build_service(service_descriptor, did):
"""
Build a service.
:param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes
and the second item is a dict of parameters and values required by the service
:param did: DID, str
:return: Service... | 0.00327 |
def initialize(self, timeouts):
""" Bind or connect the nanomsg socket to some address """
# Bind or connect to address
if self.bind is True:
self.socket.bind(self.address)
else:
self.socket.connect(self.address)
# Set send and recv timeouts
self... | 0.005814 |
def undefinedImageType(self):
"""
Returns the name of undefined image type for the invalid image.
.. versionadded:: 2.3.0
"""
if self._undefinedImageType is None:
ctx = SparkContext._active_spark_context
self._undefinedImageType = \
ctx._... | 0.007109 |
def _parse_objects_from_xml_elts(bucket_name, contents, common_prefixes):
"""Internal function that extracts objects and common prefixes from
list_objects responses.
"""
objects = [
Object(bucket_name,
content.get_child_text('Key'),
content.get_localized_time_elem('... | 0.001342 |
def run(self, steps=None, resume=False, redo=None):
"""
Run a Stimela recipe.
steps : recipe steps to run
resume : resume recipe from last run
redo : Re-run an old recipe from a .last file
"""
recipe = {
"name" : self.name,
... | 0.006104 |
def _roundSlist(slist):
""" Rounds a signed list over the last element and removes it. """
slist[-1] = 60 if slist[-1] >= 30 else 0
for i in range(len(slist)-1, 1, -1):
if slist[i] == 60:
slist[i] = 0
slist[i-1] += 1
return slist[:-1] | 0.003546 |
def _try_reduce_list(statements: List["HdlStatement"]):
"""
Simplify statements in the list
"""
io_change = False
new_statements = []
for stm in statements:
reduced, _io_change = stm._try_reduce()
new_statements.extend(reduced)
io_chan... | 0.004049 |
def _package_path(name):
"""Returns the path to the package containing the named module or
None if the path could not be identified (e.g., if
``name == "__main__"``).
"""
loader = pkgutil.get_loader(name)
if loader is None or name == '__main__':
return None
if hasattr(loader, 'get_f... | 0.001767 |
def _send_resolve_request(self):
"sends RESOLVE_PTR request (Tor custom)"
host = self._addr.host.encode()
self._data_to_send(
struct.pack(
'!BBBBB{}sH'.format(len(host)),
5, # version
0xF0, # command
... | 0.003802 |
def timerEvent( self, event ):
"""
When the timer finishes, hide the tooltip popup widget.
:param event | <QEvent>
"""
if self.currentMode() == XPopupWidget.Mode.ToolTip:
self.killTimer(event.timerId())
event.accept()
sel... | 0.012469 |
def delete_activity(self, id_num):
"""Delete an activity (run).
:param id_num: The activity ID to delete
"""
url = self._build_url('my', 'activities', id_num)
r = self.session.delete(url)
r.raise_for_status()
return r | 0.007246 |
def srem(self, name, *values):
"""
send raw (source) values here. Right functioning with other values
not guaranteed (and even worse).
"""
return self.storage.srem(name, *self.dump(values, False)) | 0.008475 |
def _register_user_models(user_models, admin=None, schema=None):
"""Register any user-defined models with the API Service.
:param list user_models: A list of user-defined models to include in the
API service
"""
if any([issubclass(cls, AutomapModel) for cls in user_models])... | 0.001873 |
def _copyAllocatedStates(self):
"""If state is allocated in CPP, copy over the data into our numpy arrays."""
# Get learn states if we need to print them out
if self.verbosity > 1 or self.retrieveLearningStates:
(activeT, activeT1, predT, predT1) = self.cells4.getLearnStates()
self.lrnActiveSta... | 0.017823 |
def get_field_by_showname(self, showname):
"""
Gets a field by its "showname"
(the name that appears in Wireshark's detailed display i.e. in 'User-Agent: Mozilla...', 'User-Agent' is the
showname)
Returns None if not found.
"""
for field in self._get_all_fields... | 0.006397 |
def plot_dry_adiabats(self, p=None, theta=None, **kwargs):
r'''Plot dry adiabats.
Adds dry adiabats (lines of constant potential temperature) to the
plot. The default style of these lines is dashed red lines with an
alpha value of 0.5. These can be overridden using keyword arguments.
... | 0.000736 |
def copy_dir(src, dst):
""" this function will simply copy the file from the source path to the dest
path given as input
"""
try:
debug.log("copy dir from "+ src, "to "+ dst)
shutil.copytree(src, dst)
except Exception as e:
debug.log("Error: happened while copying!\n%s\n"%e) | 0.032468 |
def deserialize_bitarray(ser):
# type: (str) -> bitarray
"""Deserialize a base 64 encoded string to a bitarray (bloomfilter)
"""
ba = bitarray()
ba.frombytes(base64.b64decode(ser.encode(encoding='UTF-8', errors='strict')))
return ba | 0.011494 |
def document(self):
"""
Return :class:`~prompt_toolkit.document.Document` instance from the
current text, cursor position and selection state.
"""
return self._document_cache[
self.text, self.cursor_position, self.selection_state] | 0.007092 |
def format_file_node(import_graph, node, indent):
"""Prettyprint nodes based on their provenance."""
f = import_graph.provenance[node]
if isinstance(f, resolve.Direct):
out = '+ ' + f.short_path
elif isinstance(f, resolve.Local):
out = ' ' + f.short_path
elif isinstance(f, resolve.S... | 0.00198 |
def add_templatetype(templatetype,**kwargs):
"""
Add a template type with typeattrs.
"""
type_i = _update_templatetype(templatetype)
db.DBSession.flush()
return type_i | 0.010101 |
def ber(tp, tn, fp, fn):
"""Balanced Error Rate [0, 1]
:param int tp: number of true positives
:param int tn: number of true negatives
:param int fp: number of false positives
:param int fn: number of false negatives
:rtype: float
"""
return (fp / float(tn + fp) + fn / float(fn + t... | 0.009174 |
def ndb_delete(self, entity_or_key):
"""Like delete(), but for NDB entities/keys."""
if ndb is not None and isinstance(entity_or_key, ndb.Model):
key = entity_or_key.key
else:
key = entity_or_key
self.ndb_deletes.append(key) | 0.011905 |
def headers(self):
"""Return the headers for the resource. Returns the AltName, if specified; if not, then the
Name, and if that is empty, a name based on the column position. These headers
are specifically applicable to the output table, and may not apply to the resource source. FOr those heade... | 0.010471 |
def Y(self,value):
""" set phenotype """
assert value.shape[1]==1, 'Dimension mismatch'
self._N = value.shape[0]
self._Y = value | 0.025 |
def get_help_commands(server_prefix):
"""
Get the help commands for all modules
Args:
server_prefix: The server command prefix
Returns:
datapacks (list): A list of datapacks for the help commands for all the modules
"""
datapacks = []
_dir = os.path.realpath(
os.p... | 0.00299 |
def errorhandler_callback(cls, exc):
"""This function should be called in the global error handlers. This
will allow for consolidating of cleanup tasks if the exception
bubbles all the way to the top of the stack.
For example, this method will automatically rollback the database
... | 0.001784 |
def get_filter_regex(self):
"""
Used by the GUI to obtain human-readable version of the filter
"""
if self.windowInfoRegex is not None:
if self.isRecursive:
return self.windowInfoRegex.pattern
else:
return self.windowInfoRegex.patte... | 0.004484 |
def fetch(self):
"""Fetch the mbox files from the remote archiver.
Stores the archives in the path given during the initialization
of this object. Those archives which a not valid extension will
be ignored.
Groups.io archives are returned as a .zip file, which contains
... | 0.002086 |
def complete(self, return_code):
"""
Mark the process as complete with provided return_code
"""
self.return_code = return_code
self.status = 'COMPLETE' if not return_code else 'FAILED'
self.end_time = datetime.datetime.now() | 0.007353 |
def get_model_class(self):
"""Get model class"""
if getattr(self, 'model', None):
return self.model
elif getattr(self, 'object', None):
return self.object.__class__
elif 'app' in self.kwargs and 'model' in self.kwargs:
return apps.get_model(self.kwargs... | 0.006186 |
def dihed_single(self, g_num, at_1, at_2, at_3, at_4):
""" Dihedral/out-of-plane angle among four atoms.
Returns the out-of-plane angle among four atoms from geometry
`g_num`, in degrees. The reference plane
is spanned by `at_1`, `at_2` and `at_3`. The out-of-plane angle is
def... | 0.002107 |
def _read_image_slice(self, arg):
"""
workhorse to read a slice
"""
if 'ndims' not in self._info:
raise ValueError("Attempt to slice empty extension")
if isinstance(arg, slice):
# one-dimensional, e.g. 2:20
return self._read_image_slice((arg,)... | 0.000723 |
def context(self):
""" Provides request context """
type = "client_associate" if self.key is None else "client_update"
data = {
"type": type,
"application_type": self.type,
}
# is this an update?
if self.key:
data["client_id"] = self.k... | 0.002475 |
def set_row_min_height(self, y: int, min_height: int):
"""Sets a minimum height for blocks in the row with coordinate y."""
if y < 0:
raise IndexError('y < 0')
self._min_heights[y] = min_height | 0.008734 |
def _izip(*iterables):
""" Iterate through multiple lists or arrays of equal size """
# This izip routine is from itertools
# izip('ABCD', 'xy') --> Ax By
iterators = map(iter, iterables)
while iterators:
yield tuple(map(next, iterators)) | 0.003745 |
def state(name):
'''
Returns the state of the container
name
Container name or ID
**RETURN DATA**
A string representing the current state of the container (either
``running``, ``paused``, or ``stopped``)
CLI Example:
.. code-block:: bash
salt myminion docker.state... | 0.001776 |
def dist(x1, x2=None, metric='sqeuclidean', to_numpy=True):
"""Compute distance between samples in x1 and x2 on gpu
Parameters
----------
x1 : np.array (n1,d)
matrix with n1 samples of size d
x2 : np.array (n2,d), optional
matrix with n2 samples of size d (if None then x2=x1)
m... | 0.001271 |
def classFactory(iface):
"""Load Plugin class from file Plugin."""
# Try to import submodule to check if there are present.
try:
from parameters.generic_parameter import GenericParameter
except ImportError:
# Don't use safe.utilities.i18n.tr as we need to be outside of `safe`.
# ... | 0.000939 |
def tasks_by_tag(self, registry_tag):
""" Get tasks from registry by its tag
:param registry_tag: any hash-able object
:return: Return task (if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is not True) or \
list of tasks
"""
if registry_tag not in self.__registry.keys():
return None
tasks ... | 0.028369 |
def requirements(collector):
"""Just print out the requirements"""
out = sys.stdout
artifact = collector.configuration['dashmat'].artifact
if artifact not in (None, "", NotSpecified):
if isinstance(artifact, six.string_types):
out = open(artifact, 'w')
else:
out =... | 0.002004 |
def _sending_task(self, backend):
"""
Used internally to safely increment `backend`s task count. Returns the
overall count of tasks for `backend`.
"""
with self.backend_mutex:
self.backends[backend] += 1
self.task_counter[backend] += 1
this_ta... | 0.007979 |
def standardize(self, axis=1):
"""
Divide by standard deviation either within or across records.
Parameters
----------
axis : int, optional, default = 0
Which axis to standardize along, within (1) or across (0) records
"""
if axis == 1:
re... | 0.003731 |
def run_hive_script(script):
"""
Runs the contents of the given script in hive and returns stdout.
"""
if not os.path.isfile(script):
raise RuntimeError("Hive script: {0} does not exist.".format(script))
return run_hive(['-f', script]) | 0.003802 |
def _init_multicast_socket(self):
"""
Init multicast socket
:rtype: None
"""
self.debug("()")
# Create a UDP socket
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
# Allow reuse of addresses
... | 0.001516 |
def get_default_config_parsers() -> List[AnyParser]:
"""
Utility method to return the default parsers able to parse a dictionary from a file.
:return:
"""
return [SingleFileParserFunction(parser_function=read_config,
streaming_mode=True,
... | 0.004464 |
def calls(self, truncate=False):
"""
Show 10 most frequently called queries. Requires the pg_stat_statements
Postgres module to be installed.
Record(
query='BEGIN;',
exec_time=datetime.timedelta(0, 0, 288174),
prop_exec_time='0.0%',
ncalls... | 0.001936 |
def setup_schema(command, conf, vars):
"""Place any commands to setup depotexample here"""
# Load the models
# <websetup.websetup.schema.before.model.import>
from depotexample import model
# <websetup.websetup.schema.after.model.import>
# <websetup.websetup.schema.before.metadata.create_a... | 0.004902 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.