Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
370,900 | def parse_args(self):
self._compile()
self.args = None
self._self_event(, , *sys.argv[1:], **{})
cmds = [cmd for cmd in sys.argv[1:] if not cmd.startswith("-")]
if (len(cmds) > 0 and not utils.check_help() and self.default_cmd
a... | Parse our arguments. |
370,901 | def filter(self, criteria):
if isinstance(criteria, str) or isinstance(criteria, unicode):
_criteria = criteria
criteria = lambda x: x.get(_criteria)
return CoursesList(filter(criteria, self)) | Return a filtered version of this list following the given criteria,
which can be a string (take only courses where this attribute is
truthy) or a function which takes a course and return a boolean. |
370,902 | def state_args(id_, state, high):
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(... | Return a set of the arguments passed to the named state |
370,903 | def rewrite_elife_datasets_json(json_content, doi):
elife_dataset_dates = []
elife_dataset_dates.append(("10.7554/eLife.00348", "used", "dataro17", u"2010"))
elife_dataset_dates.append(("10.7554/eLife.01179", "used", "dataro4", u"2016"))
elife_dataset_dates.append(("10.7554/eLife.01603", "use... | this does the work of rewriting elife datasets json |
370,904 | def prepend(self, other, inplace=True, pad=None, gap=None, resize=True):
out = other.append(self, inplace=False, gap=gap, pad=pad,
resize=resize)
if inplace:
self.resize(out.shape, refcheck=False)
self[:] = out[:]
self.x0 = out.x0.c... | Connect another series onto the start of the current one.
Parameters
----------
other : `Series`
another series of the same type as this one
inplace : `bool`, optional
perform operation in-place, modifying current series,
otherwise copy data and retu... |
370,905 | def save_imgs(x, fname):
n = x.shape[0]
fig = figure.Figure(figsize=(n, 1), frameon=False)
canvas = backend_agg.FigureCanvasAgg(fig)
for i in range(n):
ax = fig.add_subplot(1, n, i+1)
ax.imshow(x[i].squeeze(),
interpolation="none",
cmap=cm.get_cmap("binary"))
ax.axis("... | Helper method to save a grid of images to a PNG file.
Args:
x: A numpy array of shape [n_images, height, width].
fname: The filename to write to (including extension). |
370,906 | def pelix_infos(self):
framework = self.__context.get_framework()
return {
"version": framework.get_version(),
"properties": framework.get_properties(),
} | Basic information about the Pelix framework instance |
370,907 | def attribute_labels(self, attribute_id, params=None):
if params is None:
params = {}
if not self.can_update():
self._tcex.handle_error(910, [self.type])
for al in self.tc_requests.attribute_labels(
self.api_type,
self.api_sub_type,
... | Gets the security labels from a attribute
Yields: Security label json |
370,908 | def object_merge(old, new, unique=False):
if isinstance(old, list) and isinstance(new, list):
if old == new:
return
for item in old[::-1]:
if unique and item in new:
continue
new.insert(0, item)
if isinstance(old, dict) and isinstance(new,... | Recursively merge two data structures.
:param unique: When set to True existing list items are not set. |
370,909 | def _scan(positions):
scores = []
for start in range(0, len(positions) - 17, 5):
end = start = 17
scores.add(_enrichment(positions[start:end], positions[:start], positions[end:])) | get the region inside the vector with more expression |
370,910 | def square_root(n, epsilon=0.001):
guess = n / 2
while abs(guess * guess - n) > epsilon:
guess = (guess + (n / guess)) / 2
return guess | Return square root of n, with maximum absolute error epsilon |
370,911 | def create_effect(self, label: str, name: str, *args, **kwargs) -> Effect:
effect_cls = effects.find_effect_class(name)
effect = effect_cls(*args, **kwargs)
effect._label = label
if label in self._effects:
raise ValueError("An effect with label already exist... | Create an effect instance adding it to the internal effects dictionary using the label as key.
Args:
label (str): The unique label for the effect instance
name (str): Name or full python path to the effect class we want to instantiate
args: Positional arguments to the e... |
370,912 | def recursively_register_child_states(self, state):
self.logger.info("Execution status observer add new state {}".format(state))
if isinstance(state, ContainerState):
state.add_observer(self, "add_state",
notify_after_function=self.on_add_state)
... | A function tha registers recursively all child states of a state
:param state:
:return: |
370,913 | def _send_packet(self, data):
if self._closed:
return
data = json.dumps(data)
def send():
try:
yield From(self.pipe_connection.write(data))
except BrokenPipeError:
self.detach_and_close()
ensure_future(send()) | Send packet to client. |
370,914 | def make_zigzag(points, num_cols):
new_points = []
points_size = len(points)
forward = True
idx = 0
rev_idx = -1
while idx < points_size:
if forward:
new_points.append(points[idx])
else:
new_points.append(points[rev_idx])
rev_idx -= 1
... | Converts linear sequence of points into a zig-zag shape.
This function is designed to create input for the visualization software. It orders the points to draw a zig-zag
shape which enables generating properly connected lines without any scanlines. Please see the below sketch on the
functionality of the ``... |
370,915 | def TypeFactory(v):
if v is None:
return Nothing()
elif issubclass(type(v), Type):
return v
elif issubclass(v, Type):
return v()
elif issubclass(type(v), type):
return Generic(v)
else:
raise InvalidTypeError("Invalid type %s" % v) | Ensure `v` is a valid Type.
This function is used to convert user-specified types into
internal types for the verification engine. It allows Type
subclasses, Type subclass instances, Python type, and user-defined
classes to be passed. Returns an instance of the type of `v`.
Users should never ac... |
370,916 | def get_an_int(self, arg, msg_on_error, min_value=None, max_value=None):
ret_value = self.get_int_noerr(arg)
if ret_value is None:
if msg_on_error:
self.errmsg(msg_on_error)
else:
self.errmsg( % str(arg))
pass
r... | Like cmdfns.get_an_int(), but if there's a stack frame use that
in evaluation. |
370,917 | def valid_project(self):
try:
path = self.projects.get_active_project_path()
except AttributeError:
return
if bool(path):
if not self.projects.is_valid_project(path):
if path:
QMessageBox.critical(
... | Handle an invalid active project. |
370,918 | def line_ball_intersection(start_points, end_points, center, radius):
L = end_points - start_points
oc = start_points - center
r = radius
ldotl = np.einsum(, L, L)
ldotoc = np.einsum(, L, oc)
ocdotoc = np.einsum(, oc, oc)
discrims = ldotoc**2 - ldotl * (ocdotoc -... | Compute the length of the intersection of a line segment with a ball.
Parameters
----------
start_points : (n,3) float, list of points in space
end_points : (n,3) float, list of points in space
center : (3,) float, the sphere center
radius : float, the sphere radius
Returns
... |
370,919 | def functional(self):
if self._model:
tree, _ = parse_gpr(self.gene_reaction_rule)
return eval_gpr(tree, {gene.id for gene in self.genes if
not gene.functional})
return True | All required enzymes for reaction are functional.
Returns
-------
bool
True if the gene-protein-reaction (GPR) rule is fulfilled for
this reaction, or if reaction is not associated to a model,
otherwise False. |
370,920 | def html_elem(e, ct, withtype=False):
if ct == :
return .format(*e) if withtype else .format(e)
if e[1] in (, ):
html = u.format(ct, e[0], escape(e[0]))
else:
html = u.format(ct, escape(e[0]))
if withtype:
html += u.format(ct, e[1])
return html | Format a result element as an HTML table cell.
@param e (list): a pair \c (value,type)
@param ct (str): cell type (th or td)
@param withtype (bool): add an additional cell with the element type |
370,921 | def _new_extension(name, value, critical=0, issuer=None, _pyfree=1):
t support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension.
subjectKeyIdentifier0123456789abcdefABCDEF:value must be precomputed hashNot enough memory when creating a new X509 extension{0}{1}'"... | Create new X509_Extension, This is required because M2Crypto
doesn't support getting the publickeyidentifier from the issuer
to create the authoritykeyidentifier extension. |
370,922 | def _fw_policy_create(self, drvr_name, data, cache):
policy = {}
fw_policy = data.get()
tenant_id = fw_policy.get()
LOG.info("Creating policy for tenant %s", tenant_id)
policy_id = fw_policy.get()
policy_name = fw_policy.get()
pol_rule_dict = fw_policy.ge... | Firewall Policy create routine.
This function updates its local cache with policy parameters.
It checks if local cache has information about the rules
associated with the policy. If not, it means a restart has
happened. It retrieves the rules associated with the policy by
callin... |
370,923 | def _call_command_in_repo(comm, repo, log, fail=False, log_flag=True):
if log_flag:
log.debug("Running .".format(" ".join(comm)))
process = subprocess.Popen(
comm, cwd=repo, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = process.communicate()
if stderr is not Non... | Use `subprocess` to call a command in a certain (repo) directory.
Logs the output (both `stderr` and `stdout`) to the log, and checks the
return codes to make sure they're valid. Raises error if not.
Raises
------
exception `subprocess.CalledProcessError`: if the command fails |
370,924 | def connect(self, dests=[], name=None, id=, props={}):
with self._mutex:
if self.porttype == or self.porttype == :
for prop in props:
if prop in self.properties:
if props[prop] not in [x.strip() for x in self.properties[prop].spli... | Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suit... |
370,925 | def prefix_iter(self, ns_uri):
ni = self.__lookup_uri(ns_uri)
return iter(ni.prefixes) | Gets an iterator over the prefixes for the given namespace. |
370,926 | def summary_df(df_in, **kwargs):
true_values = kwargs.pop(, None)
include_true_values = kwargs.pop(, False)
include_rmse = kwargs.pop(, False)
if kwargs:
raise TypeError(.format(kwargs))
if true_values is not None:
assert true_values.shape[0] == df_in.shape[1], (
... | Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This is similar to pandas.DataFrame.describe but also includes estimates of
the numerical uncertainties.
The output DataFrame has multiindex levels:
'calculation type': mean and st... |
370,927 | def is_out_of_range(brain_or_object, result=_marker):
analysis = api.get_object(brain_or_object)
if not IAnalysis.providedBy(analysis) and \
not IReferenceAnalysis.providedBy(analysis):
api.fail("{} is not supported. Needs to be IAnalysis or "
"IReferenceAnalysis".forma... | Checks if the result for the analysis passed in is out of range and/or
out of shoulders range.
min max
warn min max warn
·········|---------------|=====================|---------------|·········
... |
370,928 | def _parallel_receive_loop(self, seconds_to_wait):
sleep(seconds_to_wait)
with self._lock:
self._number_of_threads_receiving_messages += 1
try:
with self._lock:
if self.state.is_waiting_for_start():
self.start()
whi... | Run the receiving in parallel. |
370,929 | def notice(txt, color=False):
"print notice"
if color:
txt = config.Col.WARNING + txt + config.Col.ENDC
print(txt) | print notice |
370,930 | def __generate_really (self, prop_set):
assert isinstance(prop_set, property_set.PropertySet)
best_alternative = self.__select_alternatives (prop_set, debug=0)
self.best_alternative = best_alternative
if not best_alternative:
self.manager_.... | Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible
that no targets are generated. |
370,931 | def n_exec_stmt(self, node):
self.write(self.indent, )
self.preorder(node[0])
if not node[1][0].isNone():
sep =
for subnode in node[1]:
self.write(sep); sep = ", "
self.preorder(subnode)
self.println()
self.prune() | exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT
exec_stmt ::= expr exprlist EXEC_STMT |
370,932 | def assert_same(self, first, second):
if not isinstance(first, list):
first = [first]
if not isinstance(second, list):
second = [second]
if not self.driver.execute_script(, first, second):
raise AssertionError("unequal") | Compares two items for identity. The items can be either single
values or lists of values. When comparing lists, identity
obtains when the two lists have the same number of elements
and that the element at position in one list is identical to
the element at the same position in the other... |
370,933 | def disassemble(self, *, transforms=None) -> Iterator[Instruction]:
if transforms is None:
if self.cf.classloader:
transforms = self.cf.classloader.bytecode_transforms
else:
transforms = []
transforms = [self._bind_transform(t) for t in t... | Disassembles this method, yielding an iterable of
:class:`~jawa.util.bytecode.Instruction` objects. |
370,934 | def do_execute(self):
if isinstance(self.input.payload, Instances):
inst = None
data = self.input.payload
elif isinstance(self.input.payload, Instance):
inst = self.input.payload
data = inst.dataset
index = str(self.resolve_option("index"... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str |
370,935 | def serialize_artifact_json_blobs(artifacts):
for artifact in artifacts:
blob = artifact[]
if (artifact[].lower() == and
not isinstance(blob, str)):
artifact[] = json.dumps(blob)
return artifacts | Ensure that JSON artifact blobs passed as dicts are converted to JSON |
370,936 | def calc_spectrum(signal, rate):
npts = len(signal)
padto = 1 << (npts - 1).bit_length()
npts = padto
sp = np.fft.rfft(signal, n=padto) / npts
freq = np.arange((npts / 2) + 1) / (npts / rate)
return freq, abs(sp) | Return the spectrum and frequency indexes for real-valued input signal |
370,937 | def session_to_epoch(timestamp):
utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple()
return calendar.timegm(utc_timetuple) | converts Synergy Timestamp for session to UTC zone seconds since epoch |
370,938 | def predict(self, dataset, missing_value_action=):
return super(RandomForestRegression, self).predict(dataset,
output_type=,
missing_value_action=missing_value_action) | Predict the target column of the given dataset.
The target column is provided during
:func:`~turicreate.random_forest_regression.create`. If the target column is in the
`dataset` it will be ignored.
Parameters
----------
dataset : SFrame
A dataset that has the... |
370,939 | def preprocessor(dom):
"Removes unwanted parts of DOM."
options = {
"processing_instructions": False,
"remove_unknown_tags": False,
"safe_attrs_only": False,
"page_structure": False,
"annoying_tags": False,
"frames": False,
"meta": False,
"links": ... | Removes unwanted parts of DOM. |
370,940 | def _timer(self, state_transition_event=None):
while not self._teardown.value:
state = self.get_roaster_state()
if(state == or state == ):
time.sleep(1)
self.total_time += 1
if(self.time_remaining > 0):
self.ti... | Timer loop used to keep track of the time while roasting or
cooling. If the time remaining reaches zero, the roaster will call the
supplied state transistion function or the roaster will be set to
the idle state. |
370,941 | def dmag_magic(in_file="measurements.txt", dir_path=".", input_dir_path="",
spec_file="specimens.txt", samp_file="samples.txt",
site_file="sites.txt", loc_file="locations.txt",
plot_by="loc", LT="AF", norm=True, XLP="",
save_plots=True, fmt="svg"):
dir_path = os.path.realpa... | plots intensity decay curves for demagnetization experiments
Parameters
----------
in_file : str, default "measurements.txt"
dir_path : str
output directory, default "."
input_dir_path : str
input file directory (if different from dir_path), default ""
spec_file : str
in... |
370,942 | def skus_get(self, product_id, session):
request = TOPRequest()
request[] = product_id
self.create(self.execute(request, session), fields=[,], models={:FenxiaoSku})
return self.skus | taobao.fenxiao.product.skus.get SKU查询接口
产品sku查询 |
370,943 | def info(self):
itext = self.class_info
if self.prop.info:
itext += .format(self.prop.info)
if self.max_length is None and self.min_length is None:
return itext
if self.max_length is None:
lentext = .format(self.min_length)
elif self.m... | Supplemental description of the list, with length and type |
370,944 | def save_dict(self, key: str, my_dict: dict, hierarchical: bool = False):
for _key, _value in my_dict.items():
if isinstance(_value, dict):
if not hierarchical:
self._db.hmset(key, {_key: json.dumps(_value)})
else:
self... | Store the specified dictionary at the specified key. |
370,945 | def main(argv=None):
import getopt
test_read = None
test_write = None
n = 3
if argv is None:
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, , [])
for o,a in opts:
if o == :
print(HELP)
return 0
... | Main function to run benchmarks.
@param argv: command-line arguments.
@return: exit code (0 is OK). |
370,946 | def create_record(self, dns_type, name, content, **kwargs):
data = {
: dns_type,
: name,
: content
}
if kwargs.get() and kwargs[] != 1:
data[] = kwargs[]
if kwargs.get() is True:
data[] = True
else:
... | Create a dns record
:param dns_type:
:param name:
:param content:
:param kwargs:
:return: |
370,947 | def _get_distance_term(self, C, rrup, backarc):
distance_scale = -np.log10(np.sqrt(rrup ** 2 + 3600.0))
distance_scale[backarc] += (C["c2"] * rrup[backarc])
idx = np.logical_not(backarc)
distance_scale[idx] += (C["c1"] * rrup[idx])
return dista... | Returns the distance scaling term, which varies depending on whether
the site is in the forearc or the backarc |
370,948 | def welch(timeseries, segmentlength, noverlap=None, scheme=None, **kwargs):
from pycbc.psd import welch as pycbc_welch
kwargs.setdefault(, )
if scheme is None:
scheme = null_context()
with scheme:
pycbc_fseries = pycbc_welch(timeseries.to_pycbc(copy=False),
... | Calculate a PSD using Welch's method with a mean average
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`
input `TimeSeries` data.
segmentlength : `int`
number of samples in single average.
noverlap : `int`
number of samples to overlap between segments, def... |
370,949 | def mkdir(dirname, overwrite=False):
if op.isdir(dirname):
if overwrite:
shutil.rmtree(dirname)
os.mkdir(dirname)
logging.debug("Overwrite folder `{0}`.".format(dirname))
else:
return False
else:
try:
os.mkdir(dirname)
... | Wraps around os.mkdir(), but checks for existence first. |
370,950 | def posterior_to_xarray(self):
posterior = self.posterior
posterior_predictive = self.posterior_predictive
if posterior_predictive is None:
posterior_predictive = []
elif isinstance(posterior_predictive, str):
posterior_predictive = [poste... | Extract posterior samples from fit. |
370,951 | def get_logexp(a=1, b=0, a2=None, b2=None, backend=None):
if a2 is None:
a2 = a
if b2 is None:
b2 = b
if backend is None:
import sympy as backend
return (lambda x: backend.log(a*x + b),
lambda x: (backend.exp(x) - b2)/a2) | Utility function for use with :func:symmetricsys.
Creates a pair of callbacks for logarithmic transformation
(including scaling and shifting): ``u = ln(a*x + b)``.
Parameters
----------
a : number
Scaling (forward).
b : number
Shift (forward).
a2 : number
Scaling (b... |
370,952 | def reset(self):
super(MorseSmaleComplex, self).reset()
self.base_partitions = {}
self.merge_sequence = {}
self.persistences = []
self.min_indices = []
self.max_indices = []
self.persistence = 0. | Empties all internal storage containers |
370,953 | def get_genes(
path_or_buffer, valid_biotypes,
chunksize=10000,
chromosome_pattern=None,
only_manual=False,
remove_duplicates=True,
sort_by=):
chrompat = None
if chromosome_pattern is not None:
chrompat = re.compile(chromosome_pattern)
... | Get all genes of a specific a biotype from an Ensembl GTF file.
Parameters
----------
path_or_buffer : str or buffer
The GTF file (either the file path or a buffer).
valid_biotypes : set of str
The set of biotypes to include (e.g., "protein_coding").
chromosome_pattern : str, op... |
370,954 | def get_internal_call_graph(fpath, with_doctests=False):
import utool as ut
fpath = ut.truepath(fpath)
sourcecode = ut.readfrom(fpath)
self = ut.BaronWraper(sourcecode)
G = self.internal_call_graph(with_doctests=with_doctests)
return G | CommandLine:
python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/ibeis/ibeis/init/main_helpers.py --show
python -m utool.util_inspect get_internal_call_graph --show --modpath=~/code/dtool/dtool/depcache_table.py --show
Example:
>>> # DISABLE_DOCTEST
>>> from... |
370,955 | def run_preassembly_duplicate(preassembler, beliefengine, **kwargs):
logger.info( %
len(preassembler.stmts))
dump_pkl = kwargs.get()
stmts_out = preassembler.combine_duplicates()
beliefengine.set_prior_probs(stmts_out)
logger.info( % len(stmts_out))
if dump_pkl:
dump... | Run deduplication stage of preassembly on a list of statements.
Parameters
----------
preassembler : indra.preassembler.Preassembler
A Preassembler instance
beliefengine : indra.belief.BeliefEngine
A BeliefEngine instance.
save : Optional[str]
The name of a pickle file to sa... |
370,956 | def task_done(self) -> None:
if self._unfinished_tasks <= 0:
raise ValueError("task_done() called too many times")
self._unfinished_tasks -= 1
if self._unfinished_tasks == 0:
self._finished.set() | Indicate that a formerly enqueued task is complete.
Used by queue consumers. For each `.get` used to fetch a task, a
subsequent call to `.task_done` tells the queue that the processing
on the task is complete.
If a `.join` is blocking, it resumes when all items have been
proces... |
370,957 | def entity_to_bulk(entities, resource_type_parent):
if not isinstance(entities, list):
entities = [entities]
bulk_array = []
for e in entities:
bulk = {: e.get(), : e.get()}
if resource_type_parent in [, , ]:
bulk[] = e.get()
... | Convert Single TC Entity to Bulk format.
.. Attention:: This method is subject to frequent changes
Args:
entities (dictionary): TC Entity to be converted to Bulk.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(dic... |
370,958 | def get_default_config(self):
config = super(StatsdHandler, self).get_default_config()
config.update({
: ,
: 1234,
: 1,
})
return config | Return the default config for the handler |
370,959 | def getEmpTraitCorrCoef(self):
cov = self.getEmpTraitCovar()
stds=SP.sqrt(cov.diagonal())[:,SP.newaxis]
RV = cov/stds/stds.T
return RV | Returns the empirical trait correlation matrix |
370,960 | def uniquetwig(self, ps=None):
if ps is None:
ps = self._bundle
if ps is None:
return self.twig
return ps._uniquetwig(self.twig) | see also :meth:`twig`
Determine the shortest (more-or-less) twig which will point
to this single Parameter in a given parent :class:`ParameterSet`
:parameter ps: :class:`ParameterSet` in which the returned
uniquetwig will point to this Parameter. If not provided
or Non... |
370,961 | def VerifyStructure(self, parser_mediator, lines):
try:
structure = self._SDF_HEADER.parseString(lines)
except pyparsing.ParseException:
logger.debug()
return False
try:
dfdatetime_time_elements.TimeElementsInMilliseconds(
time_elements_tuple=structure.header_date_tim... | Verify that this file is a SkyDrive log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
lines (str): one or more lines from the text file.
Returns:
bool: True if this is the correct parser, False o... |
370,962 | def calculate_normals(vertices):
verts = np.array(vertices, dtype=float)
normals = np.zeros_like(verts)
for start, end in pairwise(np.arange(0, verts.shape[0] + 1, 3)):
vecs = np.vstack((verts[start + 1] - verts[start], verts[start + 2] - verts[start]))
vecs /= np.linalg.norm(vecs, ax... | Return Nx3 normal array from Nx3 vertex array. |
370,963 | def filter_objects_by_section(self, rels, section):
subtree = section.get_descendants(include_self=True)
kwargs_list = [{ % rel.field.name: subtree} for rel in rels]
q = Q(**kwargs_list[0])
for kwargs in kwargs_list[1:]:
q |= Q(**kwargs)
return self.get_mana... | Build a queryset containing all objects in the section subtree. |
370,964 | def image_exists(self, image_name, tag=):
code, image = self.image_tags(image_name)
if code != httplib.OK:
return False
tag = tag.lower()
return any(x.lower() == tag for x in image.tags) | :param image_name:
:return: True the image_name location in docker.neg pos |
370,965 | def _points(self, x_pos):
for serie in self.all_series:
serie.points = [(x_pos[i], v) for i, v in enumerate(serie.values)]
if serie.points and self.interpolate:
serie.interpolated = self._interpolate(x_pos, serie.values)
else:
serie.in... | Convert given data values into drawable points (x, y)
and interpolated points if interpolate option is specified |
370,966 | def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None:
self.pfx = None
if shex is not None:
if isinstance(shex, ShExJ.Schema):
self._schema = shex
else:
shext = shex.strip()
loader = SchemaLoader()
... | Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema.
:param shex: Schema |
370,967 | def _syscal_write_electrode_coords(fid, spacing, N):
fid.write()
for i in range(0, N):
fid.write(.format(i + 1, i * spacing, 0, 0)) | helper function that writes out electrode positions to a file descriptor
Parameters
----------
fid: file descriptor
data is written here
spacing: float
spacing of electrodes
N: int
number of electrodes |
370,968 | def add_named_metadata(self, name, element=None):
if name in self.namedmetadata:
nmd = self.namedmetadata[name]
else:
nmd = self.namedmetadata[name] = values.NamedMetaData(self)
if element is not None:
if not isinstance(element, values.Value):
... | Add a named metadata node to the module, if it doesn't exist,
or return the existing node.
If *element* is given, it will append a new element to
the named metadata node. If *element* is a sequence of values
(rather than a metadata value), a new unnamed node will first be
create... |
370,969 | def getMugshot(self):
mugshot = self.store.findUnique(
Mugshot, Mugshot.person == self, default=None)
if mugshot is not None:
return mugshot
return Mugshot.placeholderForPerson(self) | Return the L{Mugshot} associated with this L{Person}, or an unstored
L{Mugshot} pointing at a placeholder mugshot image. |
370,970 | def _dispatch_handler(args, cell, parser, handler, cell_required=False,
cell_prohibited=False):
if cell_prohibited:
if cell and len(cell.strip()):
parser.print_help()
raise Exception(
% parser.prog)
return handler(args)
if cell_required and not cell:
pars... | Makes sure cell magics include cell and line magics don't, before
dispatching to handler.
Args:
args: the parsed arguments from the magic line.
cell: the contents of the cell, if any.
parser: the argument parser for <cmd>; used for error message.
handler: the handler to call if the cell present/a... |
370,971 | def validate(self, strict=True):
result = self._validate()
if strict and len(result):
for r in result:
logger.error(r)
raise errs.ValidationError(.format(len(result)))
return result | check if this Swagger API valid or not.
:param bool strict: when in strict mode, exception would be raised if not valid.
:return: validation errors
:rtype: list of tuple(where, type, msg). |
370,972 | def level_grouper(text, getreffs, level=None, groupby=20):
if level is None or level > len(text.citation):
level = len(text.citation)
references = [ref.split(":")[-1] for ref in getreffs(level=level)]
_refs = OrderedDict()
for key in references:
k = ".".join(key.split(".")[:level-... | Alternative to level_chunker: groups levels together at the latest level
:param text: Text object
:param getreffs: GetValidReff query callback
:param level: Level of citation to retrieve
:param groupby: Number of level to groupby
:return: Automatically curated references |
370,973 | def _write(self, session, openFile, replaceParamFile=None):
openFile.write(
text(
yaml.dump([evt.as_yml() for evt in
self.events.order_by(ProjectFileEvent.name,
ProjectFileEvent.subfolder)]
)
... | ProjectFileEvent Write to File Method |
370,974 | def forwards(apps, schema_editor):
RecurrenceRule = apps.get_model(, )
for description, recurrence_rule in RULES:
RecurrenceRule.objects.get_or_create(
description=description,
defaults=dict(recurrence_rule=recurrence_rule),
) | Create initial recurrence rules. |
370,975 | def marker_tags(self, iid):
tags = self._markers[iid]["tags"]
for tag in tags:
yield tag | Generator for all the tags of a certain marker |
370,976 | def F_beta(self, beta):
try:
F_dict = {}
for i in self.TP.keys():
F_dict[i] = F_calc(
TP=self.TP[i],
FP=self.FP[i],
FN=self.FN[i],
beta=beta)
return F_dict
except ... | Calculate FBeta score.
:param beta: beta parameter
:type beta : float
:return: FBeta score for classes as dict |
370,977 | def line(self, p1, p2, resolution=1):
xdiff = max(p1.x, p2.x) - min(p1.x, p2.x)
ydiff = max(p1.y, p2.y) - min(p1.y, p2.y)
xdir = [-1, 1][int(p1.x <= p2.x)]
ydir = [-1, 1][int(p1.y <= p2.y)]
r = int(round(max(xdiff, ydiff)))
if r == 0:
return
... | Resolve the points to make a line between two points. |
370,978 | def is_terminal(self):
return (self.raised_exception or self.is_timeout or
self.phase_result == openhtf.PhaseResult.STOP) | True if this result will stop the test. |
370,979 | def update_search_space(self, search_space):
self.json = search_space
search_space_instance = json2space(self.json)
rstate = np.random.RandomState()
trials = hp.Trials()
domain = hp.Domain(None, search_space_instance,
pass_expr_memo_ctrl=None)
... | Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict |
370,980 | def bytes2str_in_dicts(inp
):
if isinstance(inp, MutableMapping):
for k in inp:
inp[k] = bytes2str_in_dicts(inp[k])
return inp
if isinstance(inp, MutableSequence):
for idx, value in enumerate(inp):
inp[idx] = byte... | Convert any present byte string to unicode string, inplace.
input is a dict of nested dicts and lists |
370,981 | def _get_address_translations_table(address_translations):
table = formatting.Table([,
,
,
,
,
])
for address_translation in address_translations:
ta... | Yields a formatted table to print address translations.
:param List[dict] address_translations: List of address translations.
:return Table: Formatted for address translation output. |
370,982 | def replicate_directory_tree(input_dir, output_dir):
def transplant_dir(target, dirname):
x = dirname.replace(input_dir, target)
if not os.path.exists(x):
LOGGER.info(.format(x))
os.makedirs(x)
dir_visitor(
input_dir,
functools.partial(transplant_dir... | _replicate_directory_tree_
clone dir structure under input_dir into output dir
All subdirs beneath input_dir will be created under
output_dir
:param input_dir: path to dir tree to be cloned
:param output_dir: path to new dir where dir structure will
be created |
370,983 | def stream_url(self):
path = .format(self.id)
return self.connector.get_url(path,
userId=self.connector.userid,
MaxStreamingBitrate=140000000,
Container=,
TranscodingContainer=,
AudioCodec=,
MaxSampleRate=48000,
... | stream for this song - not re-encoded |
370,984 | def send(self, send_email=True):
url = str(self.api.base_url + ).format(code=self.code)
payload = {
: True,
: send_email,
}
stat = self.api.connection.make_put(url, payload) | Marks the invoice as sent in Holvi
If send_email is False then the invoice is *not* automatically emailed to the recipient
and your must take care of sending the invoice yourself. |
370,985 | def get_body(self, msg):
body = ""
charset = ""
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
cdispo = str(part.get())
if ctype == and not in cdispo:
bo... | Extracts and returns the decoded body from an EmailMessage object |
370,986 | def fetchall_sp(s,p):
query = .format(s=s, p=prefixmap[p])
bindings = run_sparql(query)
rows = [r[][] for r in bindings]
return rows | fetch all triples for a property |
370,987 | def obj_to_grid(self, file_path=None, delim=None, tab=None,
quote_numbers=True, quote_empty_str=False):
div_delims = {"top": [, ,
, ],
"divide": [,
,
, ],
... | This will return a str of a grid table.
:param file_path: path to data file, defaults to
self's contents if left alone
:param delim: dict of deliminators, defaults to
obj_to_str's method:
:param tab: stri... |
370,988 | def list_nodes_full(call=None):
if call == :
raise SaltCloudException(
)
ret = {}
for device in get_devices_by_token():
ret[device.hostname] = device.__dict__
return ret | List devices, with all available information.
CLI Example:
.. code-block:: bash
salt-cloud -F
salt-cloud --full-query
salt-cloud -f list_nodes_full packet-provider
.. |
370,989 | def validate_url(url):
scheme = url.split()[0].lower()
if scheme not in url_schemes:
return False
if not bool(url_regex.search(url)):
return False
return True | Auxiliary method to validate an urllib
:param url: An url to be validated
:type url: string
:returns: True if the url is valid
:rtype: bool |
370,990 | def _run_sbgenomics(args):
assert not args.no_container, "Seven Bridges runs require containers"
main_file, json_file, project_name = _get_main_and_json(args.directory)
flags = []
cmd = ["sbg-cwl-runner"] + flags + args.toolargs + [main_file, json_file]
_run_tool(cmd) | Run CWL on SevenBridges platform and Cancer Genomics Cloud. |
370,991 | def pcapname(dev):
if isinstance(dev, NetworkInterface):
if dev.is_invalid():
return None
return dev.pcap_name
try:
return IFACES.dev_from_name(dev).pcap_name
except ValueError:
return IFACES.dev_from_pcapname(dev).pcap_name | Get the device pcap name by device name or Scapy NetworkInterface |
370,992 | def override_options(config: DictLike, selected_options: Tuple[Any, ...], set_of_possible_options: Tuple[enum.Enum, ...], config_containing_override: DictLike = None) -> DictLike:
if config_containing_override is None:
config_containing_override = config
override_opts = config_containing_override.p... | Determine override options for a particular configuration.
The options are determined by searching following the order specified in selected_options.
For the example config,
.. code-block:: yaml
config:
value: 3
override:
2.76:
track:
... |
370,993 | def get_phone_numbers(self):
phone_dict = {}
for child in self.vcard.getChildren():
if child.name == "TEL":
type = helpers.list_to_string(
self._get_types_for_vcard_object(child, "voice"), ", ")
if type not in phon... | : returns: dict of type and phone number list
:rtype: dict(str, list(str)) |
370,994 | def match_resource_id(self, resource_id, match):
if not isinstance(resource_id, Id):
raise errors.InvalidArgument()
self._add_match(, str(resource_id), match) | Sets the resource ``Id`` for this query.
arg: resource_id (osid.id.Id): a resource ``Id``
arg: match (boolean): ``true`` if a positive match, ``false``
for a negative match
raise: NullArgument - ``resource_id`` is ``null``
*compliance: mandatory -- This method mus... |
370,995 | def delete_file(self, sass_filename, sass_fileurl):
if self.use_static_root:
destpath = os.path.join(self.static_root, os.path.splitext(sass_fileurl)[0] + )
else:
destpath = os.path.splitext(sass_filename)[0] +
if os.path.isfile(destpath):
os.remove(... | Delete a *.css file, but only if it has been generated through a SASS/SCSS file. |
370,996 | def deserialize_logical(self, node):
term1_attrib = node.getAttribute()
term1_value = node.getAttribute()
op = node.nodeName.lower()
term2_attrib = node.getAttribute()
term2_value = node.getAttribute()
if op not in _op_map:
_exc()
if term1_att... | Reads the logical tag from the given node, returns a Condition object.
node -- the xml node (xml.dom.minidom.Node) |
370,997 | def _create_model(model, ident, **params):
with log_errors(pdb=True):
model = clone(model).set_params(**params)
return model, {"model_id": ident, "params": params, "partial_fit_calls": 0} | Create a model by cloning and then setting params |
370,998 | def _set_mpls_traffic_lsps(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("mpls_traffic_lsp_name",mpls_traffic_lsps.mpls_traffic_lsps, yang_name="mpls-traffic-lsps", rest_name="lsp", parent=self, is_container=, user_ordered=False, path_h... | Setter method for mpls_traffic_lsps, mapped from YANG variable /telemetry/profile/mpls_traffic_lsp/mpls_traffic_lsps (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_traffic_lsps is considered as a private
method. Backends looking to populate this variable should
... |
370,999 | def half_duration(self):
if self._interval is not None:
a, b = self._interval
return (b - a) * .5
else:
return self.interval_duration * .5 | Half of the duration of the current interval. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.