content stringlengths 42 6.51k |
|---|
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured data to conform to the schema.
"""
# No further processing
return proc_data |
def simplify_http_accept_header(accept):
"""Parse an HTTP Accept header (RFC 2616) into a preferred value.
The quality factors in the header determine the preference.
Possible media-range parameters are allowed, but will be ignored.
This function can also be used for the Accept-Charset,
Accept-Enco... |
def nuclear_charge(sym):
""" nuclear charge
"""
return {'H': 1, 'HE': 2,
'C': 6,
'N': 7,
'O': 8, 'S': 16,
'F': 9, 'CL': 17,
'NE': 10, 'AR': 18}[sym.upper()] |
def iou(label_mhv1, label_mhv2):
"""
Calculate the ious given two lists
Args:
l1: list1 containing one hot vector of labels
l2: list2 containing one hot vectot of labels
Returns:
iou_score: IOU for the two labels lists
"""
union = len(label_mhv1)
intersection = 0
... |
def solutionToString(solution):
""":returns: Provide on solution as string."""
return ",".join(["(%s, %d)" % (i+1, v+1)
for i, v in enumerate(solution)]) |
def filter_dict(result_dict, key_tag):
"""
Filter a subset of the result_dict, where keys ends with 'key_tag'.
"""
filtered = {}
for k, v in result_dict.items():
if k.endswith(key_tag):
filtered[k] = v
return filtered |
def mix(colors):
"""
Mixes a list of colors
by taking the average of the rgb values
"""
new_color = [0, 0, 0]
color_sum = [0, 0, 0]
for color in colors:
for i in range(0, 3):
color_sum[i] += color[i]
for i in range(0, 3):
try:
... |
def lower_case_dict(translations=None):
"""Returns a new dict, with its keys converted to lowercase.
:param dict[str, Any] translations: A dictionnary to be converted.
"""
if translations is None:
return
return {k.lower(): v for k, v in translations.items()} |
def inttodate(i, lim=1965, unknown='U', sep='-', order="asc", startsatyear=0):
"""
transforms an int representing days into a date
Args:
----
i: the int
lim: the limited year below which we have a mistake
unknown: what to return when unknown (date is bellow the limited year)
sep... |
def simplify_address(address):
"""Return the first four and last four of a wallet address"""
length = len(address)
if length > 8:
return f'{address[0:4]}...{address[(length-4):length]}'
else:
return address |
def rosenbrock_2d(x):
""" The 2 dimensional Rosenbrock function as a toy model
The Rosenbrock function is well know in the optimization community and
often serves as a toy problem. It can be defined for arbitrary
dimensions. The minimium is always at x_i = 1 with a function value of
zero. All input ... |
def is_cwl_record(d):
"""Check if an input is a CWL record, from any level of nesting.
"""
if isinstance(d, dict):
if d.get("type") == "record":
return d
else:
recs = list(filter(lambda x: x is not None, [is_cwl_record(v) for v in d.values()]))
return recs... |
def filter_output_fields(configs):
"""Remove fields that are not required by CloudWatch agent config file."""
desired_keys = ["log_stream_name", "file_path", "timestamp_format", "log_group_name"]
return [{desired_key: config[desired_key] for desired_key in desired_keys} for config in configs] |
def split(tree):
"""attempts to split, return tree,has_split
where has_split is the flag if a split has occured
"""
if type(tree) is int:
if tree < 10:
return tree, False
left = tree // 2
return [left, tree - left], True
left, has_split = split(tree[0])
if has... |
def calculateBounds(coordinates):
"""
caculates the upper and lower bounds of the coordinate set
"""
x_values = [coordinate[0] for coordinate in coordinates]
y_values = [coordinate[1] for coordinate in coordinates]
max_x, min_x = max(x_values), min(x_values)
max_y, min_y = max(y_values), min(y_values)
return ... |
def seconds_to_multiple_time_units(secs):
"""
This function receives a number of seconds and return how many min, hours,
days those seconds represent.
"""
return {
"seconds": int(secs),
"minutes": round(int(secs) / 60.0),
"hours": round(int(secs) / (60.0 * 60.0)),
"da... |
def palindrome(name):
"""
Returns true if name is a palindrome (equals itself reversed)
"""
return name == name[::-1] |
def reverse(text):
""" Reverse a string (trivial in python) """
return text[::-1] |
def get_recording_nodes(service_list):
"""
Returns a list of all nodes which off a recording_cmd service.
"""
recording_srv_list = [srv for srv in service_list if 'recording_cmd' in srv.split('/')]
recording_node_list = ['/'.join(srv.split('/')[:4]) for srv in recording_srv_list]
return record... |
def read_in_github_token_list(file="tokens.txt"):
"""If a tokens file exists, extract tokens line by line.
This functionality enables reading in multiple GitHub personal
access tokens so that a user can use the GitHub API more than
if he or she had only one token.
Args:
file - a txt docume... |
def reverse(dictionary):
"""reverses a keys and values of a dictionary"""
return {v: k for k, v in dictionary.items()} |
def _fm0decodemeta(data):
"""Return string to string dictionary from encoded version."""
d = {}
for l in data.split('\0'):
if l:
key, value = l.split(':')
d[key] = value
return d |
def _replace_task_dependencies_with_task_outputs(tasks):
"""Replace a task dependency with the output of the task.
Since users are allowed to reference tasks as dependencies, we need to replace tasks
with the outputs of the task to form the workflow.
"""
for task_info in tasks.values():
de... |
def is_extension_table(table_id):
"""
Return True if specified table is an OMOP extension table.
Extension tables provide additional detail about an OMOP records taht does
not inherently fit in with the OMOP common data model.
:param table_id: identifies the table
:return: True if specified ta... |
def get_vim_start(settings):
"""
Returns the init lines for a VIM colour file.
"""
theme = "dark" if settings.get("theme", "Dark") == "Dark" else "light"
name = settings.get("name", "TheUnknown")
return ("highlight clear\n"
"set background=%s\n"
"if exists(\"syntax_on\")... |
def merge(line):
"""
Helper function that merges a single row or column in 2048
line: list like [8, 0, 16, 0, 16, 8]
returns: merged list [8, 32, 8, 0]
loop cur pos and index in list:
if two equal numbers seperated by 0s, double the previous index and replace number at current position with ... |
def parser_smoothing_buffer_Descriptor(data,i,length,end):
"""\
parser_smoothing_buffer_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "smoothing_buffer", "contents" : unparsed_descriptor_contents }
... |
def is_latinx_or_black(ethnicities):
"""
Checks if Latinx or Black was provided by the developer
in their list of race-ethnicities
"""
return 'Hispanic or Latino/Latina' in ethnicities or 'Black or of African descent' in ethnicities |
def create_basic_sheet(owner=-1, project=-1):
""" Return data of a basic `Sheet` """
return {
'name': 'Base',
'url': 'base',
'owner': owner,
'project': project,
'ranking': 1,
'meta': 'Basic CSS sheet, this is your first css sheet.',
'data': '###### BASE CS... |
def tokenize(text):
"""Tokenize a passage of text, i.e. return a list of words"""
text = text.replace('.', '')
return text.split(' ') |
def mod_abs_diff(a, b, base):
"""Shortest distance between `a` and `b` in the modular integers base `base`.
The smallest distance between a and b is returned.
Example: mod_abs_diff(1, 99, 100) ==> 2. It is not 98.
mod_abs_diff is symmetric, i.e. `a` and `b` are interchangeable.
Args:
... |
def fontInfoOpenTypeOS2WidthClassValidator(value):
"""
Version 2+.
"""
if not isinstance(value, int):
return False
if value < 1:
return False
if value > 9:
return False
return True |
def check_api_token(api_key):
"""Check if the user's API key is valid. Change the API key if you want it to be private!"""
if (api_key == '123abc'):
return True
else:
return False |
def _parse_dim_from_string(filepath):
"""
example: "image_FLOAT_3D.nii.gz" -> 3
"""
if '1D' in filepath:
return 1
elif '2D' in filepath:
return 2
elif '3D' in filepath:
return 3
elif '4D' in filepath:
return 4
else:
raise ValueError('cant parse dim... |
def transform_zip(number):
"""Get rid of extended format ZIP code."""
zip_code = number.split("-")[0]
return zip_code |
def get_peer_port(conn_data, dut_hostname, dut_intf):
"""
Get the peer port of the DUT port
Args:
conn_data (dict): the dictionary returned by conn_graph_fact.
Example format of the conn_data is given below:
{u'device_conn': {u'sonic-s6100-dut':
{u'Ethernet6... |
def selection_sort(array):
"""
Selection Sort
Complexity: O(N^2)
"""
array_len = len(array)
for k in range(array_len - 1):
minimum = k
for i in range(k + 1, array_len):
if array[i] < array[minimum]:
minimum = i
temp = array[minimum]
... |
def scaleprob(prob: float, factor: float=100) -> int:
"""
Provide consistent scaling of values into integer space. This maintains a
minimum value of 1.
Args:
prob: probability value, typically from 0 to 1
factor: scale factor
Returns:
scaled probability value
"""
pr... |
def splitListIntoTasks(wordList):
"""Returns given_list split into chunks
Given_list is handed to function by selectMode()
"""
chunkList = []
# nodeCount = countNodes() !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
nodeCount = 1
factor = 3
equalChunks = nodeCoun... |
def get_original_file_name(full_file_path):
"""Get the file name from the path."""
return full_file_path.split("/")[-1] |
def squared_btn(value):
"""Return the square of the current value."""
try:
x = float(value)
return x ** 2
except ValueError:
return "ERROR" |
def testBit(int_type: int, offset: int) -> int:
"""
testBit() returns a nonzero result, 2**offset, if the bit at
'offset' is one.
"""
mask = 1 << offset
return int_type & mask |
def listAxes(axd):
"""
make a list of the axes from the dictionary
Parameters
----------
axd : axes (list, dict)
Returns
-------
list of axes
"""
if type(axd) is not dict:
if type(axd) is list:
return axd
else:
print("listAxes expects dic... |
def normsq3d(v):
"""
Square of the norm of a 3D vector
Args:
v (np.ndarray): 3D vector
Returns:
np.ndarray: Square of the norm of the vector
"""
return v[0]*v[0]+v[1]*v[1]+v[2]*v[2] |
def hex_to_rgba(h, alpha):
"""
converts color value in hex format to rgba format with alpha transparency
"""
return tuple([int(h.lstrip('#')[i:i + 2], 16) for i in (0, 2, 4)] + [alpha]) |
def parseLines(chunk):
"""Take the given chunk of lines and turn it into a test data dictionary
[(int, str)] -> {str:(int, str)}
"""
items = {}
for (lineno, line) in chunk:
header, data = line.split(':', 1)
header = header.lower()
items[header] = (lineno, data.strip())
... |
def is_valid_provider(user_input: str, static_provider: str) -> bool:
"""
Validate a user's provider input irrespectve of case
"""
try:
return user_input.lower() == static_provider.lower()
except AttributeError:
return False |
def name_extractor_hesiod_old(l):
"""Can probably be removed - use to recreate old reports
"""
return '/'.join( l.split('=')[-1].split('/')[-3:-1] ) |
def sloppy_merge_dicts( dicts ):
"""
Merge a list of dictionaries where some values may be overridden
"""
result = {}
for mapping in dicts:
for key, value in mapping.items():
result[ key ] = value
return result |
def merge_dicts(*dicts):
"""Return a dict whose keys are all the keys in the dict given,
and the values are the value for the last dict given.
Example:
>>> merge_dicts(
... {"a": 0, "b": 1},
... {"a": 2, "c": 2}
... )
{"a": 2, "b": 1, "c": 2}
"""
res = {}
for d in di... |
def reassemble_addresses(seq):
"""Takes a sequence of strings and combines any sub-sequence that looks
like an IPv4 address into a single string.
Example:
['listener', '0', '0', '0', '0_80', downstream_cx_total'] ->
['listener', '0.0.0.0:80', 'downstream_cx_total']
"""
reassembled =... |
def get_nr_bits(ring_size: int) -> int:
"""Get number of bits.
Args:
ring_size (int): Ring Size.
Returns:
int: Bit length.
"""
return (ring_size - 1).bit_length() |
def space_replace(output, content_data, modification_flag):
"""
Converts two spaces to one.
Args:
output: What is to be returned by the profiler
content_data: "$var= 'EXAMPLE'"
modification_flag:
Returns:
output: What is to be returned by the profiler
... |
def metadata_function(metadata_batches):
"""Gets the metadata."""
metadata_list = [metadata_batches[0][i] for i in range(len(metadata_batches[0]))]
return metadata_list |
def MD5_f3(b, c, d):
""" Third ternary bitwise operation."""
return (b ^ c ^ d) & 0xFFFFFFFF |
def color_pval(p_value, alpha=0.05, significant_color='red', null_color='black'):
"""Return a text color based on the significance of a p-value.
Parameters
----------
p_value : float
The p-value to check.
alpha : float, optional, default: 0.05
The significance level to check against... |
def timefromstring(s):
"""
:param s : String to parse time from
:returns : Time in seconds
"""
t = 0
words = s.split(" ")
prev = words[0]
for word in words[1:]:
try:
if word in ["hours", "hour"]:
t += int(prev) * 3600
elif word in ["minutes... |
def getChanceAgreementFromList(l1):
"""
Returns p_e, the probability of chance agreement: (1/N^2) * sum(n_k1 * n_k2) for k categories (i.e. two in this case, 0 or 1), from binary list L1
"""
count_zeros = sum([1 for i in range(0, len(l1)) if l1[i] == 0])
count_ones = sum([1 for i in range(0, len(l1)... |
def lists_are_equal(list_1, list_2) -> bool:
"""Assert that the unordered lists contain the same elements."""
if len(list_1) != len(list_2):
return False
found = False
for i in list_1:
for j in list_2:
if i == j:
found = True
break
... |
def canJump( nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums: return False
first = nums[0]
if first == 0 and len(nums) == 1:return True
for x in range(first, 0, -1):
if x >= len(nums):
return True
ans = canJump(nums[x:])
if ans:
return ans
else:
continue
return False |
def read_corpus(lines):
"""
convert corpus into features and labels
"""
features = list()
labels = list()
tmp_fl = list()
tmp_ll = list()
for line in lines:
if not (line.isspace() or (len(line) > 10 and line[0:10] == '-DOCSTART-')):
line = line.rstrip('\n').... |
def split_list(X, idxs, feature, split, low, high):
""" Sort the list, if the element in the array is less than result index,
the element value is less than the split. Otherwise, the element value is
equal to or greater than the split.
Arguments:
X {list} -- 2d list object with int or float
... |
def validate_password_rules(password: str,
min_number: int,
max_number: int,
test_char: str) -> bool:
"""
Old Password Rules
The password policy indicates the lowest and highest number of times a given letter must
appea... |
def min_blocks(length: int, block: int) -> int:
"""
Returns minimum number of blocks with length ``block``
necessary to cover the array with non-zero length ``length``.
"""
if length <= 0:
raise ValueError("The length must be positive")
return (length - 1) // block + 1 |
def pick_best_solution(xys):
"""
Return the value of x where abs(y) is at its minimum and xys is a list of
x-y pairs.
Examples
--------
>>> pick_best_solution([(0.1, 0.3), (0.2, -1.), (-0.5, 0.001)])
-0.5
"""
y_best = 1e16
x_best = 0.
abs_ = abs
for x, y in xys:... |
def get_stochastic_depth_rate(init_rate, i, n):
"""Get drop connect rate for the ith block.
Args:
init_rate: A `float` of initial drop rate.
i: An `int` of order of the current block.
n: An `int` total number of blocks.
Returns:
Drop rate of the ith block.
"""
if init_rate ... |
def alt_solution_1(n):
"""Find the sum of all multiples of 3 or 5 below `n`.
This solution is slow.
"""
x = 0
total = 0
while x < n:
for d in [3, 2, 1, 3, 1, 2, 3]:
x += d
if x >= n:
break
total += x
return total |
def retain_reference(journal_reference, min_size=3, required_fields=["author","title"]):
"""
Determine whether the input reference should be retained, and thus resolved, or skipped.
This allows to skip erroneously extracted references, partial ones, etc.
:param journal_reference: the input reference (e... |
def map_values(fun, a_dict):
"""Return copy of a_dict with fun applied to each of its values.
:: Hashable K => ((X->Y), {K : X}) -> {K : Y}
Equivalent to the following in Python 3:
{k:fun(v) for (k, v) in a_dict.items()}
>>> a_dict = {'a': 2, 'b': 3, 'c': 4}
>>> times_2 = map_values(lambda ... |
def _cluster_has_pending_steps(steps):
"""Does *cluster* have any steps in the ``PENDING`` state?"""
return any(step['Status']['State'] == 'PENDING' for step in steps) |
def file_read(file_handle, file_blocks):
"""A simple function to read a part of a file in chunks. It is decorated
with a timer to track duration.
- Args:
- file_handle (file): the open file to read
- file_blocks (file): the size in bytes to read
- Returns:
- [file]: returns the... |
def applyCoder(text, coder):
"""
Applies the coder to the text. Returns the encoded text.
text: string
coder: dict with mappings of characters to shifted characters
returns: text after mapping coder chars to original text
"""
encrypted = ''
for char in text:
if char in coder:
... |
def twoset_segment_metrics_to_list(twoset_metrics_results):
""" Converting detailed event metric results to a list (position of each item is fixed)
Argument:
twoset_metrics_results (dictionary): as provided by the 1st item in the results of eval_events function
Returns:
list: Item order: 0... |
def IO_safe(func, *args, _tries=5, _raise=True, **kwargs):
""" Wrapper calling function func with arguments args and keyword arguments kwargs to catch input/output errors
on cluster.
:param func: function to execute (intended to be read/write operation to a problematic cluster drive, but can be
... |
def to_bytestring (s):
"""Convert the given unicode string to a bytestring, using the standard encoding,
unless it's already a bytestring"""
if s:
if isinstance(s, str):
return s
else:
return s.encode('utf-8') |
def snaga_tokarenje(glavna_sila, brzina_rezanja):
"""
snaga_tokarenje [kW]
\tglavna_sila [N]\n
\tbrzina_rezanja [m/min]
"""
return glavna_sila*brzina_rezanja/60e3 |
def a_record(query, ipaddr):
""" Formats an A record using fields in 'query' and ipaddr, suitable for
printing in a 'DATA' reply to pdns.
Example:
ndt.iupui.donar.measurement-lab.org IN A 60 -1 192.168.1.2\\n
"""
reply = "%(name)s\t"
reply += "%(class)s\t"
reply += "A\t"
reply ... |
def latlonbox(imrange):
""" generate kml latlonbox """
#<north>%s</north>
#<south>%s</south>
#<west>%s</west>
#<east>%s</east>
[lon0,lon1,lat0,lat1] = imrange
north = "<north>%s</north>" % str(lat1)
south = "<south>%s</south>" % str(lat0)
west = "<west>%s</west>" % str(lon0)
ea... |
def complete_args_dict(args):
"""
Compatibility function; adds all missing values to the command line
arguments dictionaryionary.
"""
arg_list = ['-cnf', '-s', '-ho', '-n', '-po', '-ssl', '-pw', '-npw']
defaults = {'-cnf': False, '-s': None, '-ho': 'localhost', '-n': 'P1tr',
'-po... |
def strip_figure(figure):
"""Strip a Plotly figure into multiple figures with a trace on each of them.
Parameters
----------
figure : dict or Figure
Plotly figure to strip into multiple figures.
"""
if figure is not None:
if isinstance(figure, dict):
pass
... |
def get_from_dict(d, path):
"""
Extract a value pointed by ``path`` from a nested dict.
Example:
>>> d = {
... "path": {
... "to": {
... "item": "value"
... }
... }
... }
>>> get_from_dict(d, "/path/to/item")
'value'
"""
compon... |
def _linearify(seq):
"""Format sequence into an array of instructions."""
seq = seq.replace('\n', ' ').replace('\r', ' ').split(' ')
seq = filter(lambda x: len(x) > 0, seq)
return list(seq) |
def word(l, h):
"""
Given a low and high bit, converts the number back into a word.
"""
return (h << 8) + l |
def sum_abs_of_all_without_range(sequence):
"""
Same specification as sum_abs_of_all above,
but with a different implementation.
"""
# ------------------------------------------------------------------
# EXAMPLE 2. Iterates through a sequence of numbers, summing them.
# Same as Example ... |
def iterable(obj):
"""
Grabbed from Python Cookbook / matplotlib.cbook.
Returns true/false for *obj* iterable.
"""
try:
len(obj)
except:
return False
return True |
def _get_application_import_names(pyproject):
"""Return the application package name the config."""
# Otherwise override with what was specified
app_name = (
pyproject.get("tool", {})
.get("ni-python-styleguide", {})
.get("application-import-names", "")
)
# Allow the poetry ... |
def args_rep(*args, **kwargs):
"""
Return the representation of args and kwargs.
:return: The representation string.
:rtype: str
"""
a = ", ".join(repr(a) for a in args)
k = ", ".join(k + "=" + repr(kwargs[k]) for k in sorted(kwargs))
s = ", " if a and k else ""
return "(" + a + s +... |
def list_loader(subloaders, value):
"""loader for the List generic"""
loader, = subloaders
return list(map(loader, value)) |
def union_lists(data):
""" performs union on list of lists """
return list(set().union(*data)) |
def determine_attributes(variable_products):
"""
Function to go through all the products and get a list of attributes and attribute terms. Single products do not
have any attributes.
:param variable_products: Dict containing list of variations of variable products
:return: dict of attributes and th... |
def _capabilities_to_dict(caps):
"""Convert the Node's capabilities into a dictionary."""
if not caps:
return {}
if isinstance(caps, dict):
return caps
return dict([key.split(':', 1) for key in caps.split(',')]) |
def reverse_string(phrase):
"""Reverse string,
>>> reverse_string('awesome')
'emosewa'
>>> reverse_string('sauce')
'ecuas'
"""
return phrase[::-1] |
def best_match(ref, read):
"""
param ref: str, the long sequence provided by the user
param read: str, the short sequence provided by the user
param similarity: integer, the similar degree (if match, similarity will plus one)
param max: integer, the maximum
param index: integer
return str
... |
def _limit_stat_length(stat_length, shape):
"""limits the stat_length to current array length along given dimension."""
return tuple((min(stat_pair[0], shape[i]), min(stat_pair[1], shape[i])) for i, stat_pair in enumerate(stat_length)) |
def lookup_grad_indices(model_name):
"""Which index in the list of grads corresponds to embedding weight and which to last linear layer bias?"""
if "transformer" in model_name: # This lookup is not automated :> Add new models here
embedding_parameter_idx = -2 if model_name == "transformer3t" else -3
... |
def suggest(product_idea):
"""
docstring
"""
if len(product_idea) < 3:
raise ValueError()
return product_idea + "inator" |
def is_extrusion_line(line: str) -> bool:
"""Check if current line is a standard printing segment.
Args:
line (str): Gcode line
Returns:
bool: True if the line is a standard printing segment
"""
return "G1" in line and " X" in line and "Y" in line and "E" in line |
def _deg2_column(d, i, j, interaction_only):
"""Compute the index of the column for a degree 2 expansion
d is the dimensionality of the input data, i and j are the indices
for the columns involved in the expansion.
"""
if interaction_only:
return int(d * i - (i**2 + 3 * i) / 2 - 1 + j)
... |
def list_comprehension(function, argument_list):
"""Apply a univariate function to a list of arguments in a serial fashion.
Uses Python's built-in list comprehension.
Args:
function: A callable object that accepts one argument
argument_list: An iterable object of input arguments
Retur... |
def password_reset_link(url_root, token):
"""Generates password reset link.
Args:
url_root (str): root url
token (str): Token to be attached to the url
Returns:
tuple: the verification link, token
"""
link = url_root + f'api/v1/user/password/reset?token={token}'
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.