text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _parse_node_data(self, data):
""" Parse the value of a node. Override to provide your own parsing. """
data = data or ''
if self.numbermode == 'basic':
return self._try_parse_basic_number(data)
elif self.numbermode == 'decimal':
return self._try_parse_decimal(... | 0.008264 |
def object_present(container, name, path, profile):
'''
Ensures a object is presnt.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param path: Local path to file
:type path: ``str``
:param profile: The profile k... | 0.004115 |
def _fetchall(self, query, vars, limit=None, offset=0):
"""
Return multiple rows.
"""
if limit is None:
limit = current_app.config['DEFAULT_PAGE_SIZE']
query += ' LIMIT %s OFFSET %s''' % (limit, offset)
cursor = self.get_db().cursor()
self._log(cursor,... | 0.004975 |
def check_user_can_view_comments(user_info, recid):
"""Check if the user is authorized to view comments for given
recid.
Returns the same type as acc_authorize_action
"""
# Check user can view the record itself first
(auth_code, auth_msg) = check_user_can_view_record(user_info, recid)
if au... | 0.001359 |
def add_transmute_route(self, *args):
"""
two formats are accepted, for transmute routes. One allows
for a more traditional aiohttp syntax, while the other
allows for a flask-like variant.
.. code-block:: python
# if the path and method are not added in describe.
... | 0.002312 |
def validate_a_time_filter(self, value):
"""
Would be for example: [2013-03-01 TO 2013-04-01:00:00:00] and/or [* TO *]
"""
if value:
try:
utils.parse_datetime_range(value)
except Exception as e:
raise serializers.ValidationError(e.m... | 0.008596 |
def _servicegroup_get_server(sg_name, s_name, s_port=None, **connection_args):
'''
Returns a member of a service group or None
'''
ret = None
servers = _servicegroup_get_servers(sg_name, **connection_args)
if servers is None:
return None
for server in servers:
if server.get_s... | 0.002101 |
def check_owners(self, request, **resources):
""" Check parents of current resource.
Recursive scanning of the fact that the child has FK
to the parent and in resources we have right objects.
We check that in request like /author/1/book/2/page/3
Page object with pk=3 has Forei... | 0.001571 |
def _clean_header_df(self, df):
"""Format the header dataframe and add units."""
if self.suffix == '-drvd.txt':
df.units = {'release_time': 'second',
'precipitable_water': 'millimeter',
'inv_pressure': 'hPa',
'inv_height... | 0.001444 |
def _emit_table_tag(self, open_open_markup, tag, style, padding,
close_open_markup, contents, open_close_markup):
"""Emit a table tag."""
self._emit(tokens.TagOpenOpen(wiki_markup=open_open_markup))
self._emit_text(tag)
if style:
self._emit_all(style)
... | 0.003947 |
def intersperse(e, iterable, n=1):
"""Intersperse filler element *e* among the items in *iterable*, leaving
*n* items between each filler element.
>>> list(intersperse('!', [1, 2, 3, 4, 5]))
[1, '!', 2, '!', 3, '!', 4, '!', 5]
>>> list(intersperse(None, [1, 2, 3, 4, 5], n=2))
[... | 0.001037 |
def default(self, o):
"""
JSONEncoder default method that converts NumPy arrays and quantities
objects to lists.
"""
if isinstance(o, Q_):
return o.magnitude
elif isinstance(o, np.ndarray):
return o.tolist()
else:
# raise TypeEr... | 0.00495 |
def white(self):
"""
Build command for turning the led into white mode.
:return: The command.
"""
return self._build_command(self._offset(0xC5),
select=True, select_command=self.on()) | 0.007752 |
def check_site_dir(self):
"""Verify that self.install_dir is .pth-capable dir, if needed"""
instdir = normalize_path(self.install_dir)
pth_file = os.path.join(instdir, 'easy-install.pth')
# Is it a configured, PYTHONPATH, implicit, or explicit site dir?
is_site_dir = instdir in... | 0.001095 |
def FanOut(self, obj, parent=None):
"""Expand values from various attribute types.
Strings are returned as is.
Dictionaries are returned with a key string, and an expanded set of values.
Other iterables are expanded until they flatten out.
Other items are returned in string format.
Args:
... | 0.006789 |
def ntp_authentication_key_encryption_type_md5_type_md5(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
authentication_key = ET.SubElement(ntp, "authentication-key")
key... | 0.00411 |
def map(self, func, items, chunksize=None):
""" Catch keyboard interuppts to allow the pool to exit cleanly.
Parameters
----------
func: function
Function to call
items: list of tuples
Arguments to pass
chunksize: int, Optional
Number ... | 0.002845 |
def import_url(self, url=None, force=None):
"""
Read a list of host entries from a URL, convert them into instances of HostsEntry and
then append to the list of entries in Hosts
:param url: The URL of where to download a hosts file
:return: Counts reflecting the attempted additio... | 0.002271 |
def cleanse(self):
"""Clean up some terms, like ensuring that the name is a slug"""
from .util import slugify
self.ensure_identifier()
try:
self.update_name()
except MetatabError:
identifier = self['Root'].find_first('Root.Identifier')
name... | 0.004739 |
def static_full_sizes(width, height, tilesize):
"""Generator for scaled-down full image sizes.
Positional arguments:
width -- width of full size image
height -- height of full size image
tilesize -- width and height of tiles
Yields [sw,sh], the size for each full-region tile that is less than
... | 0.000658 |
def __audioread_load(path, offset, duration, dtype):
'''Load an audio buffer using audioread.
This loads one block at a time, and then concatenates the results.
'''
y = []
with audioread.audio_open(path) as input_file:
sr_native = input_file.samplerate
n_channels = input_file.chann... | 0.000671 |
def check_script(vouts):
"""
Looks into the vouts list of a transaction
and returns the ``op_return`` if one exists.
Args;
vouts (list): List of outputs of a transaction.
Returns:
str: String representation of the ``op_return``.
Raises:
... | 0.002591 |
def doExperiment(numColumns, l2Overrides, objectDescriptions, noiseMu,
noiseSigma, numInitialTraversals, noiseEverywhere):
"""
Touch every point on an object 'numInitialTraversals' times, then evaluate
whether it has inferred the object by touching every point once more and
checking the number ... | 0.009022 |
def plot_events_in_signal(signal, events_onsets, color="red", marker=None):
"""
Plot events in signal.
Parameters
----------
signal : array or DataFrame
Signal array (can be a dataframe with many signals).
events_onsets : list or ndarray
Events location.
color : int or list
... | 0.003868 |
def check_ocrmypdf(input_file, output_file, *args, env=None):
"Run ocrmypdf and confirmed that a valid file was created"
p, out, err = run_ocrmypdf(input_file, output_file, *args, env=env)
if p.returncode != 0:
print('stdout\n======')
print(out)
print('stderr\n======')
print... | 0.007722 |
def message(self):
"""Return default message for this element
"""
if self.code != 200:
for code in self.response_codes:
if code.code == self.code:
return code.message
raise ValueError("Unknown response code \"%s\" in \"%s\"." % (self.c... | 0.008403 |
def _psi(self, x, y, q, s):
"""
expression after equation (8) in Keeton&Kochanek 1998
:param x:
:param y:
:param q:
:param s:
:return:
"""
return np.sqrt(q**2 * (s**2 + x**2) + y**2) | 0.007843 |
def merge_options_and_config(cls, config, options, args):
"""
Override in subclass if required.
"""
if args:
config.set(CONFIG_SECTION_NAME, 'input_files', ','.join(args))
elif config.has_option(CONFIG_SECTION_NAME, 'input_files'):
for i in config.get(CONF... | 0.002116 |
def complete(self, GET):
"""
Complete the OAuth2 flow by fetching an access token with the provided
code in the GET parameters.
"""
if 'error' in GET:
raise OAuthError(
_("Received error while obtaining access token from %s: %s") % (
... | 0.007177 |
def makeHexData(self, pos):
"""Produce hex dump of all data containing the bits
from pos to stream.pos
"""
firstAddress = pos+7>>3
lastAddress = self.stream.pos+7>>3
return ''.join(map('{:02x} '.format,
self.stream.data[firstAddress:lastAddress])) | 0.016287 |
def list_benchmarks(self,
index = None,
doc_type = None,
params = {},
cb = None,
**kwargs
):
"""
View the progress of long-running benchmarks.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/sea... | 0.028571 |
def decode_timestamp(data: str) -> datetime.datetime:
"""
Decode timestamp using bespoke decoder.
Cannot use simple strptime since the ness panel contains a bug
that P199E zone and state updates emitted on the hour cause a minute
value of `60` to be sent, causing strptime to fail. This decoder handl... | 0.001406 |
def process(dest, rulefiles):
"""process rules"""
deploy = False
while not rulefiles.empty():
rulefile = rulefiles.get()
base = os.path.basename(rulefile)
dest = os.path.join(dest, base)
if os.path.exists(dest):
# check if older
oldtime = os.stat(rulef... | 0.001712 |
def get_protocols(self, device):
"""Returns a list of available protocols for the specified device."""
return self._reg.device_builder(device, self._rv).protocols | 0.011236 |
def _set_static_route_oif(self, v, load=False):
"""
Setter method for static_route_oif, mapped from YANG variable /rbridge_id/vrf/address_family/ip/unicast/ip/route/static_route_oif (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_static_route_oif is considered as ... | 0.003512 |
def vlog(self, msg, *args):
"""Logs a message to stderr only if verbose is enabled."""
if self.verbose:
self.log(msg, *args) | 0.013158 |
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'):
"""Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings
Args:
badjson_path (str): path to input json file that doesn't properly quote
goodjson_path (str): path to output ... | 0.004348 |
def load_json(filename, to='auto'):
'''
load_json(filename) yields the object represented by the json file or stream object filename.
The optional argument to may be set to None to indicate that the JSON data should be returned
verbatim rather than parsed by neuropythy's denormalize system.
'''... | 0.011436 |
def get_all_regions_with_tiles(self):
"""
Generator which yields a set of (rx, ry) tuples which describe
all regions for which the world has tile data
"""
for key in self.get_all_keys():
(layer, rx, ry) = struct.unpack('>BHH', key)
if layer == 1:
... | 0.005865 |
def branch(options=False, *args, **kwargs):
"""Run "$ git branch" with those options
If not options then return name of the branch currently checked out
"""
return (options
and run('branch %s' % options, *args, **kwargs)
or rev_parse('--abbrev-ref HEAD', *args, **kwargs)) | 0.003195 |
def _bond_percolation(network, tmask):
r"""
This private method is called by 'find_clusters'
"""
# Perform the clustering using scipy.csgraph
csr = network.create_adjacency_matrix(weights=tmask, fmt='csr',
drop_zeros=True)
clusters = sprs.csgraph.connect... | 0.001048 |
def scan_roles(self):
"""
Iterate over each role and report its stats.
"""
for key, value in sorted(self.roles.iteritems()):
self.paths["role"] = os.path.join(self.roles_path, key)
self.paths["meta"] = os.path.join(self.paths["role"], "meta",
... | 0.000881 |
def user_query(username, email):
"""
Find a user match with username and email
:param username:
:param email:
:returns:
"""
query = db.query(User)
if username:
query = query.filter_by(username=username)
if email:
query = query.filter_by(username=username)
return... | 0.003067 |
def uncheckButton(self):
"""Removes the checked stated of all buttons in this widget.
This method is also a slot.
"""
#for button in self.buttons[1:]:
for button in self.buttons:
# supress editButtons toggled event
button.blockSignals(True)
i... | 0.007126 |
def prune(self, regex=r".*"):
"""
Prune leaves of filetree according to specified
regular expression.
Args:
regex (str): Regular expression to use in pruning tree.
"""
return filetree(self.root, ignore=self.ignore, regex=regex) | 0.006944 |
def exists(self, index, doc_type, id, **query_params):
"""
Return if a document exists
"""
path = make_path(index, doc_type, id)
return self._send_request('HEAD', path, params=query_params) | 0.008734 |
def passwordReset1to2(old):
"""
Power down and delete the item
"""
new = old.upgradeVersion(old.typeName, 1, 2, installedOn=None)
for iface in new.store.interfacesFor(new):
new.store.powerDown(new, iface)
new.deleteFromStore() | 0.003876 |
def _CurrentAuditLog():
"""Get the rdfurn of the current audit log."""
now_sec = rdfvalue.RDFDatetime.Now().AsSecondsSinceEpoch()
rollover_seconds = AUDIT_ROLLOVER_TIME.seconds
# This gives us a filename that only changes every
# AUDIT_ROLLOVER_TIfilME seconds, but is still a valid timestamp.
current_log = ... | 0.019277 |
def set_metadata_index_and_column_names(dim, meta_df):
"""
Sets index and column names to GCTX convention.
Input:
- dim (str): Dimension of metadata to read. Must be either "row" or "col"
- meta_df (pandas.DataFrame): data frame corresponding to metadata fields
of dimension speci... | 0.005495 |
def _set_cfg(self, v, load=False):
"""
Setter method for cfg, mapped from YANG variable /zoning/defined_configuration/cfg (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_cfg is considered as a private
method. Backends looking to populate this variable should
... | 0.003949 |
def get_instance(self, payload):
"""
Build an instance of NotificationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.notify.v1.service.notification.NotificationInstance
:rtype: twilio.rest.notify.v1.service.notification.NotificationInstance
... | 0.009217 |
def _get_typed_list_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
... | 0.0056 |
def authorize(*args, **kwargs):
"""View for rendering authorization request."""
if request.method == 'GET':
client = Client.query.filter_by(
client_id=kwargs.get('client_id')
).first()
if not client:
abort(404)
scopes = current_oauth2server.scopes
... | 0.001565 |
def iplot_state_hinton(rho, figsize=None):
""" Create a hinton representation.
Graphical representation of the input array using a 2D city style
graph (hinton).
Args:
rho (array): Density matrix
figsize (tuple): Figure size in pixels.
"""
# HTML
html_te... | 0.001071 |
def handle_starttag(self, tag, attrs):
'''
PDF link handler; never gets explicitly called by user
'''
if tag == 'a' and ( ('class', 'download-pdf') in attrs or ('id', 'download-pdf') in attrs ):
for attr in attrs:
if attr[0] == 'href':
self.download_link = 'http://www.natur... | 0.014881 |
def calculate_residue_counts_perstrain(protein_pickle_path, outdir, pdbflex_keys_file, wt_pid_cutoff=None, force_rerun=False):
"""Writes out a feather file for a PROTEIN counting amino acid occurences for ALL STRAINS along with SUBSEQUENCES"""
from collections import defaultdict
from ssbio.protein.sequence.... | 0.006564 |
def pad(self, pad_length):
"""
Pad the pianoroll with zeros at the end along the time axis.
Parameters
----------
pad_length : int
The length to pad with zeros along the time axis.
"""
self.pianoroll = np.pad(
self.pianoroll, ((0, pad_len... | 0.00578 |
def split(self, into = "edges", loc = None,
at = "labels", sort_index = True):
"""
Returns the decomposition of the elements.
Inputs:
* into: must be in ['edges', 'faces', 'simplices', 'angles']
* loc: None or labels of the chosen elements.
* at: must be in ['labels', 'coords']... | 0.03373 |
def success(headers = None, data = ''):
""" Generate success JSON to send to client """
passed_headers = {} if headers is None else headers
if isinstance(data, dict): data = json.dumps(data)
ret_headers = {'status' : 'ok'}
ret_headers.update(passed_headers)
return server_responce(ret_headers, da... | 0.021672 |
def spearman_correlation(X, rowvar=False):
"""
Computes the spearman correlation estimate.
This is effectively a bias corrected pearson correlation
between rank transformed columns of X.
Parameters
----------
X: array-like, shape = [n_samples, n_features]
Data matrix using which we ... | 0.001011 |
def deletecc(self, cclist, comment=None):
"""
Removes the given email addresses from the CC list for this bug.
"""
vals = self.bugzilla.build_update(comment=comment,
cc_remove=cclist)
log.debug("deletecc: update=%s", vals)
return... | 0.005479 |
def assert_json_type(value: JsonValue, expected_type: JsonCheckType) -> None:
"""Check that a value has a certain JSON type.
Raise TypeError if the type does not match.
Supported types: str, int, float, bool, list, dict, and None.
float will match any number, int will only match numbers without
fr... | 0.000735 |
def fill_rectangle(self, prepared):
''' Right-pad lines of block to equal width '''
result = []
width = max([self.clean_len(line) for line in prepared])
for line in prepared:
spacer = ' ' * (width - self.clean_len(line))
result.append(line + (self.screen.markup.... | 0.005464 |
def get_nearest_site(self, latitude=None, longitude=None):
"""
Deprecated. This function returns nearest Site object to the specified
coordinates.
"""
warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead'
warn(warning_message, Deprecati... | 0.007282 |
def lowerlim(x, y, z, a, b, c):
"""Returns the real positive root of
x/(a+t) + y/(b+t) + z/(c+t) = 1
when x/a + y/b + z/c > 1 else zero
"""
if x/a + y/b + z/c > 1:
B = a + b + c - x - y - z
C = a*b + a*c + b*c - a*y - a*z - b*x - b*z - c*x - c*y
D = a*b*c - a*b*z - a*c*y - ... | 0.011038 |
def ExceptionHookPDB(exctype, value, tb):
'''
A custom exception handler, with :py:obj:`pdb` post-mortem for debugging.
'''
for line in traceback.format_exception_only(exctype, value):
log.error(line.replace('\n', ''))
for line in traceback.format_tb(tb):
log.error(line.replace('\n... | 0.002611 |
def find_models(self, constructor, constraints=None, *, columns=None, order_by=None,
limiting=None, table_name=None):
"""Specialization of DataAccess.find_all that returns models instead of cursor objects."""
return self._find_models(
constructor, table_name or constructor.table_name, co... | 0.012788 |
def CMP(self, params):
"""
CMP Rm, Rn
CMP Rm, #imm8
Subtract Rn or imm8 from Rm, set the NZCV flags, and discard the result
Rm and Rn can be R0-R14
"""
Rm, Rn = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
if self.is_register(Rn):
... | 0.00432 |
async def api_post(self, url, params):
"""Make api post request."""
post = None
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
post = await self._api_session.post(
url, params=params)
if post.status != 204:
... | 0.002907 |
def features_keep_using_features(obj, bounds):
"""
Filter all features in a collection by retaining only those that
fall within the features in the second collection.
"""
# Build an R-tree index of bound features and their shapes.
bounds_shapes = [
(feature, shapely.geometry.shape(featur... | 0.005046 |
def set_backend(self, backend):
"""Set the simulation backend."""
if isinstance(backend, str):
name = backend
args = []
kwargs = {}
elif isinstance(backend, (tuple, list)):
name = ''
args = []
kwargs = {}
for i i... | 0.001647 |
def pages():
"""Load pages."""
p1 = Page(
url='/example1',
title='My page with default template',
description='my description',
content='hello default page',
template_name='invenio_pages/default.html',
)
p2 = Page(
url='/example2',
title='My page w... | 0.001745 |
def free(self, request_key):
"""
Works together with 'mark_as_forwarded' and
'mark_as_executed' methods.
It makes request to be removed if all replicas request was
forwarded to freed it and if request executor marked it as executed.
"""
state = self.get(request_k... | 0.004739 |
def _clean_error_msg(self, msg):
"""converts a Powershell CLIXML message to a more human readable string
"""
# TODO prepare unit test, beautify code
# if the msg does not start with this, return it as is
if msg.startswith(b"#< CLIXML\r\n"):
# for proper xml, we need t... | 0.001103 |
def _send_container_healthcheck_sc(self, containers_by_id):
"""Send health service checks for containers."""
for container in containers_by_id.itervalues():
healthcheck_tags = self._get_tags(container, HEALTHCHECK)
match = False
for tag in healthcheck_tags:
... | 0.00339 |
def mounts():
'''
Return a list of current MooseFS mounts
CLI Example:
.. code-block:: bash
salt '*' moosefs.mounts
'''
cmd = 'mount'
ret = {}
out = __salt__['cmd.run_all'](cmd)
output = out['stdout'].splitlines()
for line in output:
if not line:
c... | 0.00117 |
def _handle_command_buffer(self):
"""Checks if we should write to the command buffer, writes all of the queued commands to the buffer, and then
clears the contents of the self._commands list"""
if self._should_write_to_command_buffer:
self._write_to_command_buffer(self._commands.to_j... | 0.007177 |
def get_values(self, lst, list_columns):
"""
Get Values: formats values for list template.
returns [{'col_name':'col_value',....},{'col_name':'col_value',....}]
:param lst:
The list of item objects from query
:param list_columns:
T... | 0.005587 |
async def restart(request: web.Request) -> web.Response:
""" Restart the robot.
Blocks while the restart lock is held.
"""
async with request.app[RESTART_LOCK_NAME]:
asyncio.get_event_loop().call_later(1, _do_restart)
return web.json_response({'message': 'Restarting in 1s'},
... | 0.002899 |
def astype(self, dtype, copy=True, errors='raise', **kwargs):
"""
Cast a pandas object to a specified dtype ``dtype``.
Parameters
----------
dtype : data type, or dict of column name -> data type
Use a numpy.dtype or Python type to cast entire pandas object to
... | 0.000437 |
def _score_macro_average(self, n_classes):
"""
Compute the macro average scores for the ROCAUC curves.
"""
# Gather all FPRs
all_fpr = np.unique(np.concatenate([self.fpr[i] for i in range(n_classes)]))
avg_tpr = np.zeros_like(all_fpr)
# Compute the averages per c... | 0.004566 |
def tornado_run(app, port=5000, address="", use_gevent=False, start=True,
monkey_patch=None, Container=None,
Server=None, threadpool=None): # pragma: no cover
"""Run your app in one tornado event loop process
:param app: wsgi application, Microservice instance
:param port: ... | 0.002156 |
def many_from_config(config):
"""
Retrieves all CredentialParams from configuration parameters
from "credentials" section. If "credential" section is present instead,
than it returns a list with only one CredentialParams.
:param config: a configuration parameters to retrieve cre... | 0.002049 |
def participants(self):
"""agents + computers (i.e. all non-observers)"""
ret = []
for p in self.players:
try:
if p.isComputer: ret.append(p)
if not p.isObserver: ret.append(p) # could cause an exception if player isn't a PlayerPreGame
... | 0.021858 |
def publication_info2marc(self, key, values):
"""Populate the ``773`` MARC field.
Also populates the ``7731`` MARC field through side effects.
"""
result_773 = self.get('773', [])
result_7731 = self.get('7731', [])
for value in force_list(convert_new_publication_info_to_old(values)):
p... | 0.000715 |
def get(self, wrap_exception=False):
"""
Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised.
"""
if self.has_exception:
if wrap_exception:
... | 0.004107 |
def serialize(self):
"""This function serializes into a simple dict object.
The only usage is to send to poller, and it does not need to have the
depend_on and depend_on_me properties.
:return: json representation of a Check
:rtype: dict
"""
res = super(Check, s... | 0.00409 |
def included(self, start, stop):
"""Iterates (in chronological order) over every event that is included
in the timespan between `start` and `stop`
Args:
start : (Arrow object)
stop : (Arrow object)
"""
for event in self:
if (start <= event.beg... | 0.010707 |
def bind(self, isnap, istep):
"""Register the isnap / istep correspondence.
Users of :class:`StagyyData` should not use this method.
Args:
isnap (int): snapshot index.
istep (int): time step index.
"""
self._isteps[isnap] = istep
self.sdat.steps[... | 0.005882 |
def read_gtf_line(cols, field="name"):
"""parse gtf line to get class/name information"""
field = field.lower()
try:
group = cols[2]
attrs = cols[8].split(";")
name = [attr.strip().split(" ")[1] for attr in attrs if attr.strip().split(" ")[0].lower().endswith(field)]
if not n... | 0.003997 |
def getSrcBlockParents(self, url, block):
"""
List block at src DBS
"""
#blockname = block.replace("#", urllib.quote_plus('#'))
#resturl = "%s/blockparents?block_name=%s" % (url, blockname)
params={'block_name':block}
return cjson.decode(self.callDBSService(url, '... | 0.020173 |
def _setup(self):
"""
Generates _id_map from _alternatives to allow validating contents
"""
cls = self.__class__
cls._id_map = {}
cls._name_map = {}
for index, info in enumerate(cls._alternatives):
if len(info) < 3:
info = info + ({},)... | 0.004 |
def split_string(self, string, splitter='.', allow_empty=True):
"""Split the string with respect of quotes"""
i = 0
rv = []
need_split = False
while i < len(string):
m = re.compile(_KEY_NAME).match(string, i)
if not need_split and m:
i = m.... | 0.00139 |
def _get_objects(self, ignore=[]):
"""Get all currently existing objects.
XXX - ToDo: This method is a copy&paste from muppy.get_objects, but
some modifications are applied. Specifically, it allows to ignore
objects (which includes the current frame).
keyword arguments
... | 0.008399 |
def acknowledge_host_problem(self, host, sticky, notify, author, comment):
"""Acknowledge a host problem
Format of the line that triggers function call::
ACKNOWLEDGE_HOST_PROBLEM;<host_name>;<sticky>;<notify>;<persistent:obsolete>;<author>;
<comment>
:param host: host to acknow... | 0.004736 |
def vcf_annotator(self):
"""Vcf annotator"""
tstart = datetime.now()
# python ../scripts/annotate_vcfs.py -i mm13173_14.ug.target1.vcf -r 1000genomes dbsnp138 clinvar esp6500 -a ../data/1000genomes/ALL.wgs.integrated_phase1_v3.20101123.snps_indels_sv.sites.vcf.gz ../data/dbsnp138/00-All.vcf.gz... | 0.006222 |
def find_meta(meta):
"""
Extract __*meta*__ from META_FILE.
"""
meta_match = re.search(
r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta),
META_FILE, re.M
)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(me... | 0.00304 |
def identify_raw_files(task: Task, test_mode: bool = False) -> List[str]:
"""
Identify raw files that need to be downloaded for a given task.
:param task: Sequence-to-sequence task.
:param test_mode: Run in test mode, only downloading test data.
:return: List of raw file names.
"""
raw_file... | 0.003856 |
def read_uint32(self, little_endian=True):
"""
Read 4 bytes as an unsigned integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int:
"""
if little_endian:
endian = "<"
... | 0.007463 |
def get_entry(self, key, column=None, table=None):
"""Get a specific entry."""
if table is None: table = self.main_table
if column is None: column = "id"
if isinstance(key, basestring): key = key.replace("'","''")
query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;'
q... | 0.016055 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.