text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def set_file_notice(self, doc, text):
"""Raises OrderError if no package or file defined.
Raises CardinalityError if more than one.
"""
if self.has_package(doc) and self.has_file(doc):
if not self.file_notice_set:
self.file_notice_set = True
se... | 0.003717 |
def sitetree_children(parser, token):
"""Parses sitetree_children tag parameters.
Six arguments:
{% sitetree_children of someitem for menu template "sitetree/mychildren.html" %}
Used to render child items of specific site tree 'someitem'
using template "sitetree/mychildren.h... | 0.004223 |
def _update_vdr_vxrheadtail(self, f, vdr_offset, VXRoffset):
'''
This sets a VXR to be the first and last VXR in the VDR
'''
# VDR's VXRhead
self._update_offset_value(f, vdr_offset+28, 8, VXRoffset)
# VDR's VXRtail
self._update_offset_value(f, vdr_offset+36, 8, VX... | 0.006098 |
def handle_user_exception(self, e):
"""This method is called whenever an exception occurs that should be
handled. A special case are
:class:`~werkzeug.exception.HTTPException`\s which are forwarded by
this function to the :meth:`handle_http_exception` method. This
function will... | 0.002149 |
def _mirbase_stats(data, out_dir):
"""Create stats from miraligner"""
utils.safe_makedir(out_dir)
out_file = os.path.join(out_dir, "%s_bcbio_mirbase.txt" % dd.get_sample_name(data))
out_file_novel = os.path.join(out_dir, "%s_bcbio_mirdeeep2.txt" % dd.get_sample_name(data))
mirbase_fn = data.get("seq... | 0.004769 |
def register(self, plugin, columnType=None, columnName=None):
"""
Registers a plugin to handle particular column types and column names
based on user selection.
:param plugin | <XOrbQueryPlugin>
columnType | <orb.ColumnType> || None
... | 0.007026 |
def change_location(src, tgt, move=False, verbose=True):
'''
Copies/moves/deletes locations
:param src:
Source location where to copy from
:param tgt:
Target location where to copy to
* To backup `src`, set `tgt` explicitly to ``True``. \
`tgt` will be set to `src` + '_... | 0.001259 |
def get_missing_options(self):
"""
Get a list of options that are required, but with default values
of None.
"""
return [option.name for option in self._options.values() if option.required and option.value is None] | 0.035714 |
def create_mnist_model(hyper_params, input_shape=(H, W, 1), num_classes=NUM_CLASSES):
'''
Create simple convolutional model
'''
layers = [
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2,... | 0.00615 |
def config(self, averaging=1, datarate=15, mode=MODE_NORMAL):
"""
Set the base config for sensor
:param averaging: Sets the numer of samples that are internally averaged
:param datarate: Datarate in hertz
:param mode: one of the MODE_* constants
"""
averaging_con... | 0.003711 |
def commit_input_persist_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
commit = ET.Element("commit")
config = commit
input = ET.SubElement(commit, "input")
persist_id = ET.SubElement(input, "persist-id")
persist_id.text = kwa... | 0.00463 |
def _add_header_domains_xml(self, document):
"""
Generates the XML elements for allowed header domains.
"""
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
'allow-http-request-headers-from'
)
... | 0.003289 |
def get_from_cache(self, org_id, id):
'''
Get an object from the cache
Use all cache folders available (primary first, then secondary in order) and look for the ID in the dir
if found unpickle and return the object, else return False
FIXME: Check for expiry of o... | 0.008929 |
def visit_UnaryOp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return representation of `node`s operator and operand."""
op = node.op
with self.op_man(op):
return self.visit(op) + self.visit(node.operand) | 0.008 |
def _hm_form_message(
self,
thermostat_id,
protocol,
source,
function,
start,
payload
):
"""Forms a message payload, excluding CRC"""
if protocol == constants.HMV3_ID:
start_low = (start & cons... | 0.002185 |
def score_file(filename):
"""Score each line in a file and return the scores."""
# Prepare model.
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = "inputs" in encoders
# Prepare features for feeding into the model.
if has_inputs:
inpu... | 0.016598 |
def process_raw_trace(raw_trace):
"""Processes raw trace data and returns the UI data."""
trace = trace_events_pb2.Trace()
trace.ParseFromString(raw_trace)
return ''.join(trace_events_json.TraceEventsJsonStream(trace)) | 0.022124 |
def addslashes(s, escaped_chars=None):
"""Add slashes for given characters. Default is for ``\`` and ``'``.
:param s: string
:param escaped_chars: list of characters to prefix with a slash ``\``
:return: string with slashed characters
:rtype: str
:Example:
>>> addslashes("'")
"... | 0.005607 |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(OpenvzCollector, self).get_default_config()
config.update({
'path': 'openvz',
'bin': '/usr/sbin/vzlist',
'keyname': 'hostname'
})
return... | 0.006116 |
def dataset_dict(
self, dataset_name, imagesize, voxelres,
offset, timerange, scalinglevels, scaling):
"""Generate the dataset dictionary"""
dataset_dict = {}
dataset_dict['dataset_name'] = dataset_name
dataset_dict['imagesize'] = imagesize
dataset_dict['voxel... | 0.004304 |
def estimate_entropy(X, epsilon=None):
r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information esti... | 0.000294 |
def process_request(self, request):
"""Process a request."""
batcher = PrioritizedBatcher.global_instance()
if batcher.is_started:
# This can happen in old-style middleware if consequent middleware
# raises exception and thus `process_response` is not called.
... | 0.004491 |
def is_package_installed(self, package_name):
"""Check if the RPM package is installed."""
if not package_name:
raise ValueError('package_name required.')
installed = True
try:
Cmd.sh_e('{0} --query {1} --quiet'.format(self.rpm_path,
... | 0.004515 |
def launch(self, args, unknown):
"""Launch something according to the provided arguments
:param args: arguments from the launch parser
:type args: Namespace
:param unknown: list of unknown arguments
:type unknown: list
:returns: None
:rtype: None
:raises:... | 0.00304 |
def _parse_supl(content):
"""Parse supplemental measurements data.
Parameters
----------
content : str
Data to parse
Returns
-------
:class:`pandas.DataFrame` containing the data
"""
col_names = ['year', 'month', 'day', 'hour', '... | 0.003899 |
def print_rows(self, num_rows=10, num_columns=40, max_column_width=30,
max_row_width=80, output_file=None):
"""
Print the first M rows and N columns of the SFrame in human readable
format.
Parameters
----------
num_rows : int, optional
Numb... | 0.004823 |
def dropbox_basename(url):
""" Strip off the dl=0 suffix from dropbox links
>>> dropbox_basename('https://www.dropbox.com/s/yviic64qv84x73j/aclImdb_v1.tar.gz?dl=1')
'aclImdb_v1.tar.gz'
"""
filename = os.path.basename(url)
match = re.findall(r'\?dl=[0-9]$', filename)
if match:
re... | 0.008108 |
def accept(self, **kws):
"""Accept a connection. The socket must be bound to an address and
listening for connections. The return value is a pair (conn, address)
where conn is a new socket object usable to send and receive data on the
connection, and address is the address bound to t... | 0.005484 |
def kv_format_dict(d, keys=None, separator=DEFAULT_SEPARATOR):
"""Formats the given dictionary ``d``.
For more details see :func:`kv_format`.
:param collections.Mapping d:
Dictionary containing values to format.
:param collections.Iterable keys:
List of keys to extract from the dict.
... | 0.001712 |
def cprint(self, cstr):
"""
Clear line, then reprint on same line
:param cstr: string to print on current line
"""
cstr = str(cstr) # Force it to be a string
cstr_len = len(cstr)
prev_cstr_len = len(self._prev_cstr)
num_spaces = 0
if cstr_len < pr... | 0.003257 |
def quick_sort(array, left, right):
"""快速排序"""
if left >= right:
return
low = left
high = right
key = array[low]
while left < right:
# 将大于key的值放到右边
while left < right and array[right] > key:
right -= 1
array[left] = array[right]
# 将小于key的值放... | 0.001761 |
def calc_mse(q1, q2):
"""Compare the results of two simulations"""
# Difference in positions between two simulations
dq = q2 - q1
# Mean squared error in AUs
return np.sqrt(np.mean(dq*dq))/au2m | 0.004695 |
def _check_data_flow_types(self, check_data_flow):
"""Checks the validity of the data flow connection
Checks whether the ports of a data flow have matching data types.
:param rafcon.core.data_flow.DataFlow check_data_flow: The data flow to be checked
:return bool validity, str message:... | 0.006028 |
def bookmark_show(bookmark_id_or_name):
"""
Executor for `globus bookmark show`
"""
client = get_client()
res = resolve_id_or_name(client, bookmark_id_or_name)
formatted_print(
res,
text_format=FORMAT_TEXT_RECORD,
fields=(
("ID", "id"),
("Name", "n... | 0.001499 |
def preprocess_rules(self):
"""Calculate shortest reference-paths of each rule (and Or field),
and prune all unreachable rules.
"""
to_prune = self._find_shortest_paths()
self._prune_rules(to_prune)
self._rules_processed = True | 0.007246 |
def rank(expr, sort=None, ascending=True):
"""
Calculate rank of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column
"""
return _rank_op(expr, Rank, types.int6... | 0.002825 |
def cancelPendingResultsFor( self, ps ):
"""Cancel all pending results for the given parameters. Note that
this only affects the notebook's record, not any job running in a lab.
:param ps: the parameters"""
k = self._parametersAsIndex(ps)
if k in self._results.keys():
... | 0.012862 |
def send_report(report, config):
"""
Sends the report to IOpipe's collector.
:param report: The report to be sent.
:param config: The IOpipe agent configuration.
"""
headers = {"Authorization": "Bearer {}".format(config["token"])}
url = "https://{host}{path}".format(**config)
try:
... | 0.003155 |
def name_from_base(base, max_length=63, short=False):
"""Append a timestamp to the provided string.
This function assures that the total length of the resulting string is not
longer than the specified max length, trimming the input parameter if necessary.
Args:
base (str): String used as prefi... | 0.00267 |
def less_or_equal(a, b, *args):
"""Implements the '<=' operator with JS-style type coertion."""
return (
less(a, b) or soft_equals(a, b)
) and (not args or less_or_equal(b, *args)) | 0.005 |
def merge_chromosome_dfs(df_tuple):
# type: (Tuple[pd.DataFrame, pd.DataFrame]) -> pd.DataFrame
"""Merges data from the two strands into strand-agnostic counts."""
plus_df, minus_df = df_tuple
index_cols = "Chromosome Bin".split()
count_column = plus_df.columns[0]
if plus_df.empty:
ret... | 0.000932 |
def AddValue(self, registry_value):
"""Adds a value.
Args:
registry_value (WinRegistryValue): Windows Registry value.
Raises:
KeyError: if the value already exists.
"""
name = registry_value.name.upper()
if name in self._values:
raise KeyError(
'Value: {0:s} already... | 0.005013 |
def srp(x, promisc=None, iface=None, iface_hint=None, filter=None,
nofilter=0, type=ETH_P_ALL, *args, **kargs):
"""Send and receive packets at layer 2"""
if iface is None and iface_hint is not None:
iface = conf.route.route(iface_hint)[0]
s = conf.L2socket(promisc=promisc, iface=iface,
... | 0.002198 |
def design_stat_heating(self, value="Heating"):
"""Corresponds to IDD Field `design_stat_heating`
Args:
value (str): value for IDD Field `design_stat_heating`
Accepted values are:
- Heating
Default value: Heating
if `valu... | 0.001612 |
def read_file(rel_path, paths=None, raw=False, as_list=False, as_iter=False,
*args, **kwargs):
'''
find a file that lives somewhere within a set of paths and
return its contents. Default paths include 'static_dir'
'''
if not rel_path:
raise ValueError("rel_path can not ... | 0.000855 |
def _emplace_transcript(transcripts, parent):
"""Retrieve the primary transcript and discard all others."""
transcripts.sort(key=lambda t: (len(t), t.get_attribute('ID')))
pt = transcripts.pop()
parent.children = [pt] | 0.004292 |
def getMaxDelay(inferences):
"""
Returns the maximum delay for the InferenceElements in the inference
dictionary
Parameters:
-----------------------------------------------------------------------
inferences: A dictionary where the keys are InferenceElements
"""
maxDelay = 0
for i... | 0.007762 |
def format_price(price, currency='$'):
"""
Format the price to have the appropriate currency and digits..
:param price: The price amount.
:param currency: The currency for the price.
:return: A formatted price string, i.e. '$10', '$10.52'.
"""
if int(price) == price:
return '{}{}'.f... | 0.002538 |
def ins(mnemonic):
"""Lookup instruction information.
Lookup an instruction by its mnemonic.
"""
try:
opcode = bytecode.opcode_table[mnemonic]
except KeyError:
click.secho(u'No definition found.', fg='red')
return
click.echo(u'{mnemonic} (0x{op})'.format(
mnemon... | 0.000646 |
def tryAcquire(self, lockID, callback=None, sync=False, timeout=None):
"""Attempt to acquire lock.
:param lockID: unique lock identifier.
:type lockID: str
:param sync: True - to wait until lock is acquired or failed to acquire.
:type sync: bool
:param callback: if sync ... | 0.006859 |
def from_composition_and_pd(comp, pd, working_ion_symbol="Li"):
"""
Convenience constructor to make a ConversionElectrode from a
composition and a phase diagram.
Args:
comp:
Starting composition for ConversionElectrode, e.g.,
Composition("FeF3... | 0.001101 |
def create_content_type(json):
"""Create :class:`.resource.ContentType` from JSON.
:param json: JSON dict.
:return: ContentType instance.
"""
result = ContentType(json['sys'])
for field in json['fields']:
field_id = field['id']
del field['id']
... | 0.004202 |
def get_token(url: str, scopes: str, credentials_dir: str) -> dict:
"""
Get access token info.
"""
tokens.configure(url=url, dir=credentials_dir)
tokens.manage('lizzy', [scopes])
tokens.start()
return tokens.get('lizzy') | 0.004 |
def add_tunnel_interface(self, interface_id, address, network_value,
zone_ref=None, comment=None):
"""
Creates a tunnel interface for a virtual engine.
:param str,int interface_id: the tunnel id for the interface, used as nicid also
:param str address: ip ad... | 0.00863 |
def fault_barrier(fn):
"""Method decorator to catch and log errors, then send fail message."""
@functools.wraps(fn)
def process(self, tup):
try:
return fn(self, tup)
except Exception as e:
if isinstance(e, KeyboardInterrupt):
return
print(s... | 0.002571 |
def set_target_variable (self, targets, variable, value, append=0):
""" Sets a target variable.
The 'variable' will be available to bjam when it decides
where to generate targets, and will also be available to
updating rule for that 'taret'.
"""
if isinstance (targets, s... | 0.007712 |
def leave(self, node):
"""walk on the tree from <node>, getting callbacks from handler"""
method = self.get_callbacks(node)[1]
if method is not None:
method(node) | 0.010101 |
def _on_connection_failed(self, conn_id, handle, clean, reason):
"""Callback called from another thread when a connection attempt has failed.
"""
with self.count_lock:
self.connecting_count -= 1
self._logger.info("_on_connection_failed conn_id=%d, reason=%s", conn_id, str(r... | 0.006289 |
def freeNSynapses(self, numToFree, inactiveSynapseIndices, verbosity= 0):
"""Free up some synapses in this segment. We always free up inactive
synapses (lowest permanence freed up first) before we start to free up
active ones.
@param numToFree number of synapses to free up
@param inact... | 0.010775 |
def release(self, resource):
"""release(resource)
Returns a resource to the pool. Most of the time you will want
to use :meth:`transaction`, but if you use :meth:`acquire`,
you must release the acquired resource back to the pool when
finished. Failure to do so could result in de... | 0.004184 |
def _eval_call(self, node):
"""
Evaluate a function call
:param node: Node to eval
:return: Result of node
"""
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(sel... | 0.003604 |
def eth_addr(f):
"""eth_addr
:param f: eth frame
"""
data = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (f[0],
f[1],
f[2],
f[3],
... | 0.002545 |
def _get_parameter(self, name, tp, timeout=1.0, max_retries=2):
""" Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to chec... | 0.001041 |
def environment_exists(self, name=None, prefix=None, abspath=True,
log=True):
"""Check if an environment exists by 'name' or by 'prefix'.
If query is by 'name' only the default conda environments directory is
searched.
"""
if log:
logger.de... | 0.004539 |
def _expand_nbest_translation(translation: Translation) -> List[Translation]:
"""
Expand nbest translations in a single Translation object to one Translation
object per nbest translation.
:param translation: A Translation object.
:return: A list of Translation objects.
"""
nbest_list = ... | 0.006865 |
def hfft(a, n=None, axis=-1, norm=None):
"""
Compute the FFT of a signal which has Hermitian symmetry (real spectrum).
Parameters
----------
a : array_like
The input array.
n : int, optional
Length of the transformed axis of the output.
For `n` output points, ``n//2+1`` ... | 0.000361 |
def render_template(tpl, context):
'''
A shortcut function to render a partial template with context and return
the output.
'''
templates = [tpl] if type(tpl) != list else tpl
tpl_instance = None
for tpl in templates:
try:
tpl_instance = template.loader.get_t... | 0.001739 |
def tuples2ids(tuples, ids):
"""Update `ids` according to `tuples`, e.g. (3, 0, X), (4, 0, X)..."""
for value in tuples:
if value[0] == 6 and value[2]:
ids = value[2]
elif value[0] == 5:
ids[:] = []
elif value[0] == 4 and value[1] and value[1] not in ids:
... | 0.002208 |
def multidict(ordered_pairs):
"""Convert duplicate keys values to lists."""
# read all values into lists
d = defaultdict(list)
for k, v in ordered_pairs:
d[k].append(v)
# unpack lists that have only 1 item
dict_copy = deepcopy(d)
for k, v in iteritems(dict_copy):
if len(v) ==... | 0.002732 |
def get_last_live_chat(self):
""" Check if there is a live chat that ended in the last 3 days, and
return it. We will display a link to it on the articles page.
"""
now = datetime.now()
lcqs = self.get_query_set()
lcqs = lcqs.filter(
chat_ends_at__lte=now... | 0.004065 |
def _interception(self, joinpoint):
"""Intercept call of joinpoint callee in doing pre/post conditions.
"""
if self.pre_cond is not None:
self.pre_cond(joinpoint)
result = joinpoint.proceed()
if self.post_cond is not None:
joinpoint.exec_ctx[Condition.R... | 0.005051 |
def add_nodes_from(self, nodes, **kwargs):
"""
Add multiple nodes to the cluster graph.
Parameters
----------
nodes: iterable container
A container of nodes (list, dict, set, etc.).
Examples
--------
>>> from pgmpy.models import ClusterGraph
... | 0.004073 |
def _extract_gcs_api_response_error(message):
""" A helper function to extract user-friendly error messages from service exceptions.
Args:
message: An error message from an exception. If this is from our HTTP client code, it
will actually be a tuple.
Returns:
A modified version of the message th... | 0.018149 |
def to_cloudformation(self, **kwargs):
"""Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanill... | 0.004824 |
def apply_parameters(self, parameters):
"""Recursively apply dictionary entries in 'parameters' to {item}s in recipe
structure, leaving undefined {item}s as they are. A special case is a
{$REPLACE:item}, which replaces the string with a copy of the referenced
parameter item.
Exa... | 0.002616 |
def adjust(self, to):
'''
Adjusts the time from kwargs to timedelta
**Will change this object**
return new copy of self
'''
if self.date == 'infinity':
return
new = copy(self)
if type(to) in (str, unicode):
to = to.lower()
... | 0.003939 |
def _build_argspec(self):
"""Builds the ansible argument spec using the fields from the schema
definition. It's the caller's responsibility to add any arguments which
are not defined in the schema (e.g. login parameters)
"""
fields = self.manager._schema.fields
argspec = ... | 0.002203 |
def clear(self, models=None, commit=True):
"""
Clears all indexes for the current project.
:param models: if specified, only deletes the entries for the given models.
:param commit: This is ignored by Haystack (maybe a bug?)
"""
for language in self.languages:
... | 0.006981 |
def refine_water_bridges(self, wbridges, hbonds_ldon, hbonds_pdon):
"""A donor atom already forming a hydrogen bond is not allowed to form a water bridge. Each water molecule
can only be donor for two water bridges, selecting the constellation with the omega angle closest to 110 deg."""
donor_at... | 0.005882 |
def cleanup(self):
"""
Clean up finished children.
:return: None
"""
self.lock.acquire()
logger.debug('Acquired lock in cleanup for ' + str(self))
self.children = [child for child in self.children if child.is_alive()]
self.lock.release() | 0.006623 |
def getAltitudeFromLatLon(self, lat, lon):
"""Get the altitude of a lat lon pair, using the four neighbouring
pixels for interpolation.
"""
# print "-----\nFromLatLon", lon, lat
lat -= self.lat
lon -= self.lon
# print "lon, lat", lon, lat
if lat < 0.0 ... | 0.003249 |
def register():
"""
Return dictionary of tranform factories
"""
registry = {
key: bake_html(key)
for key in ('css', 'css-all', 'tag', 'text')
}
registry['xpath'] = bake_parametrized(xpath_selector, select_all=False)
registry['xpath-all'] = bake_parametrized(xpath_selector, se... | 0.002825 |
def tempfile_writer(target):
'''write cache data to a temporary location. when writing is
complete, rename the file to the actual location. delete
the temporary file on any error'''
tmp = target.parent / ('_%s' % target.name)
try:
with tmp.open('wb') as fd:
yield fd
except:... | 0.004717 |
def start(self, name: str, increment_count: bool = True) -> None:
"""
Start a named timer.
Args:
name: name of the timer
increment_count: increment the start count for this timer
"""
if not self._timing:
return
now = get_now_utc_pendu... | 0.002415 |
def add_named_foreign_key_constraint(
self, name, foreign_table, local_columns, foreign_columns, options
):
"""
Adds a foreign key constraint with a given name.
:param name: The constraint name
:type name: str
:param foreign_table: Table instance or table name
... | 0.002828 |
def list(showgroups):
"""
Show list of Anchore data feeds.
"""
ecode = 0
try:
result = {}
subscribed = {}
available = {}
unavailable = {}
current_user_data = contexts['anchore_auth']['user_info']
feedmeta = anchore_feeds.load_anchore_feedmeta()
... | 0.001848 |
def isalive(path):
"""
Returns True if the file with the given name contains a process
id that is still alive.
Returns False otherwise.
:type path: str
:param path: The name of the pidfile.
:rtype: bool
:return: Whether the process is alive.
"""
# try to read the pid from the ... | 0.001439 |
def cfnumber_to_number(cfnumber):
"""Convert CFNumber to python int or float."""
numeric_type = cf.CFNumberGetType(cfnumber)
cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16,
kCFNumberSInt32Type: c_int32,
kCFNumberSInt64Type: c_int64,
... | 0.000863 |
def remove(self):
"""
Call this to remove the node/replicas from the ring.
"""
pipeline = self.conn.pipeline()
for replica in self.replicas:
pipeline.zrem(self.key, '{start}:{name}'.format(
start=replica[0],
name=replica[1]
... | 0.005376 |
def parameters(self):
"""
Get the dictionary of parameters (either ra,dec or l,b)
:return: dictionary of parameters
"""
if self._coord_type == 'galactic':
return collections.OrderedDict((('l', self.l), ('b', self.b)))
else:
return collections.... | 0.00813 |
def list_minus(l: List, minus: List) -> List:
"""Returns l without what is in minus
>>> list_minus([1, 2, 3], [2])
[1, 3]
"""
return [o for o in l if o not in minus] | 0.010753 |
def do_command(self, words):
"""Parse and act upon the command in the list of strings `words`."""
self.output = ''
self._do_command(words)
return self.output | 0.010582 |
def remove(self, item):
"""Remove an item from the list
:param item: The item to remove from the list.
:raises ValueError: If the item is not present in the list.
"""
if item not in self:
raise ValueError('objectlist.remove(item) failed, item not in list')
it... | 0.006424 |
def save(path, im):
"""
Saves an image to file.
If the image is type float, it will assume to have values in [0, 1].
Parameters
----------
path : str
Path to which the image will be saved.
im : ndarray (image)
Image.
"""
from PIL import Image
if im.dtype == np.u... | 0.002203 |
def get_bgcolor(self, index):
"""Background color depending on value"""
value = self.get_value(index)
if index.column() < 3:
color = ReadOnlyCollectionsModel.get_bgcolor(self, index)
else:
if self.remote:
color_name = value['color']
... | 0.004193 |
def __do_case_6_work(d_w, d_u, case_1, case_2, case_3, dfs_data):
"""Encapsulates the work that will be done for case 6 of __embed_frond,
since it gets used in more than one place."""
# --We should only ever see u-cases 1 and 3
if case_2:
# --We should never get here
return False
co... | 0.003326 |
def OnMacroListLoad(self, event):
"""Macro list load event handler"""
# Get filepath from user
wildcards = get_filetypes2wildcards(["py", "all"]).values()
wildcard = "|".join(wildcards)
message = _("Choose macro file.")
style = wx.OPEN
filepath, filterindex =... | 0.002604 |
def _create_table(self, table_name, column_types, primary=None, nullable=()):
"""Creates a sqlite3 table from the given metadata.
Parameters
----------
column_types : list of (str, str) pairs
First element of each tuple is the column name, second element is the sqlite3 type... | 0.002346 |
def clear_session(self, response):
"""Clear the session.
This method is invoked when the session is found to be invalid.
Subclasses can override this method to implement a custom session
reset.
"""
session.clear()
# if flask-login is installed, we try to clear t... | 0.003145 |
def to_gpio(self, spec):
"""
Parses a pin *spec*, returning the equivalent Broadcom GPIO port number
or raising a :exc:`ValueError` exception if the spec does not represent
a GPIO port.
The *spec* may be given in any of the following forms:
* An integer, which will be a... | 0.00156 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.