content stringlengths 42 6.51k |
|---|
def unpack(arg, singleton=False):
"""Unpack variables from a list or tuple.
Parameters
----------
arg : object
Either a list or tuple, or any other Python object. If passed a
list or tuple of length one, the only element of that list will
be returned. If passed a tuple of length... |
def create_column_index(table, colindex):
"""creates index from column value to corresponding table row"""
return dict([(row[colindex], row) for row in table]) |
def to_dict(condset: set) -> dict:
"""
Create a dictionary of conditions with a unique integer value for each
condition.
:param condset: Conditions set.
:return: Dictionary of all conditions with integer values.
"""
conds = {}
index = 0
for item in condset:
conds[str(item)] =... |
def generalupper(str):
"""this uses the object's upper method - works with string and unicode"""
if str is None: return str
return str.upper() |
def get_instance_group_name(experiment: str):
"""Returns the name of the instance group of measure workers for
|experiment|."""
# "worker-" needs to come first because name cannot start with number.
return 'worker-' + experiment |
def community2name(community):
"""
Given a list of concepts (words), return a string as its name.
"""
return " ".join(community) |
def get_remote_url(remote_url):
"""
Takes a GitHub remote URL (e.g., `mozilla/fireplace`) and
returns full remote URL (e.g., `git@github.com:mozilla/fireplace.git`).
"""
if ':' not in remote_url:
remote_url = 'git@github.com:' + remote_url
if not remote_url.endswith('.git'):
rem... |
def return_unique_items_in_both_lists(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs):
result.extend(ys[yi:])
return result
if yi >= len(ys):
result.extend(xs[xi:])
... |
def reverse(s):
"""
reverse the sequence string in reverse order
"""
letters = list(s)
letters.reverse()
return ''.join(letters) |
def iselement(element):
"""Return True if *element* appears to be an Element."""
return hasattr(element, 'tag') |
def valid_for_gettext(value):
"""Gettext acts weird when empty string is passes, and passing none would be even weirder"""
return value not in (None, "") |
def l_to_srm(lovibond):
"""
Convert from Lovibond to EBC
https://en.wikipedia.org/wiki/Standard_Reference_Method
"""
return 1.3546 * lovibond - 0.76 |
def getShortName(name):
"""
Returns a shorter kernel name
"""
sname = name.split("<")[0] \
.replace("void ", "") \
.replace("at::","") \
.replace("cuda::", "") \
.replace("native::","") \
.replace("(anonymous namespace)::", "")
sname = sname.split("(")[0]
return snam... |
def rename_friendly_name(attributes):
"""
Given the attributes to be stored, replace the friendly name. Helpful
if names changed during the course of history and you want to quickly
correct the naming.
"""
rename_table = {
"Old Sensor Name": "New Sensor Name",
}
if "friendly_nam... |
def compute_circular_sorted_median(ls):
"""
Question 22.12: Given a sorted circular linked list,
find the median
"""
if ls is None:
return None
if ls == ls.next:
return float(ls.val)
# use slow and fast to find size of cycle
slow = ls
fast = ls
size = 0
wh... |
def choose_exchange_cards(cards):
"""cards is a list of card choices"""
return " ".join([str(i) for i in cards]) |
def find(input_data, path, current_path=None):
"""Finds all elements based on path
:param input_data: dict or list
:param path: the path list, example: b.*.name
:param current_path: the current path, default=None
:return: list elements of shape (path, value)
"""
fields_found = []
if isi... |
def coding_problem_09(numbers):
"""
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers.
The "largest sum of non-adjacent numbers" is the sum of any subset of non-contiguous elements.
Solution courtesy of Kye Jiang (https://github.com/Jedshady).
Examples:
... |
def extract_demonym(demonyms, gender):
"""
Search through the list of demonyms and find the right one by gender
:param demonyms:
:param gender: may be male (u'Q499327') od female (u'Q1775415')
:return: demonym in Serbian language
"""
description = u''
for demonym in demonyms:
loc... |
def _is_positive_float(value):
""" Check whether a value is a positive float or not.
"""
try:
value = float(value)
return value > 0
except (TypeError, ValueError):
return False |
def target_policy(obs):
"""
Collect checkpoints if they are close
"""
theta, dist = obs['target']
steer = 0.1*theta
throttle = 0
if abs(theta) < 0.2:
throttle = 0.2
return [steer, throttle] |
def FP_Derivative(t, y):
"""
Function computing the Flight Path Angle Derivative.
"""
# dFPdt = (T/(m*v)) * np.sin(alpha+delta) + Lift/(m*v) - g*np.cos(FP)
return 0 |
def sol(s):
"""
From both ends check the character that is occurring only once
! This is failing one test case
"""
n = len(s)
h = {}
for x in s:
h[x] = h[x]+1 if x in h else 1
hc = dict(h)
start = 0
end = n-1
while start < n and h[s[start]] > 1:
h[s[sta... |
def repack(dict_obj, key_map, rm_keys=[]):
""" Repackage a dict object by renaming and removing keys"""
for k, v in key_map.items():
dict_obj[v] = dict_obj.pop(k)
for k in rm_keys:
del dict_obj[k]
return dict_obj |
def validate_list_to_single(v):
"""
Converts a list to a single value (the last element of the list)
Query parameters can be specified multiple times. Therefore, we will always
convert them to a list in flask. But that means we have to convert them
to single values here
"""
if isinstance(v,... |
def is_transition_allowed(constraint_type: str,
from_tag: str,
from_entity: str,
to_tag: str,
to_entity: str):
"""
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin... |
def assign_subtasks(total_num, num_tasks=2):
"""
Split the task into sub-tasks.
Parameters:
-----------
total_num: int
Total number of the task to be split.
num_tasks: int
The number of sub-tasks.
Returns:
--------
subtask_ids: list of list
List of the list ... |
def wraps(wrapped, fun, namestr="{fun}", docstr="{doc}", **kwargs):
"""
Like functools.wraps, but with finer-grained control over the name and docstring
of the resulting function.
"""
try:
name = getattr(wrapped, "__name__", "<unnamed function>")
doc = getattr(wrapped, "__doc__", "") or ""
fun.__d... |
def split_args_into_google_and_kafka(args):
"""
Split a dict of arguments into Google and Kafka dictionaries, based on the key prefixes.
>>> from pprint import pprint
>>> pprint(split_args_into_google_and_kafka({'kafka_bootstrap_servers': 'localhost', 'google_topic': 'foo',
... 'kafka_group_id'... |
def get_attributes_string(class_name, object_dict):
"""Unimportant utility function to format __str__() and __repr()"""
return f"""{class_name}({', '.join([
f"{str(k)}: {str(v)}"
for k, v in object_dict.items()
])})""" |
def popdefault(dictionary, key, default):
"""
If the key is present and the value is not None, return it.
If the key is present and the value is None, return ``default`` instead.
If the key is not present, return ``default`` too.
"""
value = dictionary.pop(key, None)
return value or default |
def striskey(str):
"""IS str AN OPTION LIKE -C or -ker
(IT'S NOT IF IT'S -2 or -.9)"""
iskey = 0
if str:
if str[0] == '-':
iskey = 1
if len(str) > 1:
iskey = str[1] not in ['0', '1', '2', '3', '4', '5', '6', '7',
'8',... |
def ld(w1, w2):
"""
`ld` returns the Levenshtein distance between `w1` and `w2`.
"""
this_row = range(len(w1)+1)
for row_num in range(1, len(w2)+1):
prev_row = this_row
this_row = [row_num]
for j in range(1, len(prev_row)):
this_row.append(min(
thi... |
def add_newline(text: str) -> str:
"""
Adds a newline if a string does not have one.
:param text: String to add the newline character to.
:return: String with a newline character on the end.
"""
return text if text.endswith("\n") else text + "\n" |
def exchange(program_list, this_position, that_position):
"""Exchange program at __this__ position with program
at __that__ position."""
new_list = list(program_list)
new_list[this_position] = program_list[that_position]
new_list[that_position] = program_list[this_position]
return "".join(new_li... |
def div0(num, denom):
"""Divide operation that deals with a 0 value denominator.
num: numerator.
denom: denominator.
Returns 0.0 if the denominator is 0, otherwise returns a float."""
return 0.0 if denom == 0 else float(num) / denom |
def getFolder(path):
"""
Removes levels from the path
:param path: String which contains a path, e.g. 'C:/'
:return:
"""
return "/".join(
path.replace("\\","/").split("/")[:-1]
)+"/" |
def bh2u(x: bytes) -> str:
"""
str with hex representation of a bytes-like object
>>> x = bytes((1, 2, 10))
>>> bh2u(x)
'01020A'
"""
return x.hex() |
def get_groups_for_container(inventory, container_name):
"""Return groups for a particular container.
Keyword arguments:
inventory -- inventory dictionary
container_name -- name of a container to lookup
Will return a list of groups that the container belongs to.
"""
# Beware, this dictiona... |
def remove_sequential_duplicates(l):
"""Drops duplicate values from a list while maintaining list order
l : list
"""
seen = set()
return [x for x in l if not (x in seen or seen.add(x))] |
def sum_matrix(n):
""" Returns a sum of all elements in a given matrix """
return sum([sum(x) for x in n]) |
def overlap(interval1, interval2):
"""computed overlap
Given [0, 4] and [1, 10] returns [1, 4]
Given [0, 4] and [8, 10] returns False
"""
if interval2[0] <= interval1[0] <= interval2[1]:
start = interval1[0]
elif interval1[0] <= interval2[0] <= interval1[1]:
start = interval2[0]
else:
return ... |
def int_to_bits(x, width):
"""Return `list` of `bool` for integer value `x`."""
# Adapted from the function
# `omega.logic.bitvector.int_to_twos_complement`.
# The sign bit is not needed.
n = x.bit_length()
if x >= 0:
y = x
else:
y = 2**n + x
m = max(width, n, 1) # if ... |
def check_ellipsis_shape_size(data_shape, value_shape, data_size, value_size):
"""Checks the shape and size of the sensor and value."""
if data_shape == value_shape or data_size == value_size or value_size == 1:
return True
raise ValueError("The value(shape={}), can not assign to tensor(shape={}).".... |
def clean_html(html):
"""Remove some extra things from html"""
import re
return re.sub(r'\<style\>.*\<\/style\>', '', html, flags=re.S) |
def get_recursively(search_dict, field):
"""Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in search_dict.items():
if key == field:
fields_found.append(value)
elif isinstance(va... |
def derive_http_method(method, data):
"""Derives the HTTP method from Data, etc
:param method: Method to check
:type method: `str`
:param data: Data to check
:type data: `str`
:return: Method found
:rtype: `str`
"""
d_method = method
# Method not provided: Determine method from ... |
def derivative(f, x0, eps=1e-6):
"""Computes a numerical approximation of the first derivative of the function f(x)
at the point x0 using central differences."""
e = 1e-6
return ((f(x0 + (eps/2))) - (f(x0 - (eps/2)))) / eps |
def multiply(a, b):
"""Return the product of two numbers"""
print(a * b)
return a * b |
def indent(text, n=4):
"""
Indent each line of text with spaces
:param text: text
:param n: amount of spaces to ident
>>> indent("")
''
>>> indent("the quick brown fox\\njumped over an lazy dog\\nend")
' the quick brown fox\\n jumped over an lazy dog\\n end'
"""
if not... |
def getMenuEntry(menu, selected_index):
"""Given a menu and a selected index, return the full menu entry
:param menu: array of menu entries, see printMenu() for details
:param selected_index: integer, selected index value
:returns: dictionary, menu entry
"""
for entry in menu:
if entry... |
def calculatePercentage(covered, missed) :
"""Calculates the coverage percentage from number of
covered and number of missed. Returns 1 if both are 0
to handle the special case of running on an empty class
(no instructions) or a case with no if, switch, loops (no
branches).
Keyword arguments:
... |
def short_bucket_name(bucket_name):
"""Returns bucket name without "luci.<project_id>." prefix."""
parts = bucket_name.split('.', 2)
if len(parts) == 3 and parts[0] == 'luci':
return parts[2]
return bucket_name |
def average_limit_of_truncation(dataset):
"""
Takes the histogram data, returns the average length of records. To appoint the optimal value for truncation.
Args:
dataset (list of lists): The MSNBC dataset
Returns:
Average length of records rounde... |
def nth_hexagonal(n):
"""
Compute the nth hexagonal number
"""
return n * (2 * n - 1) |
def two_fer(name="you"):
"""Returns a string in the two-fer format."""
return "One for " + name + ", one for me." |
def transpose(table):
"""
Returns a copy of table with rows and columns swapped
Example:
1 2 1 3 5
3 4 => 2 4 6
5 6
Parameter table: the table to transpose
Precondition: table is a rectangular 2d List of numbers
"""
# Find the size of ... |
def _merge_dicts(*dicts):
"""Given any number of dicts, shallow copy and merge into a new dict"""
result = {}
for dictionary in dicts:
result.update(dictionary)
return result |
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
if len(input_list) == 0:
return -1
list_len = len(input_list... |
def _build_css_asset(css_uri):
"""Wrap a css asset so it can be included on an html page"""
return '<link rel="stylesheet" href="{uri}" />'.format(uri=css_uri) |
def add_me_with_my_friends(queue, index, person_name):
"""Insert the late arrival's name at a specific index of the queue.
:param queue: list - names in the queue.
:param index: int - the index at which to add the new name.
:param person_name: str - the name to add.
:return: list - queue updated wi... |
def how_many_days(month_number):
"""Returns the number of days in a month.
WARNING: This function doesn't account for leap years!
"""
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
#todo: return the correct value
return days_in_month[month_number] |
def use_filter(filter, url, input):
"""Apply a filter function to input from an URL"""
output = filter(url, input)
if output is None:
# If the filter does not return a value, it is
# assumed that the input does not need filtering.
# In this case, we simply return the input.
... |
def str_tags_to_list(tags):
"""Convert string of comma separated tags to list, stripped of empty tags and whitespace."""
tags = tags.split(",")
tags = [tag.strip() for tag in tags if tag.strip()]
return tags |
def args_to_dict(args):
"""
Convert template tag args to dict
Format {% suit_bc 1.5 'x' 1.6 'y' %} to { '1.5': 'x', '1.6': 'y' }
"""
return dict(zip(args[0::2], args[1::2])) |
def compress_cgraph(cgraph: str) -> str:
"""
"""
output = ""
magnets = {}
magnet = ""
in_magnet = False
cpt = 0
depth = 0
for symbol in cgraph:
if not in_magnet:
output += symbol
# print(output)
if symbol == "{":
in_magnet... |
def getFirstLineContaining(lines, keyLineStart):
"""
Given a split abfinfo text, return a stripped value for the given key.
"""
for line in lines:
if line.startswith(keyLineStart):
line = line.replace(keyLineStart, "")
line = line.strip()
return line
retur... |
def filter_type(type):
"""Filter the type of the node."""
if "[" in type or "]" in type:
return "arrayType"
elif "(" in type or ")" in type:
return "fnType"
elif "int" in type:
return "intType"
elif "float" in type:
return "floatType"
else:
return "type" |
def unsigned_right_shift(a, b):
"""Computes a >>> b in Java, or an unsigned right shift. Assumes longs, e.g., 64-bit integers."""
if a >= 0:
return a >> b
else:
return ((a + 2 ** 64) >> b) |
def evalint(s):
"""Evaluate string to an integer."""
return int(eval(s, {}, {})) |
def track_title_and_slug_from_penta(tracks, room_slug):
"""
Return the track title (e.g. Community) based on the room slug (mcommunity)
:param tracks:
:param room_slug:
:return:
"""
if room_slug in tracks:
return tracks[room_slug]['title'], tracks[room_slug]['slug']
return None, ... |
def discretize_val(val, min_val, max_val, num_states):
"""
Discretizes a single float
if val < min_val, it gets a discrete value of 0
if val >= max_val, it gets a discrete value of num_states-1
Args:
val (float): value to discretize
min_val (float): lower bound of discretization
max_val (float): u... |
def get_host_cl_datatype(datatype):
"""Get corresponding OpenCL datatype: float -> cl_float"""
return "cl_" + datatype |
def hamming_distance(seq_1: str, seq_2: str,
ignore_case: bool = False) -> int:
"""Calculate the Hamming distance between two sequences.
Args:
seq_1: first sequence to compare
seq_2: second sequence to compare
ignore_case: ignore case when comparing sequences (defau... |
def is_numeric(obj):
"""
Check for numerical behaviour.
Parameters
----------
obj
Object to check.
Returns
--------
:class:`bool`
"""
attrs = ["__add__", "__sub__", "__mul__", "__truediv__", "__pow__"]
return all(hasattr(obj, attr) for attr in attrs) |
def parse_bool(arg):
"""parses boolean arguments | str --> bool"""
if arg == 'True':
return True
if arg == 'False':
return False
raise ValueError('Correct format for boolean type is ' +
'"bool:True" or "bool:False"') |
def compression(sentence):
""" 1.6 String Compression: Implement a method to perform basic string
compression using the counts of repeated characters.
For example, the string aabcccccaaa would become a2blc5a3.
If the "compressed" string would not become smaller than the original string,
your method ... |
def make_imapdict(mapdict):
""" make inverse mapping dict """
result = dict()
for k, v in mapdict.items():
for _ in v:
result[_] = k
return result |
def remove_workflow_name(name):
""" Remove the workflow name from the beginning of task, input and output names (if it's there).
E.g. Task names {workflowName}.{taskName} => taskName
Input names {workflowName}.{inputName} => inputName
Output names {workflowName}.{taskName}.{outputName} => task... |
def add_run_number(bids_suffix, run_no):
"""
Safely add run number to BIDS suffix
Handle prior existence of run-* in BIDS filename template from protocol translator
:param bids_suffix, str
:param run_no, int
:return: new_bids_suffix, str
"""
if "run-" in bids_suffix:
# Preserv... |
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 taxicab(a, b):
"""taxicab metric"""
return sum(abs(a1 - b1) for a1, b1 in zip(a, b)) |
def scrub_response(response):
"""
Drop irrelevant headers.
"""
headers = response["headers"]
for header in [
"CF-Cache-Status",
"CF-RAY",
"Cache-Control",
"Connection",
"Date",
"Expect-CT",
"NEL",
"Report-To",
"Server",
... |
def signed_i(num:int) -> int:
"""Returns signed value of unsigned (or signed) 32-bit integer (struct fmt 'i')
"""
return ((num & 0xffffffff) ^ 0x80000000) - 0x80000000 |
def parse_time(time):
"""
Parses the given time into days, hours, minutes and seconds.
Useful for formatting time yourself.
----------
:param time:
The time in milliseconds.
"""
days, remainder = divmod(time / 1000, 86400)
hours, remainder = divmod(remainder, 3600)
... |
def sign(x):
"""
Return 1, 0, or -1 depending on the sign of x
"""
if x > 0.0:
return 1
elif x == 0.0:
return 0
else:
return -1 |
def _replace_string_part(s, t, i_from):
"""
>>> _replace_string_part("aaaaaa", "bb", 1)
'abbaaa'
"""
i_to = i_from + len(t)
return s[:i_from] + t + s[i_to:] |
def xlime_easy_pos(token, tag):
"""
Fix the PoS tag in some easy cases
"""
tok = token.lower().strip()
smileys = [':)', ':-)', ':(', ':-(']
if tok == 'tuseruser':
return 'MENTION'
elif tok == 'turlurl':
return 'URL'
elif tok == 'rt':
return 'CONTINUATION'
eli... |
def pythagorean_triples(n):
"""
Returns list of all unique pythagorean triples
(a, b, c) where a < b < c <= n and a*a + b*b == c*c.
"""
l = []
# loop over all a < b < c <= n
for c in range(1, n + 1):
for b in range(1, c):
for a in range(1, b):
if a*a + b*b... |
def _is_pull_request_merged(pull_request: dict) -> bool:
"""
Determine if the pull request contains meta-data indicating it was merged.
:param pull_request: Pull request section of payload to examine
:type: :class:`~dict`
:return: Boolean indicating pull request state
:rtype: :class:`~bool`
... |
def add_bed_particle(diam, bed_particles, particle_id, pack_idx):
""" Add 'particle' to the bed particle list.
Calculates center and elevation of particle
from input. Maintains pack_idx and particle_id
for next particle iteration.
Builds particle of the following structure:
... |
def check_overscan(xstart, xsize, total_prescan_pixels=24,
total_science_pixels=4096):
"""Check image for bias columns.
Parameters
----------
xstart : int
Starting column of the readout in detector coordinates.
xsize : int
Number of columns in the readout.
t... |
def get_service_type(f):
"""
Retrieves service type from function
"""
return getattr(f, 'service_type', None) |
def _parse_memory(s: str) -> int:
"""
Parse a memory string in the format supported by Java (e.g. 1g, 200m) and
return the value in MiB
Examples
--------
>>> _parse_memory("256m")
256
>>> _parse_memory("2g")
2048
"""
units = {"g": 1024, "m": 1, "t": 1 << 20, "k": 1.0 / 1024}... |
def _rgb2rgb(col):
"""
Transform RGB tuple with values 0-255 to tuple with values 0-1
"""
return tuple([ i / 255. for i in col ]) |
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
""" Return True if the values a and b are close to each other and False otherwise.
:param a: first value
:param b: second value
:param rel_tol: maximum allowed difference between a and b, relative to the larger absolute value of a or b
:param abs_tol: ... |
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. Note that this replaces runs of whitespace characters by
a single space.
"""
return (sep or ' ').join([x.c... |
def isValid_wrong(s):
"""
:type s: str
:rtype: bool
"""
mapp = {}
for x in s:
if x in ['(', '[', '{']:
if x not in mapp:
mapp[x] = 1
else:
mapp[x] += 1
else:
if x == ')':
if '(' in mapp and mapp[... |
def strip_quotes(S):
"""
String leading and trailing quotation marks
"""
if '"' in S[0] or "'" in S[0]:
S = S[1:]
if '"' in S[-1] or "'" in S[-1]:
S = S[:-1]
return S |
def export_novelty_per_group(out:dict,
id_nr:str,
novelty:list,
resonance:list):
"""Export novelty and resonance values per group
Args:
out: dictionary that holds values for all groups
id_nr: group id of the group at han... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.