content stringlengths 42 6.51k |
|---|
def _get_bot_coverage_list(sorted_infos, thresholds):
"""
generate the list of bot coverage ratio and bot coverage counts
based on the list of thresholds
:param sorted_infos:
:param thresholds:
:return:
"""
tol = len(sorted_infos)
cur_bot_coverage = tol
bot_coverage_count_list = ... |
def readbytes(path):
"""Read binary from file.
"""
with open(path, "rb") as f:
return f.read() |
def strip_epoch(nvr: str):
"""
If an NVR string is N-V-R:E, returns only the NVR portion. Otherwise
returns NVR exactly as-is.
"""
return nvr.split(':')[0] |
def galileo_nav_decode(dwrds: list) -> dict:
"""
Helper function to decode RXM-SFRBX dwrds for GALILEO navigation data.
:param list dwrds: array of navigation data dwrds
:return: dict of navdata attributes
:rtype: dict
"""
return {"dwrds": dwrds} |
def rivers_with_stations(stations):
"""This returns a list of all the rivers which have monitoring stations on them"""
rivers = []
for s in stations:
if s.river not in rivers:
rivers.append(s.river)
return rivers |
def any_scores_greater_than_one(scores):
"""Check if there are enough scores for KDE
If there are more than scores for at least one user,
we plot the density estimate of scores
"""
for score in scores:
if len(score) > 1:
return True
return False |
def validate_update_parcel_admin_status(parcel, data):
""" this funtion validates the updated parcel data """
# Check for empty status
if data['status'] == '':
data['status'] = parcel['status']
# check for valid status
if data['status'].strip(' ').isdigit():
return {'warning': ... |
def hex_16bit(value):
"""Converts 16bit value into bytearray.
args:
16bit value
returns:
bytearray of size 2
"""
if value > 0xffff or value < 0:
raise Exception('Sar file 16bit value %s out of range' % value)
return value.to_bytes(2, 'little') |
def vnesi_none(tab):
"""
Elemente, kjer nastopa prazen niz zamenja z None in vrne novo popravljeno tabelo.
"""
nova_tab = [el if el != '' else None for el in tab]
return nova_tab |
def commify(n):
"""
Add commas to an integer n.
>>> commify(1)
'1'
>>> commify(123)
'123'
>>> commify(1234)
'1,234'
>>> commify(1234567890)
'1,234,567,890'
>>> commify(123.0)
'123.0'
>>> commify(1234.5)
'1,234.5'
>>> commify(1234.56789)
'1,234.56789'
... |
def value2bool(d):
"""
Convert specific string values to boolean (input: dict, output: dict)
'true' to True and 'false' to False
"""
for k,v in d.items():
if v.lower() == 'true':
d[k] = True
elif v.lower() == 'false':
d[k] = False
return d |
def _green_ampt_infiltration_rate(F, psi, eff_theta, eff_sat, K):
"""Compute the Green-Ampt infiltration rate
Compute the infiltration rate using the Green-Ampt cumulative
infiltration.
Parameters
----------
F : scalar
The cumulative infiltration for the time-period.
psi : scalar
... |
def warn_config_absent(sections, argument, log_printer):
"""
Checks if the given argument is present somewhere in the sections and emits
a warning that code analysis can not be run without it.
:param sections: A dictionary of sections.
:param argument: The argument to check for, e.g. "files".... |
def __isFloatType__(obj):
"""
Returns true if the obj is a float
"""
return isinstance(obj, float) |
def get_attribute_from_dict(dictionary, keyword, default_value=''):
"""Get value from a dictionary if the dictionary exists.
:param dictionary: 'dict' with the elements
:param keyword: attributes that correspond to a key in the dict
:param default_value: The default value returned if the dictionary doe... |
def get_factorial(x):
"""
Computes factorial of x
:param x: int
:return: int
"""
if x < 0:
raise ValueError("Input must be positive, but {} was given")
factorial = 1
for value in range(1, x + 1):
factorial *= value
return factorial |
def to_seconds(t):
"""
Convert length of time in m:s.d format into seconds
e.g. to_seconds('1:15.2') -> 75.2
"""
m, s = t.split(':')
seconds = int(m) * 60 + float(s)
return seconds |
def format_time(time):
""" Formats the given time into HH:MM:SS. """
hours, remainder = divmod(time / 1000, 3600)
minutes, seconds = divmod(remainder, 60)
if hours:
return '%02dh %02dm %02ds' % (hours, minutes, seconds)
if minutes:
return '%02dm %02ds' % (minutes, seconds)
... |
def get_optional_height_names(num=4):
"""Get list of possible column names for optional extrapolation. (of form Ane_WS_Ht1, for example)
Parameters
----------
num : int
number of possible Additional Comparison Heights
Returns
-------
list
list of allowed names
"""
o... |
def check_if_bst(root, min, max):
"""Given a binary tree, check if it follows binary search tree property
To start off, run `check_if_bst(BT.root, -math.inf, math.inf)`"""
if root == None:
return True
if root.key < min or root.key >= max:
return False
return check_if_bst(root.left,... |
def _insert_automodapi_configs(c):
"""Add configurations related to automodapi, autodoc, and numpydoc to the
state.
"""
# Don't show summaries of the members in each class along with the
# class' docstring
c["numpydoc_show_class_members"] = False
c["autosummary_generate"] = True
c["aut... |
def findin(item, list):
"""
Find C{item} in C{list}.
"""
try:
return list.index(item)
except ValueError:
# x not in list
return -1 |
def table_name(board):
""" Table name for board 'board' """
return "idx_" + board |
def fibonacci(i):
"""Get i-th number from Fibonacci Series.
| 1 if i = 0
F(i) = { 2 if i = 1
| F(i - 1) + F(i - 2) if i >= 2
"""
if i == 0:
return 1
elif i == 1:
return 2
else:
f_minus_1 = 2
f_minus_2 = 1
for j in range(i - 2):
... |
def concat_string(target, msg=[], delimiter="", last=""):
"""
Concatenate a series of strings to the end of the target
Delimiter is optional filler between items
:param target:
:param msg:
:return: target
"""
result = target
for m in msg[:-1]:
result = result + m + delimite... |
def is_inside_tag(tag):
""" Simple helper """
return tag.startswith('I-') |
def split_into_integers(coordinate):
"""Get individual parts of a float and transform into integers
:coordinate: float value
:returns: list of integers
"""
return list(map(int, str(coordinate).split('.'))) |
def _filterData(data):
"""See method filterData().
Args:
data (dict); return value of the method fetchAppDetails()
Returns:
filtered data
"""
filtered = {}
appid = ''
for key in data:
appid = key
break
shorcut = data[appid]['data']
filtered['appid']... |
def combine_adjacent(arr):
"""Sum like signed adjacent elements
arr : starting array
Returns
-------
output: new summed array
indexes: indexes indicating the first
element summed for each group in arr
"""
output, indexes = [], []
curr_i = 0
while len(arr) > 0:
... |
def filter_debt_to_income(monthly_debt_ratio, bank_list):
"""Filters the bank list by the maximum debt-to-income ratio allowed by the bank.
Args:
monthly_debt_ratio (float): The applicant's monthly debt ratio.
bank_list (list of lists): The available bank loans.
Returns:
A list of ... |
def is_list_or_tuple(obj) -> bool:
""" Checks whether an object is a list or a tuple"""
if isinstance(obj, (list, tuple)):
return True
else:
return False |
def _hyperparameters_to_cmd_args(hyperparameters):
"""
Converts our hyperparameters, in json format, into key-value pair suitable for passing to our training
algorithm.
"""
cmd_args_list = []
for key, value in hyperparameters.items():
cmd_args_list.append("--{}".format(key))
cmd... |
def pipeline(data, funcs):
"""
Pipes *functions* onto a given *data*, where the result
of the previous function is fed to the next function.
"""
for func in funcs:
data = func(data)
return data |
def get_ovs_dpdk_cfg(k8s_conf):
"""
Returns ovs_dpdk enablement choice
:return: true/false
"""
if k8s_conf.get('enable_ovs_dpdk') :
return k8s_conf['enable_ovs_dpdk'] |
def unit_vector(v):
"""Return the unit vector of the points
v = (a,b)"""
h = ((v[0] ** 2) + (v[1] ** 2)) ** 0.5
if h == 0:
h = 0.000000000000001
ua = v[0] / h
ub = v[1] / h
return (ua, ub) |
def getGlideinCpusNum(glidein):
"""
Given the glidein data structure, get the GLIDEIN_CPUS configured.
If GLIDEIN_CPUS is not configured or is set to auto, ASSUME it to be 1
"""
glidein_cpus = 1
cpus = str(glidein['attrs'].get('GLIDEIN_CPUS', 1))
if cpus.upper() == 'AUTO':
glidein_cpus =... |
def convert_seconds_to_human_readable_form(seconds: int) -> str:
"""Convert seconds to human readable time format, e.g. 02:30
**Keyword arguments:**
- seconds (int) -- Seconds to convert
**Returns:**
Formatted string
"""
if seconds <= 0:
return "00:00"
minutes = int(seconds ... |
def hex2rgb(hexstr):
"""Converts a hex "#rrggbb" color string code to a tuble of (r,g,b)"""
if not isinstance(hexstr, str):
raise ValueError('I was expecting a string with the hex code color')
if hexstr[0] is not '#':
raise ValueError('Invalid hex color code: missing "#" at the begining')
if len(hexstr) is not ... |
def getDomainFromFP(fp):
""" Returns domain number from file path """
path, fileInfo = fp.split("LSBU_") #split returns ["/user/.../data/subdomain_8/LSBU", "<timestep>_<subdomain>.vtu"]
timestep, domain = fileInfo.split("_")
return domain[:-4] |
def ParseRegisterNotices(notices):
"""Parses registration notices.
Args:
notices: list of notices (lowercase-strings).
Returns:
Pair (public privacy ack: bool, hsts ack: bool).
"""
if not notices:
return False, False
return 'public-contact-data-acknowledgement' in notices, 'hsts-preloaded' in ... |
def find_string_anagrams(s, pattern):
"""Find all anagrams of pattern in the given string, s.
>>> find_string_anagrams("ppqp", "pq")
[1, 2]
>>> find_string_anagrams("abbcabc", "abc")
[2, 3, 4]
"""
results = []
k = len(pattern)
if k > len(s):
return results
counts = {}... |
def vectorproduct(a,b):
"""
Return vector cross product of input vectors a and b
"""
a1, a2, a3 = a
b1, b2, b3 = b
return [a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1] |
def colorize(value: str, is_warning: bool) -> str:
"""
Utility to set a color for the output string when it exceeds the threshold.
Args:
value: String to be output.
is_warning: Whether it exceeds the threshold.
Returns:
colorized string output
"""
if is_warning:
... |
def strahler_stream_order(start_arc_id, start_up_node,
nodes_per_arc, arcs_per_node, stream_orders):
"""Calculate the Strahler stream order
This function recursively computes the Strahler stream order using
the algorithm described by Gleyzer et al. (2004). The sequence of
stre... |
def sample_service(name=None):
"""
This is a sample service. Give it your name
and prepare to be greeted!
:param name: Your name
:type name: basestring
:return: A greeting or an error
"""
if name:
return { 'hello': name}
else:
return {"error": "what's your name?"} |
def eir_to_rate(match_to, compounds):
"""
"""
return (match_to + 1) ** (1 / compounds) - 1 |
def has_callables(iterable):
"""
A function used to determine if an iterable contains at least one callable.
"""
for item in iterable:
if callable(item):
return True
return False |
def squeeze_list(listA, val=-1):
""" Compact a list of lists into a single list.
Squeezes (spaghettify) a list of lists into a single list.
The lists are concatenated into a single one, and to separate
them it is used a separating value to mark the split location
when unsqueezing the list.
Par... |
def get_rgb_from_value(n):
""" Bins and some bit shifting """
if n < 2:
k = 0xFF0000
elif n < 4:
k = 0xFFFF00
elif n < 8:
k = 0x009900
elif n < 32:
k = 0x0080FF
elif n < 128:
k = 0x00FFFF
else:
k = 0xFFFFFF
R = (k & 0xFF0000) >> 16
G = (k & 0x00FF00) >> 8
B = (k & 0x0000FF)
return (R, G, B) |
def base16encode(string, layer = 1, upper = False):
"""
>>> base16encode("string")
'737472696e67'
"""
from binascii import hexlify
if(layer > 0):
res = base16encode(
hexlify(string.encode('UTF-8')).decode(),
layer - 1,
upper)
if(upp... |
def simple_closure(s, implications):
"""
Input: A set of implications and an attribute set s
Output: The closure of s with respect to implications
Examples
========
>>> from fca.implication import Implication
>>> cd2a = Implication(set(('c', 'd')), set(('a')))
>>> ad2c = Impli... |
def config_bool(value):
"""Represent a boolean in a way compatible with configparser."""
return "true" if value else "false" |
def serialize_header(value, style='simple', explode=False): # noqa
"""
Serialize a header according to https://swagger.io/docs/specification/serialization/.
Parameters
----------
value :
Value to serialize
style : str ('simple')
Serialization style.
explode : bool
E... |
def encode(string):
"""
Encode the string
"""
result, index = "", 0
while index < len(string):
count, j = 1, index + 1
while j < len(string) and string[j] == string[index]:
count += 1
j += 1
if count > 1:
result += str(count) + string[i... |
def leading_num_key(s):
"""Keys for sorting strings, based on leading multidigit numbers.
A normal string comparision will compare the strings character by
character, e.g., "101P" is less than "1P" because "0" < "P".
`leading_num_key` will generate keys so that `str.sort` can
consider the leading m... |
def is_email(token):
"""
Return True for e-mails. Very rough, some other words for instance duygu@SonyCenter return True as well.
However, most probably one doesn't want to process that token types anyway.
Args:
token: single token
Returns:
Booelan
Raises:
None
Examp... |
def dragon_step(a):
"""
Call the data you have at this point "a".
Make a copy of "a"; call this copy "b".
Reverse the order of the characters in "b".
In "b", replace all instances of 0 with 1 and all 1s with 0.
The resulting data is "a", then a single 0, then "b".
"""
b = a[::-1]
b =... |
def filter_errors(e, select=None, ignore=None, **params):
""" Filter a erros by select and ignore options.
:return bool:
"""
if select:
for s in select:
if e['text'].startswith(s):
return True
if ignore:
for s in ignore:
if e['text'].starts... |
def to_tuple(param, low=None, bias=None):
"""Convert input argument to min-max tuple
Args:
param (scalar, tuple or list of 2+ elements): Input value.
If value is scalar, return value would be (offset - value, offset + value).
If value is tuple, return value would be value + offse... |
def to_int(s, default=0):
"""
Return input converted into an integer. If failed, then return ``default``.
Examples::
>>> to_int('1')
1
>>> to_int(1)
1
>>> to_int('')
0
>>> to_int(None)
0
>>> to_int(0, default='Empty')
0
... |
def wrap_string_in_list(maybe_string):
""" This function checks if maybe_string is a string (or anything derived
from str). If so, it wraps it in a list.
The motivation for this function is that some functions return either a
single string or multiple strings as a list. The return value of ... |
def _extended_gcd(a, b):
"""
Division in integers modulus p means finding the inverse of the
denominator modulo p and then multiplying the numerator by this
inverse (Note: inverse of A is B such that A*B % p == 1) this can
be computed via extended Euclidean algorithm
http://en.wikipedia.org/wiki... |
def _normalize(obj):
"""
Normalize dicts and lists
:param obj:
:return: normalized object
"""
if isinstance(obj, list):
return [_normalize(item) for item in obj]
elif isinstance(obj, dict):
return {k: _normalize(v) for k, v in obj.items() if v is not None}
elif hasattr(o... |
def get_basis(vectors, vector_num, vector_len):
"""Get vectors basis
Args:
vectors (:obj:`list` of :obj:`int`): The list of
vectors.
vector_num (int): The number of vectors in the list.
vector_len (int): The length of vectors in the list.
Returns:
:rtype: (:obj:... |
def value_to_string(val, precision=3):
"""
Convert a number to a human readable string.
"""
if (not isinstance(val, float)) or (val == 0):
text = str(val)
elif (abs(val) >= 10.0**(precision)) or \
(abs(val) <= 10.0**(-precision)):
text = "{val:.{prec}e}".format(val=val, prec... |
def quotes(q):
"""Allows user to specify if they want pdfcp() to automatically add quotes
to both sides of copied pdf text in addition to removing line breaks
while pdfcp() is running.
Parameters
----------
q : str ("y" or "")
Quote append option user input spe... |
def GetTickTexts(ticks):
""" GetTickTexts(ticks)
Get tick labels of maximally 9 characters (plus sign char).
All ticks will be formatted in the same manner, and with the same number
of decimals. In exponential notation, the exponent is written with as
less characters as possible, leaving ... |
def parse_room_config(config):
"""
This method provides backwards compatibility with the previous room
list as dict format by transforming dicts like `{"main": "#myroom:matrix.org"}` into
`{"main": {"alias": "#myroom:matrix.org"}}`.
"""
new_rooms = {}
for name, room in config["rooms"].items(... |
def fade_copies_left(s):
""" Returns the string made by concatenating `s` with it's left slices of
decreasing sizes.
Parameters
----------
s : string
String to be repeated and added together.
Returns
-------
output : string
String after it has had ever decreasing slice... |
def trsplit(trin):
"""Split data segments with marked gaps"""
rc = trin.split()
return rc |
def check_bad_next_streams(stream_array):
"""
make sure all next streams in list are within current stream
"""
# loop through all but last
streams_indexes = range(0, len(stream_array) - 1)
for i in streams_indexes:
if stream_array[i + 1][0] > stream_array[i][1]:
ret... |
def indentify(stuff, rep = 1, indent = '\t'):
""" From http://code.activestate.com/recipes/66055-changing-the-indentation-of-a-multi-line-string/#c4 """
lines = [(rep * indent) + line for line in stuff.splitlines()]
return "\n".join(lines) |
def is_urllib_network_error(exc: BaseException) -> bool:
"""Is the provided exception from urllib a network-related error?
This should be passed an exception which resulted from opening or
reading a urllib Request. It returns True for any errors that could
conceivably arise due to unavailable/poor netw... |
def relu_grad(z):
"""
Relu derivative.
g'(z) = 0 if g(z) <= 0
g'(z) = 1 if g(z) > 0
"""
return 1*(z > 0) |
def get_tasks(boards: dict) -> dict:
"""
Take boards dictionaries and return tasks dictionaries.
Extract tasks dictionary from the all boards and merge them all together.
Args:
----
boards (dict): A dictionary containing dictionaries of all the boards.
Returns
-------
A di... |
def rm_party(senators, party):
""" remoe party if no senator in the party
"""
if senators[party] == 0: del senators[party]
return senators |
def find_odd_occurred_number_sol2(nums):
"""
You are given an array of repeating numbers. All numbers repeat in even way, except for
one. Find the odd occurring number.
- This solution takes less space.
- More details: https://youtu.be/bMF2fG9eY0A
- Time: O(len(nums))
- Space: worst: O(len... |
def check_node(left, right) -> int:
"""
Count 1 for each node found.
(Unpacking directly in the parameters is faster)
"""
return 1 if left is None else 1 + check_node(*left) + check_node(*right) |
def generate_managed_policy(resource_name: str, permissions):
"""Generate an IAM Managed Policy resource"""
return {
resource_name: {
"Type": "AWS::IAM::ManagedPolicy",
"Properties": {
"PolicyDocument": {"Version": "2012-10-17", "Statement": permissions}
... |
def integerize(value):
"""Convert value to integer.
Args:
value: Value to convert
Returns:
result: Value converted to iteger
"""
# Try edge case
if value is True:
return None
if value is False:
return None
# Try conversion
try:
result = int... |
def spo2SignleMeasurementHandler(data):
"""
For get this answer need to sent AB 05 FF 31 11 00 FF
"""
# Only for testing - no detailed parsing, just form answer
return bytearray([0xAB, 0x04, 0xFF, 0x31, 0x11, 0x22])
pass |
def find_method_label(method, local_align_method=None, srm_components=0,
srm_atlas=None, atlas_name="", ha_radius=5,
ha_sparse_radius=3, smoothing_fwhm=6):
"""
Creates a 'method_label' string, used in naming output files with
derived results. Ensures that all poss... |
def reduce_file_select_results(results):
"""Reduces a list of file select results to a single determining result."""
for (result, test), _rule in reversed(results):
if result is not None:
return result, test
return None, None |
def index(mask: int) -> int:
""": indexw { mask n k n-k+1 index }
1 dup 2dup to n to k to n-k+1 to index
1 0 mask
begin dup while 1 and
if dup index + to index
swap n * k / swap n * k 1 + dup to k /
else over + swap n * n-k+1 dup 1 + to n-k+1 / swap then
n 1 ... |
def booleanize(value):
"""
Convert a string to a boolean.
:raises: ValueError if unable to convert.
:param str value: String to convert.
:return: True if value in lowercase match yes, true, or False if no or
false.
:rtype: bool
"""
valuemap = {
'true': True,
'yes'... |
def replace_all(text, replace_dict):
"""
Replace multiple strings in a text.
.. note::
Replacements are made successively, without any warranty on the order \
in which they are made.
:param text: Text to replace in.
:param replace_dict: Dictionary mapping strings to replace with ... |
def iou_score(bbox1, bbox2):
"""Jaccard index or Intersection over Union.
https://en.wikipedia.org/wiki/Jaccard_index
"""
assert len(bbox1) == 4
assert len(bbox2) == 4
s1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
s2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
intersection_... |
def make_required_test_packages():
"""Prepare extra packages needed for 'python setup.py test'."""
return [
'apache-airflow>=1.10,<2',
'docker>=4.0.0,<5.0.0',
# LINT.IfChange
'kfp>=0.1.30,<0.2; python_version >= "3.0"',
# LINT.ThenChange(
# testing/github/common.sh,
# ... |
def flatten(elements):
"""Flatten a collection of collections"""
if isinstance(elements, list):
return [item for element in elements for item in flatten(element)]
elif isinstance(elements, dict):
return flatten(list(elements.values()))
else:
return [elements] |
def flatten_list(tier_list):
"""
Given a list of lists, this returns a flat list of all items.
:params list tier_list: A 2D list.
:returns: A flat list of all items.
"""
if tier_list is None:
return []
flat_list = [item for sublist in tier_list for item in sublist]
return flat_... |
def oppositeColour(colour):
""" Returns the opposite colour to that given """
if colour == "RED":
return "BLUE"
elif colour == "BLUE":
return "RED"
else:
return "NONE" |
def most_recent_unbanned(booru_results):
"""
Get the first booru post from an artist that isn't banned.
That's because posts from banned artists don't have the id field.
:param booru_results: List<dict>: A list of booru results.
:return: dict: The first booru result that is not banned.
"""
f... |
def set_abort_status(status):
"""Terminate MPI execution environment at Python exit.
Terminate MPI execution environment at Python exit by calling
``MPI.COMM_WORLD.Abort(status)``. This function should be called
within an ``except`` block. Afterwards, exceptions should be
re-raised.
"""
imp... |
def remote_resources_data_to_metax(resources):
"""
Converts external resources from qvain light schema to metax schema.
Arguments:
data {object} -- External resources.
Returns:
object -- Object containing external resources array that complies with Metax schema.
"""
metax_remo... |
def vector_multiply(vector_in, scalar):
""" Multiplies the vector with a scalar value.
This operation is also called *vector scaling*.
:param vector_in: vector
:type vector_in: list, tuple
:param scalar: scalar value
:type scalar: int, float
:return: updated vector
:rtype: tuple
""... |
def fans(shape):
"""Returns fan_in and fan_out according to the shape.
Assumes the len of shape is 2 or 4.
"""
assert(len(shape) == 2 or len(shape) == 4)
if len(shape) == 2:
return shape[0], shape[1]
else:
S = shape[0] * shape[1]
return S * shape[2], S * shape[3] |
def split_command(command):
"""
:param command: the command introduced by the user
:return: the command word and command parameters
"""
tokens = command.split(maxsplit=1) # splits the input in the command word and command parameters
command_word, command_params = None, None
command_... |
def stretch_array(data, newlength):
"""Stretch an array to a new length."""
oldlength = len(data)
assert oldlength <= newlength, "Can't shrink in stretch function"
factor = float(newlength) / float(oldlength)
result = bytearray(newlength)
i = 0
offset = 0.0
for byte in data:
of... |
def group_codon_usages_by_ids(codon_usages, ids, field='GeneId'):
"""Sorts codon usages into 2 lists: non-matching and matching ids."""
result = [[],[]]
for c in codon_usages:
result[getattr(c, field) in ids].append(c)
return result |
def search_codetree_isleftsub(tword,codetree):
""" Stored in codetree having any value terminal node (i.e., reaching terminal node)
"""
pos = 0
while True:
s = tword[pos]
if s not in codetree:
return 0
elif pos==len(tword)-1:
return 1
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.