text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def deep_unicode(s, encodings=None):
"""decode "DEEP" S using the codec registered for encoding."""
if encodings is None:
encodings = ['utf-8', 'latin-1']
if isinstance(s, (list, tuple)):
return [deep_unicode(i) for i in s]
if isinstance(s, dict):
return dict([
(deep_... | 0.002857 |
def remove(self, element):
"""
Return a new PSet with element removed. Raises KeyError if element is not present.
>>> s1 = s(1, 2)
>>> s1.remove(2)
pset([1])
"""
if element in self._map:
return self.evolver().remove(element).persistent()
rais... | 0.007979 |
def main(argv=sys.argv):
# type: (List[str]) -> int
"""Parse and check the command line arguments."""
parser = optparse.OptionParser(
usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]
Look recursively in <module_path> for Python modules and packages and create
... | 0.000358 |
def parse(s):
"""
Parse string representation back into the SparseVector.
>>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )')
SparseVector(4, {0: 4.0, 1: 5.0})
"""
start = s.find('(')
if start == -1:
raise ValueError("Tuple should start with '('")
... | 0.001185 |
def dlf_notation(atom_key):
"""Return element for atom key using DL_F notation."""
split = list(atom_key)
element = ''
number = False
count = 0
while number is False:
element = "".join((element, split[count]))
count += 1
if is_number(split[count]) is True:
num... | 0.001105 |
def add_newline(self, number=1):
""" Starts over again at the new line. If number is specified,
it will leave multiple lines."""
if isinstance(number, int):
try:
self.page._add_newline(self.font, number, self.double_spacing)
except ValueError:
... | 0.004587 |
def item(self, current_item):
"""
Return the current item.
@param current_item: Current item
@type param: django.models
@return: Value and label of the current item
@rtype : dict
"""
return {
'value': text(getattr(current_item, self.get_fiel... | 0.005168 |
def do_mfa(self, args):
"""
Enter a 6-digit MFA token. Nephele will execute the appropriate
`aws` command line to authenticate that token.
mfa -h for more details
"""
parser = CommandArgumentParser("mfa")
parser.add_argument(dest='token',help='MFA token... | 0.024248 |
def get_provider_choices():
"""Returns a list of currently available metrics providers
suitable for use as model fields choices.
"""
choices = []
for provider in METRICS_PROVIDERS:
choices.append((provider.alias, provider.title))
return choices | 0.00361 |
def _find_fuse_next(working_list, homology, tm):
'''Find the next sequence to fuse, and fuse it (or raise exception).
:param homology: length of terminal homology in bp
:type homology: int
:raises: AmbiguousGibsonError if there is more than one way for the
fragment ends to combine.
... | 0.000421 |
def _unpublish(self):
"""
Process an unpublish action on the related object, returns a boolean if a change is made.
Only objects with a current active version will be updated.
"""
obj = self.content_object
actioned = False
# Only update if needed
if obj.... | 0.006048 |
def iflat_tasks(self, status=None, op="==", nids=None):
"""
Generator to iterate over all the tasks of the :class:`Flow`.
If status is not None, only the tasks whose status satisfies
the condition (task.status op status) are selected
status can be either one of the flags defined... | 0.007005 |
def detect_devices(soapy_args=''):
"""Returns detected SoapySDR devices"""
devices = simplesoapy.detect_devices(soapy_args, as_string=True)
text = []
text.append('Detected SoapySDR devices:')
if devices:
for i, d in enumerate(devices):
text.append(' {}'.format(d))
else:
... | 0.002525 |
def to_script(self, wf_name='wf'):
"""Generated and print the scriptcwl script for the currunt workflow.
Args:
wf_name (str): string used for the WorkflowGenerator object in the
generated script (default: ``wf``).
"""
self._closed()
script = []
... | 0.001093 |
def expr_items(expr):
"""
Returns a set() of all items (symbols and choices) that appear in the
expression 'expr'.
"""
res = set()
def rec(subexpr):
if subexpr.__class__ is tuple:
# AND, OR, NOT, or relation
rec(subexpr[1])
# NOTs only have a singl... | 0.001984 |
def delete(self, id):
"""
Deletes document with ID on all Solr cores
"""
for core in self.endpoints:
self._send_solr_command(self.endpoints[core], "{\"delete\" : { \"id\" : \"%s\"}}" % (id,)) | 0.012766 |
def get_tasks(self, list_id, completed=False):
''' Gets tasks for the list with the given ID, filtered by the given completion flag '''
return tasks_endpoint.get_tasks(self, list_id, completed=completed) | 0.013699 |
def target_to_ipv6_long(target):
""" Attempt to return a IPv6 long-range list from a target string. """
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
end_packed = inet_pton(socket.AF_INET6, splitted[1]... | 0.002101 |
def merge_table_records(self, table, record_data, match_column_names):
""" Responsys.mergeTableRecords call
Accepts:
InteractObject table
RecordData record_data
list match_column_names
Returns a MergeResult
"""
table = table.get_soap_object(s... | 0.003953 |
def site_cleanup(sender, action, instance, **kwargs):
"""
Make sure there is only a single preferences object per site.
So remove sites from pre-existing preferences objects.
"""
if action == 'post_add':
if isinstance(instance, Preferences) \
and hasattr(instance.__class__, 'obje... | 0.002981 |
def instantiate(self, parallel_envs, seed=0, preset='default') -> VecEnv:
""" Create vectorized environments """
envs = DummyVecEnv([self._creation_function(i, seed, preset) for i in range(parallel_envs)])
if self.frame_history is not None:
envs = VecFrameStack(envs, self.frame_hist... | 0.008696 |
def update(self, pid, session, **kwargs):
'''taobao.fenxiao.product.update 更新产品
- 更新分销平台产品数据,不传更新数据返回失败
- 对sku进行增、删操作时,原有的sku_ids字段会被忽略,请使用sku_properties和sku_properties_del。'''
request = TOPRequest('taobao.fenxiao.product.update')
request['pid'] = pid
for k, v in... | 0.036347 |
def get_service_display_name(name):
"""
Get the service display name for the given service name.
@see: L{get_service}
@type name: str
@param name: Service unique name. You can get this value from the
C{ServiceName} member of the service descriptors returned by
... | 0.006329 |
def inv(self):
"""In place invert"""
self.v = 1/self.v
tmp = self.v**2
if self.deriv > 1:
self.dd[:] = tmp*(2*self.v*np.outer(self.d, self.d) - self.dd)
if self.deriv > 0:
self.d[:] = -tmp*self.d[:] | 0.007634 |
def convective_adjustment_direct(p, T, c, lapserate=6.5):
"""Convective Adjustment to a specified lapse rate.
Input argument lapserate gives the lapse rate expressed in degrees K per km
(positive means temperature increasing downward).
Default lapse rate is 6.5 K / km.
Returns the adjusted Column... | 0.00707 |
def read_vpcs_stdout(self):
"""
Reads the standard output of the VPCS process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._vpcs_stdout_file:
try:
with open(self._vpcs_stdout_file, "rb") as file:
... | 0.005714 |
def line_intersects_itself(lons, lats, closed_shape=False):
"""
Return ``True`` if line of points intersects itself.
Line with the last point repeating the first one considered
intersecting itself.
The line is defined by lists (or numpy arrays) of points'
longitudes and latitudes (depth is not ... | 0.000726 |
def get_h_distance(self, latlonalt1, latlonalt2):
'''get the horizontal distance between threat and vehicle'''
(lat1, lon1, alt1) = latlonalt1
(lat2, lon2, alt2) = latlonalt2
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)
... | 0.003497 |
def makeWidget(self):
"""
Return a single widget that should be placed in the second tree column.
The widget must be given three attributes:
========== ============================================================
sigChanged a signal that is emitted when the widget's value is c... | 0.001341 |
def _normalize_slice(self, index, pipe=None):
"""Given a :obj:`slice` *index*, return a 4-tuple
``(start, stop, step, fowrward)``. The first three items can be used
with the ``range`` function to retrieve the values associated with the
slice; the last item indicates the direction.
... | 0.001735 |
def serialize(self):
"""Serializes the ExpectAssert object for collection.
Warning, this will only grab the available information.
It is strongly that you only call this once all specs and
tests have completed.
"""
converted_dict = {
'success': self.success,
... | 0.004619 |
def _find_function_from_code(frame, code):
"""
Given a frame and a compiled function code, find the corresponding function object within the frame.
This function addresses the following problem: when handling a stacktrace, we receive information about
which piece of code was being executed in the form ... | 0.007944 |
def _encode_ndef_uri_type(self, data):
"""
Implement NDEF URI Identifier Code.
This is a small hack to replace some well known prefixes (such as http://)
with a one byte code. If the prefix is not known, 0x00 is used.
"""
t = 0x0
for (code, prefix) in uri_identif... | 0.005445 |
def do_xmlattr(_eval_ctx, d, autospace=True):
"""Create an SGML/XML attribute string based on the items in a dict.
All values that are neither `none` nor `undefined` are automatically
escaped:
.. sourcecode:: html+jinja
<ul{{ {'class': 'my_list', 'missing': none,
'id': 'list-%d... | 0.001037 |
def __set_amount(self, value):
'''
Sets the amount of the payment operation.
@param value:float
'''
try:
self.__amount = quantize(Decimal(str(value)))
except:
raise ValueError('Invalid amount value') | 0.01107 |
def AddBatchJob(client):
"""Add a new BatchJob to upload operations to.
Args:
client: an instantiated AdWordsClient used to retrieve the BatchJob.
Returns:
The new BatchJob created by the request.
"""
# Initialize appropriate service.
batch_job_service = client.GetService('BatchJobService', versio... | 0.013972 |
def pubkey(self, identity, ecdh=False):
"""Return public key."""
_verify_support(identity)
data = self.vk.to_string()
x, y = data[:32], data[32:]
prefix = bytearray([2 + (bytearray(y)[0] & 1)])
return bytes(prefix) + x | 0.007519 |
def tshift(self, periods=1, freq=None, axis=0):
"""
Shift the time index, using the index's frequency if available.
Parameters
----------
periods : int
Number of periods to move, can be positive or negative
freq : DateOffset, timedelta, or time rule string, d... | 0.001057 |
def getNodeByName(node, name):
"""
Get the first child node matching a given local name
"""
if node is None:
raise Exception(
"Cannot search for a child '%s' in a None object" % (name,)
)
if not name:
raise Exception("Unspecified name to find node for.")
try:... | 0.004545 |
async def async_connect(self):
"""Connect to the ASUS-WRT Telnet server."""
self._reader, self._writer = await asyncio.open_connection(
self._host, self._port)
with (await self._io_lock):
try:
await asyncio.wait_for(self._reader.readuntil(b'login: '), 9)
... | 0.002088 |
def rndstr(size=16):
"""
Returns a string of random ascii characters or digits
:param size: The length of the string
:return: string
"""
_basech = string.ascii_letters + string.digits
return "".join([rnd.choice(_basech) for _ in range(size)]) | 0.00369 |
def runtime_values(self, **kwargs):
"""
=====API DOCS=====
Context manager that temporarily override runtime level configurations.
:param kwargs: Keyword arguments specifying runtime configuration settings.
:type kwargs: arbitrary keyword arguments
:returns: N/A
... | 0.001522 |
def visit_Operation(self, expression, *operands):
""" constant folding, if all operands of an expression are a Constant do the math """
if all(isinstance(o, Constant) for o in operands):
expression = constant_folder(expression)
if self._changed(expression, operands):
expr... | 0.007692 |
def decipher_atom_key(atom_key, forcefield):
"""
Return element for deciphered atom key.
This functions checks if the forcfield specified by user is supported
and passes the atom key to the appropriate function for deciphering.
Parameters
----------
atom_key : str
The atom key whic... | 0.00085 |
def _speak_as_digits_inherit(self, element):
"""
Speak the digit at a time for each number for element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
self._reverse_speak_as(element, 'digits')
se... | 0.004963 |
def reind_proc(self, inputstring, **kwargs):
"""Add back indentation."""
out = []
level = 0
for line in inputstring.splitlines():
line, comment = split_comment(line.strip())
indent, line = split_leading_indent(line)
level += ind_change(indent)
... | 0.004237 |
def filter(self, destination_object=None, source_object=None, **kwargs):
"""
See ``QuerySet.filter`` for full documentation
This adds support for ``destination_object`` and ``source_object``
as kwargs. This converts those objects into the values necessary
to handle the ``Generi... | 0.0025 |
def add(self, synchronous=True, **kwargs):
"""Add provided Content View Component.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
... | 0.002814 |
def reply_to_request(self, req, rep):
"""
Send a reply for a synchronous request sent by send_request.
The first argument should be an instance of EventRequestBase.
The second argument should be an instance of EventReplyBase.
"""
assert isinstance(req, EventRequestBase)
... | 0.003984 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'class_name') and self.class_name is not None:
_dict['class'] = self.class_name
if hasattr(self, 'score') and self.score is not None:
_dict['score'] = self.scor... | 0.004167 |
def add_molecular_graph(self, molecular_graph, atom_types=None, charges=None, split=True, molecule=None):
"""Add the molecular graph to the data structure
Argument:
| ``molecular_graph`` -- a MolecularGraph instance
Optional arguments:
| ``atom_types`` -- a li... | 0.00382 |
def _logging_env_conf_overrides(log_init_warnings=None):
"""Returns a dictionary that is empty or has a "logging" key that refers to
the (up to 3) key-value pairs that pertain to logging and are read from the env.
This is mainly a convenience function for ConfigWrapper so that it can accurately
repo... | 0.004115 |
def get_db_args_env(self):
"""
Get a dictionary of database connection parameters, and create an
environment for running postgres commands.
Falls back to omego defaults.
"""
db = {
'name': self.args.dbname,
'host': self.args.dbhost,
'us... | 0.001874 |
def from_array(array):
"""
Deserialize a new PassportData from a given dictionary.
:return: new PassportData instance.
:rtype: PassportData
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_nam... | 0.008333 |
def ascii_text(text):
"""Transliterate the given text and make sure it ends up as ASCII."""
text = latinize_text(text, ascii=True)
if isinstance(text, six.text_type):
text = text.encode('ascii', 'ignore').decode('ascii')
return text | 0.003906 |
def magic_string(string, filename=None):
""" Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first
If filename is provided it will be used in the computation.
:param string: string representation to check
:param filename: original filename
:return: list of ... | 0.001543 |
def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value and returns it."""
xml_value = _hooks_apply_before_serialize(self._hooks, state, value)
return self._processor.serialize(x... | 0.011905 |
def create(self):
"""Deploy a cluster on Amazon's EKS Service configured
for Jupyterhub Deployments.
"""
steps = [
(self.create_role, (), {}),
(self.create_vpc, (), {}),
(self.create_cluster, (), {}),
(self.create_node_group, (), {}),
... | 0.003527 |
def triangle_address(fx, pt):
'''
triangle_address(FX, P) yields an address coordinate (t,r) for the point P in the triangle
defined by the (3 x d)-sized coordinate matrix FX, in which each row of the matrix is the
d-dimensional vector representing the respective triangle vertx for triangle [A,B,C]. The... | 0.006211 |
def setup(product_name):
"""Setup logging."""
if CONF.log_config:
_load_log_config(CONF.log_config)
else:
_setup_logging_from_conf()
sys.excepthook = _create_logging_excepthook(product_name) | 0.004505 |
def csi_wrap(self, value, capname, *args):
"""Return a value wrapped in the selected CSI and does a reset."""
if isinstance(value, str):
value = value.encode('utf-8')
return b''.join([
self.csi(capname, *args),
value,
self.csi('sgr0'),
]) | 0.006289 |
def to_vcf(in_tsv, data):
"""Convert seq2c output file into BED output.
"""
call_convert = {"Amp": "DUP", "Del": "DEL"}
out_file = "%s.vcf" % utils.splitext_plus(in_tsv)[0]
if not utils.file_uptodate(out_file, in_tsv):
with file_transaction(data, out_file) as tx_out_file:
with op... | 0.005801 |
def expand_parameters(self, para):
'''
Enumerate all possible combinations of all parameters
para: {key1: [v11, v12, ...], key2: [v21, v22, ...], ...}
return: {{key1: v11, key2: v21, ...}, {key1: v11, key2: v22, ...}, ...}
'''
if len(para) == 1:
for key, value... | 0.002813 |
def get_script_header(script_text, executable=sys_executable, wininst=False):
"""Create a #! line, getting options (if any) from script_text"""
from distutils.command.build_scripts import first_line_re
# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
if not isinstance(first_line_re.pat... | 0.001647 |
def connect_all(self):
"""[Re-]connects all signals and slots.
If already in "connected" state, ignores the call.
"""
if self.__connected:
return # assert not self.__connected, "connect_all() already in \"connected\" state"
with self.__lock:
for ... | 0.005484 |
def GetLocation(location=None,alias=None,session=None):
"""Returns a list of anti-affinity policies within a specific location.
>>> clc.v2.AntiAffinity.GetLocation("VA1")
[<clc.APIv2.anti_affinity.AntiAffinity object at 0x105eeded0>]
"""
if not location: location = clc.v2.Account.GetLocation(session=sessio... | 0.0325 |
def edge_tuple(self, vertex0_id, vertex1_id):
"""To avoid duplicate edges where the vertex ids are reversed,
we maintain that the vertex ids are ordered so that the corresponding
pathway names are alphabetical.
Parameters
-----------
vertex0_id : int
one vertex... | 0.002103 |
def read_register(self, addr, numBytes):
"""Reads @numBytes bytes from the grizzly starting at @addr. Due
to packet format, cannot read more than 127 packets at a time.
Returns a byte array of the requested data in little endian.
@addr should be from the Addr class e.g. Addr.Speed"""
... | 0.003861 |
def exit(self, status=0, message=None):
'''
Argparse expects exit() to be a terminal function and not return.
As such, this function must raise an exception instead.
'''
self.exited = True
self.status = status
if message is not None:
self.outp.printf(... | 0.005155 |
def lovasz_softmax(probas, labels, only_present=False, per_image=False, ignore=None):
"""
Multi-class Lovasz-Softmax loss
probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1)
labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1)
only_present: av... | 0.007407 |
def meta(self, remote_path, **kwargs):
"""获取单个文件或目录的元信息.
:param remote_path: 网盘中文件/目录的路径,必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名... | 0.003175 |
def get_pem_entries(glob_path):
'''
Returns a dict containing PEM entries in files matching a glob
glob_path:
A path to certificates to be read and returned.
CLI Example:
.. code-block:: bash
salt '*' x509.get_pem_entries "/etc/pki/*.crt"
'''
ret = {}
for path in glo... | 0.001745 |
def list_menu(self, options, title="Choose a value", message="Choose a value", default=None, **kwargs):
"""
Show a single-selection list menu
Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)}
@param options: li... | 0.008643 |
def gff(args):
"""
%prog gff *.gff
Draw exons for genes based on gff files. Each gff file should contain only
one gene, and only the "mRNA" and "CDS" feature will be drawn on the canvas.
"""
align_choices = ("left", "center", "right")
p = OptionParser(gff.__doc__)
p.add_option("--align"... | 0.001378 |
def retrieve_crls(self, cert):
"""
:param cert:
An asn1crypto.x509.Certificate object
:param path:
A certvalidator.path.ValidationPath object for the cert
:return:
A list of asn1crypto.crl.CertificateList objects
"""
if not self._all... | 0.002472 |
def read_code_bytes(self, size = 128, offset = 0):
"""
Tries to read some bytes of the code currently being executed.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the program counter to begin reading.
@rty... | 0.011385 |
def pretty_duration(seconds):
""" Returns a user-friendly representation of the provided duration in seconds.
For example: 62.8 => "1m2.8s", or 129837.8 => "2d12h4m57.8s"
"""
if seconds is None:
return ''
ret = ''
if seconds >= 86400:
ret += '{:.0f}d'.format(int(seconds / 86400))... | 0.003106 |
def theme_set(new):
"""
Change the current(default) theme
Parameters
----------
new : theme
New default theme
Returns
-------
out : theme
Previous theme
"""
if (not isinstance(new, theme) and
not issubclass(new, theme)):
raise PlotnineError("... | 0.002257 |
def dict_from_cookiejar(cj):
"""Returns a key/value dictionary from a CookieJar.
:param cj: CookieJar object to extract cookies from.
"""
cookie_dict = {}
for _, cookies in cj._cookies.items():
for _, cookies in cookies.items():
for cookie in cookies.values():
... | 0.002415 |
def step_worker(step, pipe, max_entities):
"""
All messages follow the form: <message>, <data>
Valid messages
--------------
run, <input_data>
finalise, None
next, None
stop, None
"""
state = None
while True:
message, input = pipe.recv()
if message == 'run':
... | 0.002935 |
def subject(self):
""" Normalized subject.
Only used for debugging and human-friendly logging.
"""
# Fetch subject from first message.
subject = self.message.get('Subject', '')
subject, _ = re.subn(r'\s+', ' ', subject)
return subject | 0.006873 |
def earnings(symbol, token='', version=''):
'''Earnings data for a given company including the actual EPS, consensus, and fiscal period. Earnings are available quarterly (last 4 quarters) and annually (last 4 years).
https://iexcloud.io/docs/api/#earnings
Updates at 9am, 11am, 12pm UTC every day
Args:... | 0.003466 |
def add_command_arguments(parser):
"""
Additional command line arguments for the behave management command
"""
parser.add_argument(
'--noinput',
'--no-input',
action='store_const',
const=False,
dest='interactive',
help='Tells Django to NOT prompt the user ... | 0.000779 |
def from_file(cls, db_file=ALL_SETS_PATH):
"""Reads card data from a JSON-file.
:param db_file: A file-like object or a path.
:return: A new :class:`~mtgjson.CardDb` instance.
"""
if callable(getattr(db_file, 'read', None)):
return cls(json.load(db_file))
wi... | 0.004963 |
def get_subdir(index):
"""
Return the sub-directory given the index dictionary. The return
value is obtained in the following order:
1. when the 'subdir' key exists, it's value is returned
2. if the 'arch' is None, or does not exist, 'noarch' is returned
3. otherwise, the return value is const... | 0.001389 |
def delete(self, client=None):
"""Deletes a task from Task Queue.
:type client: :class:`gcloud.taskqueue.client.Client` or ``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the task's taskqueue.
:rtype... | 0.003195 |
def inertia(X,y,samples=False):
""" return the within-class squared distance from the centroid"""
# pdb.set_trace()
if samples:
# return within-class distance for each sample
inertia = np.zeros(y.shape)
for label in np.unique(y):
inertia[y==label] = (X[y==label] - np.mean... | 0.020101 |
def given(self):
"""Given name could include both first and middle name"""
if self._primary.value[0] and self._primary.value[2]:
return self._primary.value[0] + ' ' + self._primary.value[2]
return self._primary.value[0] or self._primary.value[2] | 0.007117 |
def panel_index(time, panels, names=None):
"""
Returns a multi-index suitable for a panel-like DataFrame.
Parameters
----------
time : array-like
Time index, does not have to repeat
panels : array-like
Panel index, does not have to repeat
names : list, optional
List ... | 0.000734 |
def __walk_rec(self, top, rec):
"""
Yields each subdirectories of top, doesn't follow symlinks.
If rec is false, only yield top.
@param top: root directory.
@type top: string
@param rec: recursive flag.
@type rec: bool
@return: path of one subdirectory.
... | 0.003731 |
def new_format(self, navbar: BeautifulSoup, content: BeautifulSoup) -> List[str]:
"""
Extracts email message information if it uses the new Mailman format
Args:
content: BeautifulSoup
Returns: List[str]
"""
sender = content.find(id='from').text.spli... | 0.007477 |
def forward(self, # pylint: disable=arguments-differ
text_field_input: Dict[str, torch.Tensor],
num_wrapping_dims: int = 0) -> torch.Tensor:
"""
Parameters
----------
text_field_input : ``Dict[str, torch.Tensor]``
A dictionary that was the out... | 0.010456 |
def _process_transform(self, data, transform, step_size):
'''
Process transforms on the data.
'''
if isinstance(transform, (list,tuple,set)):
return { t : self._transform(data,t,step_size) for t in transform }
elif isinstance(transform, dict):
return { tn : self._transform(data,tf,step_s... | 0.046341 |
def sync(self):
"""
Syncs the parent app changes with the current app instance.
:return: Synced App object.
"""
app = self._api.post(url=self._URL['sync'].format(id=self.id)).json()
return App(api=self._api, **app) | 0.007634 |
def find_local_uuid(tw, keys, issue, legacy_matching=False):
""" For a given issue issue, find its local UUID.
Assembles a list of task IDs existing in taskwarrior
matching the supplied issue (`issue`) on the combination of any
set of supplied unique identifiers (`keys`) or, optionally,
the task's ... | 0.000329 |
def _create_w_objective(m, X, R):
"""
Creates an objective function and its derivative for W, given M and X (data)
Args:
m (array): genes x clusters
X (array): genes x cells
R (array): 1 x genes
"""
genes, clusters = m.shape
cells = X.shape[1]
R1 = R.reshape((genes, ... | 0.004776 |
def from_netcdf(filename):
"""Initialize object from a netcdf file.
Expects that the file will have groups, each of which can be loaded by xarray.
Parameters
----------
filename : str
location of netcdf file
Returns
-------
InferenceData obj... | 0.004777 |
def to_call(self, func, *args, **kwargs):
"""
Sets the function & its arguments to be called when the task is
processed.
Ex::
task.to_call(my_function, 1, 'c', another=True)
:param func: The callable with business logic to execute
:type func: callable
... | 0.003279 |
def copy_node(node):
"""Makes a copy of a node with the same attributes and text, but no children."""
element = node.makeelement(node.tag)
element.text = node.text
element.tail = node.tail
for key, value in node.items():
element.set(key, value)
return element | 0.006849 |
def function(script, x_func='x', y_func='y', z_func='z'):
"""Geometric function using muparser lib to generate new Coordinates
You can change x, y, z for every vertex according to the function specified.
See help(mlx.muparser_ref) for muparser reference documentation.
It's possible to use the followin... | 0.002812 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.