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 co... |
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
``t... |
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,... |
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... |
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',... |
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 str... |
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:
... |
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 err... |
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 ... |
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].stri... |
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
... |
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 c... |
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 app... |
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_l... |
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]
... |
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("/"):
pa... |
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:
... |
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,... |
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(eva... |
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 c... |
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... |
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)
... |
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 potent... |
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
retur... |
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.
"""
# exte... |
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
... |
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', '... |
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"])
... |
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``
... |
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'
)... |
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,... |
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(st... |
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}_pa... |
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... |
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.3... |
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] == '(':
... |
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... |
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... |
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"
"""
... |
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... |
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:])
... |
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 def... |
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'.j... |
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 dim... |
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", ""),
... |
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 t... |
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' ... |
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... |
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.