content
stringlengths 42
6.51k
|
---|
def str2bool(value):
"""Convert a string into boolean.
:Parameters:
* **value** (:obj:`str`): Value to be converted to boolean.
:Example:
>>> pycof.str2bool('true')
... True
>>> pycof.str2bool(1)
... True
>>> pycof.str2bool(0)
... False
:Returns:
* :obj:`bool`: Returns either True or False.
"""
return str(value).lower() in ("yes", "y", "true", "t", "1")
|
def pointer_top(body_output, targets, model_hparams, vocab_size):
"""Like identity_top() with is_pointwise annotation."""
del targets, model_hparams, vocab_size # unused arg
return body_output
|
def make_coffee(resources, menue, drink):
"""make a coffee and deduct from the resources"""
resources['water'] -= menue[drink]['ingredients']['water']
resources['coffee'] -= menue[drink]['ingredients']['coffee']
if drink != 'espresso':
resources['milk'] -= menue[drink]['ingredients']['milk']
print(f"Here is your {drink}. Enjoy!")
return resources
|
def pay_excess(principal, minimum, remainder):
"""Pay any excess remaining after making minimum payments."""
excess = remainder
if principal - excess <= 0:
excess = principal
remainder = remainder - principal
else:
remainder = 0
return principal - excess, minimum + excess, remainder
|
def ktoe_to_twh(ktoe):
"""Conversion of ktoe to TWh
Arguments
----------
ktoe : float
Energy demand in ktoe
Returns
-------
data_gwh : float
Energy demand in TWh
Notes
-----
https://www.iea.org/statistics/resources/unitconverter/
"""
data_twh = ktoe * 0.01163
return data_twh
|
def ExtractWordsFromLines(lines):
"""Extract all words from a list of strings."""
words = set()
for line in lines:
for word in line.split():
words.add(word)
return words
|
def _munge_node_attribute(node, attribute='name'):
"""Munge node attribute."""
if node.get(attribute) is None:
return str(node)
else:
return node.get(attribute)
|
def Fib(n):
"""Return the n-th Fibonacci number."""
assert type(n) is int and n >= 0, "ERROR (Fib): index should be positive and integer!"
return Fib(n-1) + Fib(n-2) if n > 1 else 1 if n is 1 else 0
|
def merge(intervals):
"""
intervals: list of tuples representing context windows
"""
ans = []
i = 1
intervals.sort()
tempans = intervals[0]
while i < len(intervals):
# seeing if context windows overlap with each other - if they do merge them together
if tempans[0] <= intervals[i][1] and tempans[1] >= intervals[i][0]:
newtempans = [min(tempans[0] , intervals[i][0]) , max(tempans[1] , intervals[i][1])]
tempans = newtempans
i += 1
else:
ans.append(tempans)
tempans = intervals[i]
i += 1
ans.append(tempans)
return ans
|
def strip_suffix(s, suffix):
"""Remove suffix frm the end of s
is s = "aaa.gpg" and suffix = ".gpg", return "aaa"
if s is not a string return None
if suffix is not a string, return s
:param str s: string to modify
:param str suffix: suffix to remove
:rtype: Optional[str]=None
"""
if not isinstance(s, str):
return None
if not isinstance(suffix, str):
return s
if s.endswith(suffix):
return s[: -len(suffix)]
return s
|
def useful_tokens(tokens):
"""Gets rid of noise, where possible. Currently just removes 'AUTO CR - LOG SUMMARY' lines"""
ret_tokens = []
lines = {}
for token in tokens:
line_key = (token['line_num'], token['par_num'], token['block_num'])
if line_key not in lines:
lines[line_key] = []
lines[line_key].append(token)
for pos, toks in lines.items():
line_text = ' '.join([t['text'] for t in toks if t['text']])
if line_text.startswith('AUTO CR - LOG SUMMARY'):
continue
if line_text.startswith('CPD 00'):
continue
for tok in toks:
ret_tokens.append(tok)
return ret_tokens
|
def human_tidy(agents, self_state, self_name, cube, box):
"""
@semantic_name:
@param agents:
@param self_state:
@param self_name:
@param cube:
@return:
@ontology_type cube: Cube
"""
return [("human_pick_cube", cube), ("human_drop_cube", box)]
|
def num_of_indels(locus):
"""Count number of indels at end sequence,
and return number of bps to trim from end"""
indels = 0
for ind in locus:
ind = ind.split()
#check if sequence ends with gaps
if ind[1].endswith('-'):
#Reverse sequence and count number of '-'s
seq = ind[1][::-1]
for i in range(len(seq)):
if seq[i] == '-':
continue
else:
#first time we encounter a valid bp
if i > indels:
indels = i
break
else:
break
return indels
|
def subscription_update_request_feedback(flag):
"""
The subscription message sent to the person requesting pausing or restarting the subscription.
:param flag: True, means subscription should be made active, False, means subscription should be made inactive.
None, means there was some error.
:return: subscription message
"""
if flag is None:
subscription_message = \
"We were unable to update your subscription. We are working to fix this up. Sorry, says the Zombie."
elif flag:
subscription_message = \
"Welcome back! Your subscription has been restarted. Best of luck answering questions."
else:
subscription_message = \
"Your subscription has been paused. \n" \
"For each day your subscription is inactive, you lose 10 karma points"
return subscription_message
|
def _ecmaCodeTableCoordinate(column, row):
"""
Return the byte in 7- or 8-bit code table identified by C{column}
and C{row}.
"An 8-bit code table consists of 256 positions arranged in 16
columns and 16 rows. The columns and rows are numbered 00 to 15."
"A 7-bit code table consists of 128 positions arranged in 8
columns and 16 rows. The columns are numbered 00 to 07 and the
rows 00 to 15 (see figure 1)."
p.5 of "Standard ECMA-35: Character Code Structure and Extension
Techniques", 6th Edition (December 1994).
"""
# 8 and 15 both happen to take up 4 bits, so the first number
# should be shifted by 4 for both the 7- and 8-bit tables.
return bytes(bytearray([(column << 4) | row]))
|
def freq_in_doc(word, doc_bow):
"""
Returns the number of iterations of a given word in a bag of words.
"""
return doc_bow.get(word, 0)
|
def _flatten_keys(key_seq):
"""returns a flat list of keys, i.e., ``('foo', 'bar')`` tuples, from
a nested sequence.
"""
flat_keys = []
for key in key_seq:
if not isinstance(key, tuple):
flat_keys += _flatten_keys(key)
else:
flat_keys.append(key)
return flat_keys
|
def cnf_paths_from_locs(cnf_fs, cnf_locs):
""" Get paths
"""
cnf_paths = []
if cnf_locs:
for locs in cnf_locs:
cnf_paths.append(cnf_fs[-1].path(locs))
return cnf_paths
|
def score_substitute(a_c1, a_c2):
"""Score substitution of two characters.
Args:
a_c1 (str): first word to compare
a_c2 (str): second word to compare
Returns:
int: 2 if the last characters of both words are equal, -3 otherwise
"""
return 2 if a_c1[-1] == a_c2[-1] else -3
|
def countNodes(root):
"""
Parameters
----------
root :
Returns
-------
"""
if root is None:
return 0
return countNodes(root.lesser) + countNodes(root.greater) + 1
|
def import_class(name):
"""
Import a class a string and return a reference to it.
THIS IS A GIANT SECURITY VULNERABILITY.
See: http://stackoverflow.com/questions/547829/how-to-dynamically-load-a-python-class
"""
if not isinstance(name, str):
return name
package = ".".join(name.split(".")[: - 1])
class_name = name.split(".")[ - 1]
mod = __import__(package, fromlist=[class_name])
return getattr(mod, class_name)
|
def default_medication():
"""Generate default medication features.
Used in case a patient has a missing medication.
"""
return {
'count': 0,
'boolean': False,
}
|
def get_consensus_through_voting(seq1, weight1, seq2, weight2):
"""
Use majority vote. This is a temporary replacement for get_consensus_through_pbdagcon()
since I don't want to deal with dependency right now.
"""
#pdb.set_trace()
if weight1 > weight2: return seq1
else: return seq2
|
def find_header_index(lines):
"""returns a position to insert an header into a file (just before the first header, if it exists, or on the first line)"""
for i,line in enumerate(lines):
if line.startswith("#include"):
return i
return 0
|
def add_helpfulness(row):
"""
Add helpfulness scores and ratio as separate variables to a row
:param row: A python dict containing data for a single review
:return: A python dict containing the original data plus the number of users
that rated this review as helpful, the total votes received by the review,
and the ratio between the two. Reviews with no ratings have a NaN ratio
"""
helpful_pos = row['helpful'][0]
helpful_tot = row['helpful'][1]
helpful_ratio = helpful_pos / helpful_tot if helpful_tot else float("NaN")
row.update({
'helpful_pos': helpful_pos,
'helpful_tot': helpful_tot,
'helpful_ratio': helpful_ratio
})
return row
|
def _slice_at_axis(sl, axis):
"""
Construct tuple of slices to slice an array in the given dimension.
This function is copied from numpy's arraypad.py
Parameters
----------
sl : slice
The slice for the given dimension.
axis : int
The axis to which `sl` is applied. All other dimensions are left
"unsliced".
Returns
-------
sl : tuple of slices
A tuple with slices matching `shape` in length.
Examples
--------
>>> _slice_at_axis(slice(None, 3, -1), 1)
(slice(None, None, None), slice(None, 3, -1), (...,))
"""
return (slice(None),) * axis + (sl,) + (...,)
|
def flatten(seq):
"""
For [[1, 2], [3, 4]] returns [1, 2, 3, 4]. Does not recurse.
"""
return [x for sub in seq for x in sub]
|
def json_get(item, path, default=None):
"""
Return the path of the field in a dict.
Arguments:
item (dict): The object where we want to put a field.
path (unicode): The path separated with dots to the field.
default: default value if path not found.
Return:
The value.
"""
tab = path.split(u".")
if tab[0] in item:
if len(tab) > 1:
return json_get(item[tab[0]], u".".join(tab[1:]), default=default)
return item[tab[0]]
return default
|
def bounding_box2D(pts):
"""
bounding box for the points pts
"""
dim = len(pts[0]) # should be 2
bb_min = [min([t[i] for t in pts]) for i in range(dim)]
bb_max = [max([t[i] for t in pts]) for i in range(dim)]
return bb_min[0], bb_min[1], bb_max[0] - bb_min[0], bb_max[1] - bb_min[1]
|
def primerDictToNEBPrimerSeq(primerDict):
"""turn a primer dict from primer3 in fastCloningPrimer to the NEB readdable format"""
NEBPrimerString = ""
for primerPairName, primerPairInfo in primerDict.items():
currentLPrimerName = str(primerPairName) + "Left"
currentLPrimerSeq = primerPairInfo[0][2]
currentRPrimerName = str(primerPairName) + "Right"
currentRPrimerSeq = primerPairInfo[1][2]
NEBPrimerString += currentLPrimerName + "; " + currentLPrimerSeq + \
"; " + currentRPrimerName + "; " + currentRPrimerSeq + "\n"
return NEBPrimerString
|
def clip(value: float, min_value: float, max_value: float) -> float:
"""Clip a value to the given range."""
if value < min_value:
return min_value
if value > max_value:
return max_value
return value
|
def merge_lines_scores(lines, scores):
"""
both type dict
"""
ret = {}
for k, v in lines.items():
score_data = scores.get(k)
if not score_data:
score_data = [None for _ in range(5)]
row = v[0] + score_data + v[1]
ret[k] = row
return ret
|
def pagination(context, page, paginator, where=None):
"""
Shows pagination links::
{% pagination current_page paginator %}
The argument ``where`` can be used inside the pagination template to
discern between pagination at the top and at the bottom of an object
list (if you wish). The default object list template passes
``"top"`` or ``"bottom"`` to the pagination template. The default
pagination template does nothing with this value though.
"""
return {
'context': context,
'page': page,
'paginator': paginator,
'where': where,
}
|
def inclusion_params_and_context(context, arg):
"""Expected inclusion_params_and_context __doc__"""
return {"result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)}
|
def find_subroutine_call_insertion_point(lines,ifbranch,varname):
"""
The assumption is that the symbolic algebra optimization will always break
out the function evaluation. Therefore there always is a line where the
functional value is assigned to a variable. The actual functional
subroutine call, at the latest, has to happen on the line before.
This routine returns the line where the variable first appears.
"""
(lineno_start,lineno_end) = ifbranch
line = lineno_start
insert_point = -1
while line <= lineno_end:
aline = lines[line]
aline = aline.split(" = ")
key = aline[0].lstrip()
if key == varname:
insert_point = line
break
line += 1
return insert_point
|
def numberify(x):
"""convert hex numbers, return original string on failure"""
try:
return int(x, 16)
except ValueError:
return x
|
def get_counts_per_label(y_true, n_classes):
"""
Return a map of {label: number of data points with that label} for the given list of labels
Parameters:
- y_true: (integer) a list of labels
- n_classes: (integer) the number of classes
"""
label_counts = [0] * n_classes
for label in y_true:
label_counts[label] += 1
return label_counts
|
def check_valid_sequence(sequence: str) -> bool:
"""
Check that the sequence string only contains valid sequence characters
"""
return set(sequence.upper()).issubset(set("WSKMYRVHDBNZNATCGU-"))
|
def _check_header(header):
""" Check that header has the minimum mandatory fields
"""
# Check mandatory fields present:
num_samples = 0
matching = []
mandatory_fields = ["source-ontology", "COLDATA", "VERSION"]
for field in mandatory_fields:
match = ([s for s in header if field in s])
if len(match) != 0:
matching.append(match)
all_present = len(matching) == len(mandatory_fields)
if all_present:
for line in header:
if line.startswith("## COLDATA"):
samples = line.strip().split(": ")[1].strip().split(",")
num_samples = len(samples)
return [all_present, num_samples]
|
def party_from_president(name, year):
"""
Assigning political party label from president lastname. Taken from:
https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States
Using "?" to represent parties before 1964.
"""
if year < 1964:
return "?"
d = {
"Trump": "R",
"Obama": "D",
"Bush": "R",
"Clinton": "D",
"Reagan": "R",
"Carter": "D",
"Ford": "R",
"Nixon": "R",
"Johnson": "D",
}
return d[name]
|
def get_subproblems(base_elements, solutes,
p_lagrange,
enable_NS, enable_PF, enable_EC,
**namespace):
""" Returns dict of subproblems the solver splits the problem into. """
subproblems = dict()
if enable_NS:
subproblems["NS"] = [dict(name="u", element="u"),
dict(name="p", element="p")]
if p_lagrange:
subproblems["NS"].append(dict(name="p0", element="p0"))
if enable_PF:
subproblems["PF"] = [dict(name="phi", element="phi"),
dict(name="g", element="g")]
if enable_EC:
subproblems["EC"] = ([dict(name=solute[0], element="c")
for solute in solutes]
+ [dict(name="V", element="V")])
return subproblems
|
def untag(tagged_sentence):
"""
Remove the tag for each tagged term.
:param tagged_sentence: a POS tagged sentence
:type tagged_sentence: list
:return: a list of tags
:rtype: list of strings
"""
return [w for w, _ in tagged_sentence]
|
def format_error(string: str, is_warning: bool) -> str:
"""
Formats a given message in an error color using ANSI escape sequences
(see https://stackoverflow.com/a/287944/5299750
and https://stackoverflow.com/a/33206814/5299750)
:param string: to be printed
:param is_warning: determines the color of the error
"""
if is_warning:
ansi_start = '\033[93m'
else:
ansi_start = '\033[91m'
ansi_end = '\033[0m'
return f"{ansi_start}{string}{ansi_end}"
|
def get_precision(input_number):
"""
Return precision of input number.
:param input_number: input number
:type input_number: float
:return: precision as int
"""
try:
number_str = str(input_number)
_, decimalpart = number_str.split(".")
return len(decimalpart)
except Exception:
return 0
|
def indexes_of_word(words: list, word: str):
""" Return a list of indexes with the given word. """
return [i for i, s in enumerate(words) if s.lower() == word]
|
def add_one(data):
"""Adds 1 to every cell in Range"""
return [[cell + 1 for cell in row] for row in data]
|
def get_sector_size(partition):
"""Return the sector size of a partition.
Used by disk_io_counters().
"""
try:
with open("/sys/block/%s/queue/hw_sector_size" % partition, "rt") as f:
return int(f.read())
except (IOError, ValueError):
# man iostat states that sectors are equivalent with blocks and
# have a size of 512 bytes since 2.4 kernels.
return 512
|
def to_csharp(bool):
"""
Python to C# booleans.
"""
return ['false', 'true'][bool]
|
def strToBool(s):
"""
Converts a string into a bool using the following sets:
True: ['true', '1', 't', 'y', 'yes']
False: ['false', '0', 'f', 'n', 'no']
Throws ValueError s is neither None nor in either true or false value set.
:param s:
:return: True if s is in true value set, False if s is None or in false value set.
"""
if s:
test = s.lower()
if test in ['true', '1', 't', 'y', 'yes']:
return True
elif test in ['false', '0', 'f', 'n', 'no']:
return False
else:
raise ValueError
else:
return False
|
def pack_byte_to_hn(val):
"""
Pack byte to network order unsigned short
"""
return (val << 8) & 0xffff
|
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f}{unit}{suffix}"
bytes /= factor
|
def matchActor(name,targets):
"""
Determines whether a given actor name is one of a given list of targets
@type name: str
@type targets: str[]
@rtype: bool
"""
if len(targets) == 0:
# Nobody given, assume everybody is a target
return True
if name is None:
# There's nobody to match
return False
for actor in targets:
if name[:len(actor)] == actor:
return True
else:
return False
|
def is_prime(num : int) -> bool:
"""is_prime will return if a number is prime or not
Args:
num (int): the number that wil be checked if it's prime
Returns:
bool: True if the number is prime, false if not
"""
if num == 0 or num == 1:
return False
else:
for i in range(2,num):
res = num%i
if res == 0:
return False
else:
pass
return True
|
def add_data_to_json(json_obj, query_data, candidate_data):
"""Adds query and candidate datasets to json object.
"""
json_obj['query_data'] = query_data
json_obj['candidate_data'] = candidate_data
return json_obj
|
def validate_subject_samples_factors(mwtabfile):
"""Validate ``SUBJECT_SAMPLE_FACTORS`` section.
:param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`.
:type mwtabfile: :class:`~mwtab.mwtab.MWTabFile` or
:py:class:`collections.OrderedDict`
"""
subject_samples_factors_errors = list()
for index, subject_sample_factor in enumerate(mwtabfile["SUBJECT_SAMPLE_FACTORS"]):
if not subject_sample_factor["Subject ID"]:
subject_samples_factors_errors.append(
"SUBJECT_SAMPLE_FACTORS: Entry #{} missing Subject ID.".format(index+1)
)
if not subject_sample_factor["Sample ID"]:
subject_samples_factors_errors.append(
"SUBJECT_SAMPLE_FACTORS: Entry #{} missing Sample ID.".format(index + 1)
)
if subject_sample_factor.get("Factors"):
for factor_key in subject_sample_factor["Factors"]:
if not subject_sample_factor["Factors"][factor_key]:
subject_samples_factors_errors.append(
"SUBJECT_SAMPLE_FACTORS: Entry #{} missing value for Factor {}.".format(index + 1, factor_key)
)
if subject_sample_factor.get("Additional sample data"):
for additional_key in subject_sample_factor["Additional sample data"]:
if not subject_sample_factor["Additional sample data"][additional_key]:
subject_samples_factors_errors.append(
"SUBJECT_SAMPLE_FACTORS: Entry #{} missing value for Additional sample data {}.".format(
index + 1, additional_key
)
)
return subject_samples_factors_errors
|
def unpack_str(byteseq):
"""Unpack a byte sequence into a string."""
return byteseq.decode()
|
def compare_versions(version_1: str, version_2: str) -> int:
"""Compares two version strings with format x.x.x.x
Returns:
-1, if version_1 is higher than version_2
0, if version_1 is equal to version_2
1, if version_1 is lower than version_2 """
if not version_1:
return 1
version_1 = version_1.strip('v')
version_2 = version_2.strip('v')
version_1_split = version_1.split('.')
version_2_split = version_2.split('.')
for i in range(0, len(version_1_split)):
if version_1_split[i] < version_2_split[i]:
return 1
elif version_1_split[i] > version_2_split[i]:
return -1
return 0
|
def accuracy_metric(actual, predicted, correct=0) -> float:
"""calculate accuracy of the dataset comparing the actual test label vs the predicted label"""
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / len(actual) * 100.0
|
def get_other_title(title_to_entities_all, other_title, token_location):
"""Handle the case when other titles have been mentioned"""
other_title_found = False
if title_to_entities_all.get(token_location) is not None:
other_title_found = True
other_title["found"] = True
other_title["location"] = token_location
return other_title_found
|
def euler_step(f, y, t, dt, params):
""" Returns the forward euler approximation of the change in `y` over the
timestep `dt`
Parameters
----------
f (callable): accepts `y`, `t` and all of the parameters in `params`
y (ndarray or float): current system state
t (float): time value
dt (float): timestep size
params (tuple): Tuple of parameters for `f`
Returns
-------
dy (ndarray or float): approximation of the change in `y`
over the timestep `dt`
"""
dy = f(y, t, *params) * dt
return dy
|
def find_dup(arr):
"""This will find the duplicated int in the list"""
dup = set([x for x in arr if arr.count(x) > 1])
answer = list(dup)
return answer[0]
|
def make_mission_id(mission_definition, specifics_hash):
""" Returns the string mission_id which is composed from the mission_definition and specifics_hash. """
return "%s-%s" % (mission_definition, specifics_hash)
|
def is_subclass(cls, subclass) -> bool:
"""A more robust version."""
try:
return issubclass(cls, subclass)
except TypeError:
return False
|
def parse_soxi_out(cmd:bytes):
"""
this gross parser takes the bytes from the soxi output, decodes to utf-8,
splits by the newline "\n", takes the second element of the array which is
the number of channels, splits by the semi-colon ':' takes the second element
which is the string of the num channels and converts to int.
"""
return int(cmd.decode("utf-8").strip().split("\n")[1].split(':')[1].strip())
|
def single_point_crossover(population, single_point_info):
"""
Combine each two chromosomes in population by using single point crossover.
"""
crossover_points = [int(p) for p in single_point_info.split("|") if p != '']
new_population = []
for i in range(0, len(population) - 1, 2):
candidate1 = population[i]
candidate2 = population[i + 1]
# get the crossover_point
crossover_point = crossover_points[int(i / 2)]
offspring1 = candidate2[0: crossover_point] + candidate1[crossover_point:]
offspring2 = candidate1[0: crossover_point] + candidate2[crossover_point:]
new_population.append(offspring1)
new_population.append(offspring2)
# append last chromosome if odd population size
if len(population) % 2 == 1:
new_population.append(population[len(population) - 1])
return new_population
|
def pentagonal(n: int) -> int:
"""Returns the n_th pentagonal number. If fed with a negative number, it returns an
extended pentagonal number.
"""
return n * (3 * n - 1) // 2
|
def Legendre_poly(n, x):
"""
"""
if(n == 0):
return 1 # P0 = 1
elif(n == 1):
return x # P1 = x
else:
return (((2 * n)-1)*x * Legendre_poly(n-1, x)-(n-1) * Legendre_poly(n-2, x))/float(n)
|
def color_variant(hex_color, brightness_offset=1):
""" takes a color like #87c95f and produces a lighter or darker variant """
if len(hex_color) != 7:
raise Exception(
"Passed %s into color_variant(), needs to be in #87c95f format." % hex_color
)
rgb_hex = [hex_color[x : x + 2] for x in [1, 3, 5]]
new_rgb_int = [int(hex_value, 16) + brightness_offset for hex_value in rgb_hex]
new_rgb_int = [
min([255, max([0, i])]) for i in new_rgb_int
] # make sure new values are between 0 and 255
# hex() produces "0x88", we want just "88"
return "#%02x%02x%02x" % (new_rgb_int[0], new_rgb_int[1], new_rgb_int[2])
|
def search_types(params, results, meta):
"""
Convert Elasticsearch results into RPC results conforming to the spec for
the "search_types" method.
"""
# Now we need to convert the ES result format into the API format
search_time = results['search_time']
buckets = results['aggregations']['type_count']['counts']
counts_dict = {} # type: dict
for count_obj in buckets:
counts_dict[count_obj['key']] = counts_dict.get(count_obj['key'], 0)
counts_dict[count_obj['key']] += count_obj['count']
return {
'type_to_count': counts_dict,
'search_time': int(search_time)
}
|
def _is_time_between(timestamp, from_timestamp, to_timestamp):
""" self-explanatory """
return (timestamp > from_timestamp) & (timestamp < to_timestamp)
|
def break_words(stuff):
"""This funciton will break up words for us."""
words = stuff.split(' ')
return words
|
def get_dict_depth(_dict):
""" Get dictionary's depth or 'nestedness' """
if isinstance(_dict, dict):
return 1 + (min(map(get_dict_depth, _dict.values()))
if _dict else 0)
return 0
|
def score_global(x, y):
"""
Verifica o valor de scoring dos aminoacidos informados
:param x: primeiro aminoacido
:param y: segundo aminoacido
:return: valor de scoring
"""
if x == y:
return 5
return -4
|
def key_size(message):
""" Calculate the desired key size in 64 byte blocks.
"""
return (len(message) // 64) + 1
|
def __trailing_newline(eof):
"""
Helper function returning an empty string or a newling character to
append to the current output line depending on whether we want that line to
be the last line in the file (eof == True) or not (eof == False).
"""
if eof:
return ""
return "\n"
|
def get_row_multiplied(row, coefficient):
"""multiply row elements by coefficient
"""
result = []
for element in row:
result.append(element * coefficient)
return result
|
def string_to_int(string):
"""
Convert string to int
:param string: An instance of type string
:return: Integer
"""
return int(string.replace(',', ''))
|
def _get_token(results):
"""Get the token from the property results."""
return getattr(results, 'token', None)
|
def hax(string: str) -> str:
"""
funky things in the raw data that we fix here
currently for addresses only..
d is a dictionary of key-value pairs where:
key is the (company number) and,
value is the Registered Address of the Company with that company number
"""
d = {'(C2237836)': '1840 SOUTHWEST 22ND ST 4TH FL MIAMI FL 33145 United States',
'(C0168406)': '28 LIBERTY ST NEW YORK NY 10005 United States',
'(C2713864)': '235 FOSS CREEK CIRCLE HEALDSBURG CA 95448 United States',
'(C2142832)': '22995 BOUQUET CANYON MISSION VIEJO CA 92692 United States',
}
for key in d:
if key in string:
string = d[key]
break
return string
|
def verify_command(command):
"""Verify a given command is legal."""
command_length = len(command)
if command_length > 0:
if command_length == 1:
if command[0] in ["Q", "t"]:
return (command[0], None)
if command_length == 2:
if ((command[0] == 'S' and command[1] in ["r", "i", "m"])
or (command[0] in ["A", "AR", "d", "D"] and command[1].isnumeric())):
return (command[0], command[1])
return (False, " ".join(command))
|
def unwrap_args(form_query_argument_list):
"""Turn the serialized key/value pairs back into a dict."""
kwargs = {}
for arg in form_query_argument_list:
kwargs[arg['key']] = arg['value']
return kwargs
|
def reverse_sequence(sequence):
"""
Return the reverse of sequence
:param sequence: either a string or Sequence object
:return: the reverse string or Sequence object
"""
if isinstance(sequence, str):
return sequence[::-1]
else:
raise ValueError("Cannot complement object of {0}, expecting string or Sequence object".format(type(sequence)))
|
def smart_min(v1, v2):
"""
Returns min value even if one of the value is None.
By default min(None, x) == None per Python default behavior.
"""
if v1 is None:
return v2
if v2 is None:
return v1
return min(v1, v2)
|
def get_nucleotide_count(dna):
"""
Count the number of each nucleotide in the given DNA string.
:param dna: a string of DNA
:return: the number of A's, C's, G's, and T's
"""
a, c, g, t = 0, 0, 0, 0
for i in range(len(dna)):
val = dna[i].upper()
if val == 'A':
a += 1
elif val == 'C':
c += 1
elif val == 'G':
g += 1
elif val == 'T':
t += 1
return a, c, g, t
|
def safeint(x):
"""Converts to an integer if possible"""
try:
return int(x)
except BaseException:
return x
|
def parse_time(t):
"""
Convert time string to time for saving in django
:param d: date string in "%H%M%S"
:return:
"""
z = t.split(':')
return int(z[0]) * 3600 + int(z[1]) * 60 + int(z[2])
|
def remove_punctuation(data):
"""Remove punctuation from data."""
try:
if data[-1:] == ',':
data = data[:-1]
if data[-2:] == ' :':
data = data[:-2]
if data[-2:] == ' ;':
data = data[:-2]
if data[-2:] == ' /':
data = data[:-2]
if data[-2:] == ' -':
data = data[:-2]
except Exception:
pass
return data
|
def _sudoku_syntax(file):
"""
Return the full name of the given sudoku syntax based on the base name.
"""
return "Packages/Sudoku/resources/syntax/%s.sublime-syntax" % file
|
def human_bytes(n):
"""
Return the number of bytes n in more human readable form.
Examples:
>>> human_bytes(42)
'42 B'
>>> human_bytes(1042)
'1 KB'
>>> human_bytes(10004242)
'9.5 MB'
>>> human_bytes(100000004242)
'93.13 GB'
"""
if n < 1024:
return '%d B' % n
k = n/1024
if k < 1024:
return '%d KB' % round(k)
m = k/1024
if m < 1024:
return '%.1f MB' % m
g = m/1024
return '%.2f GB' % g
|
def instanceof(value, type_):
"""Check if `value` is an instance of `type_`.
:param value: an object
:param type_: a type
"""
return isinstance(value, type_)
|
def encode_golomb(x, p):
"""converts a number x to a golomb-encoded array of 0's and 1's"""
# quotient when dividing x by 2^p
q = x >> p
# q 1's and a 0 at the end
result = [1] * q + [0]
# the last p bits of x
result += [x & (1 << (p - i - 1)) > 0 for i in range(p)]
return result
|
def m2ft(meters: float) -> float:
"""
Convert meters to feet.
:param float meters: meters
:return: feet
:rtype: float
"""
if not isinstance(meters, (float, int)):
return 0
return meters * 3.28084
|
def get_url(server_name, listen_port, topic_name):
"""
Generating URL to get the information
from namenode/namenode
:param server_name:
:param listen_port:
:param topic_name:
:return:
"""
if listen_port < 0:
print ("Invalid Port")
exit()
if not server_name:
print("Pass valid Hostname")
exit()
if not topic_name:
topic_name = "*"
URL = "http://"+server_name+":" + \
str(listen_port)+"/jmx?qry=Hadoop:"+topic_name
return URL
|
def _build_localename(localetuple):
""" Builds a locale code from the given tuple (language code,
encoding).
No aliasing or normalizing takes place.
"""
try:
language, encoding = localetuple
if language is None:
language = 'C'
if encoding is None:
return language
else:
return language + '.' + encoding
except (TypeError, ValueError):
raise TypeError(
'Locale must be None, a string, or an iterable of two strings -- language code, encoding.'
)
|
def process_immediate(immediate):
"""
Returns a integer object from a string object.
"""
if not isinstance(immediate, str):
raise TypeError('Immediate must be a String object.')
if immediate.startswith("0x"):
return int(immediate, 16)
else:
return int(immediate)
|
def note_to_freq(note):
"""
Return the frequency value for a given MIDI note value.
"""
return 440.0 * pow(2.0, (note - 69) / 12.0)
|
def get_reads(seq_file):
"""
Creates reads of according to the parameters in the argument
input: The full sequence as a string
output: reads in string format INSIDE a list called "my_reads"
"""
my_reads = []
read_length = 150
overlap = 50
read_pos = 0
# have verified that the data written to file is the same that was from the sequence.
# now make the reads
while read_pos < len(seq_file):
my_reads.append(seq_file[read_pos:read_pos+read_length])
read_pos += read_length - overlap
for x in my_reads:
print(len(x))
return(my_reads)
|
def extract_annealing_log(log):
"""
Parses a VPR log line by line. Extracts the table with simulated annealing
data. Returns the table header and data line lists as separate.
"""
# Find a line starting with "# Placement"
for i, line in enumerate(log):
if line.startswith("# Placement"):
log = log[i:]
break
else:
return [], []
# Find and cut the header
header_lines = []
for i, line in enumerate(log):
if line.startswith("------"):
header_lines = log[i:i+3]
log = log[i+2:]
break
# Gather data lines until '# Placement took' is encountered
data_lines = []
for line in log:
# Reached the end of the placement section
if line.startswith("# Placement took"):
break
# Split into fields. All of them have to be numbers
fields = line.strip().split()
try:
for f in fields:
number = float(f)
except ValueError:
continue
# Append the line in text format
data_lines.append(line.strip())
return header_lines, data_lines
|
def creates_cycle(connections, test):
"""
Returns true if the addition of the 'test' connection would create a cycle,
assuming that no cycle already exists in the graph represented by 'connections'.
"""
i, o = test
if i == o:
return True
visited = {o}
while True:
num_added = 0
for a, b in connections:
if a in visited and b not in visited:
if b == i:
return True
visited.add(b)
num_added += 1
if num_added == 0:
return False
|
def is_key(config) -> list:
"""Check for interface key, two possibilities"""
try:
int_type = config.get('name', {}).get('#text', {})
except AttributeError:
int_type = config['name']
return int_type
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.