content stringlengths 42 6.51k |
|---|
def get_available_username(user_profile):
"""
Determines the username based on information available from slack.
First information is used in the following order:
1) display_name, 2) real_name
:param user_profile: Slack user_profile dict
:return: human-readable username
"""
display_nam... |
def _TypeMismatch(a, b):
"""The entries at the same position in A and B have differing types."""
return 'Types do not match, %s v. %s' % (str(a), str(b)) |
def get_python_exec(py_num: float, is_py2: bool = False) -> str:
""" Get python executable
Args:
py_num(float): Python version X.Y
is_py2(bool): for python 2 version, Set True if the returned result should have python2 or False for python.
Returns:
str: python executable
"""
... |
def step_function(x: float):
""" Mathematical step function
A type of indicatio function/characteristic function.
"""
return 1.0 if x >= 0 else 0.0 |
def mosek_test_tags(mosek_required = True):
"""Returns the test tags necessary for properly running MOSEK tests.
By default, sets mosek_required=True, which will require that the supplied
tag filters include "mosek".
MOSEK checks a license file outside the workspace, so tests that use MOSEK
must h... |
def _DictToString(dictionary):
"""Convert a dictionary to a space separated 'key=value' string.
Args:
dictionary: the key-value dictionary to be convert
Returns:
a string representing the dictionary
"""
dict_str = ' '.join(' {key}={value}'.format(key=key, value=value)
for key, ... |
def are_n(n):
"""A bit of grammar. This function returns a string with the appropriate
singular or plural present indicative form of 'to be', along with 'n'."""
choices = ['are no', 'is 1', f'are {n}']
if n < 2:
return choices[n]
else:
return choices[2] |
def parse_content_type(c):
"""
A simple parser for content-type values. Returns a (type, subtype,
parameters) tuple, where type and subtype are strings, and parameters
is a dict. If the string could not be parsed, return None.
E.g. the following string:
text/html; chars... |
def chopping(long_string):
"""
Twitch won't let you send messages > 500
:param long_string:
:return:
"""
texts = []
start, index = 0, 0
while index >= 0:
index = long_string.find(',', start + 450)
if index > 0:
texts.append(long_string[start:index])
el... |
def remove_start_end_blanks(regex, list_span):
""" if regex starts with \n and end with multiple spaces
shortens the spans of the corresponing length"""
if regex[0:2]==r"\n":
list_span = [(x[0]+1, x[1]) for x in list_span]
if regex[-2:] == " ":
list_span = [(x[0], x[1]-2) for x... |
def concatenateString(data, delimiter='\t'):
"""
Concatenate string list by using proviced delimeter
Args:
data: list of strings
delimiter: symbol, default to ' ', used to separate text
Returns:
Concatenated strings separated by delimeter
"""
return delimiter.join(data... |
def _filter_match_all(elements, keywords):
"""
Returns the elements for which all keywords are contained.
:param elements: a list of strings to filter
:param keywords: a tuple containing keywords that should all be included
:return: matching matching elements
"""
matching = []
for elem... |
def find_largest_digit(n):
"""
:param n: The integer that is given
:return: The largest digit of the integer
"""
if n < 0:
n = -n
if 0 < n < 10:
# Base case
return n
else:
if n % 10 > n // 10 % 10:
# n % 10 is the first digit counted from right side of the integer
# n // 10 % 10 is the second digit... |
def extract_attribute_ids(geographical_type_id, attributes):
"""PointSource-specific version of util.extract_attribute_ids() (q.v.)"""
id_name = 'NPDES' if geographical_type_id == 'Facility' else geographical_type_id
return [attribute[id_name] for attribute in attributes] |
def promote_columns(columns, default):
"""
Promotes `columns` to a list of columns.
- None returns `default`
- single string returns a list containing that string
- tuple of strings returns a list of string
Parameters
----------
columns : str or list of str or None
Table column... |
def countRunningCoresCondorStatus(status_dict):
"""
Counts the cores in the status dictionary
The status is redundant in part but necessary to handle
correctly partitionable slots which are
1 glidein but may have some running cores and some idle cores
@param status_dict: a dictionary with the Ma... |
def trim_sequence(
seq:str,
maxlen:int,
align:str="end") -> str:
""" Trim `seq` to at most `maxlen` characters using `align` strategy
Parameters
----------
seq : str
The (amino acid) sequence
maxlen : int
The maximum length
align : str
The strat... |
def capwords(s, sep=None):
"""capwords(s [,sep]) -> string
Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. If the optional second argument sep is absent or None,
runs of whitespace characters are replaced by a single spac... |
def get_tp_fp_fn(gold_annotation, candidate_annotation):
"""
Get the true positive, false positive, and false negative for the sets
:param gold_annotation:
:param candidate_annotation:
:return:
"""
tp, fp, fn = 0., 0., 0.
for c in candidate_annotation:
if c in gold_annotation:
... |
def _check_need_broadcast(shape1, shape2):
"""Returns True if broadcast is necessary for batchmatmul."""
return shape1[:-2] != shape2[:-2] |
def find_longest_substring(s: str, k: int) -> str:
"""
Speed: ~O(N)
Memory: ~O(1)
:param s:
:param k:
:return:
"""
# longest substring (found)
lss = ""
# current longest substring
c_lss = ""
# current list of characters for the current longest substring
c_c = []
... |
def perimeter_square(n):
"""
Take the length of the side of a square
and calculate the perimeter, given by 4*n.
"""
perimeter = 4*n
return perimeter |
def join_schema_func(func):
"""Join the schema and function, if needed, to form a qualified name
:param func: a schema, function tuple, or just an unqualified function name
:returns: a possibly-qualified schema.function string
"""
if isinstance(func, tuple):
return "%s.%s" % func
else:
... |
def escape_backticks(text: str) -> str:
"""Replace backticks with a homoglyph to prevent text in codeblocks and
inline code segments from escaping.
"""
return text.replace("\N{GRAVE ACCENT}", "\N{MODIFIER LETTER GRAVE ACCENT}") |
def lix(n_words, n_long_words, n_sents):
"""
Readability score commonly used in Sweden, whose value estimates the
difficulty of reading a foreign text. Higher value => more difficult text.
References:
https://en.wikipedia.org/wiki/LIX
"""
return (n_words / n_sents) + (100 * n_long_words... |
def get_tags(data):
"""
Gets all of the tags in the data
>>> get_tags({ \
"paths": { \
"1": {"a": {"tags": ["c"]}, \
"b": {"tags": ["c"]}}, \
"2": {"a": {"tags": ["b"]}, \
"d": {}}, \
"3": {"c": {"tags": ["d", "e"]}} \
... |
def get_star_index_files(path:str, with_sjdb_files:bool=False):
""" Find the file names necessary for a STAR index rooted at path.
Parameters
----------
path: string
the path to the directory containing the STAR index
with_sjdb_files: bool
whether to include... |
def data_resource_creator_permissions(creator, resource):
"""
Assemble a list of all permissions needed to create data on a given resource
@param creator User who needs permissions
@param resource The resource to grant permissions on
@return A list of permissions for creator on resource
"""
... |
def getMimeType(content_type):
""" Extract MIME-type from Content-Type string and convert it to
lower-case.
.. deprecated:: 0.4
"""
return content_type.partition(";")[0].strip().lower() |
def wcs_axis_to_data_axis(wcs_axis, missing_axis):
"""Converts a wcs axis number to the corresponding data axis number."""
if wcs_axis is None:
result = None
else:
if wcs_axis < 0:
wcs_axis = len(missing_axis) + wcs_axis
if wcs_axis > len(missing_axis)-1 or wcs_axis < 0:
... |
def types(items):
"""
Assignment 5 updated
"""
result = []
for i in items:
if isinstance(i, int):
i_mall = "The square of {} is {}."
result.append(i_mall.format(i, i*i))
elif isinstance(i, str):
s_mall = "The secret word is {}."
result.... |
def strict_exists(l, f):
"""Takes an iterable of elements, and returns (False, None)
if f applied to each element returns False. Otherwise
it returns (True, e) where e is the first element for which
f returns True.
Arguments:
- `l`: an iterable of elements
- `f`: a function that applies... |
def sentiment_display(sentiment_score):
"""
Returns a human readable display value for a sentiment score
"""
if sentiment_score is None:
return None
sentiment = 'Neutral'
if sentiment_score < 0:
sentiment = 'Negative'
elif sentiment_score > 0:
sentiment = 'Positive'
... |
def step_backward(position, panel_l, panel_r, connection_map):
"""
This function sounds as the character moves from the reflex board to the plug.
Its similar to the previous one, but vice versa
:param position: Position of the char in the list.
:param panel_r: The list that represents the right sid... |
def size (paper):
"""Returns the size of `paper` as `(nrows, ncols)`."""
nrows = max(y for _, y in paper) + 1
ncols = max(x for x, _ in paper) + 1
return nrows, ncols |
def _format_mp4(input_path, offset):
"""Formats the video to an MP4."""
return offset, ("-f", "mp4",) |
def combine_bolds(graph_text):
"""
Make ID marker bold and remove redundant bold markup between bold elements.
"""
if graph_text.startswith("("):
graph_text = (
graph_text.replace(" ", " ")
.replace("(", "**(", 1)
.replace(")", ")**", 1)
.replace(... |
def create_index_card(name: str, text: str, a_href:str,
img_href: str, img_alt: str) -> dict:
"""Return HTML/CSS card created with the information provided."""
return {
'name': name,
'text': text,
'a_href': a_href,
'img_href': img_href,
'img_alt': im... |
def isclose(a0, a1, tol=1.0e-4):
"""
Check if two elements are almost equal with a tolerance.
:param a0: number to compare
:param a1: number to compare
:param tol: The absolute tolerance
:return: Returns boolean value if the values are almost equal
"""
return abs(a0 - a1) < tol |
def is_handler_authentication_exempt(handler):
"""Return True if the endpoint handler is authentication exempt."""
try:
is_unauthenticated = handler.__caldera_unauthenticated__
except AttributeError:
is_unauthenticated = False
return is_unauthenticated |
def largest_element(a, loc=False):
""" Return the largest element of a sequence a.
"""
try:
Largest_value = a[0]
location = 0
for i in range(1,len(a)):
if a[i] > Largest_value:
Largest_value = a[i]
location = i
if loc == True:
... |
def remove_zero_amount_coproducts(db):
"""Remove coproducts with zero production amounts from ``exchanges``"""
for ds in db:
ds[u"exchanges"] = [
exc
for exc in ds["exchanges"]
if (exc["type"] != "production" or exc["amount"])
]
return db |
def _convert_lists_to_tuples(node):
"""Recursively converts all lists to tuples in a nested structure.
Recurses into all lists and dictionary values referenced by 'node',
converting all lists to tuples.
Args:
node: A Python structure corresponding to JSON (a dictionary, a list,
scalars, and composit... |
def build_kde_parameters_matrix(jsons_list):
"""Contructs the list of good QAOA input parameters from jsons provided."""
good_params_matrix = []
for json in jsons_list:
good_params = json["good_params"]
good_params_matrix = good_params_matrix + good_params
return good_params_matrix |
def average_accuracy(y_true, y_pred):
"""
Compute the average accuracy.
.. function:: average_accuracy(y_true, y_pred)
:param y_true: The true labels.
:type y_true: list(str)
:param y_pred: The predicted labels.
:type y_pred: list(str)
:return: The average accuracy.
... |
def depolarizing_par_to_eps(alpha, d):
"""
Convert depolarizing parameter to infidelity.
Dugas et al. arXiv:1610.05296v2 contains a nice overview table of
common RB paramater conversions.
Parameters
----------
alpha (float):
depolarizing parameter, also commonly referred to as lam... |
def create_labels(sizes):
"""create labels starting at 0 with specified sizes
sizes must be a tuple
"""
labels = []
for i, size in enumerate(sizes):
labels += size*[i]
return(labels) |
def split_cmd(cmds) -> list:
"""
Split the commands to the list for subprocess
Args:
cmds (str): command
Returns:
command list
"""
# cmds = shlex.split(cmds) # disable auto removing \ on windows
return cmds.split() if isinstance(cmds, str) else list(cmds) |
def peak_1d_brute_force(nums):
"""Find peak by naive iteration.
Time complexity: O(n).
Space complexity: O(1).
"""
# Iterate to check element is greater than its neighbors.
for i in range(len(nums)):
if ((i == 0 or nums[i] >= nums[i - 1]) and
(i == len(nums) - 1 or nums[i] ... |
def is_dna_palindrome(s1, s2):
""" (str, str) -> bool
Precondition: s1 and s2 only contain characters from 'A', 'T', 'C' or 'G'.
is_dna(s1, s2) would return True.
Return True iff s1 and s2 form a DNA palindrome.
>>> is_dna_palindrome('GATC','CTAG')
True
... |
def mask_dict_password(dictionary, secret='***'):
"""Replace passwords with a secret in a dictionary."""
d = dictionary.copy()
for k in d:
if 'password' in k:
d[k] = secret
return d |
def make_flat(folders, paths_flat = None):
"""
"""
if paths_flat is None:
paths_flat = dict()
parent_id = len(paths_flat) - 1 if paths_flat else None
for foldername, subfolders in sorted(folders.items()):
paths_flat[len(paths_flat)] = {
"id": len(paths_flat),
... |
def running_step(steps, *argv):
"""Return true if running any step in arguments.
"""
for step in argv:
if step in steps:
return True
return False |
def is_user(user):
"""Return ``True`` if passed object is User and ``False`` otherwise."""
return type(user).__name__ == 'User' |
def parse_list(spec):
"""Convert a string specification like 00-04,07,09-12 into a list [0,1,2,3,4,7,9,10,11,12]
Args:
spec (str): string specification
Returns:
List[int]
Example:
>>> parse_list("00-04,07,09-12")
[0, 1, 2, 3, 4, 7, 9, 10, 11, 12]
>>> parse_list... |
def wordparamcheck(givenparams, expectedparams):
""" New version of the word and parameter check
Returned values will be given in a list form
OUTPUT = [if it matched, matched index, matched value,\
if the correct num of params given,\
num of params, list of params] """
matchingi... |
def filter_pairs(pairs, genes):
"""
:param pairs:
:param genes:
:return: Limit only to pairsi n the genes
"""
return [p for p in pairs if p[0] in genes and p[1] in genes] |
def number_of_common_3grams(string1, string2):
""" Return the number of common tri-grams in two strings
"""
# Pure Python implementation: no numpy
tri_grams = set(zip(string1, string1[1:], string1[2:]))
tri_grams = tri_grams.intersection(zip(string2, string2[1:],
... |
def degrees_to_cardinal(degree: float):
"""
"""
dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
"S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
index = int((degree + 11.25)/22.5)
return dirs[index % 16] |
def slashAtTheEnd(url):
"""
Adds a slash at the end of given url if it is missing there.
:param url: url to check and update
:returns: updated url
"""
return url if url.endswith('/') else url + '/' |
def do_sql(conn, stmt, dry_run, *vals):
"""
run stmt on sqlite connection conn
"""
print(stmt, vals)
if dry_run == 0:
return conn.execute(stmt, vals)
else:
return [] |
def resize_by_ratio(size):
""" Resize the size according to the imagenet training ratio.
"""
resize = round(256 / 224 * size / 2) * 2
return resize |
def wheel(pos):
"""
Wheel is a width of a single rainbow line
Input a value 0 to 255 to get a color value.
The colours are a transition r - g - b - back to r.
"""
if pos < 0 or pos > 255:
return 0, 0, 0, 0
if pos < 85:
return 255 - pos * 3, pos * 3, 0, 0
if po... |
def get_players_to_sell(players):
"""
Provides a list of players that, if I have, I should consider selling for money reasons
:param players: list of players
:return: list of players
"""
if not isinstance(players, list):
raise ValueError('expected list')
return [player for player in... |
def plain(text):
"""Remove boldface formatting from text."""
import re
return re.sub('.\b', '', text) |
def prod(x):
"""Compute the product of a sequence."""
out = 1
for a in x:
out *= a
return out |
def gen_matrix(e):
""" Generating new matrix.
@param e The width and height of the matrix is 2^e.
@return New 2x2 to 2^e x 2^e matrix list.
"""
if e < 1:
return None
m_list = [[[1, 2], [3, 0]]]
_b = m_list[0]
for n in range(1, e):
m = m_list[n - 1]
m_list.append([
... |
def readBit(integer, position):
"""
:param integer:
:return boolean:
Description: This function will take in an integer and a position value. The return will be a boolean based on
whether the bit is 1 or 0 at the requested position of the integer.
Example: integer = 2... |
def search(nums, target):
"""
Search in given rotated sorted array
:param nums: given array
:type nums: list[int]
:param target: target number
:type target: int
:return: index of target
:rtype: int
"""
left = 0
right = len(nums) - 1
while left + 1 < right:
mid = ... |
def fc_wwn_to_string(wwn):
"""Convert FC WWN to string without colons.
:param wwn: FC WWN
:return: FC WWN without colons
"""
return wwn.replace(":", "") |
def is_power_of_two(num):
"""Checks whether num is a power of two.
Args:
num: A positive integer.
Returns:
True if num is a power of two.
"""
return ((num & (num - 1)) == 0) and num > 0 |
def anno_parser(annos_str):
"""Parse annotation from string to list."""
annos = []
for anno_str in annos_str:
anno = list(map(int, anno_str.strip().split(',')))
annos.append(anno)
return annos |
def pascal_triangle(n: int):
"""
Print pascal's triangle for n rows
"""
def moving_sum(arr: list):
"""moving sum sub-routine"""
n = len(arr)
if n <= 1:
return arr
out = []
for i in range(0, n-1):
out.append(arr[i]+arr[i+1])
return o... |
def extended_gcd(a, b):
"""returns gcd(a, b), s, r s.t. a * s + b * r == gcd(a, b)"""
s, old_s = 0, 1
r, old_r = b, a
while r:
q = old_r // r
old_r, r = r, old_r - q * r
old_s, s = s, old_s - q * s
return old_r, old_s, (old_r - old_s * a) // b if b else 0 |
def isunauthenticated(f):
"""Decorator to mark authentication-non-required.
Checks to see if the function is marked as not requiring authentication
with the @unauthenticated decorator. Returns True if decorator is
set to True, False otherwise.
"""
return getattr(f, 'unauthenticated', False) |
def pluralize(word, count):
"""Make a word plural by adding an *s* if `count` != 1.
Parameters
----------
word : :class:`~python:str`
the word
count : :class:`~python:int`
the word count
Returns
-------
:class:`~python:str`
"""
return word if count == 1 else wo... |
def _get_request_value(request, value_name, default=''):
"""Helper method to get header values from a request's GET/POST dict, if present."""
if request is not None:
if request.method == 'GET':
return request.GET.get(value_name, default)
elif request.method == 'POST':
ret... |
def _validate_pipeline_runtime(primary_pipeline: dict, runtime: str) -> bool:
"""
Generic pipelines do not have a persisted runtime type, and can be run on any runtime
Runtime specific pipeline have a runtime type, and con only be run on matching runtime
"""
is_valid = False
pipeline_runtime = p... |
def add_metadata_columns_to_schema(schema_message):
"""Metadata _sdc columns according to the stitch documentation at
https://www.stitchdata.com/docs/data-structure/integration-schemas#sdc-columns
Metadata columns gives information about data injections
"""
extended_schema_message = schema_message
... |
def do_right(value, width=80):
"""Right-justifies the value in a field of a given width."""
return value.rjust(width) |
def check_double_entries(entries):
"""
Process a list of tuples of filenames and corresponding hash for double hashes.
`entries`: the list of entries with their hashes
returns: a dictionary containing double entries by hash
"""
hashes = dict()
for entry in entries:
h = entry[1]
... |
def remove_extra_raw_data_fields(raw_line):
"""Used for filter() to ignore time-sensitive lines in report JSON files.
:param raw_line: A line to filter
:return: True if no time-sensitive fields are present in the line
"""
if 'grade_released_date' in raw_line:
return False
if 'last_updat... |
def geojson_driver_args(distribution):
"""
Construct driver args for a GeoJSON distribution.
"""
url = distribution.get("downloadURL") or distribution.get("accessURL")
if not url:
raise KeyError(f"A download URL was not found for {str(distribution)}")
return {"urlpath": url} |
def get_scale_offsets(scaled_w, scaled_h, origin_w, origin_h,
offset_l, offset_t, offset_w, offset_h):
"""
Inverts scaling offsets (kind of like inverting the scaling itself, really).
Calculates the scale offsets necessary to scale back to its original form an
image that was scaled to the spe... |
def format_names_and_descriptions(objects, name_attr='name', description_attr='description'):
"""Format a table with names on the left and descriptions on the right."""
pairs = []
for o in objects:
name = getattr(o, name_attr)
description = getattr(o, description_attr)
pairs.append((... |
def _filter_files(adir, filenames, filecnt, file_type, ffilter):
"""
Filter files by file type(filter function) then returns matching
files and cumulated count.
"""
rfiles = ffilter(adir, filenames)
filecnt += len(rfiles)
return rfiles, filecnt |
def _swap_labelmap_dict(labelmap_dict):
"""Swaps keys and labels in labelmap.
Args:
labelmap_dict: Input dictionary.
Returns:
A dictionary mapping class name to class numerical id.
"""
return {v:k for k, v in labelmap_dict.items()} |
def fahrenheit2kelvin(theta):
"""Convert temperature in Fahrenheit to Kelvin"""
return 5./9 * (theta - 32) + 273.15 |
def pick_bball_game(p):
"""
prob_game1 = p
prob_game2 = P(make 1+2) + P(make 1+3) + P(make 2+3) + P(make 1+2+3)
prob_game2 = p*p*(1-p) + p*(1-p)*p + (1-p)*p*p + p*p*p
prob_game2 = p**2 - p**3 + p**2 - p**3 + p**2 - p**3 + p**3
prob_game2 = 3 * p ** 2 - 2 * p ** 3
prob_game1 > prob_game2
... |
def format_user_outputs(user: dict = {}) -> dict:
"""Take GitHub API user data and format to expected context outputs
Args:
user (dict): user data returned from GitHub API
Returns:
(dict): user object formatted to expected context outputs
"""
ec_user = {
'Login': user.get('... |
def _map_response_description(item):
"""
struct like {(1,2):'3'}
"""
key, value = item
return "{} : {} : {}".format(key[0], key[1], value) |
def abbreviate_statement(text):
"""Depending on the type of statement, abbreviate it to two letters
and add a trailing underscore so it can be used as the first prefix
of a title for an SQL table.
"""
if text.find('income-statement') != -1:
text = 'income statement'
return text
e... |
def D(x, y):
"""D code generator"""
return (y << 5) | x |
def apply_ticket_permissions(env, req, tickets):
"""Apply permissions to a set of milestone tickets as returned by
`get_tickets_for_milestone()`."""
return [t for t in tickets
if 'TICKET_VIEW' in req.perm('ticket', t['id'])] |
def separator(sep):
"""Returns separator from G_OPT_F_SEP appropriately converted
to character.
>>> separator('pipe')
'|'
>>> separator('comma')
','
If the string does not match any of the separator keywords,
it is returned as is:
>>> separator(', ')
', '
:param str separ... |
def strip(s):
"""strip(s) -> string
Return a copy of the string s with leading and trailing
whitespace removed.
"""
return s.strip() |
def extract_course(transcript, course):
""" (str, int) -> str
Return a string containing a course code, course mark and final mark,
in that order. The second argument specifies the order in which the course
appears in the transcript.
>>> extract_course('MAT,90,94,ENG,92,NE,CHM,80,85', 2)
... |
def comparison_count_sort(unordered_lst):
"""Sorts a list by comparison counting.
pre: unordered_lst is an unordered list of numbers
post: sorted_lst which comprises of unordered_lst's elements
sorted in an increasing order.
"""
lst_size = len(unordered_lst)
# cre... |
def windows_folder(folder):
"""
Modify foders from files in a dataframe\
To be used with pandas .apply()
"""
folder = str(folder).replace("\\", "/")
return folder |
def _permute(c, p):
"""Returns the permutation of the given 32-bit or 64-bit code with
the specified permutation table."""
# NOTE: only difference between 32 & 64 bit permutations
# is that len(p)==8 for 32 bit, and len(p)==16 for 64 bit.
out = 0
for r in p:
out |= r[c&0xf]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.