content stringlengths 42 6.51k |
|---|
def logical_rshift(val: int, n: int):
"""Solution by NPE
https://stackoverflow.com/a/5833119
Parameters
----------
val : int
Integer to be right logical shifted
n : int
Number of bits to shift by
Returns
-------
int
Right logically shifted number
"""
return val >> n if val >= 0 else (val + 0x100000000) >> n |
def contains_class(class_list, class_match):
""" Determines if the class_match is in the class_list.
Not sure why I didn't just say class_match in class_list but
think that for some reason the BeautifulSoup list didn't support
that or there was somethign else wrong.
:param class_list: A list of HTML classes
:param class_match: The class we are looking for
:return: True if the match class is in the list
"""
for class_val in class_list:
if class_val == class_match:
return True
return False |
def judge_if_legal(s):
"""
:param s: str
:return: True or False
"""
if s.isalpha():
if len(s) == 1:
return True
else:
return False |
def get_args(tp):
"""
Simplified getting of type arguments. Should be replaced with typing.get_args from Python >= 3.8
"""
if hasattr(tp, '__args__'):
return tp.__args__
return () |
def int_to_mode(mode):
"""Returns the string representation in VPP of a given bondethernet mode,
or "" if 'mode' is not a valid id.
See src/vnet/bonding/bond.api and schema.yaml for valid pairs."""
ret = {1: "round-robin", 2: "active-backup", 3: "xor", 4: "broadcast", 5: "lacp"}
try:
return ret[mode]
except KeyError:
pass
return "" |
def convert_to_camel(data):
"""
Convert snake case (foo_bar_bat) to camel case (fooBarBat).
This is not pythonic, but needed for certain situations
"""
components = data.split('_')
return components[0] + "".join(x.title() for x in components[1:]) |
def italic(content):
"""Corresponds to ``*content*`` in the markup.
:param content: HTML that will go inside the tags.
>>> 'i would ' + italic('really') + ' like to see that'
'i would <i>really</i> like to see that'
"""
return '<i>' + content + '</i>' |
def loop_struct_has_non_simd_loop(loop_struct, config):
"""Examine if the leaf node of the loop struct has any non-SIMD loop."""
if "loop" in loop_struct:
if config["under_simd"] == 1:
return 0
else:
return 1
elif "mark" in loop_struct:
mark = loop_struct["mark"]
mark_name = mark["mark_name"]
if mark_name == "simd":
config["under_simd"] = 1
child = mark["child"]
if child == None:
return 0
else:
return loop_struct_has_non_simd_loop(child, config)
elif "user" in loop_struct:
return 0
elif "block" in loop_struct:
children = loop_struct["block"]["child"]
if children == None:
return 0
else:
for child in children:
has_non_simd_loop = loop_struct_has_non_simd_loop(child, config)
if has_non_simd_loop == 1:
return 1
return 0
elif "if" in loop_struct:
if_struct = loop_struct["if"]
then_block = if_struct["then"]
has_non_simd_loop = loop_struct_has_non_simd_loop(then_block, config)
if has_non_simd_loop == 1:
return 1
if "else" in if_struct:
else_block = if_struct["else"]
has_non_simd_loop = loop_struct_has_non_simd_loop(else_block, config)
if has_non_simd_loop == 1:
return 1
return 0
return 0 |
def zero_correct(dim_over, dim_detc):
"""
This short function calculates the correction for the change
in the location of the origin pixel (the very first, or "0"),
which is applied to the calculation of centroid computed for
a grid that has been downsampled.
"""
factor = dim_over / dim_detc
corr = factor / 2. - 0.5
return corr/factor |
def _mul_inv(a, b):
"""Source: https://rosettacode.org/wiki/Chinese_remainder_theorem#Python"""
b0 = b
x0, x1 = 0, 1
if b == 1:
return 1
while a > 1:
q = a // b
a, b = b, a % b
x0, x1 = x1 - q * x0, x0
if x1 < 0:
x1 += b0
return x1 |
def add_kwds(dictionary, key, value):
"""
A simple helper function to initialize our dictionary if it is None and then add in a single keyword if
the value is not None.
It doesn't add any keywords at all if passed value==None.
Parameters
----------
dictionary: dict (or None)
A dictionary to copy and update. If none it will instantiate a new dictionary.
key: str
A the key to add to the dictionary
value: object (or None)
A value to add to the dictionary. If None then no key, value pair will be added to the dictionary.
Returns
-------
dictionary
A copy of dictionary with (key,value) added into it or a new dictionary with (key,value) in it.
"""
if dictionary is None:
kwds = {}
else:
kwds = dictionary.copy()
if (value is not None) and (key is not None):
kwds.update({key: value})
return kwds |
def dictmask(data, mask, missing_keep=False):
"""dictmask masks dictionary data based on mask"""
if not isinstance(data, dict):
raise ValueError("First argument with data should be dictionary")
if not isinstance(mask, dict):
raise ValueError("Second argument with mask should be dictionary")
if not isinstance(missing_keep, bool):
raise ValueError("Argument missing_keep should be bool type")
res = {}
for k, v in data.items():
if k not in mask:
if missing_keep is True:
res[k] = v
continue
if mask[k] is None or mask[k] is False:
continue
if mask[k] is True or data[k] is None:
res[k] = v
continue
if isinstance(data[k], dict) and isinstance(mask[k], dict):
res[k] = dictmask(data[k], mask[k])
continue
if isinstance(data[k], list) and isinstance(mask[k], list):
if len(mask[k]) != 1:
raise ValueError("Mask inside list should have only one item")
res2 = []
for i in range(len(data[k])):
res2.append(dictmask(data[k][i], mask[k][0], missing_keep))
res[k] = res2
else:
raise ValueError(
f"Cannot proceed key {k} with values of different types:"
f"{type(data[k])}, {type(mask[k])}"
)
return res |
def get_decade(start_year, end_year):
"""divide the time legnth into decades, return list of 10 years each"""
import numpy as np
all_years = np.arange(int(start_year), int(end_year) + 1)
yr_chunks = [all_years[x: x+10] for x in range(0, len(all_years), 10)]
return yr_chunks |
def parseValue(formatString):
"""Returns the value type of data item from MXElectrix data message.
The value type is taken to be everything before opening bracket [."""
sep = formatString.find("[")
if sep < 0:
return ""
else:
return formatString[:sep] |
def longest_common_substring(s1, s2):
"""Returns longest common substring of two input strings.
see https://en.wikipedia.org/wiki/Longest_common_substring_problem
and https://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#Python_3
"""
m = [[0] * (1 + len(s2)) for i in range(1 + len(s1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(s1)):
for y in range(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
m[x][y] = m[x - 1][y - 1] + 1
if m[x][y] > longest:
longest = m[x][y]
x_longest = x
else:
m[x][y] = 0
return s1[x_longest - longest: x_longest] |
def valid_verify(pwd1, pwd2):
""" verify if both passwords given match each other """
if pwd1 != pwd2:
return "Your passwords didn't match." |
def parse_entity(entity, filter_none=False):
"""
Function creates a dict of object attributes.
Args:
entity (object): object to extract attributes from.
Returns:
result (dict): a dictionary of attributes from the function input.
"""
result = {}
attributes = [attr for attr in dir(entity) if not attr.startswith("_")]
for attribute in attributes:
value = getattr(entity, attribute, None)
if filter_none and not value:
continue
value_behavior = dir(value)
if "__call__" not in value_behavior:
result[attribute] = value
return result |
def _str_to_list(str_or_list):
"""return a `list` in either case"""
if isinstance(str_or_list, (tuple, list, set)):
return str_or_list
if str(str_or_list) == str_or_list:
return [str_or_list]
raise ValueError(str_or_list) |
def wrap(x, m, M):
"""
Rotate x to fit in range (m, M).
Useful while dealing with angles.
Parameters
----------
x : float
Value.
m : float
Lower bound.
M : float
Upper bound.
"""
diff = M - m
while x > M:
x = x - diff
while x < m:
x = x + diff
return x |
def signature(t):
"""
Given an Elm type signatue of form:
name : a -> b
or similar, return the 'a -> b' part
Also gets the constructors of a data declaration or the type of an alias
Only works on single-line declarations
"""
if t.startswith('type '):
return t[5:].split(' = ')[1].strip()
elif t.startswith('data '):
return t[5:].split(' = ')[1].strip()
return t.split(' : ')[1].strip() |
def isNumber(variable):
"""
Returns True if varible is is a number
"""
try:
float(variable)
except TypeError:
return False
return True |
def _transpose_to_columnar(raw_data):
"""Groups the same data together by key.
BEFORE:
[
{ 'product': 'apple', 'price': 10.0 },
{ 'product': 'banana', 'price': 5.0 }
]
AFTER:
{
'product': ['apple', 'banana'],
'price': [10.0, 5.0],
}
:param raw_data: list of dictionaries
:return: dictionary where keys are the column names
:rtype: dict
"""
columnar_data = {}
for entry in raw_data:
for key, val in entry.items():
if key not in columnar_data:
columnar_data[key] = []
columnar_data[key].append(val)
return columnar_data |
def _ParsePlusMinusList(value):
"""Parse a string containing a series of plus/minuse values.
Strings are seprated by whitespace, comma and/or semi-colon.
Example:
value = "one +two -three"
plus = ['one', 'two']
minus = ['three']
Args:
value: string containing unparsed plus minus values.
Returns:
A tuple of (plus, minus) string values.
"""
plus = []
minus = []
# Treat ';' and ',' as separators (in addition to SPACE)
for ch in [',', ';']:
value = value.replace(ch, ' ')
terms = [i.strip() for i in value.split()]
for item in terms:
if item.startswith('-'):
minus.append(item.lstrip('-'))
else:
plus.append(item.lstrip('+')) # optional leading '+'
return plus, minus |
def add_neighbours(pseudo_ids, pseudo_imgs, mosaic_mode, mosaic, img, id):
""" Takes a batch (N, 101, 101, 3) and list of id's. Adds mosaic data."""
if mosaic_mode not in [1, 2]:
return img
img[:, :, mosaic_mode] = 0.5
name = id[:-4]
# mask_names = ["left", "top", "right", "bottom"]
mask_offsets = [(0, 0), (50, 0), (0, 50), (50, 50)]
for neighbour in range(4):
if name in mosaic[neighbour]:
ofs = mask_offsets[neighbour]
img[ofs[0] : ofs[0]+50, ofs[1] : ofs[1]+50, mosaic_mode] = mosaic[neighbour][name]
return img |
def chi_par(x, A, x0, C):
"""
Parabola for fitting to chisq curve.
"""
return A*(x - x0)**2 + C |
def split_docstring(doc):
"""Split docstring into first line (header) and full body."""
return (doc.split("\n", 1)[0], doc) if doc is not None else ("", "") |
def poly_integral(poly, C=0):
"""Return an list of the integrated polynomial"""
if (not isinstance(poly, list) or
len(poly) == 0 or
not all(isinstance(x, (int, float)) for x in poly) or
not isinstance(C, (int, float))):
return None
ans = [C]
for i in range(len(poly)):
temp = poly[i] / (i + 1)
if temp.is_integer():
temp = round(temp)
ans.append(temp)
if ans[-1] == 0:
ans.pop()
return ans |
def _vpres(T):
""" Polynomial approximation of saturated water vapour pressure as
a function of temperature.
Parameters
----------
T : float
Ambient temperature, in Kelvin
Returns
-------
float
Saturated water vapor pressure expressed in mb
See Also
--------
es
"""
# Coefficients for vapor pressure approximation
A = [
6.107799610e0,
4.436518521e-1,
1.428945805e-2,
2.650648471e-4,
3.031240396e-6,
2.034080948e-8,
6.136820929e-11,
]
T -= 273 # Convert from Kelvin to C
vp = A[-1] * T
for ai in reversed(A[1:-1]):
vp = (vp + ai) * T
vp += A[0]
return vp |
def safe_cast(invar, totype):
"""Performs a "safe" typecast.
Ensures that `invar` properly casts to `totype`. Checks after
casting that the result is actually of type `totype`. Any exceptions raised
by the typecast itself are unhandled.
Parameters
----------
invar
(arbitrary) -- Value to be typecast.
totype
|type| -- Type to which `invar` is to be cast.
Returns
-------
outvar
`type 'totype'` -- Typecast version of `invar`
Raises
------
~exceptions.TypeError
If result of typecast is not of type `totype`
"""
# Make the typecast. Just use Python built-in exceptioning
outvar = totype(invar)
# Check that the cast type matches
if not isinstance(outvar, totype):
raise TypeError("Result of cast to '{0}' is '{1}'"
.format(totype, type(outvar)))
## end if
# Success; return the cast value
return outvar |
def is_variable(expr):
"""
Check if expression is variable
"""
for i in expr:
if i == '(':
return False
return True |
def readlines(fil=None,raw=False):
"""
Read in all lines of a file.
Parameters
----------
file : str
The name of the file to load.
raw : bool, optional, default is false
Do not trim \n off the ends of the lines.
Returns
-------
lines : list
The list of lines from the file
Example
-------
.. code-block:: python
lines = readlines("file.txt")
"""
if fil is None: raise ValueError("File not input")
f = open(fil,'r')
lines = f.readlines()
f.close()
# Strip newline off
if raw is False: lines = [l.rstrip('\n') for l in lines]
return lines |
def bubbleSort(array):
"""
input: array
return: sorted array of integers
"""
n = len(array)
for i in range(n):
for j in range(n - i - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array |
def _created_on_to_timestamp_ms(created_on):
"""
Converts the Message CreatedOn column to a millisecond timestamp value.
CreatedOn is number of 100 nanosecond increments since midnight 0000-01-01.
Output is number of millisecond increments since midnight 1970-01-01.
"""
return created_on / 10000 - 62167219200000 |
def doi_filter_list(doi_list, params):
""" influx helper adding a doi filter list (faster than array check in influx) """
if doi_list:
filter_string = """
|> filter(fn: (r) => """
i = 0
for doi in doi_list:
filter_string += 'r["doi"] == _doi_nr_' + str(i) + ' or '
params['_doi_nr_' + str(i)] = doi
i += 1
filter_string = filter_string[:-4] + ')'
return {"string": filter_string, "params": params}
return {"string": '', "params": params} |
def list_copy(seq_list):
"""copy all the seqs in the list"""
return [s.copy() for s in seq_list] |
def blink(s):
"""Return blinking string."""
return "\033[5;40m{}\033[25m".format(s) |
def _str_eval_first(eval, act, ctxt, x) :
"""Returns the first element of the argument."""
return [x[0]] |
def get_overlapping_arcodes(action_replay_list:list):
"""
input: action_replay_list = [ActionReplayCode, ...]
return [(ActionReplayCode, ActionReplayCode), ...] else None
Get overlapping action replay code in memory. Return couples of arcodes that patch sames memory addresses.
"""
if len(action_replay_list) < 2: return None
action_replay_list.sort(key=lambda x:x.address())
# Find overlaps between ARCodes
overlaps_list = []
last_arcode = action_replay_list[0]
for action_replay_code in action_replay_list[1:]:
# Intersect
if last_arcode & action_replay_code:
overlaps_list.append( (last_arcode, action_replay_code) )
last_arcode = action_replay_code
return overlaps_list if overlaps_list != [] else None |
def get_formatted_size_MB( totsizeMB ):
"""
Same as :py:meth:`get_formatted_size <howdy.core.get_formatted_size>`, except this operates on file sizes in units of megabytes rather than bytes.
:param int totsizeMB: size of the file in megabytes.
:returns: Formatted representation of that file size.
:rtype: str
.. seealso:: :py:meth:`get_formatted_size <howdy.core.get_formatted_size>`.
"""
if totsizeMB >= 1024:
size_in_gb = totsizeMB * 1.0 / 1024
return '%0.3f GB' % size_in_gb
elif totsizeMB > 0: return '%0.3f MB' % totsizeMB
else: return "" |
def to_cartesian(algebraic):
"""Convert algebraic to cartesian
Parameters
----------
algebraic: str
Algebraic coordinate
Returns
-------
tuple
Cartesian coordinate
"""
mapper = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
'F': 6,
'G': 7,
'H': 8}
hor = mapper[algebraic[0]]
ver = int(algebraic[1])
return (hor, ver) |
def get_user_id(user_id: str) -> str:
"""
Formats the user_id to a plain format removing any <, < or @
:param user_id: slack id format
:type user_id: str
:return: plain user id
:rtype: str
"""
return user_id.strip("<>@") |
def average_accuracy(outputs, targets, k=10):
"""
Computes the average accuracy at k.
This function computes the average
accuracy at k between two lists of items.
Args:
outputs (list): A list of predicted elements
targets (list): A list of elements that are to be predicted
k (int, optional): The maximum number of predicted elements
Returns:
double: The average accuracy at k over the input lists
"""
if len(outputs) > k:
outputs = outputs[:k]
score = 0.0
num_hits = 0.0
for i, predict in enumerate(outputs):
if predict in targets and predict not in outputs[:i]:
num_hits += 1.0
score += num_hits / (i + 1.0)
if not targets:
return 0.0
return score / min(len(targets), k) |
def is_sysem(title_text: str, description_text: str, requirements_text: str) -> bool:
"""
Indicate if a course is a sophomore seminar.
Parameters
----------
title_text:
Extracted title text from course JSON.
description_text:
Extracted description text from extract_course_info().
requirements_text:
Extracted requirements info from extract_course_info().
"""
flagged_text = [
"Enrollment limited to sophomores",
"Sophomore Seminar",
"Registration preference to sophomores"
"Registration preference given to sophomores",
"Registration preference is given to sophomores"
"Enrollment limited to freshmen and sophomores",
"Enrollment limited to first-years and sophomores",
"Enrollment limited to sophomores",
"Preference to sophomores",
"Sophomore standing required",
"Recommended for sophomores",
"Intended for freshmen and sophomores",
"Intended for first-year students and sophomores",
"Priority to sophomores",
"preference to freshmen and sophomores",
"preference to first-years and sophomores",
"primarily for freshmen and sophomores",
"primarily for first-years and sophomores",
]
for text in flagged_text:
if text in title_text:
return True
if text in description_text:
return True
if text in requirements_text:
return True
return False |
def first_relationship_that_matches(end_def, end_def_type, end_def_name, relationship_typedefs):
"""
Find the first relationship type that matches the end_def number, type
and name from the provided typedefs.
:param str end_def: Either 'endDef1' or 'endDef2'
:param str end_def_type: The type within the end_def.
:param str end_def_name:
The name of the relationship attribute applied to the end def's entity.
(e.g. columns, table, columnLineages, query)
:param list(dict) relationship_typedefs:
A list of dictionaries that follow the relationship type defs.
:raises ValueError:
An relationship dict was not found in the provided typedefs.
:return: The matching relationship type definition.
:rtype: dict
"""
output = None
for typedef in relationship_typedefs:
if ((end_def in typedef) and
(typedef[end_def]["type"] == end_def_type) and
(typedef[end_def]["name"] == end_def_name)):
output = typedef
if output is None:
raise ValueError(
"Unable to find a relationship type that matches: {endDef} "
"with type {end_def_type} and the name {end_def_name} from "
"the {num_defs} provided."
.format(
endDef=end_def, end_def_type=end_def_type,
end_def_name=end_def_name, num_defs=len(relationship_typedefs)
)
)
return output |
def format_funcline(name, mem_usage):
"""Create the output string for a function profile interval."""
start_memory, start_timestamp = mem_usage[0]
end_memory, end_timestamp = mem_usage[-1]
return "FUNC {name} {0:.6f} {1:.4f} {2:.6f} {3:.4f}\n".format(
start_memory,
start_timestamp,
end_memory,
end_timestamp,
name=name,
) |
def list_to_string(list, separator = "\t"):
"""
Converts a list of values to a string using SEPARATOR for joints
Args:
list: a list of values to be converted to a string
separator: a separator to be used for joints
Returns:
a string
"""
return separator.join(map(str, list))+ "\n" |
def SymbolicConstant(in_str) -> str:
"""
:param in_str:
:return:
"""
# type: "(str) -> str"
in_str = in_str
return in_str |
def comma_space(s):
"""
insert a space after every comma in s unless s ends in a comma
:param s: string to be checked for spaces after commas
:return s: improved string with commas always followed by spaces
:rtype: basestring
"""
k = s.find(',')
if -1 < k < len(s) - 1 and s[k + 1] != " ":
s = s[0:k] + ', ' + comma_space(s[k + 1:])
return s |
def options_string_builder(option_mapping, args):
"""Return arguments for CLI invocation of kal."""
options_string = ""
for option, flag in option_mapping.items():
if option in args:
options_string += str(" %s %s" % (flag, str(args[option])))
return options_string |
def DecodeFileRecordSegmentReference(ReferenceNumber):
"""Decode a file record segment reference, return the (file_record_segment_number, sequence_number) tuple."""
file_record_segment_number = ReferenceNumber & 0xFFFFFFFFFFFF
sequence_number = ReferenceNumber >> 48
return (file_record_segment_number, sequence_number) |
def electrode_distance(latlong_a, latlong_b, radius=100.0):
"""
geodesic (great-circle) distance between two electrodes, A and B
:param latlong_a: spherical coordinates of electrode A
:param latlong_b: spherical coordinates of electrode B
:return: distance
"""
import math
lat1, lon1 = latlong_a
lat2, lon2 = latlong_b
dLat = math.radians(lat2 - lat1)
dLon = math.radians(lon2 - lon1)
a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(
math.radians(lat1)
) * math.cos(math.radians(lat2)) * math.sin(dLon / 2) * math.sin(dLon / 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius * c
return d |
def descendingOrderCheck(_ordered_list):
"""
Check whether the input list is ordered descending.
:param _ordered_list: The input list that is ordered by descending order
:return: returns true if order of _ordered_list is descending else returns false.
"""
return all(earlier >= later for earlier, later in zip(_ordered_list, _ordered_list[1:])) |
def vessel_tip_coupling_data_to_str(data_list):
"""A list of vessel tip data elements is converted into a string."""
s = []
for v in data_list:
s.append('VesselTipData(')
s.append(' p = Point(x={}, y={}, z={}),'.format(v.p.x, v.p.y, v.p.z))
s.append(' vertex_id = {},'.format(v.vertex_id))
s.append(' pressure = {},'.format(v.pressure))
s.append(' concentration = {},'.format(v.concentration))
s.append(' R2 = {},'.format(v.R2))
s.append(' radius_first = {},'.format(v.radius_first))
s.append(' radius_last = {},'.format(v.radius_last))
s.append(' level = {}'.format(v.level))
s.append('),')
return '\n'.join(s) |
def convert_mw_gwh(megawatt, number_of_hours):
""""Conversion of MW to GWh
Input
-----
kwh : float
Kilowatthours
number_of_hours : float
Number of hours
Return
------
gwh : float
Gigawatthours
"""
# Convert MW to MWh
megawatt_hour = megawatt * number_of_hours
# Convert mwth to gwh
gigawatthour = megawatt_hour / 1000.0
return gigawatthour |
def unique_activities_from_log(log, name_of_activity):
"""
Returns unique activities from event log.
:param name_of_activity: name of activity.
:param log: event log.
:return: unique activities.
"""
unique_activities = []
for sequence in log:
for activity in sequence:
unique_activities.append(activity[name_of_activity])
return sorted(list(set(unique_activities))) |
def kochanekBartelsInterpolator(v0, v1, v2, v3, alpha, tension, continuity, bias):
"""
Kochanek-Bartels interpolator. Allows even better control of the bends in the spline by providing three
parameters to adjust them:
* tension: 1 for high tension, 0 for normal tension and -1 for low tension.
* continuity: 1 for inverted corners, 0 for normal corners, -1 for box corners.
* bias: 1 for bias towards the next segment, 0 for even bias, -1 for bias towards the previous segment.
Using 0 continuity gives a hermite spline.
"""
alpha2 = alpha * alpha
alpha3 = alpha2 * alpha
m0 = ((((v1 - v0) * (1 - tension)) * (1 + continuity)) * (1 + bias)) / 2.0
m0 += ((((v2 - v1) * (1 - tension)) * (1 - continuity)) * (1 - bias)) / 2.0
m1 = ((((v2 - v1) * (1 - tension)) * (1 - continuity)) * (1 + bias)) / 2.0
m1 += ((((v3 - v2) * (1 - tension)) * (1 + continuity)) * (1 - bias)) / 2.0
a0 = 2 * alpha3 - 3 * alpha2 + 1
a1 = alpha3 - 2 * alpha2 + alpha
a2 = alpha3 - alpha2
a3 = -2 * alpha3 + 3 * alpha2
return a0 * v1 + a1 * m0 + a2 * m1 + a3 * v2 |
def read_flash(filename):
"""
Read dataset from FLASH output file
Parameters
----------
filename : string containing file name
Returns
-------
data_attributes : dictionary containing data attributes
block_attributes : dictionary containg block attributes
"""
data_attributes = {}
block_attributes = [{}]
return data_attributes,block_attributes |
def pyext_coms(platform):
"""Return PYEXTCCCOM, PYEXTCXXCOM and PYEXTLINKCOM for the given
platform."""
if platform == 'win32':
pyext_cccom = "$PYEXTCC /Fo$TARGET /c $PYEXTCCSHARED "\
"$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
pyext_cxxcom = "$PYEXTCXX /Fo$TARGET /c $PYEXTCSHARED "\
"$PYEXTCXXFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
pyext_linkcom = '${TEMPFILE("$PYEXTLINK $PYEXTLINKFLAGS '\
'/OUT:$TARGET.windows $( $_LIBDIRFLAGS $) '\
'$_LIBFLAGS $_PYEXTRUNTIME $SOURCES.windows")}'
else:
pyext_cccom = "$PYEXTCC -o $TARGET -c $PYEXTCCSHARED "\
"$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
pyext_cxxcom = "$PYEXTCXX -o $TARGET -c $PYEXTCSHARED "\
"$PYEXTCXXFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
pyext_linkcom = "$PYEXTLINK -o $TARGET $PYEXTLINKFLAGS "\
"$SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_PYEXTRUNTIME"
if platform == 'darwin':
pyext_linkcom += ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
return pyext_cccom, pyext_cxxcom, pyext_linkcom |
def static_file(file_path):
"""
[This function will help in serving a static_file]
:param file_path [str]: [file path to serve as a response]
"""
return {
"response_type": "static_file",
"file_path": file_path
} |
def countinclude(data, s="sam"):
"""Count how many words occur in a list up to and including the first
occurrence of the word "sam"."""
count = 0
for i in data:
count += 1
if i == s:
break
return count |
def tau(values):
"""
Calculates the Tau value for a list of expression values
:param dist: list of values
:return: tau value
"""
n = len(values) # number of values
mxi = max(values) # max value
if mxi > 0:
t = sum([1 - (x/mxi) for x in values])/(n - 1)
return t
else:
return None |
def checksumStr(data):
"""
Take a NMEA 0183 string and compute the checksum.
@param data: NMEA message. Leading ?/! and training checksum are optional
@type data: str
@return: hexidecimal value
@rtype: str
Checksum is calculated by xor'ing everything between ? or ! and the *
>>> checksumStr("!AIVDM,1,1,,B,35MsUdPOh8JwI:0HUwquiIFH21>i,0*09")
'09'
>>> checksumStr("AIVDM,1,1,,B,35MsUdPOh8JwI:0HUwquiIFH21>i,0")
'09'
"""
# FIX: strip off new line at the end too
if data[0]=='!' or data[0]=='?': data = data[1:]
if data[-1]=='*': data = data[:-1]
if data[-3]=='*': data = data[:-3]
# FIX: rename sum to not shadown builting function
sum=0
for c in data: sum = sum ^ ord(c)
sumHex = "%x" % sum
if len(sumHex)==1: sumHex = '0'+sumHex
return sumHex.upper() |
def _config_for_dimensions(pool_cfg, dimensions_flat):
"""Determines the external scheduler for pool config and dimension set.
Pool's dimensions are matched with each config from top to down. The
last config in the file should be the default one.
"""
if not pool_cfg or not pool_cfg.external_schedulers:
return None
for e in pool_cfg.external_schedulers:
if e.dimensions.issubset(dimensions_flat):
return e if e.enabled else None
return None |
def make_summary(serialized_data):
"""
Take in a full serialized object, and return dict containing just
the id and the name
Parameter: serialized_data, dict, or list of dicts
Returns: dict, or list of dicts, containing just "name" and "id" key/values.
"""
def summarize_one(data):
if not (
isinstance(data, dict) and "id" in data.keys() and "name" in data.keys()
):
raise RuntimeError("Expected dictionary containing name and id")
return {"name": data["name"], "id": data["id"]}
if isinstance(serialized_data, list):
return [summarize_one(sd) for sd in serialized_data]
else:
return summarize_one(serialized_data) |
def is_arg(args, options):
"""Check if an option is already in the argument list."""
return any(option in args for option in options) |
def read_paragraph_element(element):
"""Returns the text in the given ParagraphElement.
Args:
element: a ParagraphElement from a Google Doc.
"""
text_run = element.get('textRun')
if not text_run:
return ''
return text_run.get('content') |
def api_key_auth(key, required_scopes=None):
"""
Function pointed to by x-apikeyInfoFunc in the swagger security definitions.
"""
if key is not None:
# Pretty much a null implementation.
return {'sub': 'unknown'}
else:
return None |
def get_bool(value: str) -> bool:
"""Get boolean from string."""
if value.upper() in ["1", "T", "TRUE"]:
return True
if value.upper() in ["0", "F", "FALSE"]:
return False
raise ValueError(f"Unable to convert {value} to boolean.") |
def r_to_z(r, a=200., b=1.6):
"""Calculates reflectivity from rain rates using
a power law Z/R relationship Z = a*R**b
Parameters
----------
r : a float or an array of floats
Corresponds to rainfall intensity in mm/h
a : float
Parameter a of the Z/R relationship
Standard value according to Marshall-Palmer is a=200., b=1.6
b : float
Parameter b of the Z/R relationship
Standard value according to Marshall-Palmer is b=1.6
Note
----
The German Weather Service uses a=256 and b=1.42 instead of
the Marshall-Palmer defaults.
Returns
-------
output : a float or an array of floats
reflectivity in mm**6/m**3
"""
return a * r ** b |
def __get_midi_csv(midi_strings):
"""split comma seperated strings into csv file
Arguments:
midi_strings {list} -- list of comma separated strings
Returns:
csv -- midi data in csv format
"""
midi_csv = []
for row in midi_strings:
midi_data = row.split(",")
midi_csv.append(midi_data)
return midi_csv |
def format_time_str(parse_time) -> str:
"""
Format execution time to be printed out
:param parse_time: Timespan.
:return: Formated string.
"""
hours = int(parse_time / 3600)
minutes = int((parse_time - hours * 3600) / 60)
seconds = int(parse_time % 60)
millis = int((parse_time % 60 - seconds) * 1000)
return "{}h {}m {}s {}ms".format(hours, minutes, seconds, millis) |
def quaternion_canonize(q):
"""Converts a quaternion into a canonic form if needed.
Parameters
----------
q : list
Quaternion as a list of four real values ``[w, x, y, z]``.
Returns
-------
list
Quaternion in a canonic form as a list of four real values ``[cw, cx, cy, cz]``.
Notes
-----
Canonic form means the scalar component is a non-negative number.
"""
if q[0] < 0.0:
return [-x for x in q]
return q[:] |
def part2(adapters):
""" Find all possible combination of adapters """
adapters.sort()
adapters.insert(0, 0) # add 0 at start for the wall jolt
adapters.append(max(adapters) + 3) # adding phone's inbuilt adapter
# memoize already visisted node
visited = dict()
def repeat(i):
if i == len(adapters) - 1:
return 1
if i in visited:
return visited[i]
answer = 0
for j in range(i + 1, len(adapters)):
if adapters[j] - adapters[i] <= 3:
answer += repeat(j)
visited[i] = answer
return answer
no_of_ways = repeat(0) # no. of ways to reach the end starting from index 0
return no_of_ways |
def solution1(rooms):
"""
Solution 1
---
:type rooms: list[list[int]]
:rtype: bool
"""
visited = {0}
def dfs(i):
for key in rooms[i]:
if key not in visited:
visited.add(key)
dfs(key)
dfs(0)
return len(visited) == len(rooms) |
def _get_image_url(photo_item, size_flag=''):
"""
size_flag: string ['']
See http://www.flickr.com/services/api/misc.urls.html for options.
'': 500 px on longest side
'_m': 240px on longest side
"""
url = "http://farm{farm}.staticflickr.com/{server}/{id}_{secret}{size}.jpg"
return url.format(size=size_flag, **photo_item) |
def get_GiB(x: int):
"""return x GiB."""
return x * (1 << 30) |
def calc_time_cost_function(natom, nkpt, kmax, nspins=1):
"""Estimates the cost of simulating a single iteration of a system"""
costs = natom**3 * kmax**3 * nkpt * nspins
return costs |
def get_rank(scores):
"""
Returns list of (index, value) of scores, sorted by decreasing order.
The order is randomized in case of tie thanks to the key_tie_break function.
"""
return sorted(enumerate(scores), key=lambda t: t[1], reverse=True) |
def pl_winp(a, b):
"""Win probability of player a over b given their PL ratings."""
return a / (a + b) |
def eqn_list_to_dict(eqn_list, reverse=None):
"""Convert a list of Sympy Relational objects to a dictionary.
Most commonly, this will be for converting things like:
[y == a*x + b, z == c*x + d]
to a Python dictionary object with keys corresponding to the left hand side
of the relational objects and values corresponding to the right hand side
of the relational objects:
{y: a*x+b, z: c*x + d}
Optional argument 'reverse' swaps the keys for the values, i.e:
{a*x + b: y, c*x +d: z}
Remember that dictionaries are *NOT* ordered, so if the list you pass
requires a special ordering, it will *NOT* be preseved by converting it to
a dictionary.
"""
eqn_dict = {}
for eqn in eqn_list:
if reverse:
eqn_dict[eqn.rhs] = eqn.lhs
else:
eqn_dict[eqn.lhs] = eqn.rhs
return eqn_dict |
def string_to_list(string_in):
""" Converts a string to a list """
list_out = []
for ch in string_in:
list_out.append(ch)
return list_out |
def get_time_in_min(timestamp):
"""
Takes a timestamp, for example 12:00 and splits it, then converts it into minutes.
"""
hours, minutes = timestamp.split(":")
total_minutes = int(hours)*60+int(minutes)
return total_minutes |
def get_block(i, k, T, B):
"""
Get's the ith block of 2^T // B, such that sum(get_block(i) * 2^ki) =
t^T // B
"""
return (pow(2, k) * pow(2, T - k * (i + 1), B)) // B |
def extract_tag(inventory, url):
"""
extract data from sphinx inventory.
The extracted datas come from a C++ project
documented using Breathe. The structure of the inventory
is a dictionary with the following keys
- cpp:class (class names)
- cpp:function (functions or class methods)
- cpp:type (type names)
each value of this dictionary is again a dictionary with
- key : the name of the element
- value : a tuple where the third index is the url to the corresponding documentation
Parameters
----------
inventory : dict
sphinx inventory
url : url of the documentation
Returns
-------
dictionary with keys class, class_methods, func, type
but now the class methods are with their class.
"""
classes = {}
class_methods = {}
functions = {}
types = {}
get_relative_url = lambda x: x[2].replace(url, '')
for c, v in inventory.get('cpp:class', {}).items():
classes[c] = get_relative_url(v)
class_methods[c] = {}
for method, v in inventory.get('cpp:function', {}).items():
found = False
for c in class_methods.keys():
find = c + '::'
if find in method:
class_methods[c][method.replace(find, '')] = get_relative_url(v)
found = True
break
if not found:
functions[method] = get_relative_url(v)
for typename, v in inventory.get('cpp:type', {}).items():
types[typename] = get_relative_url(v)
return {'class': classes,
'class_methods': class_methods,
'func':functions,
'type': types
} |
def format_line_protocol(measurement: str,field: dict,tags: dict={}) -> str:
"""Converts input into influxDB line protocol format.
Args:
measurement (str): This is the overarching "thing" you're monitoring.
field (dict): This is the metric you're collecting for the "thing."
tags (dict, optional): These are optional other attributes you want to attach to the measurement. Defaults to {}.
Raises:
Exception: Multiple fields/metrics specified. Please format each field/metric separately.
Returns:
str: Line protocol formated string ready to be pushed to InfluxDB.
Examples:
```
>>> measurement = 'serverroom'
>>> tags = {'category': 'general', 'priority': 'high', 'owningParty': 'maintenace'}
>>> field = {'humidity': 0.99} #get_sensor_humidity
>>> format_line_protocol(measurement,field,tags)
>>> 'serverroom,category=general,priority=high,owningParty=maintenace humidity=0.99'
```
"""
str_output = f'{measurement}'
if tags:
for t in tags:
str_output += f',{t}={tags[t]}'
if len(field) == 1:
f = list(field.keys())[0]
str_output += f" {f}={field[f]}"
return str_output
else:
raise Exception("Multiple fields/metrics specified. Please format each field/metric separately.") |
def parse_spotify_url(url):
"""
Parse the provided Spotify playlist URL and determine if it is a playlist, track or album.
:param url: URL to be parsed
:return tuple indicating the type and id of the item
"""
parsed_url = url.replace("https://open.spotify.com/", "")
item_type = parsed_url.split("/")[0]
item_id = parsed_url.split("/")[1]
return item_type, item_id |
def clamp(num):
"""
Return a "clamped" version of the given num,
converted to be an int limited to the range 0..255 for 1 byte.
"""
num = int(num)
if num < 0:
return 0
if num >= 256:
return 255
return num |
def is_terminal(node):
"""Whether a node in primitive tree is terminal.
Args:
node: String, deap.gp.Primitive or deap.gp.Terminal.
Returns:
Boolean.
"""
return isinstance(node, str) or node.arity == 0 |
def parse_csv(columns, line):
"""
Parse a CSV line that has ',' as a separator.
Columns is a list of the column names, must match the number of
comma-separated values in the input line.
"""
data = {}
split = line.split(',')
for idx, name in enumerate(columns):
data[name] = split[idx]
return data |
def _get_zip_urls(year):
"""Return urls for zip files based on pattern.
Parameters
----------
year : string
4 digit year in string format 'YYYY'.
Returns
-------
dict
"""
suffix = f'oesm{year[2:]}'
code = 4
return {
'national': f'https://www.bls.gov/oes/special.requests/{suffix}'
'nat.zip',
'state': f'https://www.bls.gov/oes/special.requests/{suffix}'
'st.zip',
'area': f'https://www.bls.gov/oes/special.requests/{suffix}ma.zip',
'industry': f'https://www.bls.gov/oes/special.requests/{suffix}in'
f'{code}.zip'} |
def value_or(value, default):
"""Return Value or Default if Value is None."""
return value if value is not None else default |
def safe_int(string):
""" Utility function to convert python objects to integer values without throwing an exception """
try:
return int(string)
except ValueError:
return None |
def descending_order(num):
"""
Your task is to make a function that can take any non-negative integer as a argument and return it with its digits
in descending order. Essentially, rearrange the digits to create the highest possible number.
:param num: an positive integer.
:return: the integers digits in descending order.
"""
return int("".join(sorted(str(num))[::-1])) |
def specified_or_guess(attributes):
"""Without identifier guess the elements to be removed based on markup.
:param attributes: an attribute pair of key and value
"""
if attributes:
return '{}="[^>]*?{}[^>]*?"'.format(*list(attributes.items())[0])
return '' |
def rchop(original_string, substring):
"""Return the given string after chopping of a substring from the end.
:param original_string: the original string
:param substring: the substring to chop from the end
"""
if original_string.endswith(substring):
return original_string[:-len(substring)]
return original_string |
def multiply(*args):
"""Returns the multiplication result of random amount of numbers given"""
if not args:
return None
product = 1
for x in args:
product *= x
return product |
def stringify(in_fields, formats):
"""
Arguments:
in_fields -- list of lists to stringify
formats -- list of correspoding formats
"""
olist = []
for entry in in_fields:
new_val = []
for indx, part in enumerate(entry):
if indx >= len(formats):
new_val.append(str(part))
else:
if formats[indx]:
new_val.append(formats[indx].format(part))
else:
new_val.append(str(part))
olist.append(new_val)
return olist |
def convert_to_letters(num):
"""Converts number to string of capital letters in Excel column name
fashion, i.e. 1 -> A, 26 -> Z, 27 -> AA ...."""
string_equiv = ""
while num > 0:
currNum = (num - 1) % 26
num = (num - 1) // 26
string_equiv = chr(currNum + ord("A")) + string_equiv
return string_equiv |
def preprocess_word(word):
"""standardize word form for the alignment task"""
return word.strip().lower() |
def snake_case_to_kebab_case(s):
"""Util method to convert kebab-case fieldnames to snake_case."""
return s.replace("_", "-") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.