content
stringlengths 42
6.51k
|
|---|
def parse_get_course_contents(course_contents, courseId):
"""
Extract used course contents for a specific course.
Extract only needed course contents. Ignore contents of module type forum, lti, feedback, workshop, data, chat,
survey or glossary. Return the other contents in a dictionary.
:param course_contents: All contents of a course.
:type course_contents: list(dict(str, int))
:param courseId: The id of the course the contents are from.
:type courseId: int
:return: A list of dictionaries. Each dictionary contains a course id, module name, target, type and external id.
:rtype: list(dict(str, int))
"""
content_list = []
for section in course_contents:
for module in section['modules']:
if module['modname'] == 'forum' or module['modname'] == 'lti' or module['modname'] == 'feedback' or \
module['modname'] == 'workshop' or module['modname'] == 'data' or module['modname'] == 'chat' or \
module['modname'] == 'survey' or module['modname'] == 'glossary':
continue
if module['modname'] == 'book':
for content in module['contents'][1:]:
url = "{}&chapterid={}".format(module['url'], content["filepath"][1:-1])
content_list.append(
{'course_id': courseId, 'name': content["content"], 'target': url,
'type': "chapter", 'external_id': int(content["filepath"][1:-1])}
)
content_list.append(
{'course_id': courseId, 'name': module['name'], 'target': module['url'], 'type': module['modname'],
'external_id': int(module['id'])}
)
return content_list
|
def _docrevision(docstr):
"""To reduce docstrings from RawPen class for functions
"""
if docstr is None:
return None
newdocstr = docstr.replace("turtle.","")
newdocstr = newdocstr.replace(" (for a Pen instance named turtle)","")
return newdocstr
|
def _calc_tb(eff, n_gre, tr_gre, tr_seq, ti1, ti2, a1, a2):
""" Calculate TB for MP2RAGE sequence."""
return ti2 - ti1 - n_gre * tr_gre
|
def gen_Datastream(temperature, position, drone_id):
"""Generate a datastream objects."""
datastream = {
"@type": "Datastream",
"Temperature": temperature,
"Position": position,
"DroneID": drone_id,
}
return datastream
|
def is_key_value_exist(list_of_dict, key, value):
"""
Check if at least one value of a key is equal to the specified value.
"""
for d in list_of_dict:
if d[key] == value:
return True
return False
|
def create_path(data_dir):
"""Return tuple of str for training, validation and test data sets
Args:
data_dir (str): A string representing a directory containing sub-directories for
training, validation and test data sets
Returns:
tuple: Returns a tuple of strings for
``data_dir`` - data directory
``train_dir`` - training data
``valid_dir`` - validation data
``test_dir`` - test data
"""
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
return (data_dir, train_dir, valid_dir, test_dir)
|
def _dsym_files(files):
"""Remove files that aren't dSYM files."""
return [
f
for f in files
if f.path.find(".dSYM") != -1
]
|
def group(lst, count):
"""Group a list into consecutive count-tuples. Incomplete tuples are
discarded.
`group([0,3,4,10,2,3], 2) => [(0,3), (4,10), (2,3)]`
From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303060
"""
return list(zip(*[lst[i::count] for i in range(count)]))
|
def linear_search(sequence, target):
"""Pure implementation of linear search algorithm in Python
:param sequence: some sorted collection with comparable items
:param target: item value to search
:return: index of found item or None if item is not found
Examples:
>>> linear_search([0, 5, 7, 10, 15], 0)
0
>>> linear_search([0, 5, 7, 10, 15], 15)
4
>>> linear_search([0, 5, 7, 10, 15], 5)
1
>>> linear_search([0, 5, 7, 10, 15], 6)
"""
for index, item in enumerate(sequence):
if item == target:
return index
return None
|
def test(N, n):
"""
>>> test(8, 2)
True
>>> test(8, 3)
False
>>> test(24, 4)
True
"""
for ii in range(n,0,-1): # Start from n and down till 1
if (N%ii > 0):
return False
return True
|
def regex_match_list(line, patterns):
"""Given a list of COMPILED regex patters, perform the "re.match" operation
on the line for every pattern.
Break from searching at the first match, returning the match object.
In the case that no patterns match, the None type will be returned.
@param line: (unicode string) to be searched in.
@param patterns: (list) of compiled regex patterns to search "line"
with.
@return: (None or an re.match object), depending upon whether one of
the patterns matched within line or not.
"""
m = None
for ptn in patterns:
m = ptn.match(line)
if m is not None:
break
return m
|
def get_shell(name='bash'):
"""Absolute path to command
:param str name: command
:return: command args
:rtype: list
"""
if name.startswith('/'):
return [name]
return ['/usr/bin/env', name]
|
def interpreted_value(slot):
"""
Retrieves interprated value from slot object
"""
if slot is not None:
return slot["value"]["interpretedValue"]
return slot
|
def base10toN(num,n=36):
"""Change a to a base-n number.
Up to base-36 is supported without special notation."""
num_rep = {10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f', 16:'g', 17:'h', 18:'i', 19:'j', 20:'k', 21:'l', 22:'m',
23:'n', 24:'o', 25:'p', 26:'q', 27:'r', 28:'s', 29:'t', 30:'u', 31:'v', 32:'w', 33:'x', 34:'y', 35:'z'}
new_num_string = ''
current = num
while current != 0:
remainder = current % n
if 36 > remainder > 9:
remainder_string = num_rep[remainder]
elif remainder >= 36:
remainder_string = '(' + str(remainder) + ')'
else:
remainder_string = str(remainder)
new_num_string = remainder_string + new_num_string
current = current // n
return new_num_string
|
def clickable_link(link, display_str = 'link'):
"""Converts a link string into a clickable link with html tag.
WARNING: This function is not safe to use for untrusted inputs since the
generated HTML is not sanitized.
Usage:
df.style.format(clickable_link, subset=['col_name'])
Args:
link: A link string without formatting.
display_str: What text the link should display.
Returns:
HTML-formatted link.
"""
return f'<a href="{link}">{display_str}</a>'
|
def chain(fns, x):
""" Sequentially apply a sequence of functions """
for fn in fns:
x = fn(x)
return x
|
def format_float_or_int_string(text: str) -> str:
"""Formats a float string like "1.0"."""
if "." not in text:
return text
before, after = text.split(".")
return f"{before or 0}.{after or 0}"
|
def none_if_invalid(item):
"""
Takes advantage of python's 'falsiness' check by
turning 'falsy' data (like [], "", and 0) into None.
:param item: The item for which to check falsiness.
:return: None if the item is falsy, otherwise the item.
"""
return item if bool(item) else None
|
def recreate_shots_from_counts( counts ):
"""Recreate shots from job result counts
Recreates the individual shot results for the number of times the quantum circuit is repeated
Args:
counts (dict): job result counts, e.g. For 1024 shots: {'000': 510, '111': 514}
Returns:
list: the recreated-shots, e.g. ['000', '000', '111', '111']
"""
raw_shots = []
for k, v in counts.items():
k = k[::-1]
for x in range(v):
raw_shots.append(k.replace(" ", ""))
return raw_shots
|
def _log_write_log(error, msg, *args, **kwargs):
"""
Low-Level log write
"""
def timestamp_str(timestamp_data):
return timestamp_data.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
if False:
with open(NFVI_OPENSTACK_LOG, "a") as f:
fcntl.flock(f, fcntl.LOCK_EX)
if error:
f.write(str('** ' + timestamp_str(datetime.datetime.now()) + ' ' +
msg + '\n', *args, **kwargs))
else:
f.write(str(' ' + timestamp_str(datetime.datetime.now()) + ' ' +
msg + '\n', *args, **kwargs))
fcntl.flock(f, fcntl.LOCK_UN)
|
def squareSpiralCorners(side):
"""Returns the four corners of a spiral square in the given side length.
The corners are returned in a tuple in the order:
(topRight, topLeft, bottomLeft, bottomRight)
"""
botR = side * side
botL = botR - side + 1
topL = botL - side + 1
topR = topL - side + 1
return (topR, topL, botL, botR)
|
def trim_js_ext(filename):
"""
If `filename` ends with .js, trims the extension off.
>>> trim_js_ext('foo.js')
'foo'
>>> trim_js_ext('something_else.html')
'something_else.html'
"""
if filename.endswith('.js'):
return filename[:-3]
else:
return filename
|
def genomic_del5_rel_37(genomic_del5_37_loc):
"""Create test fixture relative copy number variation"""
return {
"type": "RelativeCopyNumber",
"_id": "ga4gh:VRC.bRyIyKsXFopd8L5vhyZ55xucloQRdxQS",
"subject": genomic_del5_37_loc,
"relative_copy_class": "copy neutral"
}
|
def get_workspaces(layout_json):
"""Gets the workspace names from the layout json"""
if not layout_json:
return []
outputs = layout_json['Root']
workspaces = []
for output in outputs:
workspaces.extend(output['Output'])
return [list(workspace.keys())[0].split('Workspace')[1].strip()
for workspace in workspaces]
|
def make_pairs(sent, dist):
"""
For each word in sentence `sent`, consider its neighbors in window_size `ws`.
Assign each neighbor according to the distribution `dist` = [dist1, dist2, dist3,...]
left3, left2, left1, word, right1, right2, right3
dist1, dist2, dist3, , dist3, dist2, dist1
Return an iterator over 2 types of pair:
(left_i, word, dist_i) and
(word, right_i, dist_i)
"""
n = len(sent)
ws = min(len(dist), n-1)
pairs = []
for i in range(n-1):
pairs += [(sent[i], sent[i+w+1], dist[w]) for w in range(ws) if i+w+1 < n]
return pairs
|
def check_comparison(function, within_column_clause, returns_boolean, compare_value):
"""Because Oracle and MS SQL do not want to know Boolean and functions return 0/1 or the string 'TRUE',
we manually have to add a comparison, but only if the function is called inside the where-clause,
not in the select clause.
For example:
select .. from .. where SDO_EQUAL(.., ..) = 'TRUE'
select SDO_EQUAL(.., ..) from ..
"""
if returns_boolean and not within_column_clause:
return (function == compare_value)
else:
return function
|
def mark_doc(doc, wids, mark=None, pos=None):
"""
Given a list of words and a set of word positions, mark the words in those positions.
:param list doc: a list of words (strings)
:param set wids: the positions of the words to be marked
:param string mark: a string that sets the mark that will be applied
to each of the selected words
:param string pos: can be one of {"prefix", "suffix"}
:return: the marked list of words
"""
if mark is None:
mark = "NEG"
if pos is None:
pos = "suffix"
marked_doc = []
for i, tok in enumerate(doc):
if i in wids:
if pos == "prefix":
word = mark + "_" + tok
else:
word = tok + "_" + mark
marked_doc.append(word)
else:
marked_doc.append(tok)
return marked_doc
|
def get_len_of_bigger_sentence(sentences, default_max_len=None):
"""Bert demands a default maximun phrase len to work properly.
This lenght is measured by number of words. If the phrase is
smaller than maximun len, the remaining blank elements are filled
with padding tokens.
"""
if default_max_len:
return default_max_len
max_len = 0
for sent in sentences:
max_len = max(max_len, len(sent.split(' ')))
print('Max sentence length: ', max_len)
return max_len
|
def is_seq(obj):
"""
Returns true if `obj` is a non-string sequence.
"""
try:
len(obj)
except (TypeError, ValueError):
return False
else:
return not isinstance(obj, str)
|
def _segment_length(geometry):
""" return an array of the segment length along the root `geometry` """
import numpy as np
pos = np.array(geometry)
vec = np.diff(pos,axis=0)**2
return (vec.sum(axis=1)**.5)
|
def index_items(universe, itemset):
"""
Returns a list of indices to the items in universe that match items in itemset
"""
return [ idx for idx, item in enumerate(universe) if item in itemset ]
|
def all_equal(*args):
"""
Returns True if all of the provided args are equal to each other
Args:
*args (hashable): Arguments of any hashable type
Returns:
bool: True if all of the provided args are equal, or if the args are empty
"""
return len(set(args)) <= 1
|
def iround(m):
"""Rounds the number to the nearest number with only one significative digit."""
n = 1
while (m + n/2) / n >= 10:
n*= 10
while (m + n/2) / n >= 5:
n*= 5
rm = m - (m/n)*n
return ((m+rm)/n)*n
|
def dot_p(u, v):
""" method 1 for dot product calculation to find angle """
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]
|
def zipdict(ks, vs):
"""Returns a dict with the keys mapped to the corresponding vals."""
return dict(zip(ks, vs))
|
def split_org_repo(in_str):
"""Splits the input string to extract the repo and the org
If the repo is not provided none will be returned
Returns a pair or org, repo
"""
tokens = in_str.split('/', 1)
org = tokens[0]
repo = None
if len(tokens) > 1 and tokens[1]:
repo = tokens[1]
return org, repo
|
def make_url(portal_url, *arg):
"""Makes a URL from the given portal url and path elements."""
url = portal_url
for path_element in arg:
if path_element == "":
continue
while url.endswith("/"):
url = url[:-1]
while path_element.startswith("/"):
path_element = path_element[1:]
url = url+"/"+path_element
return url
|
def calculate_score(cards):
"""Takes a list of cards as input and returns the score calculated from the sum of the cards"""
# Sum of all cards in the list inputted to calculate_score(list_of_cards)
score = sum(cards)
# Checking for Blackjack(sum = 21) with only 2 cards
if score == 21 and len(cards) == 2:
return 0 #(0 means BLackjack)
# Checking from an Ace(11) and if the sum is over 21. We will remove Ace(11) from the cards list and append 1 as the value of Ace.
if 11 in cards and score > 21:
cards.remove(11)
cards.append(1)
return score
|
def is_binary_string(pcap_path: str):
"""test if file is a txt list or binary
Args:
pcap_path (str): Description
Returns:
bool: Description
"""
textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
binary_string = lambda bytes: bool(bytes.translate(None, textchars))
return binary_string(open(pcap_path, 'rb').read(64))
|
def convert_type(t, v):
"""Convert value 'v' to type 't'"""
_valid_type = ['int', 'float', 'long', 'complex', 'str']
if t not in _valid_type:
raise RuntimeError(
'[-] unsupported type: '
f'must be one of: {",".join([i for i in _valid_type])}')
try:
return type(eval("{}()".format(t)))(v) # nosec
except ValueError:
raise ValueError(f'type={t}, value="{v}"')
|
def isValidID(id:str) -> bool:
""" Check for valid ID. """
#return len(id) > 0 and '/' not in id # pi might be ""
return id is not None and '/' not in id
|
def tidy_string(s):
"""Tidy up a string by removing braces and escape sequences"""
s = s.replace("{", "").replace("}", "")
return s.replace("\'", "").replace('\"', "").replace('\\','')
|
def convert_where_clause(clause: dict) -> str:
"""
Convert a dictionary of clauses to a string for use in a query
Parameters
----------
clause : dict
Dictionary of clauses
Returns
-------
str
A string representation of the clauses
"""
out = "{"
for key in clause.keys():
out += "{}: ".format(key)
#If the type of the right hand side is string add the string quotes around it
if type(clause[key]) == str:
out += '"{}"'.format(clause[key])
else:
out += "{}".format(clause[key])
out += ","
out += "}"
return out
|
def accepts(source):
""" Test if source matches a Twitter handle """
# If the source equals the plugin name, assume a yes
if source["type"] == "twitter":
return True
# Default to not recognizing the source
return False
|
def petal_rotation(npos, reverse=False):
"""Return a dictionary that implements the petal rotation.
"""
rot_petal = dict()
for p in range(10):
if reverse:
newp = p - npos
if newp < 0:
newp += 10
else:
newp = p + npos
if newp > 9:
newp -= 10
rot_petal[p] = newp
return rot_petal
|
def check_rows(board):
"""
check_rows: determines if any row is complete
"""
for j in [1, 2]:
for i in range(0, 3):
if (
((board >> 6 * i & 3) == j)
and ((board >> 2 + (6 * i) & 3) == j)
and ((board >> 4 + (6 * i) & 3) == j)
):
return j
return None
|
def extract_keys(nested_dict):
"""
This function is used in order to parse the.json output generated by executing conda search <package-name>
for potential install candidates.
Parameters
----------
nested_dict : dictionary
.json file
Returns
-------
key_lst: list
list containing only the keys (the potential installation candidates)
"""
key_lst = []
for key, value in nested_dict.items():
key_lst.append(key)
if isinstance(value, dict):
extract_keys(value)
return key_lst
|
def weighted_sum(scores, query):
"""Computes a weighted sum based on the query"""
DEFAULT_WEIGHT = 0
total = 0
for feature in scores.keys():
if feature in query:
total += scores[feature] * query[feature]
else:
total += scores[feature] * DEFAULT_WEIGHT
return total
|
def check_format(input_data, data_type):
"""
input_data will be checked by the its own data type.
:param input_data: str, the given key or ciphered string.
:param data_type: str, indicate what kind of data type to check format.
:return: str, input data all checked in legal format.
"""
# extension: check secret number isdigit
if data_type == "int":
if not input_data.isdigit():
input_data = check_format(input("Secret number should be a number, enter again: "), "int")
else:
# all upper
input_data = input_data.upper()
return input_data
|
def is_answerable(example):
"""
unchanged from @chrischute
"""
return len(example['y2s']) > 0 and len(example['y1s']) > 0
|
def _filter_runs(runs, args):
"""
Constructs a filter for runs from query args.
"""
try:
run_id, = args["run_id"]
except KeyError:
pass
else:
runs = ( r for r in runs if r.run_id == run_id )
try:
job_id, = args["job_id"]
except KeyError:
pass
else:
runs = ( r for r in runs if r.inst.job_id == job_id )
return runs
|
def _apriori_gen(frequent_sets):
"""
Generate candidate itemsets
:param frequent_sets: list of tuples, containing frequent itemsets [ORDERED]
>>> _apriori_gen([('A',), ('B',), ('C',)])
[('A', 'B'), ('A', 'C'), ('B', 'C')]
>>> _apriori_gen([('A', 'B'), ('A', 'C'), ('B', 'C')])
[('A', 'B', 'C')]
>>> _apriori_gen([tuple(item) for item in ['ABC', 'ABD', 'ABE', 'ACD', 'BCD', 'BCE', 'CDE']])
[('A', 'B', 'C', 'D'), ('A', 'B', 'C', 'E'), ('A', 'B', 'D', 'E'), ('B', 'C', 'D', 'E')]
>>> cc = [('55015', '55314'), ('55015', '55315'), ('55314', '55315'), ('57016', '57017'), ('57043', '57047'), ('581325', '582103')]
>>> _apriori_gen(cc)
[('55015', '55314', '55315')]
"""
# Sanity check for the input
errors = [freq for freq in frequent_sets if sorted(list(set(freq))) != sorted(list(freq))]
assert not errors, errors
assert sorted(list(set(frequent_sets))) == sorted(frequent_sets), \
set([(x, frequent_sets.count(x)) for x in frequent_sets if frequent_sets.count(x) > 1])
new_candidates = []
for index, frequent_item in enumerate(frequent_sets):
for next_item in frequent_sets[index + 1:]:
if len(frequent_item) == 1:
new_candidates.append(tuple(frequent_item) + tuple(next_item))
elif frequent_item[:-1] == next_item[:-1]:
new_candidates.append(tuple(frequent_item) + (next_item[-1],))
else:
break
return new_candidates
|
def display2classmethod(display):
"""Opposite of classmethod2display.
"""
L = display.split(" -> ")
return L[0], L[1]
|
def load_options(debug=False, pdb=False):
"""Load backend options."""
return {"debug": debug, "pdb": pdb}
|
def _get_class_name(property_repr: str) -> str:
"""
Extract the class name from the property representation.
:param property_repr: The representation
:type property_repr: str
:return: The class name
:rtype: str
"""
return property_repr[: property_repr.index("(")]
|
def get_item_from_path(obj, path):
"""
Fetch *obj.a.b.c* from path *"a/b/c"*.
Returns None if path does not exist.
"""
*head, tail = path.split("/")
for key in head:
obj = getattr(obj, key, {})
return getattr(obj, tail, None)
|
def removeCodeImage(image, photoDict):
"""
Deletes the list of images from photoDict with the alphacode as image
"""
#logging.debug("TEst 1")
alphacode = image[0:4]
#logging.debug("TEst 2")
photoDict.pop(alphacode, None)
return photoDict
|
def not_resource_cachable(bel_resource):
"""Check if the BEL resource is cacheable.
:param dict bel_resource: A dictionary returned by :func:`get_bel_resource`.
"""
return bel_resource['Processing'].get('CacheableFlag') not in {'yes', 'Yes', 'True', 'true'}
|
def prepare_jama_mention(jama_user_info):
"""
Make a html block of jama's @mention functionality
@params:
ama_user_info -> The user data get from jama's REST API /users
"""
full_name = jama_user_info["firstName"] + " " + jama_user_info["lastName"]
user_id = str(jama_user_info["id"])
return "<span contenteditable='false' data-j-object='User:" + user_id + "' data-j-type='User' data-j-name='" +\
full_name + "' data-j-key='" + jama_user_info["username"] + "' data-j-id='" + user_id +\
"' class='js-at-mention-key at-mention-key js-at-mention-user at-mention-user'>" + full_name + "</span>"
|
def statusError(pkt):
"""
Grabs the status (int) from an error packet and returns it. It retuns -1
if the packet is not a status packet.
"""
if pkt[7] == 0x55:
return pkt[8]
return -1
|
def response_formatter(text, username, max_length=140):
"""
Formats response to be below ``max_length`` characters long.
Args:
text (str): text to return
username (str): username to @. @<username> is tacked on to end of tweet
max_lenght (int): max length of tweet. Default: ``140``
Returns:
(str): the tweet text
"""
while len('{} @{}'.format(text, username)) > max_length:
text = text[:-1]
return '{} @{}'.format(text, username)
|
def get_weekday_number(str_weekday):
"""
Using name of weekday return its number representation
:param str_weekday: weekday from mon - sun
:return: integer number [0..7]
"""
weekdays = (
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
'sun'
)
return weekdays.index(str_weekday[:3].lower())
|
def get_image_detail(image):
"""
Method call to get image details
:param image: Image object to Describe
:return: return id, status and object of disk
"""
if image:
return {'id': image.image_id,
'image_name': image.image_name,
'size': image.size,
'region_id': image.region,
'disk_device_mappings': image.disk_device_mappings,
'status': image.status,
'platform': image.platform,
'launch_time': image.creation_time
}
|
def julia(a, b, e, f):
""" One run of the Julia function, returns new a and b.
f(n) = f(n)^2 + c
f(n) = f(a + bi)
c = e + fi
"""
ii = -1 # i-squared
an=0.0 # new a and b
bn=0.0 # needed so bn = ... can be done.
an = a*a + b*b*ii + e
bn = a*b + a*b + f
a=an
b=bn
return a, b
|
def reverse_number(n: int) -> int:
""" This function takes in input 'n' and returns 'n' with all digits reversed. """
if len(str(n)) == 1:
return n
k = abs(n)
reversed_n = []
while k != 0:
i = k % 10
reversed_n.append(i)
k = (k - i) // 10
return int(''.join(map(str, reversed_n))) if n > 0 else -int(''.join(map(str, reversed_n)))
|
def get_col_names(name):
"""
We store results for each simulation in indexed files.
Every simulation will indicate its results with a path and an idx property.
Returns the pair of column names for the given type of results.
Eg: "spikes" -> ("spikes_path", "spikes_idx")
"""
return f'{name}_path', f'{name}_idx'
|
def parse_ui__quit(user_input):
"""Parse quit."""
flag_run = False
return flag_run
|
def points(games):
"""
Our football team finished the championship. The result of each match look like "x:y". Results of all matches are
recorded in the collection. Write a function that takes such collection and counts the points of our team in the
championship. Rules for counting points for each match: if x>y - 3 points, if x<y - 0 point, and if x=y - 1 point
:param games: a list of strings containing the scores.
:return: the total amount of points our football team earned.
"""
score = 0
for x in games:
if x[0] > x[2]:
score += 3
elif x[0] == x[2]:
score += 1
return score
|
def basal_metabolic_rate(gender, weight, height, age):
"""Calculate and return a person's basal metabolic rate (bmr).
Parameters:
weight must be in kilograms.
height must be in centimeters.
age must be in years.
Return: a person's basal metabolic rate in kcal per day.
"""
if gender == "M":
bmr = 88.362 + 13.397 * weight + 4.799 * height - 5.677 * age
elif gender == "F":
bmr = 447.593 + 9.247 * weight + 3.098 * height - 4.330 * age
else:
bmr = -1
return round(bmr, 0)
|
def este_corect(expresie):
"""Apreciaza corectitudinea expresiei."""
memo = []
for _, val in enumerate(expresie):
if val not in '([)]':
return False
if val == '(' or val == '[':
memo.append(val)
if val == ')':
if memo and memo[len(memo)-1] == '(':
memo.pop()
else:
return False
if val == ']':
if memo and memo[len(memo)-1] == '[':
memo.pop()
else:
return False
return not memo
|
def quote(a):
"""
SQLify a string
"""
return "'"+a.replace("'","''").replace('\\','\\\\')+"'"
|
def get_pt2262_deviceid(device_id, nb_data_bits):
"""Extract and return the address bits from a Lighting4/PT2262 packet."""
import binascii
try:
data = bytearray.fromhex(device_id)
except ValueError:
return None
mask = 0xFF & ~((1 << nb_data_bits) - 1)
data[len(data)-1] &= mask
return binascii.hexlify(data)
|
def it_controller(it, process_error_value, i_gain_value):
"""Docstring here (what does the function do)"""
it = it + process_error_value
it = it * i_gain_value
return it
|
def _psfs_to_dvisc_units(visc_units: str) -> float:
"""same units as pressure, except multiplied by seconds"""
if visc_units == '(lbf*s)/ft^2':
factor = 1.
elif visc_units in ['(N*s)/m^2', 'Pa*s']:
factor = 47.88026
else:
raise RuntimeError('visc_units=%r; not in (lbf*s)/ft^2, (N*s)/m^2, or Pa*s')
return factor
|
def check_words(title, wordlist, verbose=False):
"""Helper function to check if any words in wordlist are in title."""
for word in wordlist:
if title.find(word) >= 0:
if verbose:
print("\t\tFOUND '"+word+"' IN:", title)
return True
return False
|
def cross(a, b):
""" Vector product of real-valued vectors """
return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]
|
def _mean(data, n):
"""
Calculate the mean of a list,
:param data: List of elements
:param n: Number of elements
:return: Mean
"""
return sum(data) / float(n)
|
def add_prefix(prefix, split, string):
"""
Adds a prefix to the given string
:param prefix: str, prefix to add to the string
:param split: str, split character
:param string: str, string to add prefix to
:return: str
"""
return split.join([prefix, string])
|
def quote(input_str):
"""Adds single quotes around a string"""
return "'{}'".format(input_str)
|
def parse_point_and_colour(point_or_colour_string):
"""
Parses a point or colour to just space separated characters
Args:
point_string (string): The point in string format as "(x, y)" or colour as "[r, g, b]"
Returns:
string: the point parsed into "x y" or clour as "r g b"
"""
point_or_colour_string = point_or_colour_string[1:-1]
return " ".join(point_or_colour_string.split(", "))
|
def text_to_emoji(text: str):
""" Convert text to a string of regional emoji.
Text must only contain characters in the alphabet from A-Z.
:param text: text of characters in the alphabet from A-Z.
:return: str: formatted emoji unicode.
"""
regional_offset = 127397 # This number + capital letter = regional letter
return "".join(chr(ord(c) + regional_offset) for c in text.upper())
|
def modpos(mod):
"""Return aminoacid__position of modification
Because some fixed mods can be on aa * (e.g. N-term)"""
return '{}__{}'.format(mod[1], mod[3])
|
def star_char(num_stars: int):
"""
Given a number of stars (0, 1, or 2), returns its leaderboard
representation.
"""
return " .*"[num_stars]
|
def merge(ll, lr):
"""
:param ll: sorted list
:param lr: sorted list
:return: sorted list
"""
result = []
i = 0
j = 0
while True:
if i >= len(ll):
result.extend(lr[j:])
return result
elif j >= len(lr):
result.extend(ll[i:])
return result
elif ll[i] < lr[j]:
result.append(ll[i])
i += 1
else:
result.append(lr[j])
j += 1
|
def align_center(msg, length):
""" Align the message to center. """
return f'{msg:^{length}}'
|
def unescape(text):
"""Removes '\\' escaping from 'text'."""
rv = ''
i = 0
while i < len(text):
if i + 1 < len(text) and text[i] == '\\':
rv += text[i + 1]
i += 1
else:
rv += text[i]
i += 1
return rv
|
def removeNamespace(node):
"""
:param str node:
:return: Namespace-less path
:rtype: str
"""
sections = [
s.split(":")[-1] if s.count(":") else s
for s in node.split("|")
]
return "|".join(sections)
|
def _node(default=''):
""" Helper to determine the node name of this machine.
"""
try:
import socket
except ImportError:
# No sockets...
return default
try:
return socket.gethostname()
except OSError:
# Still not working...
return default
|
def writeidf(data):
""" formats the output format of parseidf.parse() to the IDF format.
Example input: { 'A': [['A', '0'], ['A', '1']] }
Example output:
A, 0;
A, 1;
"""
lines = []
for objecttype in sorted(data.values()):
for idfobject in objecttype:
line = ',\n\t'.join(idfobject) + ';'
lines.append(line)
return '\n'.join(lines)
|
def get_dims(dims, key1, var1, key2, var2):
"""
Parse a shape nested dictionary to derive a dimension tuple for dimensions to
marginalize over. This function is used to create
dimension tuples needed for plotting functions that plot a 2D figure with a color that
must marginalize over all higher dimensions. The first 2 values in the tuple are the
plotted variables while the others are the ones to be marginalized over.
Parameters
----------
dims : dict of dict
Dictionary containing body and variable and dimensional position of that variable, e.g.
shape = {"secondary" : {"Eccentricity" : 0}} indicates that this simulation suite was
run where secondary eccentricity was the first varied variable (1st line in the
vspace input file).
key1, key2 : str
Names of bodies
var1, var2 : str
Names of variables associated with given body
Returns
-------
dims : tuple
dims of your data, e.g. (1,3)
Example
-------
>>> dims = {"secondary" : {"Eccentricity" : 0, "SemimajorAxis" : 1}, "cbp": {"Eccentricity" : 2,
"SemimajorAxis" : 3}}
>>> get_dims(dims, "cbp", "Eccentricity", "secondary", "SemimajorAxis")
(3, 0)
"""
holder = []
# Loop over bodies
for key in dims.keys():
# Loop over variables for each body
for var in dims[key].keys():
# If key-var pair not a user-defined one, append it
# These are the dimensions to marginalize over!
if (var != var1 or key != key1) and (var != var2 or key != key2):
holder.append(dims[key][var])
return list(holder)
|
def make_scenario_name_nice(name):
"""Make a scenario name nice.
Args:
name (str): name of the scenario
Returns:
nice_name (str): nice name of the scenario
"""
replacements = [
("_", " "),
(" with", "\n with"),
("fall", ""),
("spring", ""),
("summer", ""),
]
nice_name = name
for old, new in replacements:
nice_name = nice_name.replace(old, new)
nice_name = nice_name.lstrip("\n")
return nice_name
|
def desc2fn(description: tuple) -> tuple:
"""Extract tuple of field names from psycopg2 cursor.description."""
return tuple(d.name for d in description)
|
def any_public_tests(test_cases):
"""
Returns whether any of the ``Test`` named tuples in ``test_cases`` are public tests.
Args:
test_cases (``list`` of ``Test``): list of test cases
Returns:
``bool``: whether any of the tests are public
"""
return any(not test.hidden for test in test_cases)
|
def aspect_in_filters(aspect_type, aspect_name, filters):
"""Checks if an aspect is in the existing set of filters
Arguments:
aspect_type (string): Either 'builtin' or 'dimension'
aspect_name (string or qname): if 'builtin' this will be a string with values of 'concept', 'unit', 'period', 'entity' or 'cube', otherwise it is a qname
of the dimensional aspect name.
filters (dictionary): Dictionary of aspect filters.
"""
for filter_type, filter_name, _x, _y, _z in filters:
if filter_type == aspect_type and filter_name == aspect_name:
return True
# This will only hit if the aspect was not found in the filters.
return False
|
def get_data_path(name):
"""get_data_path
:param name:
:param config_file:
"""
if name == 'cityscapes':
return '../data/CityScapes/'
if name == 'gta' or name == 'gtaUniform':
return '../data/gta/'
if name == 'synthia':
return '../data/RAND_CITYSCAPES'
|
def _look_before (index_sentence,context) :
"""Generate the look before context starting with the sentence index and looking no less than the first sentence"""
context_pairs=[]
for i in range(1,context+1) :
s_index=index_sentence-i
if s_index>=0 :
context_pairs.append(( s_index,index_sentence))
return context_pairs
|
def getwords(line):
""" Get words on a line.
"""
line = line.replace('\t', ' ').strip()
return [w for w in line.split(' ') if w]
|
def get_optimal_cloud_resolution(res_x=10, res_y=10):
"""
Determines the optimal resolution for cloud detection:
* 80m x 80m or worse
"""
cloud_res_x = 80 if res_x < 80 else res_x
cloud_res_y = 80 if res_y < 80 else res_y
return cloud_res_x, cloud_res_y
|
def parse_int(val: bytes) -> int:
"""Bytes to int
"""
return int.from_bytes(val, byteorder="big")
|
def sqlquote( value ):
"""Naive SQL quoting
All values except NULL are returned as SQL strings in single quotes,
with any embedded quotes doubled.
"""
if value is None or value=="":
return 'NULL'
return "'{}'".format(str(value).replace( "'", "''" ))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.