Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
21,100 | def _cumsum(group_idx, a, size, fill_value=None, dtype=None):
sortidx = np.argsort(group_idx, kind=)
invsortidx = np.argsort(sortidx, kind=)
group_idx_srt = group_idx[sortidx]
a_srt = a[sortidx]
a_srt_cumsum = np.cumsum(a_srt, dtype=dtype)
increasing = np.arange(len(a), dtype=int)
gro... | N to N aggregate operation of cumsum. Perform cumulative sum for each group.
group_idx = np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1])
a = np.array([3, 4, 1, 3, 9, 9, 6, 7, 7, 0, 8, 2, 1, 8, 9, 8])
_cumsum(group_idx, a, np.max(group_idx) + 1)
>>> array([ 3, 4, 5, 6, 15, 9, 15, 22, 7, ... |
21,101 | def get(self, sid):
return VerificationContext(self._version, service_sid=self._solution[], sid=sid, ) | Constructs a VerificationContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.verify.v2.service.verification.VerificationContext
:rtype: twilio.rest.verify.v2.service.verification.VerificationContext |
21,102 | def is_possible_type(
self, abstract_type: GraphQLAbstractType, possible_type: GraphQLObjectType
) -> bool:
possible_type_map = self._possible_type_map
try:
possible_type_names = possible_type_map[abstract_type.name]
except KeyError:
possible_types = ... | Check whether a concrete type is possible for an abstract type. |
21,103 | def setup_random_seed(seed):
if seed == -1:
seed = np.random.randint(0,
int(1e9))
np.random.seed(seed) | Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \
positive, that seed is used for all runs, thereby giving reproducible results.
Parameters
----------
seed : int
The seed of the random number generator. |
21,104 | def pickle_dict(items):
t instances of
basestring are pickled. Also, a new key contains a comma
separated list of keys corresponding to the pickled values.
_pickled,'.join(pickled_keys)
return ret | Returns a new dictionary where values which aren't instances of
basestring are pickled. Also, a new key '_pickled' contains a comma
separated list of keys corresponding to the pickled values. |
21,105 | def parse_string(self, string):
self.log.info("Parsing ASCII data")
if not string:
self.log.warning("Empty metadata")
return
lines = string.splitlines()
application_data = []
application = lines[0].split()[0]
self.log.debug("Reading met... | Parse ASCII output of JPrintMeta |
21,106 | def execute(self, method, *args, **kargs):
result = None
for i in range(0, 10):
try:
method_map = {
: self.get_lead_by_id,
: self.get_multiple_leads_by_filter_type,
: self.get_multiple_leads_by_list_id,
... | max 10 rechecks |
21,107 | async def search_participant(self, name, force_update=False):
if force_update or self.participants is None:
await self.get_participants()
if self.participants is not None:
for p in self.participants:
if p.name == name:
return p
... | search a participant by (display) name
|methcoro|
Args:
name: display name of the participant
force_update (dfault=False): True to force an update to the Challonge API
Returns:
Participant: None if not found
Raises:
APIException |
21,108 | def shape(self):
shp = (self.ds.RasterYSize, self.ds.RasterXSize, self.ds.RasterCount)
return shp[:2] if shp[2] <= 1 else shp | Returns a tuple of row, column, (band count if multidimensional). |
21,109 | def default_start():
(config, daemon, pidfile, startup, fork) = parsearg()
if config is None:
if os.path.isfile():
config =
else:
print()
elif not config:
config = None
main(config, startup, daemon, pidfile, fork) | Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start` |
21,110 | def follow(ctx, nick, url, force):
source = Source(nick, url)
sources = ctx.obj[].following
if not force:
if source.nick in (source.nick for source in sources):
click.confirm("➤ You’re already following {0}. Overwrite?".format(
click.style(source.nick, bold=True)), ... | Add a new source to your followings. |
21,111 | def fetchall(self, mode=5, after=0, parent=, order_by=,
limit=100, page=0, asc=1):
fields_comments = [, , , , ,
, , , ,
, , , ]
fields_threads = [, ]
sql_comments_fields = .join([ + f
... | Return comments for admin with :param:`mode`. |
21,112 | def type_validator(validator, types, instance, schema):
if schema.get() == :
return []
return _validators.type_draft3(validator, types, instance, schema) | Swagger 1.2 supports parameters of 'type': 'File'. Skip validation of
the 'type' field in this case. |
21,113 | def get_fallback_resolution(self):
ppi = ffi.new()
cairo.cairo_surface_get_fallback_resolution(
self._pointer, ppi + 0, ppi + 1)
return tuple(ppi) | Returns the previous fallback resolution
set by :meth:`set_fallback_resolution`,
or default fallback resolution if never set.
:returns: ``(x_pixels_per_inch, y_pixels_per_inch)`` |
21,114 | def as_xml_index(self, basename="/tmp/sitemap.xml"):
num_parts = self.requires_multifile()
if (not num_parts):
raise ListBaseIndexError(
"Request for sitemapindex for list with only %d entries when max_sitemap_entries is set to %s" %
(len(self), str(
... | Return a string of the index for a large list that is split.
All we need to do is determine the number of component sitemaps will
be is and generate their URIs based on a pattern.
Q - should there be a flag to select generation of each component sitemap
in order to calculate the md5sum... |
21,115 | def find():
spark_home = os.environ.get(, None)
if not spark_home:
for path in [
,
,
,
,
]:
if os.path.exists(path):
spark_home = path
break
if not spark_home:
raise Va... | Find a local spark installation.
Will first check the SPARK_HOME env variable, and otherwise
search common installation locations, e.g. from homebrew |
21,116 | def parse_timespan_value(s):
number, unit = split_number_and_unit(s)
if not unit or unit == "s":
return number
elif unit == "min":
return number * 60
elif unit == "h":
return number * 60 * 60
elif unit == "d":
return number * 24 * 60 * 60
else:
raise ... | Parse a string that contains a time span, optionally with a unit like s.
@return the number of seconds encoded by the string |
21,117 | def adjustPoolSize(self, newsize):
if newsize < 0:
raise ValueError("pool size must be nonnegative")
self.log("Adjust pool size from %d to %d." % (self.target_pool_size, newsize))
self.target_pool_size = newsize
self.kill_excess_pending_conns()
self.kill_exc... | Change the target pool size. If we have too many connections already,
ask some to finish what they're doing and die (preferring to kill
connections to the node that already has the most connections). If
we have too few, create more. |
21,118 | def parse_segment(text, version=None, encoding_chars=None, validation_level=None, reference=None):
version = _get_version(version)
encoding_chars = _get_encoding_chars(encoding_chars, version)
validation_level = _get_validation_level(validation_level)
segment_name = text[:3]
text = text[4:] if... | Parse the given ER7-encoded segment and return an instance of :class:`Segment <hl7apy.core.Segment>`.
:type text: ``str``
:param text: the ER7-encoded string containing the segment to be parsed
:type version: ``str``
:param version: the HL7 version (e.g. "2.5"), or ``None`` to use the default
... |
21,119 | def depth_profile(list_, max_depth=None, compress_homogenous=True, compress_consecutive=False, new_depth=False):
r
if isinstance(list_, dict):
list_ = list(list_.values())
level_shape_list = []
if not any(map(util_type.is_listlike, list_)):
return len(list_)
if False and new... | r"""
Returns a nested list corresponding the shape of the nested structures
lists represent depth, tuples represent shape. The values of the items do
not matter. only the lengths.
Args:
list_ (list):
max_depth (None):
compress_homogenous (bool):
compress_consecutive (boo... |
21,120 | def bs_values_df(run_list, estimator_list, estimator_names, n_simulate,
**kwargs):
tqdm_kwargs = kwargs.pop(, {: })
assert len(estimator_list) == len(estimator_names), (
.format(len(estimator_list), len(estimator_names)))
bs_values_list = pu.parallel_apply(
nes... | Computes a data frame of bootstrap resampled values.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators to apply to runs.
estimator_names: list of strs
Name of each func in estimator_list.
n_simul... |
21,121 | def find_modules_with_decorators(path,decorator_module,decorator_name):
modules_paths = []
if path[-3:] == :
modules_paths.append(path)
else :
modules_paths += find_file_regex(path,)
return [module for module in modules_paths if is_module_has_decorated(module,de... | Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorator_module : Then full name of the module defining the decorator.
decorator... |
21,122 | def cumulative_distance(lat, lon,dist_int=None):
une ligne.
;
; @Author : Renaud DUSSURGET, LEGOS/CTOH
; @History :
; - Feb. 2009 : First release (adapted from calcul_distance)
;-
'
rt = 6378.137
nelts=lon.size
... | ;+
; CUMULATIVE_DISTANCE : permet de calculer la distance le long d'une ligne.
;
; @Author : Renaud DUSSURGET, LEGOS/CTOH
; @History :
; - Feb. 2009 : First release (adapted from calcul_distance)
;- |
21,123 | def receive_message(self, message, data):
if data[] == TYPE_RESPONSE_STATUS:
self.is_launched = True
return True | Currently not doing anything with received messages. |
21,124 | def show_proportions(adata):
layers_keys = [key for key in [, , ] if key in adata.layers.keys()]
tot_mol_cell_layers = [adata.layers[key].sum(1) for key in layers_keys]
mean_abundances = np.round(
[np.mean(tot_mol_cell / np.sum(tot_mol_cell_layers, 0)) for tot_mol_cell in tot_mol_cell_layers],... | Fraction of spliced/unspliced/ambiguous abundances
Arguments
---------
adata: :class:`~anndata.AnnData`
Annotated data matrix.
Returns
-------
Prints the fractions of abundances. |
21,125 | def _lexical_chains(self, doc, term_concept_map):
concepts = list({c for c in term_concept_map.values()})
n_cons = len(concepts)
adj_mat = np.zeros((n_cons, n_cons))
for i, c in enumerate(concepts):
for j, c_ in enumerate(con... | Builds lexical chains, as an adjacency matrix,
using a disambiguated term-concept map. |
21,126 | def charge(self):
if self._reader._level == 3:
for ns in (FBC_V2, FBC_V1):
charge = self._root.get(_tag(, ns))
if charge is not None:
return self._parse_charge_string(charge)
else:
charge = self._root.get()... | Species charge |
21,127 | def _mom(self, kloc, cache, **kwargs):
if evaluation.get_dependencies(*list(self.inverse_map)):
raise StochasticallyDependentError(
"Joint distribution with dependencies not supported.")
output = 1.
for dist in evaluation.sorted_dependencies(self):
... | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
>>> print(numpy.around(dist.mom([[0, 0, 1], [0, 1, 1]]), 4))
[1. 0. 0.]
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(numpy.around(dist.mom([1,... |
21,128 | def parse(self,DXfield):
self.DXfield = DXfield
self.currentobject = None
self.objects = []
self.tokens = []
with open(self.filename,) as self.dxfile:
self.use_parser()
f... | Parse the dx file and construct a DX field object with component classes.
A :class:`field` instance *DXfield* must be provided to be
filled by the parser::
DXfield_object = OpenDX.field(*args)
parse(DXfield_object)
A tokenizer turns the dx file into a stream of tokens. A... |
21,129 | def custom_to_pmrapmdec(pmphi1,pmphi2,phi1,phi2,T=None,degree=False):
if T is None: raise ValueError("Must set T= for custom_to_pmrapmdec")
return pmrapmdec_to_custom(pmphi1, pmphi2, phi1, phi2,
T=nu.transpose(T),
degree=degree) | NAME:
custom_to_pmrapmdec
PURPOSE:
rotate proper motions in a custom set of sky coordinates (phi1,phi2) to ICRS (ra,dec)
INPUT:
pmphi1 - proper motion in custom (multplied with cos(phi2)) [mas/yr]
pmphi2 - proper motion in phi2 [mas/yr]
phi1 - custom longitude
p... |
21,130 | def coarsen_all_traces(level=2, exponential=False, axes="all", figure=None):
if axes=="gca": axes=_pylab.gca()
if axes=="all":
if not figure: f = _pylab.gcf()
axes = f.axes
if not _fun.is_iterable(axes): axes = [axes]
for a in axes:
lines = a.get_lines()
... | This function does nearest-neighbor coarsening of the data. See
spinmob.fun.coarsen_data for more information.
Parameters
----------
level=2
How strongly to coarsen.
exponential=False
If True, use the exponential method (great for log-x plots).
axes="all"
Which axes... |
21,131 | def set_grade(
self,
assignment_id,
student_id,
grade_value,
gradebook_id=,
**kwargs
):
grade_info = {
: student_id,
: assignment_id,
: 2,
: .format(ti... | Set numerical grade for student and assignment.
Set a numerical grade for for a student and assignment. Additional
options
for grade ``mode`` are: OVERALL_GRADE = ``1``, REGULAR_GRADE = ``2``
To set 'excused' as the grade, enter ``None`` for letter and
numeric grade values,
... |
21,132 | def CopyToDateTimeString(self):
if (self._timestamp is None or self._timestamp < self._INT64_MIN or
self._timestamp > self._INT64_MAX):
return None
return super(APFSTime, self)._CopyToDateTimeString() | Copies the APFS timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or
None if the timestamp is missing or invalid. |
21,133 | def chunk(self, regex):
chunks = []
for component in self._content:
chunks.extend(
StringComponent(component.placeholder, s) for s in
regex.split(str(component)))
for i, (chunk1, chunk2) in enumerate(
zip(chunks, islice(chunks,... | FIXME: |
21,134 | def switch_to_app(self, package):
log.debug("switching to app ...".format(package))
cmd, url = DEVICE_URLS["switch_to_app"]
widget_id = self._get_widget_id(package)
url = url.format(, package, widget_id)
self.result = self._exec(cmd, url) | activates an app that is specified by package. Selects the first
app it finds in the app list
:param package: name of package/app
:type package: str
:return: None
:rtype: None |
21,135 | def list_js_files(dir):
for dirpath, dirnames, filenames in os.walk(dir):
for filename in filenames:
if is_js_file(filename):
yield os.path.join(dirpath, filename) | Generator for all JavaScript files in the directory, recursively
>>> 'examples/module.js' in list(list_js_files('examples'))
True |
21,136 | def merge_dictionaries(a, b):
res = {}
for k in a:
res[k] = a[k]
for k in b:
res[k] = b[k]
return res | Merge two dictionaries; duplicate keys get value from b. |
21,137 | def normalized(self):
qr = self.qr /1./ np.linalg.norm(self.qr)
return DualQuaternion(qr, self.qd, True) | :obj:`DualQuaternion`: This quaternion with qr normalized. |
21,138 | def from_directory(cls, directory):
cert_path = os.path.join(directory, )
key_path = os.path.join(directory, )
for path, name in [(cert_path, ), (key_path, )]:
if not os.path.exists(path):
raise context.FileNotFoundError(
"Security %s file... | Create a security object from a directory.
Relies on standard names for each file (``skein.crt`` and
``skein.pem``). |
21,139 | def find_raw_devices(vendor=None, product=None, serial_number=None,
custom_match=None, **kwargs):
def is_usbraw(dev):
if custom_match and not custom_match(dev):
return False
return bool(find_interfaces(dev, bInterfaceClass=0xFF,
... | Find connected USB RAW devices. See usbutil.find_devices for more info. |
21,140 | def log(self, n=None, template=None):
cmd = [, ]
if n:
cmd.append( % n)
return self.sh(cmd, shell=False) | Run the repository log command
Returns:
str: output of log command (``bzr log -l <n>``) |
21,141 | def readSTATION0(path, stations):
stalist = []
f = open(path + , )
for line in f:
if line[1:6].strip() in stations:
station = line[1:6].strip()
lat = line[6:14]
if lat[-1] == :
NS = -1
else:
NS = 1
if ... | Read a Seisan STATION0.HYP file on the path given.
Outputs the information, and writes to station.dat file.
:type path: str
:param path: Path to the STATION0.HYP file
:type stations: list
:param stations: Stations to look for
:returns: List of tuples of station, lat, long, elevation
:rtyp... |
21,142 | def sg_int(tensor, opt):
r
return tf.cast(tensor, tf.sg_intx, name=opt.name) | r"""Casts a tensor to intx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A `Tensor` or `SparseTensor` with same shape as `tensor`. |
21,143 | def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
meta = {}
props = {}
if datasetMetaProps:
props.update(datasetMetaProps)
if fieldMetaProps:
meta["fieldMetaProps"] = fieldMetaProps
if len(props) > 0:
m... | This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name for the file to write to
:param thinOutput: Write only new data, not structures. Result type will be BasicObject
... |
21,144 | def convert(credentials):
credentials_class = type(credentials)
try:
return _CLASS_CONVERSION_MAP[credentials_class](credentials)
except KeyError as caught_exc:
new_exc = ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
six.raise_from(new_exc, caught_exc) | Convert oauth2client credentials to google-auth credentials.
This class converts:
- :class:`oauth2client.client.OAuth2Credentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.client.GoogleCredentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class... |
21,145 | def split_into(iterable, sizes):
it = iter(iterable)
for size in sizes:
if size is None:
yield list(it)
return
else:
yield list(islice(it, size)) | Yield a list of sequential items from *iterable* of length 'n' for each
integer 'n' in *sizes*.
>>> list(split_into([1,2,3,4,5,6], [1,2,3]))
[[1], [2, 3], [4, 5, 6]]
If the sum of *sizes* is smaller than the length of *iterable*, then the
remaining items of *iterable* will not be returned.... |
21,146 | def ls(args):
table = []
for bucket in filter_collection(resources.s3.buckets, args):
bucket.LocationConstraint = clients.s3.get_bucket_location(Bucket=bucket.name)["LocationConstraint"]
cloudwatch = resources.cloudwatch
bucket_region = bucket.LocationConstraint or "us-east-1"
... | List S3 buckets. See also "aws s3 ls". Use "aws s3 ls NAME" to list bucket contents. |
21,147 | def write_peps(self, peps, reverse_seqs):
if reverse_seqs:
peps = [(x[0][::-1],) for x in peps]
cursor = self.get_cursor()
cursor.executemany(
, peps)
self.conn.commit() | Writes peps to db. We can reverse to be able to look up
peptides that have some amino acids missing at the N-terminal.
This way we can still use the index. |
21,148 | def merge(self, data, clean=False, validate=False):
try:
model = self.__class__(data)
except ConversionError as errors:
abort(self.to_exceptions(errors.messages))
for key, val in model.to_native().items():
if key in data:
setattr(sel... | Merge a dict with the model
This is needed because schematics doesn't auto cast
values when assigned. This method allows us to ensure
incoming data & existing data on a model are always
coerced properly.
We create a temporary model instance with just the new
data so all... |
21,149 | def image_list(auth=None, **kwargs):
**
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_images(**kwargs) | List images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_list
salt '*' glanceng.image_list |
21,150 | def _init(self):
for goid in self.godag.go_sources:
goobj = self.godag.go2obj[goid]
self.godag.go2obj[goid] = goobj
if self.traverse_parent and goid not in self.seen_cids:
self._traverse_parent_objs(goobj)
if self... | Given GO ids and GOTerm objects, create mini GO dag. |
21,151 | def f1_score(y_true, y_pred, average=, suffix=False):
true_entities = set(get_entities(y_true, suffix))
pred_entities = set(get_entities(y_pred, suffix))
nb_correct = len(true_entities & pred_entities)
nb_pred = len(pred_entities)
nb_true = len(true_entities)
p = nb_correct / nb_pred if n... | Compute the F1 score.
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score are
equal. The formula for the F1 score is::
F1 = 2 * (... |
21,152 | def _parse_memory_embedded_health(self, data):
memory_mb = 0
memory = self._get_memory_details_value_based_on_model(data)
if memory is None:
msg = "Unable to get memory data. Error: Data missing"
raise exception.IloError(msg)
total_memory_size = 0
... | Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: memory size in MB.
:raises IloError, if unable to get the memory details. |
21,153 | def is_ipv6_ok(soft_fail=False):
if os.path.isdir():
if not is_module_loaded():
try:
modprobe()
return True
except subprocess.CalledProcessError as ex:
hookenv.log("Couldnt working
... | Check if IPv6 support is present and ip6tables functional
:param soft_fail: If set to True and IPv6 support is broken, then reports
that the host doesn't have IPv6 support, otherwise a
UFWIPv6Error exception is raised.
:returns: True if IPv6 is working, False otherwi... |
21,154 | def rowsBeforeValue(self, value, count):
if value is None:
query = self.inequalityQuery(None, count, False)
else:
pyvalue = self._toComparableValue(value)
currentSortAttribute = self.currentSortColumn.sortAttribute()
query = self.inequalityQuery(
... | Retrieve display data for rows with sort-column values less than the
given value.
@type value: Some type compatible with the current sort column.
@param value: Starting value in the index for the current sort column
at which to start returning results. Rows with a column value for the
... |
21,155 | def set_wrappable_term(self, v, term):
import textwrap
for t in self[].find(term):
self.remove_term(t)
for l in textwrap.wrap(v, 80):
self[].new_term(term, l) | Set the Root.Description, possibly splitting long descriptions across multiple terms. |
21,156 | def _arburg2(X, order):
x = np.array(X)
N = len(x)
if order <= 0.:
raise ValueError("order must be > 0")
rho = sum(abs(x)**2.) / N
den = rho * 2. * N
ef = np.zeros(N, dtype=complex)
eb = np.zeros(N, dtype=complex)
for j in range(0, N):
ef[j] = x... | This version is 10 times faster than arburg, but the output rho is not correct.
returns [1 a0,a1, an-1] |
21,157 | def join_state_collections( collection_a, collection_b):
return StateCollection(
(collection_a.states + collection_b.states),
{ grouping_name:_combined_grouping_values(grouping_name, collection_a,collection_b)
for grouping_name in set( list(collection_a.groupings.k... | Warning: This is a very naive join. Only use it when measures and groups will remain entirely within each subcollection.
For example: if each collection has states grouped by date and both include the same date, then the new collection
would have both of those groups, likely causing problems for group mea... |
21,158 | def RAMON(typ):
if six.PY2:
lookup = [str, unicode]
elif six.PY3:
lookup = [str]
if type(typ) is int:
return _ramon_types[typ]
elif type(typ) in lookup:
return _ramon_types[_types[typ]] | Takes str or int, returns class type |
21,159 | def serach_path():
operating_system = get_os()
return [os.path.expanduser("~/.kerncraft/iaca/{}/".format(operating_system)),
os.path.abspath(os.path.dirname(os.path.realpath(__file__))) + .format(
operating_system)] | Return potential locations of IACA installation. |
21,160 | def subscribe_topic(self, topics=[], pattern=None):
if not isinstance(topics, list):
topics = [topics]
self.consumer.subscribe(topics, pattern=pattern) | Subscribe to a list of topics, or a topic regex pattern.
- ``topics`` (list): List of topics for subscription.
- ``pattern`` (str): Pattern to match available topics. You must provide either topics or pattern,
but not both. |
21,161 | def dispatch(self, receiver):
super(SessionCallbackAdded, self).dispatch(receiver)
if hasattr(receiver, ):
receiver._session_callback_added(self) | Dispatch handling of this event to a receiver.
This method will invoke ``receiver._session_callback_added`` if
it exists. |
21,162 | def get_all_scores(self, motifs, dbmotifs, match, metric, combine,
pval=False, parallel=True, trim=None, ncpus=None):
if trim:
for m in motifs:
m.trim(trim)
for m in dbmotifs:
m.trim(trim)
... | Pairwise comparison of a set of motifs compared to reference motifs.
Parameters
----------
motifs : list
List of Motif instances.
dbmotifs : list
List of Motif instances.
match : str
Match can be "partial", "subtotal" or "total". Not all met... |
21,163 | def xml_findall(xpath):
def xpath_findall(value):
validate(ET.iselement, value)
return value.findall(xpath)
return transform(xpath_findall) | Find a list of XML elements via xpath. |
21,164 | def data(self):
header = struct.pack(,
4,
self.created,
self.algo_id)
oid = util.prefix_len(, self.curve_info[])
blob = self.curve_info[](self.verifying_key)
return header + o... | Data for packet creation. |
21,165 | def add_log_type(name, display, color, bcolor):
global MESSAGE_LOG
v_name = name.replace(" ", "_").upper()
val = 0
lkey = MESSAGE_LOG.keys()
while val in lkey:
val += 1
MESSAGE_LOG[val] = [v_name, (display, color, bcolor,)]
setattr(LOG, v_name, val) | name : call name (A-Z and '_')
display : display message in [-]
color : text color (see bashutils.colors)
bcolor : background color (see bashutils.colors) |
21,166 | def do_macro_arg(parser, token):
parser.delete_first_token()
return MacroArgNode(nodelist) | Function taking a parsed template tag
to a MacroArgNode. |
21,167 | def has_abiext(self, ext, single_file=True):
if ext != "abo":
ext = ext if ext.startswith() else + ext
files = []
for f in self.list_filepaths():
if ext == "_DDB" and f.endswith(".nc"): continue
if ext == "_MDF" and not f.e... | Returns the absolute path of the ABINIT file with extension ext.
Support both Fortran files and netcdf files. In the later case,
we check whether a file with extension ext + ".nc" is present
in the directory. Returns empty string is file is not present.
Raises:
`ValueError` ... |
21,168 | def largest_graph(mol):
mol.require("Valence")
mol.require("Topology")
m = clone(mol)
if m.isolated:
for k in itertools.chain.from_iterable(m.isolated):
m.remove_atom(k)
return m | Return a molecule which has largest graph in the compound
Passing single molecule object will results as same as molutil.clone |
21,169 | def _pushMessages(self):
self.showStatus()
if len(self._statusMsgsToShow) > 0:
self.top.after(200, self._pushMessages) | Internal callback used to make sure the msg list keeps moving. |
21,170 | def copy(self):
if self.select_line_on_copy_empty and not self.textCursor().hasSelection():
TextHelper(self).select_whole_line()
super(CodeEdit, self).copy() | Copy the selected text to the clipboard. If no text was selected, the
entire line is copied (this feature can be turned off by
setting :attr:`select_line_on_copy_empty` to False. |
21,171 | def _compute_ymean(self, **kwargs):
y = np.asarray(kwargs.get(, self.y))
dy = np.asarray(kwargs.get(, self.dy))
if dy.size == 1:
return np.mean(y)
else:
return np.average(y, weights=1 / dy ** 2) | Compute the (weighted) mean of the y data |
21,172 | async def processClaims(self, allClaims: Dict[ID, Claims]):
res = []
for schemaId, (claim_signature, claim_attributes) in allClaims.items():
res.append(await self.processClaim(schemaId, claim_attributes, claim_signature))
return res | Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition. |
21,173 | def initiate_close(self):
self._running = False
self._accumulator.close()
self.wakeup() | Start closing the sender (won't complete until all data is sent). |
21,174 | def list_ctx(self):
if self._data is None:
if self._deferred_init:
return self._deferred_init[1]
raise RuntimeError("Parameter has not been initialized"%self.name)
return self._ctx_list | Returns a list of contexts this parameter is initialized on. |
21,175 | def create_user(self, user_name, path=):
params = { : user_name,
: path}
return self.get_response(, params) | Create a user.
:type user_name: string
:param user_name: The name of the new user
:type path: string
:param path: The path in which the user will be created.
Defaults to /. |
21,176 | def _render(self, template, context, is_file, at_paths=None,
at_encoding=ENCODING, **kwargs):
eopts = self.filter_options(kwargs, self.engine_valid_options())
self._env_options.update(eopts)
loader = FileSystemExLoader(at_paths, encoding=at_encoding.lower(),
... | Render given template string and return the result.
:param template: Template content
:param context: A dict or dict-like object to instantiate given
template file
:param is_file: True if given `template` is a filename
:param at_paths: Template search paths
:param at... |
21,177 | def get_all_instances(self, instance_ids=None, filters=None):
params = {}
if instance_ids:
self.build_list_params(params, instance_ids, )
if filters:
if in filters:
gid = filters.get()
if not gid.startswith() or len(gid) != 11:
... | Retrieve all the instances associated with your account.
:type instance_ids: list
:param instance_ids: A list of strings of instance IDs
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
... |
21,178 | def predict(self, x):
if isinstance(x, RDD):
return x.map(lambda v: self.predict(v))
x = _convert_to_vector(x)
if self.numClasses == 2:
margin = self.weights.dot(x) + self._intercept
if margin > 0:
prob = 1 / (1 + exp(-margin))
... | Predict values for a single data point or an RDD of points
using the model trained. |
21,179 | def load(filename):
path, name = os.path.split(filename)
path = path or
with util.indir(path):
return pickle.load(open(name, )) | Load the state from the given file, moving to the file's directory during
load (temporarily, moving back after loaded)
Parameters
----------
filename : string
name of the file to open, should be a .pkl file |
21,180 | def get_form(self, request, obj=None, **kwargs):
template = get_template_from_request(request, obj)
form = make_form(self.model, get_placeholders(template))
language = get_language_from_request(request)
form.base_fields[].initial = language
if obj:
... | Get a :class:`Page <pages.admin.forms.PageForm>` for the
:class:`Page <pages.models.Page>` and modify its fields depending on
the request. |
21,181 | def abort_copy_file(self, share_name, directory_name, file_name, copy_id, timeout=None):
_validate_not_none(, share_name)
_validate_not_none(, file_name)
_validate_not_none(, copy_id)
request = HTTPRequest()
request.method =
request.host_locations = self._get_ho... | Aborts a pending copy_file operation, and leaves a destination file
with zero length and full metadata.
:param str share_name:
Name of destination share.
:param str directory_name:
The path to the directory.
:param str file_name:
Name of destinatio... |
21,182 | def reconstructed_pixelization_from_solution_vector(self, solution_vector):
recon = mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=solution_vector,
shape=self.shape)
return sc... | Given the solution vector of an inversion (see *inversions.Inversion*), determine the reconstructed \
pixelization of the rectangular pixelization by using the mapper. |
21,183 | def handle_exception(exc_info=None, source_hint=None, tb_override=_NO):
global _make_traceback
if exc_info is None:
exc_info = sys.exc_info()
if _make_traceback is None:
from .runtime.debug import make_traceback as _make_traceback
exc_type, exc_value, tb = exc_in... | Exception handling helper. This is used internally to either raise
rewritten exceptions or return a rendered traceback for the template. |
21,184 | def traverse_layout(root, callback):
callback(root)
if isinstance(root, collections.Iterable):
for child in root:
traverse_layout(child, callback) | Tree walker and invokes the callback as it
traverse pdf object tree |
21,185 | def _check_file(self):
if not os.path.exists(self.file_path):
return False
self._migrate()
config = configparser.RawConfigParser()
config.read(self.file_path)
try:
config.get(
escape_for_ini(),
escape_for_ini(),
... | Check if the file exists and has the expected password reference. |
21,186 | def deregister(self, reg_data, retry=True, interval=1, timeout=3):
Retry(target=self.publish.direct.delete,
args=("/controller/registration", reg_data,),
kwargs={"timeout": timeout},
options={"retry": retry, "interval": interval})
_logger.debug("Deregis... | Deregister model/view of this bundle |
21,187 | def metadata(self):
md = self.xml(src="docProps/core.xml")
if md is None:
md = XML(root=etree.Element("{%(cp)s}metadata" % self.NS))
return md.root | return a cp:metadata element with the metadata in the document |
21,188 | def _add_sub_elements_from_dict(parent, sub_dict):
for key, value in sub_dict.items():
if isinstance(value, list):
for repeated_element in value:
sub_element = ET.SubElement(parent, key)
_add_element_attrs(sub_element, repeated_element.get("attrs", {}))
children = repeated_element.get("children", No... | Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
... |
21,189 | def recarrayequalspairs(X,Y,weak=True):
if (weak and set(X.dtype.names) != set(Y.dtype.names)) or \
(not weak and X.dtype.names != Y.dtype.names):
return [np.zeros((len(X),),int),np.zeros((len(X),),int),None]
else:
if X.dtype.names != Y.dtype.names:
Y = np.rec.fromarrays(... | Indices of elements in a sorted numpy recarray (or ndarray with
structured dtype) equal to those in another.
Record array version of func:`tabular.fast.equalspairs`, but slightly
different because the concept of being sorted is less well-defined for a
record array.
Given numpy recarray `X` and ... |
21,190 | def replica_lag(self, **kwargs):
if not self._use_replica():
return 0
try:
kwargs[] = self.stack_mark(inspect.stack())
sql = "select EXTRACT(EPOCH FROM NOW() - pg_last_xact_replay_timestamp()) AS replication_lag"
return self.collection_instance(
... | Returns the current replication lag in seconds between the master and replica databases.
:returns: float |
21,191 | def disk_pick_polar(n=1, rng=None):
if rng is None:
rng = np.random
a = np.zeros([n, 2], dtype=np.float)
a[:, 0] = np.sqrt(rng.uniform(size=n))
a[:, 1] = rng.uniform(0.0, 2.0 * np.pi, size=n)
return a | Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
-------
r: array, shape (n, 2)
Sample vectors. |
21,192 | def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]):
assert_is_instance(expected, dict)
assert_is_instance(actual, dict)
expected_keys = set(expected.keys())
actual_keys = set(actual.keys())
assert expected_keys <= actual_keys, "Actual dict at %s is missing keys: %r" % (
... | Asserts that two dictionaries are equal, producing a custom message if they are not. |
21,193 | def _unascii(s):
chunks = []
pos = 0
while m:
start = m.start()
end = m.end()
g = m.group(1)
if g is None:
chunks.append(s[pos:end])
else:
| Unpack `\\uNNNN` escapes in 's' and encode the result as UTF-8
This method takes the output of the JSONEncoder and expands any \\uNNNN
escapes it finds (except for \\u0000 to \\u001F, which are converted to
\\xNN escapes).
For performance, it assumes that the input is valid JSON, and performs few
... |
21,194 | def cat(ctx, archive_name, version):
_generate_api(ctx)
var = ctx.obj.api.get_archive(archive_name)
with var.open(, version=version) as f:
for chunk in iter(lambda: f.read(1024 * 1024), ):
click.echo(chunk) | Echo the contents of an archive |
21,195 | def metadata_converter_help_content():
message = m.Message()
paragraph = m.Paragraph(tr(
))
message.add(paragraph)
paragraph = m.Paragraph(tr(
))
message.add(paragraph)
return message | Helper method that returns just the content in extent mode.
This method was added so that the text could be reused in the
wizard.
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message |
21,196 | def dumps(data):
if not isinstance(data, _TOMLDocument) and isinstance(data, dict):
data = item(data)
return data.as_string() | Dumps a TOMLDocument into a string. |
21,197 | def _get_table_data(self):
data = self._simplify_shape(
self.table_widget.get_data())
if self.table_widget.array_btn.isChecked():
return array(data)
elif pd and self.table_widget.df_btn.isChecked():
info = self.table_widget.pd_info
... | Return clipboard processed as data |
21,198 | def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1.,
sep:str=, decoder=decode_spec_tokens):
"Return the `n_words` that come after `text` using beam search."
ds = self.data.single_dl.dataset
self.model.reset()
... | Return the `n_words` that come after `text` using beam search. |
21,199 | def set_access_port(self, port_number, vlan_id):
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocated".format(port_number))
nio = self._nios[port_number]
yield from self._hypervisor.send(.format(name=self._name,
... | Sets the specified port as an ACCESS port.
:param port_number: allocated port number
:param vlan_id: VLAN number membership |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.