text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def appdatadirectory( ):
"""Attempt to retrieve the current user's app-data directory
This is the location where application-specific
files should be stored. On *nix systems, this will
be the ${HOME}/.config directory. On Win32 systems, it will be
the "Application Data" directory. Note that for... | 0.012436 |
def parse_imethodcall(self, tup_tree):
"""
::
<!ELEMENT IMETHODCALL (LOCALNAMESPACEPATH, IPARAMVALUE*)>
<!ATTLIST IMETHODCALL
%CIMName;>
"""
self.check_node(tup_tree, 'IMETHODCALL', ('NAME',))
k = kids(tup_tree)
if not k:
... | 0.002591 |
def connections_to_object(self, to_obj):
"""
Returns a ``Connection`` query set matching all connections with
the given object as a destination.
"""
self._validate_ctypes(None, to_obj)
return self.connections.filter(to_pk=to_obj.pk) | 0.007143 |
def db_create():
"""Create the database"""
try:
migrate_api.version_control(url=db_url, repository=db_repo)
db_upgrade()
except DatabaseAlreadyControlledError:
print 'ERROR: Database is already version controlled.' | 0.004 |
def cache(self, mode="r", encoding=Constants.default_codec, errors=Constants.codec_error):
"""
Reads given file content and stores it in the content cache.
:param mode: File read mode.
:type mode: unicode
:param encoding: File encoding codec.
:type encoding: unicode
... | 0.00466 |
def with_edges(structure, edges):
"""
Constructor for MoleculeGraph, using pre-existing or pre-defined edges
with optional edge parameters.
:param molecule: Molecule object
:param edges: dict representing the bonds of the functional
group (format: {(from_index, t... | 0.001949 |
def calculate_energy(self, energies):
"""
Calculates the energy of the reaction.
Args:
energies ({Composition: float}): Energy for each composition.
E.g ., {comp1: energy1, comp2: energy2}.
Returns:
reaction energy as a float.
"""
... | 0.004386 |
def reset_backend(self, warn_user=True, reset_interps=True):
"""
Resets GUI data and updates GUI displays such as plots, boxes, and
logger
Parameters
----------
warn_user : bool which decides if a warning dialog is displayed to
the user to ask about reseting ... | 0.001799 |
def get_attr_value(self, name):
'''Retrieve the ``value`` for the attribute ``name``. The ``name``
can be nested following the :ref:`double underscore <tutorial-underscore>`
notation, for example ``group__name``. If the attribute is not available it
raises :class:`AttributeError`.'''
if name in self._me... | 0.002646 |
def _isna_old(obj):
"""Detect missing values. Treat None, NaN, INF, -INF as null.
Parameters
----------
arr: ndarray or object value
Returns
-------
boolean ndarray or boolean
"""
if is_scalar(obj):
return libmissing.checknull_old(obj)
# hack (for now) because MI regist... | 0.001131 |
def filepath(self) -> str:
"""The NetCDF file path."""
return os.path.join(self._dirpath, self.name + '.nc') | 0.016129 |
def _utf_strip_bom(self, encoding):
"""Return an encoding that will ignore the BOM."""
if encoding is None:
pass
elif encoding.lower() == 'utf-8':
encoding = 'utf-8-sig'
elif encoding.lower().startswith('utf-16'):
encoding = 'utf-16'
elif enco... | 0.004878 |
def remove(text, exclude):
"""Remove ``exclude`` symbols from ``text``.
Example:
>>> remove("example text", string.whitespace)
'exampletext'
Args:
text (str): The text to modify
exclude (iterable): The symbols to exclude
Returns:
``text`` with ``exclude`` symbo... | 0.002208 |
def _encrypt_password(self, password):
"""encrypt the password for given mode """
if self.encryption_mode.lower() == 'crypt':
return self._crypt_password(password)
elif self.encryption_mode.lower() == 'md5':
return self._md5_password(password)
elif self.encryption... | 0.004193 |
def build(level, code, validity=None):
'''Serialize a GeoID from its parts'''
spatial = ':'.join((level, code))
if not validity:
return spatial
elif isinstance(validity, basestring):
return '@'.join((spatial, validity))
elif isinstance(validity, datetime):
return '@'.join((sp... | 0.001751 |
def episode_info(self):
"""
Search for the episode with the requested experience Id
:return:
"""
if self.show_info:
for season in self.show_info["seasons"]:
for episode in season["episodes"]:
for lang in episode["languages"].values(... | 0.003953 |
def get_neutron_endpoint(cls, json_resp):
"""
Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service
Sends a CRITICAL service check when none are found registered in the Catalog
"""
catalog = json_resp.get('token', {}).get('catalog', [... | 0.004721 |
def release():
"""Bump version, tag, build, gen docs."""
if check_staged():
raise EnvironmentError('There are staged changes, abort.')
if check_unstaged():
raise EnvironmentError('There are unstaged changes, abort.')
bump()
tag()
build()
doc_gen()
puts(colored.yellow("Rem... | 0.002062 |
def __getBucketVersioning(self, bucket):
"""
For newly created buckets get_versioning_status returns an empty dict. In the past we've
seen None in this case. We map both to a return value of False.
Otherwise, the 'Versioning' entry in the dictionary returned by get_versioning_status can... | 0.009783 |
def GetFirstWrittenEventSource(self):
"""Retrieves the first event source that was written after open.
Using GetFirstWrittenEventSource and GetNextWrittenEventSource newly
added event sources can be retrieved in order of addition.
Returns:
EventSource: event source or None if there are no newly ... | 0.003731 |
def get_hyperedge_weight_matrix(H, hyperedge_ids_to_indices):
"""Creates the diagonal matrix W of hyperedge weights as a sparse matrix.
:param H: the hypergraph to find the weights.
:param hyperedge_weights: the mapping from the indices of hyperedge IDs to
the corresponding hype... | 0.00107 |
def add(self, phrase, id=None):
"""
Adds a new phrase to the dictionary
:param phrase: the new phrase as a list of tokens
:param phrase_id: optionally the phrase_id can be set on addition. Beware, if you set one id you should set
them all as the auto-generated ids do not tak... | 0.007042 |
def add_router_to_hosting_device(self, client, hosting_device_id, body):
"""Adds a router to hosting device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.post((res_path + DEVICE_L3_ROUTERS) %
hosting_device_id, body=body) | 0.006734 |
def _get_samples(self, subset=None):
"""
Helper function to get sample names from subset.
Parameters
----------
subset : str
Subset name. If None, returns all samples.
Returns
-------
List of sample names
"""
if subset is None... | 0.002882 |
def trace_job(self, jobId):
""" Get information about the specified remote job
:param jobId: the job identifier
:return: a dictionary with the information
"""
header = self.__check_authentication()
status_url = self.address + "/jobs/" + jobId + "/trace"
status_re... | 0.005445 |
def start(self, host='127.0.0.1', port=None, debug=False, **kwargs):
"""
Start the built in webserver, bound to the host and port you'd like.
Default host is `127.0.0.1` and port 8080.
:param host: The host you want to bind the build in webserver to
:param port: The port number ... | 0.003503 |
def remove(h, i):
"""Remove the item at position i of the heap."""
n = h.size() - 1
if n != i:
h.swap(i, n)
down(h, i, n)
up(h, i)
return h.pop() | 0.005376 |
def instance_variables(self):
"""
Returns all instance variables in the class, sorted
alphabetically as a list of `pydoc.Variable`. Instance variables
are attributes of `self` defined in a class's `__init__`
method.
"""
p = lambda o: isinstance(o, Variable) and se... | 0.007653 |
def getControllerState(self, unControllerDeviceIndex, unControllerStateSize=sizeof(VRControllerState_t)):
"""
Fills the supplied struct with the current state of the controller. Returns false if the controller index
is invalid. This function is deprecated in favor of the new IVRInput system.
... | 0.010657 |
def current_timestamp(self) -> datetime:
"""Get the current state timestamp."""
timestamp = DB.get_hash_value(self._key, 'current_timestamp')
return datetime_from_isoformat(timestamp) | 0.009662 |
def join_accesses(unique_id, accesses, from_date, until_date, dayly_granularity):
"""
Esse metodo recebe 1 ou mais chaves para um documento em específico para que
os acessos sejam recuperados no Ratchet e consolidados em um unico id.
Esse processo é necessário pois os acessos de um documento podem ser r... | 0.002594 |
def _get_col_dimstr(tdim, is_string=False):
"""
not for variable length
"""
dimstr = ''
if tdim is None:
dimstr = 'array[bad TDIM]'
else:
if is_string:
if len(tdim) > 1:
dimstr = [str(d) for d in tdim[1:]]
else:
if len(tdim) > 1 or ... | 0.001984 |
def dsc_comment(self, comment):
""" Emit a comment into the PostScript output for the given surface.
The comment is expected to conform to
the PostScript Language Document Structuring Conventions (DSC).
Please see that manual for details on the available comments
and their meani... | 0.000615 |
def split_extension(file_name, special=['tar.bz2', 'tar.gz']):
"""
Find the file extension of a file name, including support for
special case multipart file extensions (like .tar.gz)
Parameters
----------
file_name: str, file name
special: list of str, multipart extensions
... | 0.001471 |
def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'):
"""
Find blog entries with the most comments:
qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id'))
for entry in qs:
print entry.title, entry.sco... | 0.010398 |
def get_version(version=None):
"""Returns a tuple of the django version. If version argument is non-empty,
then checks for correctness of the tuple provided.
"""
if version[4] > 0: # 0.2.1-alpha.1
return "%s.%s.%s-%s.%s" % (version[0], version[1], version[2], version[3], version[4])
elif v... | 0.00335 |
def _javascript_helper(self, position):
""" Add javascript links for the current page and for the plugins """
if position not in ["header", "footer"]:
position = "footer"
# Load javascript files from plugins
if position == "header":
entries = [entry for entry in ... | 0.006386 |
def card_transfer(provider: Provider, card: CardTransfer, inputs: dict,
change_address: str, locktime: int=0) -> Transaction:
'''Prepare the CardTransfer Transaction object
: card - CardTransfer object
: inputs - utxos (has to be owned by deck issuer)
: change_address - addr... | 0.003302 |
def normal_cloud_im(self, ksize=3):
"""Generate a NormalCloudImage from the PointCloudImage using Sobel filtering.
Parameters
----------
ksize : int
Size of the kernel to use for derivative computation
Returns
-------
:obj:`NormalCloudImage`
... | 0.008065 |
def delete(self, endpoint, params=None, version='1.1', json_encoded=False):
"""Shortcut for delete requests via :class:`request`"""
return self.request(endpoint, 'DELETE', params=params, version=version, json_encoded=json_encoded) | 0.012195 |
def _remove_boundaries(self, interval):
"""
Removes the boundaries of the interval from the boundary table.
"""
begin = interval.begin
end = interval.end
if self.boundary_table[begin] == 1:
del self.boundary_table[begin]
else:
self.boundary... | 0.004184 |
def save(self, *args, **kwargs):
"""
Save object in database, updating the datetimes accordingly.
"""
# Now in UTC
now_datetime = timezone.now()
# If we are in a creation, assigns creation_datetime
if not self.id:
self.creation_datetime = now_datetime
# Las update datetime is always updated
se... | 0.038244 |
def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
ns_packages = value
assert_string_list(dist, attr, ns_packages)
for nsp in ns_packages:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or ... | 0.001462 |
def getShareInfo(item):
'''
Get a dictionary of special annotations for a Telepath Proxy.
Args:
item: Item to inspect.
Notes:
This will set the ``_syn_telemeth`` attribute on the item
and the items class, so this data is only computed once.
Returns:
dict: A dictio... | 0.0013 |
def delete_vnic_template_for_vlan(self, vlan_id):
"""Deletes VNIC Template for a vlan_id and physnet if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(ucsm_model.VnicTemplate).filter_by(
vlan_id=vlan_id).delete()
... | 0.005277 |
def main():
"""
NAME
zeq.py
DESCRIPTION
plots demagnetization data. The equal area projection has the X direction (usually North in geographic coordinates)
to the top. The red line is the X axis of the Zijderveld diagram. Solid symbols are lower hemisphere.
The solid ... | 0.03965 |
def get_indicators(self):
"""List indicators available on the remote instance."""
response = self._get('', 'get-indicators')
response['message'] = "%i indicators:\n%s" % (
len(response['indicators']),
"\n".join(response['indicators'])
)
return response | 0.006329 |
def add_permission(self, queue, label, aws_account_id, action_name, callback=None):
"""
Add a permission to a queue.
:type queue: :class:`boto.sqs.queue.Queue`
:param queue: The queue object
:type label: str or unicode
:param label: A unique identification of the permis... | 0.00563 |
def infer(self, number_of_processes=1, *args, **kwargs):
"""
:param number_of_processes: If set to more than 1, the inference routines will be paralellised
using ``multiprocessing`` module
:param args: arguments to pass to :meth:`Inference.infer`
:para... | 0.006737 |
def form_invalid(self, form, forms, open_tabs, position_form_default):
"""
Called if a form is invalid. Re-renders the context data with the data-filled forms and errors.
"""
# return self.render_to_response( self.get_context_data( form = form, forms = forms ) )
return self.rende... | 0.011211 |
def hist(hists,
stacked=True,
reverse=False,
xpadding=0, ypadding=.1,
yerror_in_padding=True,
logy=None,
snap=True,
axes=None,
**kwargs):
"""
Make a matplotlib hist plot from a ROOT histogram, stack or
list of histograms.
Parameter... | 0.000424 |
def zpopmin(self, key, count=None, *, encoding=_NOTSET):
"""Removes and returns up to count members with the lowest scores
in the sorted set stored at key.
:raises TypeError: if count is not int
"""
if count is not None and not isinstance(count, int):
raise TypeError... | 0.003831 |
def bar(msg='', width=40, position=None):
r"""
Returns a string with text centered in a bar caption.
Examples:
>>> bar('test', width=10)
'== test =='
>>> bar(width=10)
'=========='
>>> bar('Richard Dean Anderson is...', position='top', width=50)
'//========= Richard Dean Anderson is... | 0.001289 |
def launch(self, task, **kwargs):
"""
Build the input files and submit the task via the :class:`Qadapter`
Args:
task: :class:`TaskObject`
Returns:
Process object.
"""
if task.status == task.S_LOCKED:
raise ValueError("You shall not su... | 0.004551 |
def setEnabled(self, state):
"""
Updates the drop shadow effect for this widget on enable/disable
state change.
:param state | <bool>
"""
super(XToolButton, self).setEnabled(state)
self.updateUi() | 0.014085 |
def check_pidfile(pidfile, debug):
"""Check that a process is not running more than once, using PIDFILE"""
# Check PID exists and see if the PID is running
if os.path.isfile(pidfile):
pidfile_handle = open(pidfile, 'r')
# try and read the PID file. If no luck, remove it
try:
... | 0.002759 |
def set_alpn_select_callback(self, callback):
"""
Specify a callback function that will be called on the server when a
client offers protocols using ALPN.
:param callback: The callback function. It will be invoked with two
arguments: the Connection, and a list of offered pr... | 0.002782 |
def baltree(ntips, treeheight=1.0):
"""
Returns a balanced tree topology.
"""
# require even number of tips
if ntips % 2:
raise ToytreeError("balanced trees must have even number of tips.")
# make first cherry
rtree = toytree.tree()
rtree.tree... | 0.003339 |
def boolean(text):
"""
An alternative to the "bool" argument type which interprets string
values.
"""
tmp = text.lower()
if tmp.isdigit():
return bool(int(tmp))
elif tmp in ('t', 'true', 'on', 'yes'):
return True
elif tmp in ('f', 'false', 'off', 'no'):
return Fa... | 0.002632 |
def pack(header, s):
"""Pack a string into MXImageRecord.
Parameters
----------
header : IRHeader
Header of the image record.
``header.label`` can be a number or an array. See more detail in ``IRHeader``.
s : str
Raw image string to be packed.
Returns
-------
s ... | 0.002014 |
def save(self, filename):
""" save colormap to file"""
plt.savefig(filename, fig=self.fig, facecolor='black', edgecolor='black') | 0.020833 |
def Huq_Loth(x, rhol, rhog):
r'''Calculates void fraction in two-phase flow according to the model of
[1]_, also given in [2]_, [3]_, and [4]_.
.. math::
\alpha = 1 - \frac{2(1-x)^2}{1 - 2x + \left[1 + 4x(1-x)\left(\frac
{\rho_l}{\rho_g}-1\right)\right]^{0.5}}
Parameters
---------... | 0.007039 |
def credentials(self, credentials):
"""
Sets the credentials of this WebAuthorization.
The confidential portion of the `Authorization` header that follows the `type` field. This field is write-only. It is omitted by read operations. If authorization is required, the `credentials` value must be... | 0.005761 |
def q12d_local(vertices, lame, mu):
"""Local stiffness matrix for two dimensional elasticity on a square element.
Parameters
----------
lame : Float
Lame's first parameter
mu : Float
shear modulus
See Also
--------
linear_elasticity
Notes
-----
Vertices sho... | 0.001133 |
def _try_trigger_before_first_request_funcs(self): # pylint: disable=C0103
"""Runs each function from ``self.before_first_request_funcs`` once and only once."""
if self._after_first_request_handled:
return
else:
with self._before_first_request_lock:
if se... | 0.005714 |
def add_ephemeral_listener(self, callback, event_type=None):
"""Add a callback handler for ephemeral events going to this room.
Args:
callback (func(room, event)): Callback called when an ephemeral event arrives.
event_type (str): The event_type to filter for.
Returns:
... | 0.005979 |
def sim(self, src, tar, qval=2, alpha=1, beta=1, bias=None):
"""Return the Tversky index of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for compa... | 0.000869 |
def create_rsa_public_and_private_from_pem(pem, passphrase=None):
"""
<Purpose>
Generate public and private RSA keys from an optionally encrypted PEM. The
public and private keys returned conform to
'securesystemslib.formats.PEMRSA_SCHEMA' and have the form:
'-----BEGIN RSA PUBLIC KEY----- ... ---... | 0.007729 |
def add_view(self, view_name, map_func, reduce_func=None, **kwargs):
"""
Appends a MapReduce view to the locally cached DesignDocument View
dictionary. To create a JSON query index use
:func:`~cloudant.database.CloudantDatabase.create_query_index` instead.
A CloudantException is... | 0.002099 |
def _verify(certificate_or_public_key, signature, data, hash_algorithm):
"""
Verifies an RSA, DSA or ECDSA signature
:param certificate_or_public_key:
A Certificate or PublicKey instance to verify the signature with
:param signature:
A byte string of the signature to verify
:param... | 0.001152 |
def stringify(self, value):
"""Convert value to string
This method is used to generate a simple JSON representation of the
object (without dereferencing objects etc.)
"""
# SuperModel -> UID
if ISuperModel.providedBy(value):
return str(value)
# DateTi... | 0.001656 |
def mode(self, axis=0, numeric_only=False, dropna=True):
"""Perform mode across the DataFrame.
Args:
axis (int): The axis to take the mode on.
numeric_only (bool): if True, only apply to numeric columns.
Returns:
DataFrame: The mode of the DataFrame.... | 0.00354 |
def _call_numpy(self, x):
"""Return ``self(x)`` for numpy back-end.
Parameters
----------
x : `numpy.ndarray`
Array representing the function to be transformed
Returns
-------
out : `numpy.ndarray`
Result of the transform
"""
... | 0.001531 |
def pos(self):
"""
Lazy-loads the part of speech tag for this word
:getter: Returns the plain string value of the POS tag for the word
:type: str
"""
if self._pos is None:
poses = self._element.xpath('POS/text()')
if len(poses) > 0:
... | 0.005435 |
def dec(data, **kwargs):
'''
Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. ... | 0.002732 |
def hmean(nums):
r"""Return harmonic mean.
The harmonic mean is defined as:
:math:`\frac{|nums|}{\sum\limits_{i}\frac{1}{nums_i}}`
Following the behavior of Wolfram|Alpha:
- If one of the values in nums is 0, return 0.
- If more than one value in nums is 0, return NaN.
Cf. https://en.wiki... | 0.000855 |
def basic_recover(self, requeue=False):
"""Redeliver unacknowledged messages
This method asks the broker to redeliver all unacknowledged
messages on a specified channel. Zero or more messages may be
redelivered. This method is only allowed on non-transacted
channels.
R... | 0.001908 |
def add_env(url, saltenv):
'''
append `saltenv` to `url` as a query parameter to a 'salt://' url
'''
if not url.startswith('salt://'):
return url
path, senv = parse(url)
return create(path, saltenv) | 0.004329 |
def createNewTriples(Win):
"""Add entries to the triples tables based on new images in the db"""
win.help("Building list of exposures to look for triples")
cols=('e.expnum', 'object',
'mjdate',
'uttime',
'elongation',
'filter',
'obs_iq_refccd','qso_status' )
header='%6s %... | 0.026464 |
def send_start(remote, code, device=None, address=None):
"""
All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
code: str
device: str
address: str
Notes
-----
No attempt is made to catch or h... | 0.001946 |
def add(name,
uid=None,
gid=None,
groups=None,
home=None,
shell=None,
fullname=None,
createhome=True,
**kwargs):
'''
Add a user to the minion
CLI Example:
.. code-block:: bash
salt '*' user.add name <uid> <gid> <groups> <home> <s... | 0.000638 |
def antenna1(self, context):
""" antenna1 data source """
lrow, urow = MS.uvw_row_extents(context)
antenna1 = self._manager.ordered_uvw_table.getcol(
MS.ANTENNA1, startrow=lrow, nrow=urow-lrow)
return antenna1.reshape(context.shape).astype(context.dtype) | 0.006689 |
def _format_response(self, request, response):
""" Format response using appropriate datamapper.
Take the devil response and turn it into django response, ready to
be returned to the client.
"""
res = datamapper.format(request, response, self)
# data is now formatted, l... | 0.003876 |
def synchronize(func):
""" Decorator for :meth:`synchronize`. """
@wraps(func)
def outer(self, *args, **kwargs):
@self.synchronize
def inner(self, *args, **kwargs):
return func(self, *args, **kwargs)
return inner(self, *args, **kwargs)
return outer | 0.0033 |
def callback(self):
"""Callback after this async pipeline finishes."""
if self.was_aborted:
return
mapreduce_id = self.outputs.job_id.value
mapreduce_state = model.MapreduceState.get_by_job_id(mapreduce_id)
if mapreduce_state.result_status != model.MapreduceState.RESULT_SUCCESS:
self.re... | 0.006601 |
def spec(self):
"""Return a SourceSpec to describe this source"""
from ambry_sources.sources import SourceSpec
d = self.dict
d['url'] = self.url
# Will get the URL twice; once as ref and once as URL, but the ref is ignored
return SourceSpec(**d) | 0.010135 |
def _GetRecordValue(self, record, value_entry):
"""Retrieves a specific value from the record.
Args:
record (pyesedb.record): ESE record.
value_entry (int): value entry.
Returns:
object: value.
Raises:
ValueError: if the value is not supported.
"""
column_type = record... | 0.009685 |
def _print_installed_apps(self, controller):
"""Print out a list of installed sprockets applications
:param str controller: The name of the controller to get apps for
"""
print('\nInstalled Sprockets %s Apps\n' % controller.upper())
print("{0:<25} {1:>25}".format('Name', 'Module... | 0.003868 |
def assert_rank_at_most(x, rank, data=None, summarize=None, message=None,
name=None):
"""Assert `x` has rank equal to `rank` or smaller.
Example of adding a dependency to an operation:
```python
with tf.control_dependencies([tf.assert_rank_at_most(x, 2)]):
output = tf.reduce_sum(x)... | 0.002625 |
def execute(self, conn, app="", release_version="", pset_hash="", output_label="",
global_tag='', transaction = False):
"""
returns id for a given application
"""
sql = self.sql
binds = {}
setAnd=False
if not app == "":
sql += " A.APP_NAME=:app_name"
binds[... | 0.043601 |
def killTask(self, driver, taskId):
"""
Kill parent task process and all its spawned children
"""
try:
pid = self.runningTasks[taskId]
pgid = os.getpgid(pid)
except KeyError:
pass
else:
os.killpg(pgid, signal.SIGKILL) | 0.00639 |
def expire_queues(self):
'''
Expires old queue_dict keys that have not been used in a long time.
Prevents slow memory build up when crawling lots of different domains
'''
curr_time = time.time()
for key in list(self.queue_dict):
diff = curr_time - self.queue_d... | 0.003478 |
def clean_meta(meta, including_info=False, logger=None):
""" Clean meta dict. Optionally log changes using the given logger.
@param logger: If given, a callable accepting a string message.
@return: Set of keys removed from C{meta}.
"""
modified = set()
for key in meta.keys():
i... | 0.001529 |
def j0_1(a=1):
r"""Hankel transform pair J0_1 ([Ande75]_)."""
def lhs(x):
return x*np.exp(-a*x**2)
def rhs(b):
return np.exp(-b**2/(4*a))/(2*a)
return Ghosh('j0', lhs, rhs) | 0.004831 |
def select_time(da, **indexer):
"""Select entries according to a time period.
Parameters
----------
da : xarray.DataArray
Input data.
**indexer : {dim: indexer, }, optional
Time attribute and values over which to subset the array. For example, use season='DJF' to select winter values,
... | 0.003979 |
def sortedIndex(self, obj, iterator=lambda x: x):
"""
Use a comparator function to figure out the smallest index at which
an object should be inserted so as to maintain order.
Uses binary search.
"""
array = self.obj
value = iterator(obj)
low = 0
h... | 0.003643 |
def register(self, resource=None, **meta):
""" Add resource to the API.
:param resource: Resource class for registration
:param **meta: Redefine Meta options for the resource
:return adrest.views.Resource: Generated resource.
"""
if resource is None:
def wr... | 0.001229 |
def get_task_statuses(self):
"""
Get all tasks' statuses
:return: a dict which key is the task name and value is the :class:`odps.models.Instance.Task` object
:rtype: dict
"""
params = {'taskstatus': ''}
resp = self._client.get(self.resource(), params=params)
... | 0.006928 |
def match_via_squared_difference(image, template, raw_tolerance=1, sq_diff_tolerance=0.1):
""" Matchihng algorithm based on normalised cross correlation.
Using this matching prevents false positives occuring for bright patches in the image
"""
h, w = image.shape
th, tw = template.shape
# fft... | 0.007752 |
def _insert_uncompressed(collection_name, docs, check_keys,
safe, last_error_args, continue_on_error, opts):
"""Internal insert message helper."""
op_insert, max_bson_size = _insert(
collection_name, docs, check_keys, continue_on_error, opts)
rid, msg = __pack_message(2002, op_insert)
... | 0.004175 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.