content
stringlengths 42
6.51k
|
---|
def flatten2d(l):
""" Returns a flattened version of a list of lists. """
try:
test = l[0][0]
return [item for sublist in l for item in sublist]
except TypeError:
return l
|
def parse_result(result):
"""
This function is used to reorganize the result of my_lda_func for plotting.
"""
result_dic = {}
for topic_num, dist in result:
unpack = []
for obj in dist.split('+'):
prob, word = obj.split('*')
unpack.append((float(prob), word.strip().strip('"')))
prob, word = zip(*unpack)
result_dic[topic_num] = [prob, word]
return result_dic
|
def split_comma_list(comma_str: str):
"""
Split a comma-separated list of values, stripping whitespace
"""
return [item.strip() for item in comma_str.split(',')]
|
def _matrix(nrows, ncols):
"""Creates a matrix with no borders."""
matrix = (
" x" + " x" * (ncols - 1) + " \n" + (
" " + " " * (ncols - 1) + " \n" +
" x" + " x" * (ncols - 1) + " \n") * (nrows - 1))
return matrix
|
def add_blank_choice(choices):
"""
Add a blank choice to the beginning of a choices list.
"""
return ((None, "---------"),) + tuple(choices)
|
def level_from_severity(severity):
"""Converts tool's severity to the 4 level
suggested by SARIF
"""
if severity == "CRITICAL":
return "error"
elif severity == "HIGH":
return "error"
elif severity == "MEDIUM":
return "warning"
elif severity == "LOW":
return "note"
else:
return "warning"
|
def merge_dicts(*dicts):
"""
Shallow copy and merge dicts into a new dict; precedence goes to
key value pairs in latter dict. Only keys in both dicts will be kept.
:param dicts: iterable of dict;
:return: dict;
"""
merged = dict()
for d in dicts:
merged.update(d)
return merged
|
def strip_nulls(unicode_contents):
"""
CRS data seems to have null control characters (NUL) in various fields, which confuse pandas
"""
return unicode_contents.replace(u'\0', u'')
|
def median(scores):
"""Returns the median of only valid scores in the given list [0,100]"""
# Checks and adds valid scores to valid_scores
valid_scores = []
for score in scores:
if not(score < 0 or score > 100):
valid_scores.append(score)
if len(valid_scores) == 0:
return -1
half = len(valid_scores) // 2
# Return avg of 2 middle scores if even
if len(valid_scores) % 2 == 0:
return (valid_scores[half] + valid_scores[half - 1]) / 2
# Otherwise return middle score for odd
return valid_scores[half]
|
def _mapping_repr(mapping):
"""Helper to return class names in the dict values."""
return {
version: [klass.__name__ for klass in classes_list]
for version, classes_list in mapping.items()
}
|
def is_valid_transaction_hash(tx_hash):
"""Determines if the provided string is a valid Stellar transaction hash.
:param str tx_hash: transaction hash to check
:return: True if this is a correct transaction hash
:rtype: boolean
"""
if len(tx_hash) != 64:
return False
try:
int(tx_hash, 16)
return True
except:
return False
|
def Position_downrange(downrange, velocity, angle_of_attack):
""" **Still under development**
Calculates the position in the x direction from the launch site based on an ascent profile.
Args:
downrange (float): Position downrange calculated at timestep i-1. Initial value = 0
velocity (float): From rocket.Velocity(): The Instantaneous velocity of the Rocket
angle_of_attack (float): From rocket.Angle_of_attack(): Angle of the rocket from the vertical in degrees
Returns:
down_range (float): Position downrange at timestep i
"""
from numpy import cos
theta = angle_of_attack * 3.14159/180
TIME_STEP = .1
down_range = downrange + velocity * cos(theta) * TIME_STEP
return down_range
|
def parse_wfo_location_group(form):
"""Parse wfoLimiter"""
limiter = ''
if 'wfo[]' in form:
wfos = form.getlist('wfo[]')
wfos.append('XXX') # Hack to make next section work
if 'ALL' not in wfos:
limiter = " and w.wfo in %s " % (str(tuple(wfos)),)
if 'wfos[]' in form:
wfos = form.getlist('wfos[]')
wfos.append('XXX') # Hack to make next section work
if 'ALL' not in wfos:
limiter = " and w.wfo in %s " % (str(tuple(wfos)),)
return limiter
|
def worst_range(nums, target):
"""
Given a sorted list, find the range nums[lo:hi] such that all values in the range equal to target.
"""
if not target in nums:
return None
lo = nums.index(target)
if lo == len(nums) - 1:
return (lo, lo)
hi = lo + 1
while hi < len(nums):
if nums[hi] != target:
return (lo, hi - 1)
hi += 1
return (lo, hi - 1)
|
def I_beam(b, h):
"""gets the Iyy, Izz, Iyz for a solid beam"""
f = 1 / 12. * b * h
Iyy = f * h * h # 1/12.*b*h**3
Izz = f * b * b # 1/12.*h*b**3
Iyz = 0.
return (Iyy, Izz, Iyz)
|
def _render_limit(limit):
"""Render the limit part of a query.
Parameters
----------
limit : int, optional
Limit the amount of data needed to be returned.
Returns
-------
str
A string that represents the "limit" part of a query.
"""
if not limit:
return ''
return "LIMIT %s" % limit
|
def payloads_config(param):
"""Create a valid payloads config from the config file contents."""
if not param:
return {'enabled': True}
payloads_config = param.copy()
payloads_config['enabled'] = bool(param.get('enabled', True))
return payloads_config
|
def prefixCombiner(prefix, itemlist, glue=''):
"""Returns a list of items where each element is prepend by given
prefix."""
result = []
for item in itemlist:
result.append(prefix + glue + item)
return result
|
def extract_string(data, begin, end):
""" Extracts the main string from the message sent by the client and cuts it specifically.
:param end: The end of the string.
:param begin: The beginning of the string.
:param data: Data sent by the client.
:return: String part of the message.
"""
try:
string = data.split("nif:isString")[1].split("\"")[1][begin:end]
return string
except IndexError:
return -1
|
def duplicate_in(l):
"""Returns True if there is at least one duplicated element in the list of
strings l, and False otherwise"""
l.sort()
for i in range(len(l)-1):
if l[i] == l[i+1]: return True
return False
|
def convert_conditions(conditions):
"""
Convert the conditions to a mapping of nodename->list of conditions.
"""
if conditions is None:
return {}
res = {}
if 'attributes' in conditions:
for condition in conditions['attributes']:
cond = condition[0]
node = condition[1][0]
attr = condition[1][1]
if node in res:
res[node].append((cond, attr))
else:
res[node] = [(cond, attr)]
if 'compositions' in conditions:
for condition in conditions['compositions']:
cond = condition[0]
if cond in ['same', 'diff']:
for item in condition[1]:
node = item
if node in res:
res[node].append((cond, [item for item in condition[1]
if item != node][0]))
else:
res[node] = [(cond, [item for item in condition[1]
if item != node][0])]
else:
for item in condition[1][1]:
node = item
attr = condition[1][0]
if node in res:
res[node].append((cond, (attr, [item for item in
condition[1]
if item != node])))
else:
res[node] = [(cond, (attr, [item for item in
condition[1]
if item != node]))]
return res
|
def sortDictByKey(dct: dict) -> dict:
"""
@brief Sort the dict by its key as of Python 3.7.
@param dct The dict
@return The sorted dict
"""
dctNew = {}
for key in sorted(dct.keys()):
dctNew[key] = dct[key]
return dctNew
|
def myfunc(a, b, c, d):
""" A random function. Important to define this globally
because the multiprocessing package can't pickle locally
defined functions."""
return a ** b + c * d
|
def camel_to_snake(camel: str) -> str:
"""Convert camel case to snake."""
if not camel:
return camel
snake = camel[0].lower()
for c in camel[1:]:
if c.isupper():
snake = snake + '_'
snake = snake + c.lower()
return snake
|
def to_none(text):
"""
Convert a string to None if the string is empty or contains only spaces.
"""
if str(text).strip():
return text
return None
|
def buildBeat(time):
"""
The module class 64 of time (numbers time%64) are represented in binary
representation, changint the 0's by ones, this in order to be more
suitable to affec the result in the weight matrixes to be determined.
This in fact is a binary representation of the time withing the time for
the note played or hold at a given time.
"""
return [2 * x - 1 for x in [time % 2, (time // 2) % 2, (time // 4) % 2,
(time // 8) % 2]]
|
def diff(obj, amount):
"""Returns the difference between obj and amount (obj - amount).
Example usage: {{ my_counter|diff:"5" }} or {{ my_counter|diff:step_id }}
"""
return obj-float(amount)
|
def suppress_none(value):
""" Returns empty string for none, otherwise the passed value """
return value if value else ""
|
def sum_accumulators(accs):
"""Takes a list of accumulators or Nones and adds them together.
"""
valid = [acc for acc in accs if acc]
if len(valid) == 0:
return None
ret = valid[0]
for v in valid[1:]:
ret += v
return ret
|
def any_value(dict_):
"""Return any value in dict."""
try:
return next(iter(dict_.values()))
except StopIteration:
raise ValueError("dict has no values")
|
def derive_new_filename(filename):
"""Derives a non-numbered filename from a possibly numbered one."""
while filename[-1].isdigit():
filename = filename[:-1]
return filename
|
def _build_final_method_name(method_name, dataset_name, repeat_suffix):
"""
Return a nice human friendly name, that almost looks like code.
Example: a test called 'test_something' with a dataset of (5, 'hello')
Return: "test_something(5, 'hello')"
Example: a test called 'test_other_stuff' with dataset of (9) and repeats
Return: "test_other_stuff(9) iteration_<X>"
:param method_name:
Base name of the method to add.
:type method_name:
`unicode`
:param dataset_name:
Base name of the data set.
:type dataset_name:
`unicode` or None
:param repeat_suffix:
Suffix to append to the name of the generated method.
:type repeat_suffix:
`unicode` or None
:return:
The fully composed name of the generated test method.
:rtype:
`unicode`
"""
if not dataset_name and not repeat_suffix:
return method_name
# Place data_set info inside parens, as if it were a function call
test_method_suffix = '({})'.format(dataset_name or "")
if repeat_suffix:
test_method_suffix = test_method_suffix + " " + repeat_suffix
test_method_name_for_dataset = "{}{}".format(
method_name,
test_method_suffix,
)
return test_method_name_for_dataset
|
def mkdosname(company_name, default='noname'):
""" convert a string to a dos-like name"""
if not company_name:
return default
badchars = ' !@#$%^`~*()+={}[];:\'"/?.<>'
n = ''
for c in company_name[:8]:
n += (c in badchars and '_') or c
return n
|
def _color_idx(val):
""" Take a value between 0 and 1 and return the idx of color """
return int(val * 30)
|
def color_position_negative(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'darkred' if val < 0 else 'darkblue'
return 'color: %s' % color
|
def sort_gift_code(code):
"""
Sorts a string in alphabetical order.
:param code: a string containing up to 26 unique alphabetical characters.
:return: a string containing the same characters in alphabetical order.
"""
return "".join(sorted(code))
|
def _b(s):
"""A byte literal."""
return s.encode("latin-1")
|
def validateTransactionBody(data):
"""Validates incoming json body
Arguments:
data {[dict]} -- [json body]
Returns:
[bool] -- [if validation passes]
[dict] -- [if validation fails]
"""
keys = [*data]
allowedKeys = ["amount", "transactionType"]
if len(keys) != 2:
return {"error": "two keys are required in transaction body"}
for key in keys:
if key not in allowedKeys:
return {
"error": "only the following keys are allowed in transaction body:"
+ ",".join(allowedKeys)
}
return True
|
def sanitize_href(href):
"""
Verify that a given href is benign and allowed.
This is a stupid check, which probably should be much more elaborate
to be safe.
"""
if href.startswith(("/", "mailto:", "http:", "https:", "#", "tel:")):
return href
return "#"
|
def concatenate_path_pk(path, *args):
"""
Receive path and args and concatenate to create the path needed
for an object query.
Make sure parameters are plugged in in the right order. It must
be aligned with the Bexio API, so the endpoints are valid. Check
out the official docs to see, how the final path should look like.
:param: str, endpoint path to be used (must be first arg)
:param: list, *args that come after
:return: str, concatenated path
"""
return '/'.join([str(path)] + [str(arg) for arg in args])
|
def include_tagcanvas(element_id, width, height, url_name='tagcanvas-list',
forvar=None, limit=3):
"""
Args:
element_id - str - html id
width - int - pixels width
height - int - pixels height
url_name - if url_name=='' then no links. Default: tagcanvas-list
"""
if url_name == 'default':
url_name = 'tagcanvas-list'
return {
'forvar': forvar,
'element_id': element_id,
'width': width,
'height': height,
'url_name': url_name,
'limit': limit}
|
def yesno(question, noprompt=False):
"""Simple Yes/No Function."""
if noprompt:
return True
prompt = f"{question} ? (y/n): "
ans = input(prompt).strip().lower()
if ans not in ["y", "n"]:
print(f"{ans} is invalid, please try again...")
return yesno(question)
if ans == "y":
return True
return False
|
def read_path(path):
"""
Fetch the contents of a filesystem `path` as bytes.
"""
return open(path, 'rb').read()
|
def find_multiples(integer, limit):
"""
Finds all integers multiples.
:param integer: integer value.
:param limit: integer value.
:return: a list of its multiples up to another value, limit.
"""
return [x for x in range(1, limit + 1) if x % integer == 0]
|
def normalize(x, xmin, xmax):
"""Normalize `x` given explicit min/max values. """
return (x - xmin) / (xmax - xmin)
|
def coord_to_index(x_coord, y_coord, width):
""" translate an (x, y) coord to an index """
return y_coord * width + x_coord
|
def capture_current_size(thread_list, recorded):
"""
Amount captured so far is the sum of the bytes recorded by warcprox,
and the bytes pending in our background threads.
"""
return recorded + sum(getattr(thread, 'pending_data', 0) for thread in thread_list)
|
def fix_django_headers(meta):
"""
Fix this nonsensical API:
https://docs.djangoproject.com/en/1.11/ref/request-response/
https://code.djangoproject.com/ticket/20147
"""
ret = {}
for k, v in meta.items():
if k.startswith("HTTP_"):
k = k[len("HTTP_"):]
elif k not in ("CONTENT_LENGTH", "CONTENT_TYPE"):
# Skip CGI garbage
continue
ret[k.lower().replace("_", "-")] = v
return ret
|
def parse_key_val_var(var_str):
"""Convert key=val string to tuple.
Arguments:
var_str -- String in the format 'foo=bar'
"""
items = var_str.split('=')
return (items[0].strip(), items[1].strip())
|
def get_link(obj, rel):
"""Get link information from a resource.
Parameters
----------
obj : dict
rel : str
Returns
-------
dict
"""
if isinstance(obj, dict) and 'links' in obj:
if isinstance(obj['links'], dict):
return obj['links'].get(rel)
links = [l for l in obj.get('links', []) if l.get('rel') == rel]
if not links:
return None
if len(links) == 1:
return links[0]
return links
if isinstance(obj, dict) and 'rel' in obj and obj['rel'] == rel:
# Object is already a link, just return it
return obj
|
def some_function(t):
"""Another silly function."""
return t + " python"
|
def get_api_url(account):
"""construct the tumblr API URL"""
global blog_name
blog_name = account
if '.' not in account:
blog_name += '.tumblr.com'
return 'http://api.tumblr.com/v2/blog/' + blog_name + '/posts'
|
def num_eights(x):
"""Returns the number of times 8 appears as a digit of x.
>>> num_eights(3)
0
>>> num_eights(8)
1
>>> num_eights(88888888)
8
>>> num_eights(2638)
1
>>> num_eights(86380)
2
>>> num_eights(12345)
0
>>> from construct_check import check
>>> # ban all assignment statements
>>> check(HW_SOURCE_FILE, 'num_eights',
... ['Assign', 'AugAssign'])
True
"""
"*** YOUR CODE HERE ***"
if x < 10:
if x == 8:
return 1
return 0
if x % 10 == 8:
return num_eights(x // 10) + 1
return num_eights(x // 10)
|
def strStr(haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
|
def dec_to_bin(decimal_number: int) -> str:
"""Convert decimal number to binary.
Examples:
>>> dec_to_bin(5)
'101'
>>> dec_to_bin("Q")
Traceback (most recent call last):
...
ValueError: Integer value expected!
"""
# Check for correct argument type.
if not isinstance(decimal_number, int):
raise ValueError("Integer value expected!")
# Empty string for outputting results.
out: str = ""
# Worker variable to process decmal_number.
n: int = decimal_number
# Append remainder of decimal number divided by 2 to `out`
# Set `n` to quotient of the prior decimal number divided by 2.
while n > 0:
out += f"{n % 2}"
n //= 2
# Reverse binary result before returning the value.
return out[::-1]
|
def append_line(buf, linearr):
"""Append lines
Args:
buf (obj): Nvim buffer
linearr (Array[string]): Line contents
Returns:
suc (bool): True if success
"""
for l in linearr:
buf.append(l)
return True
|
def get_attribute(item, attribute):
"""A version of getattr that will return None if attribute
is not found on the item"""
if hasattr(item, attribute):
return getattr(item, attribute)
return None
|
def beacon_link(variant_obj, build=None):
"""Compose link to Beacon Network."""
build = build or 37
url_template = (
"https://beacon-network.org/#/search?pos={this[position]}&"
"chrom={this[chromosome]}&allele={this[alternative]}&"
"ref={this[reference]}&rs=GRCh37"
)
# beacon does not support build 38 at the moment
# if build == '38':
# url_template = ("https://beacon-network.org/#/search?pos={this[position]}&"
# "chrom={this[chromosome]}&allele={this[alternative]}&"
# "ref={this[reference]}&rs=GRCh38")
return url_template.format(this=variant_obj)
|
def instructions(r1, r2):
"""
"""
def robot1(x,y):
"""
convert coordinates of robot1 to island
"""
if x <= 2 and y <= 1:
return 'r1_home'
elif x <= 1 and y >= 3:
return 'r1_near'
elif x >= 3 and y >= 3:
return 'r1_far'
elif x == 1 and y == 2:
return 'r1_bridge1'
elif x == 2 and y == 4:
return 'r1_bridge2'
else:
print('error: abstraction is not defined for these coordinates!')
def robot2(x,y):
"""
convert coordinates of robot2 to island
"""
if x <= 2 and y <= 1:
return 'r2_home'
elif x <= 1 and y >= 3:
return 'r2_near'
elif x >= 3 and y >= 3:
return 'r2_far'
elif x == 1 and y == 2:
return 'r2_bridge1'
elif x == 2 and y == 4:
return 'r2_bridge2'
else:
print('error: abstraction not defined for these coordinates!')
x1, y1 = r1
x2, y2 = r2
return [robot1(x1,y1), robot2(x2,y2)]
|
def merge(arg_list):
"""Function: merge
Description: Method stub holder for git.Repo.git.merge().
Arguments:
"""
status = True
if arg_list:
status = True
return status
|
def convert_aa_code(three_letter, convert):
"""
Assumes a string that contains a three letter aminoacid code and
returns the corresponding one letter code.
"""
aa_code = {
'CYS': 'C',
'ASP': 'D',
'SER': 'S',
'GLN': 'Q',
'LYS': 'K',
'ILE': 'I',
'PRO': 'P',
'THR': 'T',
'PHE': 'F',
'ASN': 'N',
'GLY': 'G',
'HIS': 'H',
'LEU': 'L',
'ARG': 'R',
'TRP': 'W',
'ALA': 'A',
'VAL': 'V',
'GLU': 'E',
'TYR': 'Y',
'MET': 'M',
}
non_canonical = {
'MSE': 1,
'HYP': 2,
'MLY': 3,
'SEP': 4,
'TPO': 5,
'CSO': 6,
'PTR': 7,
'KCX': 8,
'CME': 9,
'CSD': 10,
'CAS': 11,
'MLE': 12,
'DAL': 13,
'CGU': 14,
'DLE': 15,
'FME': 16,
'DVA': 17,
'OCS': 18,
'DPR': 19,
'MVA': 20,
'TYS': 21,
'M3L': 22,
'SMC': 23,
'ALY': 24,
'CSX': 25,
'DCY': 26,
'NLE': 27,
'DGL': 28,
'DSN': 29,
'CSS': 30,
'DLY': 31,
'MLZ': 32,
'DPN': 33,
'DAR': 34,
'PHI': 35,
'IAS': 36,
'DAS': 37,
'HIC': 38,
'MP8': 39,
'DTH': 40,
'DIL': 41,
'MEN': 42,
'DTY': 43,
'CXM': 44,
'DGN': 45,
'DTR': 46,
'SAC': 47,
'DSG': 48,
'MME': 49,
'MAA': 50,
'YOF': 51,
'FP9': 52,
'FVA': 53,
'MLU': 54,
'OMY': 55,
'FGA': 56,
'MEA': 57,
'CMH': 58,
'DHI': 59,
'SEC': 60,
'OMZ': 61,
'SCY': 62,
'MHO': 63,
'MED': 64,
'CAF': 65,
'NIY': 66,
'OAS': 67,
'SCH': 68,
'MK8': 69,
'SME': 70,
'LYZ': 71
}
if three_letter in aa_code.keys():
return aa_code[three_letter]
elif convert and (three_letter in non_canonical.keys()):
return non_canonical[three_letter]
else:
return '-'
|
def bytes2hr(byte):
"""Converts the supplied file size into a human readable number, and adds a suffix."""
result = None
_s = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
if not isinstance(byte, int):
try:
byte = int(byte)
except TypeError:
raise
_si = 0
while byte > 1024 and _si < 4:
_si += 1
byte = byte / 1024.0
_result = '{0:.2f}'.format(byte)
if _result.endswith('.00'):
_result = _result.replace('.00', '')
elif _result.endswith('0'):
_result = _result.rstrip('0')
result = '{} {}'.format(_result, _s[_si])
return result
|
def Dic_Key_Value_Reverse(indic):
"""
Reverse key:value pair to value:key pair, note indic must be 1-1 projection.
"""
outdic={}
for key,value in indic.items():
outdic[value]=key
return outdic
|
def get_marble(value=0, prev=None, next=None):
"""Get new marble, with value, prev and next."""
return {'value': value, 'prev': prev, 'next': next}
|
def el_block_size(l):
"""Size needed for a given el in the dmat array."""
return (l + 1) * (l + 2) // 2
|
def bound_check(coord, w, h):
""" Checks if coord is within grid """
if (0 <= coord[1] < h) and (0 <= coord[0] < w):
return True
else:
return False
|
def get_result_facets(work_keys):
"""
Helper function takes a list of Creative Works keys and returns
all of the facets associated with those entities.
:param work_keys: Work keys
"""
facets = []
return facets
|
def distance_from_root_v1(root, key, distance=0):
"""
Distance from root is same as the level at which key is present.
:param root:
:param key:
:param distance:
:return:
"""
if root == None:
return -1
if root.key == key:
return distance
else:
ld = distance_from_root_v1(root.left, key, distance+1)
rd = distance_from_root_v1(root.right, key, distance+1)
return ld if ld > 0 else rd
|
def parse_between(text, start, end):
"""Returns all substrings occurring between given start and end strings in the given text."""
if start in text and end in text:
data = []
string = text.split(start)
# we know no data will be in first position
del string[0]
for substring in string:
data.append(substring.partition(end)[0])
return data
else:
return ["None"]
|
def cyclic_binary_derivative(string):
"""
Calculates the cyclic binary derivative, which is the "binary string of length n formed by XORing adjacent pairs of
digits including the last and the first." See:
.. code-block:: text
Croll, G. J. (2018). The BiEntropy of Some Knots on the Simple Cubic Lattice.
arXiv preprint arXiv:1802.03772.
:param string: a binary string, such as '110011'
:return: a binary string representing the cyclic binary derivative of the given string
"""
result = []
for i, d in enumerate(string):
s = string[i]
if i == len(string) - 1:
next_s = string[0]
else:
next_s = string[i + 1]
result.append(int(s) ^ int(next_s))
return ''.join([str(x) for x in result])
|
def mutindex2pos(x, start, end, mut_pos):
"""
Convert mutation indices back to genome positions
"""
if x == -.5:
return start
elif x == len(mut_pos) - .5:
return end
else:
i = int(x - .5)
j = int(x + .5)
return (mut_pos[i] + mut_pos[j]) / 2.0
|
def read_key(fd):
""" [str] = read_key(fd)
Read the utterance-key from the opened ark/stream descriptor 'fd'.
"""
str_ = ''
while True:
char = fd.read(1)
if char == '':
break
if char == ' ':
break
str_ += char
str_ = str_.strip()
if str_ == '':
return None # end of file,
return str_
|
def _stringify(value):
"""
Local helper function to ensure a value is a string
:param value: Value to verify
:return: The string value
"""
if not isinstance(value, str):
return str(value)
else:
return value
|
def _phaser_succeeded(llg, tfz):
"""Check values for job success"""
return llg > 120 and tfz > 8
|
def get_courseweeks(course_id):
"""
Returns a list of course weeks
Todo: Calculate from course table start and end date
Args:
course_id: course id
Returns:
list of course week numbers
"""
return [31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]
|
def parseMessageJson(messageList, username=None):
"""
messageList: list - Should be a bunch of dictionaries within a list.
username: string - optional - Used to find message only from that user. Username is case sensitive.
If username is not given, everyone's message will be used
Returns a big string that contains all of the user's message.
"""
retString = ""
for d in messageList:
if username != "All":
if username != d['author']['username']: # If the message doesn't belong to the specified user.
continue
retString += " [BEGIN] " + d["content"] + " [END]"
return retString
|
def arguments(function, extra_arguments=0):
"""Returns the name of all arguments a function takes"""
if not hasattr(function, '__code__'):
return ()
return function.__code__.co_varnames[:function.__code__.co_argcount + extra_arguments]
|
def get_date_from_s1_raster(path_to_raster):
"""
Small utilty function that parses a s1 raster file name to extract date.
Args:
path_to_raster: path to the s1 raster file
Returns:
a string representing the date
"""
return path_to_raster.split("/")[-1].split("-")[4]
|
def isNumber(s):
"""
Check if a string is a numeric (int or float) value
"""
try:
float(s)
return True
except ValueError:
return False
|
def is_sitemap(content):
"""Check a string to see if its content is a sitemap or siteindex.
Attributes: content (string)
"""
try:
if 'www.sitemaps.org/schemas/sitemap/' in content or '<sitemapindex' in content:
return True
except:
return False
return False
|
def passes_atomic_condition(inter, fs):
""" Tests an interpretation for the atomic condition.
For every formal species there exists an implementation species which
interprets to it.
"""
return all(any([f] == v for v in inter.values()) for f in fs)
|
def E(x):
"""
Calculates expected value given list x of values.
:param x: list of observations
:returns expected value of X
"""
return float(sum(x)) / len(x)
|
def image_inputs(images_and_videos, data_dir, text_tmp_images):
"""Generates a list of input arguments for ffmpeg with the given images."""
include_cmd = []
# adds images as video starting on overlay time and finishing on overlay end
img_formats = ['gif', 'jpg', 'jpeg', 'png']
for ovl in images_and_videos:
filename = ovl['image']
# checks if overlay is image or video
is_img = False
for img_fmt in img_formats:
is_img = filename.lower().endswith(img_fmt)
if is_img:
break
# treats image overlay
if is_img:
duration = str(float(ovl['end_time']) - float(ovl['start_time']))
is_gif = filename.lower().endswith('.gif')
has_fade = (float(ovl.get('fade_in_duration', 0)) +
float(ovl.get('fade_out_duration', 0))) > 0
# A GIF with no fade is treated as an animated GIF should.
# It works even if it is not animated.
# An animated GIF cannot have fade in or out effects.
if is_gif and not has_fade:
include_args = ['-ignore_loop', '0']
else:
include_args = ['-f', 'image2', '-loop', '1']
include_args += ['-itsoffset', str(ovl['start_time']), '-t', duration]
# GIFs should have a special input decoder for FFMPEG.
if is_gif:
include_args += ['-c:v', 'gif']
include_args += ['-i']
include_cmd += include_args + ['%s/assets/%s' % (data_dir,
filename)]
# treats video overlays
else:
duration = str(float(ovl['end_time']) - float(ovl['start_time']))
include_args = ['-itsoffset', str(ovl['start_time']), '-t', duration]
include_args += ['-i']
include_cmd += include_args + ['%s/assets/%s' % (data_dir,
filename)]
# adds texts as video starting and finishing on their overlay timing
for img2 in text_tmp_images:
duration = str(float(img2['end_time']) - float(img2['start_time']))
include_args = ['-f', 'image2', '-loop', '1']
include_args += ['-itsoffset', str(img2['start_time']), '-t', duration]
include_args += ['-i']
include_cmd += include_args + [str(img2['path'])]
return include_cmd
|
def remove_duplicates(list1: list) -> list:
"""
Removes duplicates from a list
:param list1: list to remove duplicates from
:return: list with duplicates removed
Example:
>>> remove_duplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4])
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
"""
return list(dict.fromkeys(list1))
|
def transform_to_gps(point, origin, x, y):
"""
Transforms the input point from the local frame to gps coordinates
"""
tr_point = [0, 0]
tr_point[0] = origin[0] + point[0] * x[0] + point[1] * y[0]
tr_point[1] = origin[1] + point[0] * x[1] + point[1] * y[1]
return(tr_point)
|
def chunks(l, n):
"""
@type l: list (or other iterable)
@param l: list that will be splited into chunks
@type n: int
@param n: length of single chunk
@return: list C{l} splited into chunks of length l
Splits given list into chunks. Length of the list has to be multiple of
C{chunk} or exception will be raised.
"""
return [l[i:i+n] for i in range(0, len(l), n)]
|
def SplitLine(line, width):
"""Splits a single line at comma, at most |width| characters long."""
if len(line) <= width:
return (line, None)
n = 1 + line[:width].rfind(",")
if n == 0: # If comma cannot be found give up and return the entire line.
return (line, None)
# Assume there is a space after the comma
assert line[n] == " "
return (line[:n], line[n + 1:])
|
def product_from_name(name):
"""
Return a product name from this tag name or target name.
:param name: eg. "ceph-3.0-rhel-7"
:returns: eg. "ceph"
"""
if name.startswith('guest-'):
# deal with eg. "guest-rhel-X.0-image"
name = name[6:]
parts = name.split('-', 1)
return parts[0]
|
def ht_cm_sqm(ht):
"""Converts height from centimeter to squared meter
Parameters
----------
ht: double
height in cms
Returns
-------
double
height in squared meter.
Examples
--------
>>> ht_cm_sqm(175)
1.75
"""
return (ht / 100) ** 2
|
def _WinPathToUnix(path):
"""Convert a windows path to use unix-style path separators (a/b/c)."""
return path.replace('\\', '/')
|
def _check_groups(problem):
"""Check if there is more than 1 group."""
groups = problem.get('groups')
if not groups:
return False
if len(set(groups)) == 1:
return False
return groups
|
def extract_sentiment(emotions):
"""Extract the sentiment from the facial annotations"""
joy = [0, 0, 0]
sorrow = [0, 0, 0]
anger = [0, 0, 0]
surprise = [0, 0, 0]
odds = ['VERY_LIKELY', 'LIKELY', 'POSSIBLE']
# Loop through the emotions we're pulling and get the count
for i in range(len(odds)):
joy[i] = sum(f['joyLikelihood'] == odds[i] for f in emotions)
anger[i] = sum(f['angerLikelihood'] == odds[i] for f in emotions)
sorrow[i] = sum(f['sorrowLikelihood'] == odds[i] for f in emotions)
surprise[i] = sum(f['surpriseLikelihood'] == odds[i] for f in emotions)
return joy, anger, sorrow, surprise
|
def reverse(head):
""""Reverse a singly linked list."""
# If there is no head.
if not head:
# Return nothing.
return
# Create a nodes list.
nodes = []
# Set node equal to the head node.
node = head
# While node is truthy.
while node:
# Add the node to the nodes list.
nodes.append(node)
# Set node equal to the next node.
node = node.next
# Reverse the list.
nodes.reverse()
# Set count equal to zero.
count = 0
# While count is less than the length of the nodes list
while count < len(nodes):
# If the index is less than the length of the node list minus 1.
if count < len(nodes) - 1:
# Set the current node's next node equal to the next node in the list.
nodes[count].next = nodes[count + 1]
else:
# Set the next node equal to none because this node is the tail of the list.
nodes[count].next = None
# Increment the count.
count = count + 1
# Return the first node in the nodes list.
return nodes[0]
|
def get_product_metadata(product_file):
"""
Metadata appended for labels xr.DataArray
"""
return dict({"product_file": product_file})
|
def quotas_panel(context, request, quota_form=None, quota_err=None, in_user=True):
"""quota form for 2 different user pages."""
return dict(
quota_form=quota_form,
quota_err=quota_err,
in_user=in_user,
)
|
def primary_key(row):
"""input: dict(file=, sentId=, eId=, eiId=, eText=, )
output: (file, sentId, eId, eiId)
"""
return (row["file"], int(row["sentId"]), row["eId"], row["eiId"])
|
def strip_leading_secret(path):
"""Strip leading 'secret/'"""
if path[:7].lower() == "secret/":
path = path[7:]
while path[-1] == "/":
path = path[:-1]
if not path:
raise ValueError("A non-root secret path must be specified.")
return path
|
def _build_backend_map():
"""
The set of supported backends is defined here.
"""
return {"pytorch"}
|
def get_xml_version(version):
"""Determines which XML schema to use based on the client API version.
Args:
version: string which is converted to an int. The version string is in
the form 'Major.Minor.x.y.z' and only the major version number
is considered. If None is provided assume version 1.
"""
if version is None:
return 1
return int(version.split(".")[0])
|
def fix_fp(sequence, parallel):
"""
Fix footprints
Parameters
--------------
sequence
Sequence
parallel
Parallel
Returns
-------------
sequence
Sequence
parallel
Parallel
"""
sequence = sequence.difference(parallel)
return sequence, parallel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.