_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13400 | generate_id | train | def generate_id():
""" Generate a 64bit base 16 ID for use as a Span or Trace ID """
global _current_pid
pid = os.getpid()
if _current_pid != pid:
_current_pid = pid
_rnd.seed(int(1000000 * time.time()) ^ pid)
id = format(_rnd.randint(0, 18446744073709551615), '02x')
if len(id)... | python | {
"resource": ""
} |
q13401 | package_version | train | def package_version():
"""
Determine the version of this package.
:return: String representing known version
"""
version = ""
try:
version = pkg_resources.get_distribution('instana').version
except pkg_resources.DistributionNotFound:
version = 'unknown'
finally:
... | python | {
"resource": ""
} |
q13402 | strip_secrets | train | def strip_secrets(qp, matcher, kwlist):
"""
This function will scrub the secrets from a query param string based on the passed in matcher and kwlist.
blah=1&secret=password&valid=true will result in blah=1&secret=<redacted>&valid=true
You can even pass in path query combinations:
/signup?blah=1&s... | python | {
"resource": ""
} |
q13403 | get_py_source | train | def get_py_source(file):
"""
Retrieves and returns the source code for any Python
files requested by the UI via the host agent
@param file [String] The fully qualified path to a file
"""
try:
response = None
pysource = ""
if regexp_py.search(file) is None:
r... | python | {
"resource": ""
} |
q13404 | make_middleware | train | def make_middleware(app=None, *args, **kw):
""" Given an app, return that app wrapped in iWSGIMiddleware """
app = iWSGIMiddleware(app, *args, **kw)
return app | python | {
"resource": ""
} |
q13405 | eum_snippet | train | def eum_snippet(trace_id=None, eum_api_key=None, meta={}):
"""
Return an EUM snippet for use in views, templates and layouts that reports
client side metrics to Instana that will automagically be linked to the
current trace.
@param trace_id [optional] the trace ID to insert into the EUM string
... | python | {
"resource": ""
} |
q13406 | InstanaTracer.start_span | train | def start_span(self,
operation_name=None,
child_of=None,
references=None,
tags=None,
start_time=None,
ignore_active_span=False):
"Taken from BasicTracer so we can override generate_id calls to ours"... | python | {
"resource": ""
} |
q13407 | InstanaTracer.__add_stack | train | def __add_stack(self, span, limit=None):
""" Adds a backtrace to this span """
span.stack = []
frame_count = 0
tb = traceback.extract_stack()
tb.reverse()
for frame in tb:
if limit is not None and frame_count >= limit:
break
# Exc... | python | {
"resource": ""
} |
q13408 | hook | train | def hook(module):
""" Hook method to install the Instana middleware into Flask """
if "INSTANA_DEV" in os.environ:
print("==============================================================")
print("Instana: Running flask hook")
print("=========================================================... | python | {
"resource": ""
} |
q13409 | error_class_for_http_status | train | def error_class_for_http_status(status):
"""Return the appropriate `ResponseError` subclass for the given
HTTP status code."""
try:
return error_classes[status]
except KeyError:
def new_status_error(xml_response):
if (status > 400 and status < 500):
return Une... | python | {
"resource": ""
} |
q13410 | ResponseError.response_doc | train | def response_doc(self):
"""The XML document received from the service."""
try:
return self.__dict__['response_doc']
except KeyError:
self.__dict__['response_doc'] = ElementTree.fromstring(
self.response_xml
)
return self.__dict__['r... | python | {
"resource": ""
} |
q13411 | ValidationError.transaction_error_code | train | def transaction_error_code(self):
"""The machine-readable error code for a transaction error."""
error = self.response_doc.find('transaction_error')
if error is not None:
code = error.find('error_code')
if code is not None:
return code.text | python | {
"resource": ""
} |
q13412 | ValidationError.errors | train | def errors(self):
"""A dictionary of error objects, keyed on the name of the
request field that was invalid.
Each error value has `field`, `symbol`, and `message`
attributes describing the particular invalidity of that field.
"""
try:
return self.__dict__['e... | python | {
"resource": ""
} |
q13413 | objects_for_push_notification | train | def objects_for_push_notification(notification):
"""Decode a push notification with the given body XML.
Returns a dictionary containing the constituent objects of the push
notification. The kind of push notification is given in the ``"type"``
member of the returned dictionary.
"""
notification... | python | {
"resource": ""
} |
q13414 | Account.invoice | train | def invoice(self, **kwargs):
"""Create an invoice for any outstanding adjustments this account has."""
url = urljoin(self._url, '/invoices')
if kwargs:
response = self.http_request(url, 'POST', Invoice(**kwargs), {'Content-Type':
'application/xml; charset=utf-8'})
... | python | {
"resource": ""
} |
q13415 | Account.subscribe | train | def subscribe(self, subscription):
"""Create the given `Subscription` for this existing account."""
url = urljoin(self._url, '/subscriptions')
return subscription.post(url) | python | {
"resource": ""
} |
q13416 | Account.update_billing_info | train | def update_billing_info(self, billing_info):
"""Change this account's billing information to the given `BillingInfo`."""
url = urljoin(self._url, '/billing_info')
response = billing_info.http_request(url, 'PUT', billing_info,
{'Content-Type': 'application/xml; charset=utf-8'})
... | python | {
"resource": ""
} |
q13417 | Account.create_shipping_address | train | def create_shipping_address(self, shipping_address):
"""Creates a shipping address on an existing account. If you are
creating an account, you can embed the shipping addresses with the
request"""
url = urljoin(self._url, '/shipping_addresses')
return shipping_address.post(url) | python | {
"resource": ""
} |
q13418 | GiftCard.preview | train | def preview(self):
"""Preview the purchase of this gift card"""
if hasattr(self, '_url'):
url = self._url + '/preview'
return self.post(url)
else:
url = urljoin(recurly.base_uri(), self.collection_path + '/preview')
return self.post(url) | python | {
"resource": ""
} |
q13419 | GiftCard.redeem | train | def redeem(self, account_code):
"""Redeem this gift card on the specified account code"""
redemption_path = '%s/redeem' % (self.redemption_code)
if hasattr(self, '_url'):
url = urljoin(self._url, '/redeem')
else:
url = urljoin(recurly.base_uri(), self.collection... | python | {
"resource": ""
} |
q13420 | Invoice.pdf | train | def pdf(cls, uuid):
"""Return a PDF of the invoice identified by the UUID
This is a raw string, which can be written to a file with:
`
with open('invoice.pdf', 'w') as invoice_file:
invoice_file.write(recurly.Invoice.pdf(uuid))
`
"""
url = ur... | python | {
"resource": ""
} |
q13421 | Subscription.pause | train | def pause(self, remaining_pause_cycles):
"""Pause a subscription"""
url = urljoin(self._url, '/pause')
elem = ElementTreeBuilder.Element(self.nodename)
elem.append(Resource.element_for_value('remaining_pause_cycles',
remaining_pause_cycles))... | python | {
"resource": ""
} |
q13422 | Subscription.create_usage | train | def create_usage(self, sub_add_on, usage):
"""Record the usage on the given subscription add on and update the
usage object with returned xml"""
url = urljoin(self._url, '/add_ons/%s/usage' % (sub_add_on.add_on_code,))
return usage.post(url) | python | {
"resource": ""
} |
q13423 | Transaction.get_refund_transaction | train | def get_refund_transaction(self):
"""Retrieve the refund transaction for this transaction, immediately
after refunding.
After calling `refund()` to refund a transaction, call this method to
retrieve the new transaction representing the refund.
"""
try:
url =... | python | {
"resource": ""
} |
q13424 | Transaction.refund | train | def refund(self, **kwargs):
"""Refund this transaction.
Calling this method returns the refunded transaction (that is,
``self``) if the refund was successful, or raises a `ResponseError` if
an error occurred requesting the refund. After a successful call to
`refund()`, to retrie... | python | {
"resource": ""
} |
q13425 | Plan.get_add_on | train | def get_add_on(self, add_on_code):
"""Return the `AddOn` for this plan with the given add-on code."""
url = urljoin(self._url, '/add_ons/%s' % (add_on_code,))
resp, elem = AddOn.element_for_url(url)
return AddOn.from_element(elem) | python | {
"resource": ""
} |
q13426 | Plan.create_add_on | train | def create_add_on(self, add_on):
"""Make the given `AddOn` available to subscribers on this plan."""
url = urljoin(self._url, '/add_ons')
return add_on.post(url) | python | {
"resource": ""
} |
q13427 | _load_track_estimates | train | def _load_track_estimates(track, estimates_dir, output_dir):
"""load estimates from disk instead of processing"""
user_results = {}
track_estimate_dir = os.path.join(
estimates_dir,
track.subset,
track.name
)
for target in glob.glob(
track_estimate_dir + '/*.wav'
... | python | {
"resource": ""
} |
q13428 | eval_dir | train | def eval_dir(
reference_dir,
estimates_dir,
output_dir=None,
mode='v4',
win=1.0,
hop=1.0,
):
"""Compute bss_eval metrics for two given directories assuming file
names are identical for both, reference source and estimates.
Parameters
----------
reference_dir : str
pa... | python | {
"resource": ""
} |
q13429 | eval_mus_dir | train | def eval_mus_dir(
dataset,
estimates_dir,
output_dir=None,
*args, **kwargs
):
"""Run musdb.run for the purpose of evaluation of musdb estimate dir
Parameters
----------
dataset : DB(object)
Musdb Database object.
estimates_dir : str
Path to estimates folder.
outp... | python | {
"resource": ""
} |
q13430 | eval_mus_track | train | def eval_mus_track(
track,
user_estimates,
output_dir=None,
mode='v4',
win=1.0,
hop=1.0
):
"""Compute all bss_eval metrics for the musdb track and estimated signals,
given by a `user_estimates` dict.
Parameters
----------
track : Track
musdb track object loaded using... | python | {
"resource": ""
} |
q13431 | evaluate | train | def evaluate(
references,
estimates,
win=1*44100,
hop=1*44100,
mode='v4',
padding=True
):
"""BSS_EVAL images evaluation using metrics module
Parameters
----------
references : np.ndarray, shape=(nsrc, nsampl, nchan)
array containing true reference sources
estimates :... | python | {
"resource": ""
} |
q13432 | EvalStore._q | train | def _q(self, number, precision='.00001'):
"""quantiztion of BSSEval values"""
if np.isinf(number):
return np.nan
else:
return D(D(number).quantize(D(precision))) | python | {
"resource": ""
} |
q13433 | bsseval | train | def bsseval(inargs=None):
"""
Generic cli app for bsseval results. Expects two folder with
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'reference_dir',
type=str
)
parser.add_argument(
'estimates_dir',
type=str
)
parser.add_argument('... | python | {
"resource": ""
} |
q13434 | museval | train | def museval(inargs=None):
"""
Commandline interface for museval evaluation tools
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'estimates_dir',
type=str
)
parser.add_argument('-o', help='output_dir')
parser.add_argument('--cpu', type=int, help='number of ... | python | {
"resource": ""
} |
q13435 | Page.next_page | train | def next_page(self):
"""Return the next `Page` after this one in the result sequence
it's from.
If the current page is the last page in the sequence, calling
this method raises a `ValueError`.
"""
try:
next_url = self.next_url
except AttributeError:
... | python | {
"resource": ""
} |
q13436 | Page.first_page | train | def first_page(self):
"""Return the first `Page` in the result sequence this `Page`
instance is from.
If the current page is already the first page in the sequence,
calling this method raises a `ValueError`.
"""
try:
start_url = self.start_url
except... | python | {
"resource": ""
} |
q13437 | Page.page_for_url | train | def page_for_url(cls, url):
"""Return a new `Page` containing the items at the given
endpoint URL."""
resp, elem = Resource.element_for_url(url)
value = Resource.value_for_element(elem)
return cls.page_for_value(resp, value) | python | {
"resource": ""
} |
q13438 | Page.page_for_value | train | def page_for_value(cls, resp, value):
"""Return a new `Page` representing the given resource `value`
retrieved using the HTTP response `resp`.
This method records pagination ``Link`` headers present in `resp`, so
that the returned `Page` can return their resources from its
`next... | python | {
"resource": ""
} |
q13439 | Resource.serializable_attributes | train | def serializable_attributes(self):
""" Attributes to be serialized in a ``POST`` or ``PUT`` request.
Returns all attributes unless a blacklist is specified
"""
if hasattr(self, 'blacklist_attributes'):
return [attr for attr in self.attributes if attr not in
... | python | {
"resource": ""
} |
q13440 | Resource.headers_as_dict | train | def headers_as_dict(cls, resp):
"""Turns an array of response headers into a dictionary"""
if six.PY2:
pairs = [header.split(':', 1) for header in resp.msg.headers]
return dict([(k, v.strip()) for k, v in pairs])
else:
return dict([(k, v.strip()) for k, v in r... | python | {
"resource": ""
} |
q13441 | Resource.as_log_output | train | def as_log_output(self):
"""Returns an XML string containing a serialization of this
instance suitable for logging.
Attributes named in the instance's `sensitive_attributes` are
redacted.
"""
elem = self.to_element()
for attrname in self.sensitive_attributes:
... | python | {
"resource": ""
} |
q13442 | Resource.get | train | def get(cls, uuid):
"""Return a `Resource` instance of this class identified by
the given code or UUID.
Only `Resource` classes with specified `member_path` attributes
can be directly requested with this method.
"""
if not uuid:
raise ValueError("get must ha... | python | {
"resource": ""
} |
q13443 | Resource.headers_for_url | train | def headers_for_url(cls, url):
"""Return the headers only for the given URL as a dict"""
response = cls.http_request(url, method='HEAD')
if response.status != 200:
cls.raise_http_error(response)
return Resource.headers_as_dict(response) | python | {
"resource": ""
} |
q13444 | Resource.value_for_element | train | def value_for_element(cls, elem):
"""Deserialize the given XML `Element` into its representative
value.
Depending on the content of the element, the returned value may be:
* a string, integer, or boolean value
* a `datetime.datetime` instance
* a list of `Resource` insta... | python | {
"resource": ""
} |
q13445 | Resource.element_for_value | train | def element_for_value(cls, attrname, value):
"""Serialize the given value into an XML `Element` with the
given tag name, returning it.
The value argument may be:
* a `Resource` instance
* a `Money` instance
* a `datetime.datetime` instance
* a string, integer, or... | python | {
"resource": ""
} |
q13446 | Resource.update_from_element | train | def update_from_element(self, elem):
"""Reset this `Resource` instance to represent the values in
the given XML element."""
self._elem = elem
for attrname in self.attributes:
try:
delattr(self, attrname)
except AttributeError:
pass... | python | {
"resource": ""
} |
q13447 | Resource.all | train | def all(cls, **kwargs):
"""Return a `Page` of instances of this `Resource` class from
its general collection endpoint.
Only `Resource` classes with specified `collection_path`
endpoints can be requested with this method. Any provided
keyword arguments are passed to the API endpo... | python | {
"resource": ""
} |
q13448 | Resource.count | train | def count(cls, **kwargs):
"""Return a count of server side resources given
filtering arguments in kwargs.
"""
url = recurly.base_uri() + cls.collection_path
if kwargs:
url = '%s?%s' % (url, urlencode_params(kwargs))
return Page.count_for_url(url) | python | {
"resource": ""
} |
q13449 | Resource.put | train | def put(self, url):
"""Sends this `Resource` instance to the service with a
``PUT`` request to the given URL."""
response = self.http_request(url, 'PUT', self, {'Content-Type': 'application/xml; charset=utf-8'})
if response.status != 200:
self.raise_http_error(response)
... | python | {
"resource": ""
} |
q13450 | Resource.post | train | def post(self, url, body=None):
"""Sends this `Resource` instance to the service with a
``POST`` request to the given URL. Takes an optional body"""
response = self.http_request(url, 'POST', body or self, {'Content-Type': 'application/xml; charset=utf-8'})
if response.status not in (200,... | python | {
"resource": ""
} |
q13451 | Resource.delete | train | def delete(self):
"""Submits a deletion request for this `Resource` instance as
a ``DELETE`` request to its URL."""
response = self.http_request(self._url, 'DELETE')
if response.status != 204:
self.raise_http_error(response) | python | {
"resource": ""
} |
q13452 | Resource.raise_http_error | train | def raise_http_error(cls, response):
"""Raise a `ResponseError` of the appropriate subclass in
reaction to the given `http_client.HTTPResponse`."""
response_xml = response.read()
logging.getLogger('recurly.http.response').debug(response_xml)
exc_class = recurly.errors.error_class... | python | {
"resource": ""
} |
q13453 | Resource.to_element | train | def to_element(self, root_name=None):
"""Serialize this `Resource` instance to an XML element."""
if not root_name:
root_name = self.nodename
elem = ElementTreeBuilder.Element(root_name)
for attrname in self.serializable_attributes():
# Only use values that have b... | python | {
"resource": ""
} |
q13454 | bss_eval_sources | train | def bss_eval_sources(reference_sources, estimated_sources,
compute_permutation=True):
"""
BSS Eval v3 bss_eval_sources
Wrapper to ``bss_eval`` with the right parameters.
The call to this function is not recommended. See the description for the
``bsseval_sources`` parameter of `... | python | {
"resource": ""
} |
q13455 | bss_eval_sources_framewise | train | def bss_eval_sources_framewise(reference_sources, estimated_sources,
window=30 * 44100, hop=15 * 44100,
compute_permutation=False):
"""
BSS Eval v3 bss_eval_sources_framewise
Wrapper to ``bss_eval`` with the right parameters.
The call to thi... | python | {
"resource": ""
} |
q13456 | bss_eval_images | train | def bss_eval_images(reference_sources, estimated_sources,
compute_permutation=True):
"""
BSS Eval v3 bss_eval_images
Wrapper to ``bss_eval`` with the right parameters.
"""
return bss_eval(
reference_sources, estimated_sources,
window=np.inf, hop=np.inf,
... | python | {
"resource": ""
} |
q13457 | bss_eval_images_framewise | train | def bss_eval_images_framewise(reference_sources, estimated_sources,
window=30 * 44100, hop=15 * 44100,
compute_permutation=False):
"""
BSS Eval v3 bss_eval_images_framewise
Framewise computation of bss_eval_images.
Wrapper to ``bss_eval`` with... | python | {
"resource": ""
} |
q13458 | _zeropad | train | def _zeropad(sig, N, axis=0):
"""pads with N zeros at the end of the signal, along given axis"""
# ensures concatenation dimension is the first
sig = np.moveaxis(sig, axis, 0)
# zero pad
out = np.zeros((sig.shape[0] + N,) + sig.shape[1:])
out[:sig.shape[0], ...] = sig
# put back axis in plac... | python | {
"resource": ""
} |
q13459 | _compute_projection_filters | train | def _compute_projection_filters(G, sf, estimated_source):
"""Least-squares projection of estimated source on the subspace spanned by
delayed versions of reference sources, with delays between 0 and
filters_len-1
"""
# epsilon
eps = np.finfo(np.float).eps
# shapes
(nsampl, nchan) = estim... | python | {
"resource": ""
} |
q13460 | _project | train | def _project(reference_sources, C):
"""Project images using pre-computed filters C
reference_sources are nsrc X nsampl X nchan
C is nsrc X nchan X filters_len X nchan
"""
# shapes: ensure that input is 3d (comprising the source index)
if len(reference_sources.shape) == 2:
reference_sourc... | python | {
"resource": ""
} |
q13461 | _safe_db | train | def _safe_db(num, den):
"""Properly handle the potential +Inf db SIR instead of raising a
RuntimeWarning.
"""
if den == 0:
return np.inf
return 10 * np.log10(num / den) | python | {
"resource": ""
} |
q13462 | construct_api_url | train | def construct_api_url(input, representation, resolvers=None, get3d=False, tautomers=False, xml=True, **kwargs):
"""Return the URL for the desired API endpoint.
:param string input: Chemical identifier to resolve
:param string representation: Desired output representation
:param list(str) resolvers: (Op... | python | {
"resource": ""
} |
q13463 | request | train | def request(input, representation, resolvers=None, get3d=False, tautomers=False, **kwargs):
"""Make a request to CIR and return the XML response.
:param string input: Chemical identifier to resolve
:param string representation: Desired output representation
:param list(string) resolvers: (Optional) Ord... | python | {
"resource": ""
} |
q13464 | query | train | def query(input, representation, resolvers=None, get3d=False, tautomers=False, **kwargs):
"""Get all results for resolving input to the specified output representation.
:param string input: Chemical identifier to resolve
:param string representation: Desired output representation
:param list(string) re... | python | {
"resource": ""
} |
q13465 | resolve | train | def resolve(input, representation, resolvers=None, get3d=False, **kwargs):
"""Resolve input to the specified output representation.
:param string input: Chemical identifier to resolve
:param string representation: Desired output representation
:param list(string) resolvers: (Optional) Ordered list of r... | python | {
"resource": ""
} |
q13466 | resolve_image | train | def resolve_image(input, resolvers=None, fmt='png', width=300, height=300, frame=False, crop=None, bgcolor=None,
atomcolor=None, hcolor=None, bondcolor=None, framecolor=None, symbolfontsize=11, linewidth=2,
hsymbol='special', csymbol='special', stereolabels=False, stereowedges=True, ... | python | {
"resource": ""
} |
q13467 | download | train | def download(input, filename, representation, overwrite=False, resolvers=None, get3d=False, **kwargs):
"""Convenience function to save a CIR response as a file.
This is just a simple wrapper around the resolve function.
:param string input: Chemical identifier to resolve
:param string filename: File p... | python | {
"resource": ""
} |
q13468 | Molecule.image_url | train | def image_url(self):
"""URL of a GIF image."""
return construct_api_url(self.input, 'image', self.resolvers, False, self.get3d, False, **self.kwargs) | python | {
"resource": ""
} |
q13469 | Molecule.twirl_url | train | def twirl_url(self):
"""Url of a TwirlyMol 3D viewer."""
return construct_api_url(self.input, 'twirl', self.resolvers, False, self.get3d, False, **self.kwargs) | python | {
"resource": ""
} |
q13470 | Molecule.download | train | def download(self, filename, representation, overwrite=False):
"""Download the resolved structure as a file.
:param string filename: File path to save to
:param string representation: Desired output representation
:param bool overwrite: (Optional) Whether to allow overwriting of an exis... | python | {
"resource": ""
} |
q13471 | DataSource.progress | train | def progress(self, loaded, total, msg=''):
""" Notify on a progress change """
self.fire('progress', {
'loaded': loaded,
'total': total,
'msg': msg
}) | python | {
"resource": ""
} |
q13472 | DataSource.raw | train | def raw(self, tag, raw, metadata):
""" Create a raw response object """
raw = base64.b64encode(raw)
return {
'type': 'raw',
'tag': tag,
'raw': raw,
'metadata': metadata
} | python | {
"resource": ""
} |
q13473 | assert_looks_like | train | def assert_looks_like(first, second, msg=None):
""" Compare two strings if all contiguous whitespace is coalesced. """
first = _re.sub("\s+", " ", first.strip())
second = _re.sub("\s+", " ", second.strip())
if first != second:
raise AssertionError(msg or "%r does not look like %r" % (first, seco... | python | {
"resource": ""
} |
q13474 | load_feature | train | def load_feature(fname, language):
""" Load and parse a feature file. """
fname = os.path.abspath(fname)
feat = parse_file(fname, language)
return feat | python | {
"resource": ""
} |
q13475 | run_steps | train | def run_steps(spec, language="en"):
""" Can be called by the user from within a step definition to execute other steps. """
# The way this works is a little exotic, but I couldn't think of a better way to work around
# the fact that this has to be a global function and therefore cannot know about which ste... | python | {
"resource": ""
} |
q13476 | StepsRunner.run_steps_from_string | train | def run_steps_from_string(self, spec, language_name='en'):
""" Called from within step definitions to run other steps. """
caller = inspect.currentframe().f_back
line = caller.f_lineno - 1
fname = caller.f_code.co_filename
steps = parse_steps(spec, fname, line, ... | python | {
"resource": ""
} |
q13477 | simulate_async_event | train | def simulate_async_event():
"""Simulate an asynchronous event."""
scc.state = 'executing'
def async_event(result):
"""All other asynchronous events or function calls
returned from later steps will wait until this
callback fires."""
scc.state = result
return 'some even... | python | {
"resource": ""
} |
q13478 | hook_decorator | train | def hook_decorator(cb_type):
""" Decorator to wrap hook definitions in. Registers hook. """
def decorator_wrapper(*tags_or_func):
if len(tags_or_func) == 1 and callable(tags_or_func[0]):
# No tags were passed to this decorator
func = tags_or_func[0]
return HookImpl(cb... | python | {
"resource": ""
} |
q13479 | StepImplLoader.load_steps_impl | train | def load_steps_impl(self, registry, path, module_names=None):
"""
Load the step implementations at the given path, with the given module names. If
module_names is None then the module 'steps' is searched by default.
"""
if not module_names:
module_names = ['steps']
... | python | {
"resource": ""
} |
q13480 | StepImplRegistry.find_step_impl | train | def find_step_impl(self, step):
"""
Find the implementation of the step for the given match string. Returns the StepImpl object
corresponding to the implementation, and the arguments to the step implementation. If no
implementation is found, raises UndefinedStepImpl. If more than one imp... | python | {
"resource": ""
} |
q13481 | run_command | train | def run_command(cmd):
"""
Open a child process, and return its exit status and stdout.
"""
child = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out = [s.decode("utf-8").strip() for s in child.stdout]
err = ... | python | {
"resource": ""
} |
q13482 | make_filter_list | train | def make_filter_list(filters):
"""Transform filters into list of table rows."""
filter_list = []
filter_ids = []
for f in filters:
filter_ids.append(f.index)
fullname = URL_P.sub(r'`<\1>`_', f.fullname)
filter_list.append((str(f.index + 1),
f.name,
... | python | {
"resource": ""
} |
q13483 | extract_version | train | def extract_version():
"""Extract the version from the package."""
with open('pdftools/__init__.py', 'r') as f:
content = f.read()
version_match = _version_re.search(content)
version = str(ast.literal_eval(version_match.group(1)))
return version | python | {
"resource": ""
} |
q13484 | add_pypiper_args | train | def add_pypiper_args(parser, groups=("pypiper", ), args=None,
required=None, all_args=False):
"""
Use this to add standardized pypiper arguments to your python pipeline.
There are two ways to use `add_pypiper_args`: by specifying argument groups,
or by specifying individual argumen... | python | {
"resource": ""
} |
q13485 | build_command | train | def build_command(chunks):
"""
Create a command from various parts.
The parts provided may include a base, flags, option-bound arguments, and
positional arguments. Each element must be either a string or a two-tuple.
Raw strings are interpreted as either the command base, a pre-joined
pair (or ... | python | {
"resource": ""
} |
q13486 | build_sample_paths | train | def build_sample_paths(sample):
"""
Ensure existence of folders for a Sample.
:param looper.models.Sample sample: Sample (or instance supporting get()
that stores folders paths in a 'paths' key, in which the value is a
mapping from path name to actual folder path)
"""
for path_name,... | python | {
"resource": ""
} |
q13487 | checkpoint_filename | train | def checkpoint_filename(checkpoint, pipeline_name=None):
"""
Translate a checkpoint to a filename.
This not only adds the checkpoint file extension but also standardizes the
way in which checkpoint names are mapped to filenames.
:param str | pypiper.Stage checkpoint: name of a pipeline phase/stage... | python | {
"resource": ""
} |
q13488 | checkpoint_filepath | train | def checkpoint_filepath(checkpoint, pm):
"""
Create filepath for indicated checkpoint.
:param str | pypiper.Stage checkpoint: Pipeline phase/stage or one's name
:param pypiper.PipelineManager | pypiper.Pipeline pm: manager of a pipeline
instance, relevant for output folder path.
:return str... | python | {
"resource": ""
} |
q13489 | check_shell_redirection | train | def check_shell_redirection(cmd):
"""
Determine whether a command appears to contain shell redirection symbol outside of curly brackets
:param str cmd: Command to investigate.
:return bool: Whether the command appears to contain shell redirection.
"""
curly_brackets = True
while curly_brack... | python | {
"resource": ""
} |
q13490 | get_proc_name | train | def get_proc_name(cmd):
"""
Get the representative process name from complex command
:param str | list[str] cmd: a command to be processed
:return str: the basename representative command
"""
if isinstance(cmd, Iterable) and not isinstance(cmd, str):
cmd = " ".join(cmd)
return cmd.... | python | {
"resource": ""
} |
q13491 | get_first_value | train | def get_first_value(param, param_pools, on_missing=None, error=True):
"""
Get the value for a particular parameter from the first pool in the provided
priority list of parameter pools.
:param str param: Name of parameter for which to determine/fetch value.
:param Sequence[Mapping[str, object]] para... | python | {
"resource": ""
} |
q13492 | is_in_file_tree | train | def is_in_file_tree(fpath, folder):
"""
Determine whether a file is in a folder.
:param str fpath: filepath to investigate
:param folder: path to folder to query
:return bool: whether the path indicated is in the folder indicated
"""
file_folder, _ = os.path.split(fpath)
other_folder = ... | python | {
"resource": ""
} |
q13493 | is_gzipped_fastq | train | def is_gzipped_fastq(file_name):
"""
Determine whether indicated file appears to be a gzipped FASTQ.
:param str file_name: Name/path of file to check as gzipped FASTQ.
:return bool: Whether indicated file appears to be in gzipped FASTQ format.
"""
_, ext = os.path.splitext(file_name)
return... | python | {
"resource": ""
} |
q13494 | make_lock_name | train | def make_lock_name(original_path, path_base_folder):
"""
Create name for lock file from an absolute path.
The original path must be absolute, and it should point to a location
within the location indicated by the base folder path provided. This is
particularly useful for deleting a sample's output ... | python | {
"resource": ""
} |
q13495 | is_multi_target | train | def is_multi_target(target):
"""
Determine if pipeline manager's run target is multiple.
:param None or str or Sequence of str target: 0, 1, or multiple targets
:return bool: Whether there are multiple targets
:raise TypeError: if the argument is neither None nor string nor Sequence
"""
if ... | python | {
"resource": ""
} |
q13496 | parse_cores | train | def parse_cores(cores, pm, default):
"""
Framework to finalize number of cores for an operation.
Some calls to a function may directly provide a desired number of cores,
others may not. Similarly, some pipeline managers may define a cores count
while others will not. This utility provides a single ... | python | {
"resource": ""
} |
q13497 | parse_stage_name | train | def parse_stage_name(stage):
"""
Determine the name of a stage.
The stage may be provided already as a name, as a Stage object, or as a
callable with __name__ (e.g., function).
:param str | pypiper.Stage | function stage: Object representing a stage,
from which to obtain name.
:return ... | python | {
"resource": ""
} |
q13498 | pipeline_filepath | train | def pipeline_filepath(pm, filename=None, suffix=None):
"""
Derive path to file for managed pipeline.
:param pypiper.PipelineManager | pypiper.Pipeline pm: Manager of a
particular pipeline instance.
:param str filename: Name of file for which to create full path based
on pipeline's outpu... | python | {
"resource": ""
} |
q13499 | NGSTk.bam_to_fastq_bedtools | train | def bam_to_fastq_bedtools(self, bam_file, out_fastq_pre, paired_end):
"""
Converts bam to fastq; A version using bedtools
"""
self.make_sure_path_exists(os.path.dirname(out_fastq_pre))
fq1 = out_fastq_pre + "_R1.fastq"
fq2 = None
cmd = self.tools.bedtools + " bamt... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.