text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def has_ndarray_int_columns(features, X):
""" Checks if numeric feature columns exist in ndarray """
_, ncols = X.shape
if not all(d.isdigit() for d in features if isinstance(d, str)) or not isinstance(X, np.ndarray):
return False
ndarray_columns = np.arange(0, ncols)
feature_cols = np.uniqu... | 0.00495 |
def remove(self, node, dirty=True):
"""Remove the given child node.
Args:
node (gkeepapi.Node): Node to remove.
dirty (bool): Whether this node should be marked dirty.
"""
if node.id in self._children:
self._children[node.id].parent = None
... | 0.005115 |
def reduce(self, agg=operator.add, acc=None):
"""
Submit all tasks and reduce the results
"""
return self.submit_all().reduce(agg, acc) | 0.011976 |
def save(self):
""" Exports all user attributes to the user's configuration and writes configuration
Saves the values for each attribute stored in User.configVars
into the user's configuration. The password is automatically
encoded and salted to prevent saving it as plaintext. T... | 0.009852 |
def dump(doc, output_stream=None):
"""
Dump a :class:`.Doc` object into a JSON-encoded text string.
The output will be sent to :data:`sys.stdout` unless an alternative
text stream is given.
To dump to :data:`sys.stdout` just do:
>>> import panflute as pf
>>> doc = pf.Doc(Para(Str(... | 0.001325 |
def from_files(cls, secrets=None, storage=None, scopes=None, no_webserver=False):
"""Return a spreadsheet collection making OAauth 2.0 credentials.
Args:
secrets (str): location of secrets file (default: ``%r``)
storage (str): location of storage file (default: ``%r``)
... | 0.004491 |
def add_axes_and_nodes(self):
"""
Adds the axes (i.e. 2 or 3 axes, not to be confused with matplotlib
axes) and the nodes that belong to each axis.
"""
for i, (group, nodelist) in enumerate(self.nodes.items()):
theta = self.group_theta(group)
if self.has_... | 0.004608 |
def get_child_tiers_for(self, id_tier):
"""Give all child tiers for a tier.
:param str id_tier: Name of the tier.
:returns: List of all children
:raises KeyError: If the tier is non existent.
"""
self.tiers[id_tier]
return [m for m in self.tiers if 'PARENT_REF' i... | 0.004988 |
def make_simple_merged_vcf_with_no_combinations(self, ref_seq):
'''Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the ALT for each
variant, making one new vcf_record that has all the variants
put together'''
if len(self) <= 1:
... | 0.004418 |
def status_line(self):
"""
Returns the first line of response, including http version, status
and a phrase (OK).
"""
if not self.phrase:
self.phrase = HttpStatus(self.status_code).phrase
return "{} {} {}".format("HTTP/1.1", self.status_code, self.phrase) | 0.006369 |
def RdatabasesBM(host=rbiomart_host):
"""
Lists BioMart databases through a RPY2 connection.
:param host: address of the host server, default='www.ensembl.org'
:returns: nothing
"""
biomaRt = importr("biomaRt")
print(biomaRt.listMarts(host=host)) | 0.00361 |
def removed(self):
"""
Returns list of removed ``FileNode`` objects.
"""
if not self.parents:
return []
return RemovedFileNodesGenerator([n for n in
self._get_paths_for_status('deleted')], self) | 0.010791 |
def init_blackhole(self):
"""redirects stdout/stderr to devnull if necessary"""
if self.no_stdout or self.no_stderr:
blackhole = open(os.devnull, 'w')
if self.no_stdout:
sys.stdout = sys.__stdout__ = blackhole
if self.no_stderr:
sys.std... | 0.005682 |
def _get_matching_segments(self, zf, name):
"""
Return a generator yielding each of the segments who's names
match name.
"""
for n in zf.namelist():
if n.startswith(name):
yield zf.read(n) | 0.043902 |
def enable_global_typechecked_decorator(flag = True, retrospective = True):
"""Enables or disables global typechecking mode via decorators.
See flag global_typechecked_decorator.
In contrast to setting the flag directly, this function provides
a retrospective option. If retrospective is true, this will ... | 0.006075 |
def generate_menu(self, ass, text, path=None, level=0):
"""
Function generates menu from based on ass parameter
"""
menu = self.create_menu()
for index, sub in enumerate(sorted(ass[1], key=lambda y: y[0].fullname.lower())):
if index != 0:
text += "|"
... | 0.004796 |
def _plot_residuals_to_ax(
data_all, model_ML, ax, e_unit=u.eV, sed=True, errorbar_opts={}
):
"""Function to compute and plot residuals in units of the uncertainty"""
if "group" not in data_all.keys():
data_all["group"] = np.zeros(len(data_all))
groups = np.unique(data_all["group"])
MLf_un... | 0.000424 |
def __multi_arity_dispatch_fn( # pylint: disable=too-many-arguments,too-many-locals
ctx: GeneratorContext,
name: str,
arity_map: Mapping[int, str],
default_name: Optional[str] = None,
max_fixed_arity: Optional[int] = None,
meta_node: Optional[MetaNode] = None,
is_async: bool = False,
) -> G... | 0.001133 |
def subtask(*args, **kwargs):
'''Decorator which prints out the name of the decorated function on
execution.
'''
depth = kwargs.get('depth', 2)
prefix = kwargs.get('prefix', '\n' + '#' * depth + ' ')
tail = kwargs.get('tail', '\n')
doc1 = kwargs.get('doc1', False)
color = kwargs.get('col... | 0.001279 |
def all_stats(self):
"""Compute stats for all results.
:return: :class:`results.AllStats <results.AllStats>` object
:rtype: results.AllStats
"""
schema = AllStatsSchema()
resp = self.service.post(self.base, params={'stats': 'all'})
return self.service.decode(sche... | 0.006079 |
def VORPS(cpu, dest, src, src2):
"""
Performs a bitwise logical OR operation on the source operand (second operand) and second source operand (third operand)
and stores the result in the destination operand (first operand).
"""
res = dest.write(src.read() | src2.read()) | 0.009646 |
def execute_concurrent(session, statements_and_parameters, concurrency=100, raise_on_first_error=True, results_generator=False):
"""
Executes a sequence of (statement, parameters) tuples concurrently. Each
``parameters`` item must be a sequence or :const:`None`.
The `concurrency` parameter controls ho... | 0.004608 |
def _rate_limit(self):
"""Pulls in and enforces the latest rate limits for the specified user"""
self.limits_set = True
for product in self.account_information():
self.limits[product['id']] = {'interval': timedelta(seconds=60 / float(product['per_minute_limit']))} | 0.013333 |
def classes(self, values):
"""Classes setter."""
if isinstance(values, dict):
if self.__data is not None and len(self.__data) != len(values):
raise ValueError(
'number of samples do not match the previously assigned data')
elif set(self.keys) !... | 0.00703 |
def distutils_old_autosemver_case(metadata, attr, value):
"""DEPRECATED"""
metadata = distutils_default_case(metadata, attr, value)
create_changelog(bugtracker_url=getattr(metadata, 'bugtracker_url', ''))
return metadata | 0.004237 |
def _ll_pre_transform(self, train_tfm:List[Callable], valid_tfm:List[Callable]):
"Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`"
self.train.x.after_open = compose(train_tfm)
self.valid.x.after_open = compose(valid_tfm)
return self | 0.017301 |
def inversion_psf_shape_tag_from_inversion_psf_shape(inversion_psf_shape):
"""Generate an inversion psf shape tag, to customize phase names based on size of the inversion PSF that the \
original PSF is trimmed to for faster run times.
This changes the phase name 'phase_name' as follows:
inversion_psf_... | 0.003003 |
def get_address_transactions(self, account_id, address_id, **params):
"""https://developers.coinbase.com/api/v2#list-address39s-transactions"""
response = self._get(
'v2',
'accounts',
account_id,
'addresses',
address_id,
'transactio... | 0.007299 |
def show(self):
"""Shows the new colors on the pixels themselves if they haven't already
been autowritten.
The colors may or may not be showing after this function returns because
it may be done asynchronously."""
if self.brightness > 0.99:
neopixel_write(self.pin, s... | 0.011468 |
def make(assembly, samples):
""" Make phylip and nexus formats. This is hackish since I'm recycling the
code whole-hog from pyrad V3. Probably could be good to go back through
and clean up the conversion code some time.
"""
## get the longest name
longname = max([len(i) for i in assembly.samp... | 0.008403 |
def process(self, argument_list):
"""
:param argument_list: list of str, input from user
:return: dict:
{"cleaned_arg_name": "value"}
"""
arg_index = 0
for a in argument_list:
opt_and_val = a.split("=", 1)
opt_name = opt_and_val[0]
... | 0.002736 |
def issuer(self, value):
"""
An asn1crypto.x509.Certificate or oscrypto.asymmetric.Certificate object
of the issuer.
"""
is_oscrypto = isinstance(value, asymmetric.Certificate)
if not is_oscrypto and not isinstance(value, x509.Certificate):
raise TypeError(_p... | 0.004666 |
def example_list(a, args):
""" list topics and cluster metadata """
if len(args) == 0:
what = "all"
else:
what = args[0]
md = a.list_topics(timeout=10)
print("Cluster {} metadata (response from broker {}):".format(md.cluster_id, md.orig_broker_name))
if what in ("all", "broke... | 0.002423 |
def _format_name_map(self, lon, lat):
''' Return the name of the map in the good format '''
if self.ppd in [4, 16, 64, 128]:
lolaname = '_'.join(['LDEM', str(self.ppd)])
elif self.ppd in [512]:
lolaname = '_'.join(
['LDEM', str(self.ppd), lat[0], lat[1], ... | 0.005556 |
def create_osd_keyring(conn, cluster, key):
"""
Run on osd node, writes the bootstrap key if not there yet.
"""
logger = conn.logger
path = '/var/lib/ceph/bootstrap-osd/{cluster}.keyring'.format(
cluster=cluster,
)
if not conn.remote_module.path_exists(path):
logger.warning('... | 0.002392 |
def _scan_constraint_match(self, minimum_version, maximum_version, jdk):
"""Finds a cached version matching the specified constraints
:param Revision minimum_version: minimum jvm version to look for (eg, 1.7).
:param Revision maximum_version: maximum jvm version to look for (eg, 1.7.9999).
:param bool ... | 0.010025 |
def get_cli_returns(
self,
jid,
minions,
timeout=None,
tgt='*',
tgt_type='glob',
verbose=False,
show_jid=False,
**kwargs):
'''
Starts a watcher looking at the return data for a specified JID
... | 0.001252 |
def add_to_cluster(self, name, **attrs):
"""Add attributes to a cluster.
"""
cluster = self.get_cluster(name=name)
attrs_ = cluster['cluster']
attrs_.update(**attrs) | 0.009756 |
def att_pos_mocap_send(self, time_usec, q, x, y, z, force_mavlink1=False):
'''
Motion capture attitude and position
time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t)
q : Attitude quaternion (w, x, y... | 0.006766 |
def close(self):
"""
Closes the connection to this hypervisor (but leave it running).
"""
yield from self.send("hypervisor close")
self._writer.close()
self._reader, self._writer = None | 0.008547 |
def users_changed_handler(stream):
"""
Sends connected client list of currently active users in the chatroom
"""
while True:
yield from stream.get()
# Get list list of current active users
users = [
{'username': username, 'uuid': uuid_str}
for u... | 0.001484 |
def _parse_eloss(line, lines):
"""Parse Energy [eV] eloss_xx eloss_zz"""
split_line = line.split()
energy = float(split_line[0])
eloss_xx = float(split_line[1])
eloss_zz = float(split_line[2])
return {"energy": energy, "eloss_xx": eloss_xx, "eloss_zz": eloss_zz} | 0.003367 |
def pre(self):
"""
Pre-order search of the tree rooted at this node.
(First visit current node, then visit children.)
:rtype: generator of :class:`~aeneas.tree.Tree`
"""
yield self
for node in self.children:
for v in node.pre:
yield v | 0.00627 |
def get_page_full(self, page_id):
""" Get full page info and full html code """
try:
result = self._request('/getpagefull/',
{'pageid': page_id})
return TildaPage(**result)
except NetworkError:
return [] | 0.006711 |
def adjustSizeConstraint(self):
"""
Adjusts the min/max size based on the current tab.
"""
widget = self.currentWidget()
if not widget:
return
offw = 4
offh = 4
#if self.tabBar().isVisible():
# offh += 20 # tab ... | 0.009777 |
def resize_to_shape(data, shape, zoom=None, mode='nearest', order=0):
"""
Function resize input data to specific shape.
:param data: input 3d array-like data
:param shape: shape of output data
:param zoom: zoom is used for back compatibility
:mode: default is 'nearest'
"""
# @TODO remov... | 0.000973 |
def reference_journal(self, index):
"""Return the reference journal name."""
# TODO Change the column name 'Journal' to an other?
ref_type = self.reference_type(index)
if ref_type == "journalArticle":
return self.reference_data(index)["publicationTitle"]
else:
... | 0.005634 |
def elapsed():
"""
Displays the elapsed time since the step started running.
"""
environ.abort_thread()
step = _cd.project.get_internal_project().current_step
r = _get_report()
r.append_body(render.elapsed_time(step.elapsed_time))
result = '[ELAPSED]: {}\n'.format(timedelta(seconds=step... | 0.002625 |
def set_minimum_level(self, level=0, stdoutFlag=True, fileFlag=True):
"""
Set the minimum logging level. All levels below the minimum will be ignored at logging.
:Parameters:
#. level (None, number, str): The minimum level of logging.
If None, minimum level checking is ... | 0.007216 |
def store(self, name, value, atype, new_name=None, multiplier=None, allowed_values=None):
''' store a config value in a dictionary, these values are used to populate a trasnfer spec
validation -- check type, check allowed values and rename if required '''
if value is not None:
_b... | 0.005682 |
def add_header(self, name, value):
'''Attach an email header to send with the message.
:param name: The name of the header value.
:param value: The header value.
'''
if self.headers is None:
self.headers = []
self.headers.append(dict(Name=name, Value=value)) | 0.00627 |
def write_bytes(self, addr, buf):
"""Write many bytes to the specified device. buf is a bytearray"""
assert self._device is not None, 'Bus must be opened before operations are made against it!'
self._select_device(addr)
self._device.write(buf) | 0.010909 |
def _get_nodal_planes_from_ndk_string(self, ndk_string):
"""
Reads the nodal plane information (represented by 5th line [57:] of the
tensor representation) and returns an instance of the GCMTNodalPlanes
class
"""
planes = GCMTNodalPlanes()
planes.nodal_plane_1 = {... | 0.002857 |
def build_tensor_serving_input_receiver_fn(shape, dtype=tf.float32,
batch_size=1):
"""Returns a input_receiver_fn that can be used during serving.
This expects examples to come through as float tensors, and simply
wraps them as TensorServingInputReceivers.
Arguably, ... | 0.003945 |
def merge_leading_dims(array_or_tensor, n_dims=2):
"""Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of d... | 0.011917 |
def filter(self, **kwargs):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded and recursively with query, filter,
order, sort and facet m... | 0.002914 |
def next_media_partname(self, ext):
"""Return |PackURI| instance for next available media partname.
Partname is first available, starting at sequence number 1. Empty
sequence numbers are reused. *ext* is used as the extension on the
returned partname.
"""
def first_avail... | 0.002484 |
def move_to(self, folder_id):
"""
:param str folder_id: The Calendar ID to where you want to move the event to.
Moves an event to a different folder (calendar). ::
event = service.calendar().get_event(id='KEY HERE')
event.move_to(folder_id='NEW CALENDAR KEY HERE')
"""
if not folder_id:... | 0.007921 |
def withdraw(self, uuid, organization, from_date=None, to_date=None):
"""Withdraw a unique identity from an organization.
This method removes all the enrollments between the unique identity,
identified by <uuid>, and <organization>. Both entities must exist
on the registry before being ... | 0.002451 |
def dict_cat(net, define_cat_colors=False):
'''
make a dictionary of node-category associations
'''
# print('---------------------------------')
# print('---- dict_cat: before setting cat colors')
# print('---------------------------------\n')
# print(define_cat_colors)
# print(net.viz['cat_colors'])
... | 0.01492 |
def scan_build_files(project_tree, base_relpath, build_ignore_patterns=None):
"""Looks for all BUILD files
:param project_tree: Project tree to scan in.
:type project_tree: :class:`pants.base.project_tree.ProjectTree`
:param base_relpath: Directory under root_dir to scan.
:param build_ignore_pattern... | 0.010332 |
def render(self, *args, **kwargs):
"""Override of the rendering so that if the link have no text in it, the href is used inside the <a> tag"""
if not self.childs and "href" in self.attrs:
return self.clone()(self.attrs["href"]).render(*args, **kwargs)
return super().render(*args, **k... | 0.009202 |
def save(self, filename=None, format=None, path=None,
width=None, height=None, units='in',
dpi=None, limitsize=True, verbose=True, **kwargs):
"""
Save a ggplot object as an image file
Parameters
----------
filename : str, optional
File name ... | 0.000933 |
def from_xy(cls, x_array, y_array):
""" Create a dataset from two arrays of data.
:note: infering the dimensions for the first elements of each array.
"""
if len(x_array) == 0:
raise ValueError("data array is empty.")
dim_x, dim_y = len(x_array[0]), len(y_array[0... | 0.005859 |
def get_variogram_points(self):
"""Returns both the lags and the variogram function evaluated at each
of them.
The evaluation of the variogram function and the lags are produced
internally. This method is convenient when the user wants to access to
the lags and the resulti... | 0.004121 |
def _calculate_python_sources(self, targets):
"""Generate a set of source files from the given targets."""
python_eval_targets = filter(self.is_non_synthetic_python_target, targets)
sources = set()
for target in python_eval_targets:
sources.update(
source for source in target.sources_relat... | 0.004515 |
def _get_mirror_urls(self, mirrors=None, main_mirror_url=None):
"""Retrieves a list of URLs from the main mirror DNS entry
unless a list of mirror URLs are passed.
"""
if not mirrors:
mirrors = get_mirrors(main_mirror_url)
# Should this be made "less random"? E.g.... | 0.002541 |
def get_magnitude_term(self, C, rup):
"""
Returns the magnitude scaling term in equation 3
"""
b0, stress_drop = self._get_sof_terms(C, rup.rake)
if rup.mag <= C["m1"]:
return b0
else:
# Calculate moment (equation 5)
m_0 = 10.0 ** (1.5 ... | 0.002331 |
def deep_compare(self, other, settings):
"""
Compares each field of the name one at a time to see if they match.
Each name field has context-specific comparison logic.
:param Name other: other Name for comparison
:return bool: whether the two names are compatible
"""
... | 0.00396 |
def peep_port(paths):
"""Convert a peep requirements file to one compatble with pip-8 hashing.
Loses comments and tromps on URLs, so the result will need a little manual
massaging, but the hard part--the hash conversion--is done for you.
"""
if not paths:
print('Please specify one or more ... | 0.002479 |
def _parse_single_video(self, example_proto):
"""Parses single video from the input tfrecords.
Args:
example_proto: tfExample proto with a single video.
Returns:
dict with all frames, positions and actions.
"""
context_features = {
"game_duration_loops": tf.io.FixedLenFeature([... | 0.001083 |
def get_forward_returns_columns(columns):
"""
Utility that detects and returns the columns that are forward returns
"""
pattern = re.compile(r"^(\d+([Dhms]|ms|us|ns))+$", re.IGNORECASE)
valid_columns = [(pattern.match(col) is not None) for col in columns]
return columns[valid_columns] | 0.003236 |
def write_files(self):
"""
write all data out into er_* and pmag_* files as appropriate
"""
warnings = self.validate_data()
print('-I- Writing all saved data to files')
if self.measurements:
self.write_measurements_file()
for dtype in ['specimen', 'sa... | 0.002899 |
def scan(self, cursor=0, match=None, count=None):
"""
Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
f = F... | 0.00161 |
def simultaneous_nlsq_fit(xs, ys, dys, func, params_inits, verbose=False,
**kwargs):
"""Do a simultaneous nonlinear least-squares fit
Input:
------
`xs`: tuple of abscissa vectors (1d numpy ndarrays)
`ys`: tuple of ordinate vectors (1d numpy ndarrays)
`dys`: tuple o... | 0.004358 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
C = self.COEFFS[imt]
# clip rhypo at 10 (this is the minimum ... | 0.002584 |
def complete_url(self, url):
""" Completes a given URL with this instance's URL base. """
if self.base_url:
return urlparse.urljoin(self.base_url, url)
else:
return url | 0.015625 |
def append_panel(panels, size_x, size_y, max_col=12):
"""
Appends a panel to the list of panels. Finds the highest palce at the left for the new panel.
:param panels:
:param size_x:
:param size_y:
:param max_col:
:return: a new panel or None if it is not possible to place a panel with such s... | 0.004373 |
def _get_json(value):
"""Convert the given value to a JSON object."""
if hasattr(value, 'replace'):
value = value.replace('\n', ' ')
try:
return json.loads(value)
except json.JSONDecodeError:
# Escape double quotes.
if hasattr(value, 'replace'):
value = value.... | 0.002309 |
def mock_method(self, interface, dbus_method, in_signature, *args, **kwargs):
'''Master mock method.
This gets "instantiated" in AddMethod(). Execute the code snippet of
the method and return the "ret" variable if it was set.
'''
# print('mock_method', dbus_method, self, in_sign... | 0.0033 |
def iter_errors(self):
""""Lazily yields each ValidationError for the received data dict.
"""
# Deprecate
warnings.warn(
'Property "package.iter_errors" is deprecated.',
UserWarning)
return self.profile.iter_errors(self.to_dict()) | 0.006757 |
def getuname(self, uid):
"""
Get the username of a given uid.
"""
uid = int(uid)
try:
return self.uidsmap[uid]
except KeyError:
pass
try:
name = pwd.getpwuid(uid)[0]
except (KeyError, AttributeError):
name =... | 0.005141 |
def add_mapped_chain_ids(self, mapped_chains):
"""Add chains by ID into the mapped_chains attribute
Args:
mapped_chains (str, list): Chain ID or list of IDs
"""
mapped_chains = ssbio.utils.force_list(mapped_chains)
for c in mapped_chains:
if c not in se... | 0.005282 |
def _check_inputs(self):
"""Check the inputs to ensure they are valid.
Returns
-------
status : bool
True if all inputs are valid, False if one is not.
"""
valid_detector = True
valid_filter = True
valid_date = True
# Determine the su... | 0.001235 |
def run_task(task, workspace):
"""
Runs the task and updates the workspace with results.
Parameters
----------
task - dict
Task Description
Examples:
{'task': task_func, 'inputs': ['a', 'b'], 'outputs': 'c'}
{'task': task_func, 'inputs': '*', 'outputs': '*'}
{'task': task_f... | 0.000913 |
def increment(cls, name):
"""Call this method to increment the named counter. This is atomic on
the database.
:param name:
Name for a previously created ``Counter`` object
"""
with transaction.atomic():
counter = Counter.objects.select_for_update().get(... | 0.007177 |
def _set_ethernet(self, v, load=False):
"""
Setter method for ethernet, mapped from YANG variable /interface/ethernet/logical_interface/ethernet (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ethernet is considered as a private
method. Backends looking to pop... | 0.003439 |
def refresh_signal_handler(self, signo, frame):
"""
This callback is called when SIGUSR1 signal is received.
It updates outputs of all modules by calling their `run` method.
Interval modules are updated in separate threads if their interval is
above a certain treshold value.
... | 0.001823 |
def alexa(self) -> list:
"""Returns list of Amazon Alexa compatible states of the RichMessage
instance nested controls.
Returns:
alexa_controls: Amazon Alexa representation of RichMessage instance nested
controls.
"""
alexa_controls = [control.alexa()... | 0.007895 |
def attribute_changed(self, node, column):
"""
Calls :meth:`QAbstractItemModel.dataChanged` with given Node attribute index.
:param node: Node.
:type node: AbstractCompositeNode or GraphModelNode
:param column: Attribute column.
:type column: int
:return: Method ... | 0.005376 |
def register_service(email, password, organisation_id, name=None,
service_type=None, accounts_url=None,
location=None, config=None):
"""Register a service with the accounts service
\b
EMAIL: a user's email
PASSWORD: a user's password
ORGANISATION_ID: ID of ... | 0.001609 |
def _dot_to_dec(ip, check=True):
"""Dotted decimal notation to decimal conversion."""
if check and not is_dot(ip):
raise ValueError('_dot_to_dec: invalid IP: "%s"' % ip)
octets = str(ip).split('.')
dec = 0
dec |= int(octets[0]) << 24
dec |= int(octets[1]) << 16
dec |= int(octets[2]) ... | 0.00274 |
def open_file(self, store=current_store, use_seek=False):
"""Opens the file-like object which is a context manager
(that means it can used for :keyword:`with` statement).
If ``use_seek`` is :const:`True` (though :const:`False` by default)
it guarentees the returned file-like object is a... | 0.001394 |
def should_audit(instance):
"""Returns True or False to indicate whether the instance
should be audited or not, depending on the project settings."""
# do not audit any model listed in UNREGISTERED_CLASSES
for unregistered_class in UNREGISTERED_CLASSES:
if isinstance(instance, unregistered_clas... | 0.001534 |
def shift_to_coords(self, pix, fill_value=np.nan):
"""Create a new map that is shifted to the pixel coordinates
``pix``."""
pix_offset = self.get_offsets(pix)
dpix = np.zeros(len(self.shape) - 1)
for i in range(len(self.shape) - 1):
x = self.rebin * (pix[i] - pix_off... | 0.001907 |
def parse_sra(path_to_config):
"""
Parses genetorrent config file. Returns list of samples: [ [id1, id1 ], [id2, id2], ... ]
Returns duplicate of ids to follow UUID/URL standard.
"""
samples = []
with open(path_to_config, 'r') as f:
for line in f.readlines():
if not line.iss... | 0.005115 |
def list_functions(mod_name):
"""Lists all functions declared in a module.
http://stackoverflow.com/a/1107150/3004221
Args:
mod_name: the module name
Returns:
A list of functions declared in that module.
"""
mod = sys.modules[mod_name]
return [func.__name__ for func in mod.... | 0.002632 |
def _perform_emulated_reset(self):
"""! @brief Emulate a software reset by writing registers.
All core registers are written to reset values. This includes setting the initial PC and SP
to values read from the vector table, which is assumed to be located at the based of the
boot... | 0.007869 |
def _len_lcs(x, y):
"""
Returns the length of the Longest Common Subsequence between sequences x
and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
:param x: sequence of words
:param y: sequence of words
:returns integer: Length of LCS between x and y
"""
... | 0.002513 |
def _get_links(network_id, template_id=None):
"""
Get all the links in a network
"""
extras = {'types':[], 'attributes':[]}
link_qry = db.DBSession.query(Link).filter(
Link.network_id==network_id,
Link.status=='A').o... | 0.010551 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.