content stringlengths 42 6.51k |
|---|
def keys_as_sorted_list(dict):
"""
Given a dictionary, get the keys from it, and convert it into a list,
then sort the list of keys
"""
return sorted(list(dict.keys())) |
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
"""resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Resolves a dotted attribute name to an object. Raises
an AttributeError if any attribute in the chain starts with a '_'.
If the optional allow_dotted_names argument is false, d... |
def deep_list(x):
"""Convert tuple recursively to list."""
if isinstance(x, tuple):
return map(deep_list, x)
return x |
def merge_dict(main_dict, enhance_dict):
"""Merges dictionaries by keys.
Function call itself if value on key is again dictionary.
Args:
main_dict (dict): First dict to merge second one into.
enhance_dict (dict): Second dict to be merged.
Returns:
dict: Merged result.
.. ... |
def deep(m, dflt, *pth):
"""Access to props in nested dicts / Creating subdicts by *pth
Switch to create mode a bit crazy, but had no sig possibilit in PY2:
# thats a py3 feature I miss, have to fix like that:
if add is set (m, True) we create the path in m
Example:
deep(res, True), [], 'post'... |
def selection_sort(l):
"""
:param l - a list
:return a sorted list
"""
for i in range(len(l)):
min_index = i
for j in range(i, len(l)):
if l[j] < l[min_index]:
min_index = j
l[i], l[min_index] = l[min_index], l[i]
return l |
def unique(lst):
"""
Identify the unique elements of a list (the elements that do not appear
anywhere else in the list)
"""
un_lst = []
for i,v in enumerate(lst):
if i == len(lst) - 1:
continue
if v != lst[i-1] and v != lst[i+1]:
un_lst.append(i)
... |
def queryEscape(query):
"""Certain chars need to be escaped
"""
bad_chars = [ (""", '"')
]
for char, replacement in bad_chars:
query = query.replace(char, replacement)
return query |
def task_simulation():
"""
Runs the parametrized fenics 'poission' example for a convergence plot
and a field plot
"""
return {
"file_dep": ["computation/poisson.py"],
"targets": [
"computation/poisson_convergence_Ns.npy",
"computation/poisson_convergence_erro... |
def palindrom_reverse(s):
"""Check palindrome by inverse slicing.
Time complexity: O(n).
Space complexity: O(n).
"""
return s == s[::-1] |
def __to_upper(val):
"""Convert val into ucase value."""
try:
return val.upper()
except (ValueError, TypeError):
return val |
def maprange(a, b, s):
"""remap values linear to a new range"""
(a1, a2), (b1, b2) = a, b
return b1 + ((s - a1) * (b2 - b1) / (a2 - a1)) |
def clean_text(text):
"""Cleans text.
Only cleans superfluous whitespace at the moment.
"""
return ' '.join(text.split()).strip() |
def lim_z(depth, thick, val):
"""
limits for depth
"""
return (depth - val * thick, depth + val * thick) |
def checkunique(data):
"""Quickly checks if a sorted array is all unique elements."""
for i in range(len(data) - 1):
if data[i] == data[i + 1]:
return False
return True |
def has_special_character(password: str) -> bool:
""" checks if password has at least one special character """
return any(char for char in password if not char.isalnum() and not char.isspace()) |
def tryParse(text):
"""
A convenience function for attempting to parse a string as a number (first,
attempts to create an integer, and falls back to a float if the value has
a decimal, and finally resorting to just returning the string in the case
where the data cannot be converted).
@ In, text, s... |
def strings_contain_each_other(first_str, second_str):
"""
Checks if two strings contain each other.
Returns (the bool value that says if they are containing each other,
the string that includes,
the string that is included)
"""
first_count = second_str.count(first_str)
... |
def parseOperator(value):
"""
Returns a search operator based on the type of the value to match on.
:param value: to match in the search.
:return: operator to use for the type of value.
"""
if type(value) == str:
return " LIKE "
else:
return "=" |
def user_subscribe_event(msg):
""" user subscribe event """
return msg['MsgType'] == 'event' and msg['Event'] == 'subscribe' |
def _isfloat(string):
"""
Checks if a string can be converted into a float.
Parameters
----------
value : str
Returns
-------
bool:
True/False if the string can/can not be converted into a float.
"""
try:
float(string)
return True
except ValueError... |
def convert_dashes(dash):
""" Converts a Matplotlib dash specification
bokeh.core.properties.DashPattern supports the matplotlib named dash styles,
but not the little shorthand characters. This function takes care of
mapping those.
"""
mpl_dash_map = {
"-": "solid",
"--": "dash... |
def get_angle_difference(angle, difference=90):
"""Given an azimuth angle (0-360), it will return the two azimuth angles (0-360) as a tuple that are perpendicular to it."""
angle_lower, angle_higher = (angle + difference) % 360, (angle - difference) % 360
return (angle_lower, angle_higher) |
def check_line(line: str):
"""
A funtion that checks if a string passed to this function contains key
words that need to be processed further
Parameters
----------
line : str\n
a string that needs to be checked if it contains key words
Returns
-------
list\n
... |
def split_neo_dict(neo_dict: dict) -> list:
"""
Convert NEO dictionary into a list of NEOs
Args:
neo_dict (dict): NEO dictionary pulled from NEO feed
Returns:
[list]: List of NEOs
"""
return [i for v in neo_dict.items() for i in v] |
def normalize_dot_bracket(bracket: str) -> str:
"""
Return a normalized version of the dot bracket. First pseudoknot pair
always starts with a parenthesis.
```
normalize_dot_bracket("..((..[[[..)).]]].") == "..((..[[[..)).]]]."
normalize_dot_bracket("..[[..(((..]].))).") == "..((..[[[..)).]]]."... |
def comp_dict(d1, d2):
"""
Compare the structure of two dictionaries to see if they are identical
return True if same schema, False if not
"""
if d1.keys() != d2.keys():
return False
else:
same = True
for key in d1.keys(): # both sets of keys are the same
if dict == type(d1[key]) == type(d2[key]):
sa... |
def map_int(x, in_min, in_max, out_min, out_max):
"""
Map input from one range to another.
"""
return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min); |
def check_nuvs_file_type(file_name: str) -> str:
"""
Get the NuVs analysis file type based on the extension of given `file_name`
:param file_name: NuVs analysis file name
:return: file type
"""
if file_name.endswith(".tsv"):
return "tsv"
if file_name.endswith(".fa"):
retur... |
def results_to_dict(movie_id: int, props_movie: dict):
"""
Function that returns vector of dictionaries with the results from the dbpedia to insert into data frame of all
movie properties
:param movie_id: movie id of the movie
:param props_movie: properties returned from dbpedia
:return: vector ... |
def match_videos_and_captions(videos, sentences):
"""Maps captions to videos and splits the data into train/valid/test.
arguments:
videos: a list of dicts, where each dict describes a video
sentences: a list of dicts, where each dict describes a sentence
returns:
a dict that maps f... |
def get_resource_node(platform, executable_name, base_destination_node):
"""
Gets the path to where resources should be placed in a package based on the platform.
:param platform: The platform to get the resource location for
:param executable_name: Name of the executable that is being packaged
:p... |
def deny(target, actuator, modifier):
"""
Note: return values are sent as the response to an OpenC2 cmd
"""
return "Blocking domain {}".format(target['URI']) |
def new_filename(file, ntype, snr):
"""Append noise tyep and power at the end of wav filename."""
return file.replace(".WAV", ".WAV.{}.{}dB".format(ntype, snr)) |
def pascal(row, column):
"""Returns the value of the item in Pascal's Triangle
whose position is specified by row and column.
>>> pascal(0, 0)
1
>>> pascal(0, 5) # Empty entry; outside of Pascal's Triangle
0
>>> pascal(3, 2) # Row 3 (1 3 3 1), Column 2
3
>>> pascal(4, 2) # Row 4... |
def two_pad(in_time):
"""
Takes in a number of 1 or 2 digits, returns a string of two digits.
"""
assert isinstance(in_time,int)
assert (in_time < 100 and in_time >= 0)
return "0" + str(in_time) if str(in_time).__len__() == 1 else str(in_time) |
def gcd(x, y):
"""
assume always x > y
:param x:
:param y:
:return: gcd value
"""
if x < y:
z = x
x = y
y = z
if y == 0:
print(f'gcd = {x}')
return x
else:
print(f'{x} = {(x - x % y) / y}*{y} + {x % y}')
return gcd(y, x % y) |
def map_range(x, x_min, x_max, y_min, y_max):
"""
Linear mapping between two ranges of values
"""
x = float(x)
x_range = x_max - x_min
y_range = y_max - y_min
xy_ratio = x_range / y_range
y = ((x - x_min) / xy_ratio + y_min)
return int(y) |
def split(string, sep):
"""Return the string split by sep.
Example usage: {{ value|split:"/" }}
"""
return string.split(sep) |
def _to_hass_brightness(brightness):
"""Convert percentage to Home Assistant brightness units."""
return int(brightness * 255) |
def gen_data_dict(data, columns):
"""Fill expected data tuple based on columns list
"""
return tuple(data.get(attr, '') for attr in columns) |
def get_modifications(old, new, attributes):
"""
Create a dictionary containing the old values when they are different from
the new ones at given attributes.
Does not consider other attributes than the array given in parameter.
:param old: a dictionary containing the old values
:param new: a di... |
def stringify(vals):
"""
return a string version of vals (a list of object implementing __str__)
return type: 'val1_val2_val3_ ... _valn'
"""
return '_'.join([str(e) for e in vals]) |
def matrix_divided(matrix, div):
"""
Function that divides all elements of a matrix.
Args:
matrix (list): the square matrix
div (int or float): the number that divide
Returns:
new matrix
"""
if type(div) is not int and type(div) is not float:
raise TypeError("di... |
def flatten(lst):
"""Flatten a list. See http://stackoverflow.com/questions/952914/\
making-a-flat-list-out-of-list-of-lists-in-python
"""
return [item for sublist in lst for item in sublist] |
def quicksort(l):
"""Sort list using quick sort.
Complexity: O(n log n). Worst: O(n2)
@param l list to sort.
@returns sorted list.
"""
if len(l) <= 1:
return l
pivot = l[0]
less = []
equal = []
greater = []
for e in l:
if e < pivot:
less.append... |
def tail(real_iter, n_th):
"""Returns the last nth elements of an iterable.
Takes any iterable and returns its lasth nth items from the iterable/list.
Args:
real_iter: an interable or a list (iterable or list)
n_th: nth number of items to return (int)
Returns:
A list containi... |
def calc_epsilon(sample_parent, model_parent):
"""Calculates the epsilon value, given the sample parent and model parent
composition.
Parameters
----------
sample_parent : float
Measured parent composition.
model_parent : float
Model parent composition. (Typically CHUR or... |
def get_column_as_list(matrix, column_no):
"""
Retrieves a column from a matrix as a list
"""
column = []
num_rows = len(matrix)
for row in range(num_rows):
column.append(matrix[row][column_no])
return column |
def limit_x(x, limit):
"""
This module limits the values to the range of [0,limit]
"""
x_gr_limit = x > limit
x_le_limit = x_gr_limit * limit + (1 - x_gr_limit) * x
x_gr_zero = x > 0.0
x_norm = x_gr_zero * x_le_limit
return x_norm |
def parseData(data):
"""
Parse a dict of dicts to generate a list of lists describing
the fields, and an array of the corresponding data records
:param dict data: a dict of dicts with field names as keys, and each
sub-dict containing keys of 'Type', 'Length',
... |
def calc_number_neighbours(num_electrons: int) -> int:
"""
Calculates the number of neighbours to distort by considering \
the number of extra/missing electrons.
If the change in the number of defect electrons is equal or lower than 4, then we distort \
that number of neighbours.
If i... |
def fibRecursive(n):
"""[summary]
Computes the n-th fibonacci number recursive.
Problem: This implementation is very slow.
approximate O(2^n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a po... |
def is_collection(obj):
"""
Return whether the object is a array-like collection.
"""
for typ in (list, set, tuple):
if isinstance(obj, typ):
return True
return False |
def iterable(arg):
""" Simple list typecast
"""
if not isinstance(arg, (list, tuple)):
return [arg]
else:
return arg |
def lengthOfLIS(nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
dp = [1]
for i in range(1,len(nums)):
maxx = 0
for j in range(i):
if nums[j] < nums[i]:
maxx = max(maxx, dp[j])
dp.append(maxx+1)
retur... |
def convertNodeTextToFloatList(nodeText, sep=None):
"""
Convert space or comma separated string to list of float
@ In, nodeText, str, string from xml node text
@ Out, listData, list, list of floats
"""
listData = None
if sep is None:
if ',' in nodeText:
listData = list(float(elem) for elem... |
def invalid_resource(message, response_code=400):
"""
Returns the given message, and sets the response code to given response
code. Defaults response code to 400, if not provided.
"""
return {"message": message, "code": response_code} |
def set_new_rb_kpi_dictionary(region_names):
"""
Generates an empty dictionary which collects the parameters
KPI-5, KPI-6, KPI-7, KPI-8 and KPI-9 for each region.
It defined as 'Region Based KPI Dictionary'.
"""
rb_kpi_dict = dict()
for region_name in region_names:
rb_distance_trav... |
def ucfirst(string):
"""Implementation of ucfirst and \ u in interpolated strings: uppercase the first char of the given string"""
return string[0:1].upper() + string[1:] |
def get_iterable(in_dict, in_key):
"""
Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
:param in_dict: a dictionary
:param in_key: the key to look for at in_dict
:return: in_dict[in_var] or () if it is None or not present
"""
if not in_dict.get(i... |
def clean_cases(text):
"""
Makes text all lowercase.
:param text: the text to be converted to all lowercase.
:type: string
:return: lowercase text
:type: string
"""
return text.lower() |
def safe_get(obj, attr, sentinel=None):
"""
Returns sentinel value if attr isn't in obj, otherwise attr's value
"""
try:
return getattr(obj, attr)
except AttributeError:
return sentinel |
def qualified_name_to_object(qualified_name: str, default_module_name='builtins'):
"""
Convert a fully qualified name into a Python object.
It is true that ``qualified_name_to_object(object_to_qualified_name(obj)) is obj``.
>>> qualified_name_to_object('unittest.TestCase')
<class 'unittest.case.Tes... |
def public_download_url(name, version, registry='https://registry.npmjs.org'):
"""
Return a package tarball download URL given a name, version and a base
registry URL.
"""
return '%(registry)s/%(name)s/-/%(name)s-%(version)s.tgz' % locals() |
def mean_squared_error_implementation(y_true, y_pred):
"""Calculate MSE
Arguments:
y_true {list} -- real numbers, true values
y_pred {list} -- real numbers, predicted values
"""
# intialize error at 0
error_ = 0
# loop over all samples in the true and predicted list
for yt, ... |
def checkGuid(guid):
"""
Checks whether a supplied GUID is of the correct format.
The guid is a string of 36 characters long split into 5 parts of length 8-4-4-4-12.
INPUT: guid - string to be checked .
OPERATION: Split the string on '-', checking each part is correct length.
... |
def process_index(item):
"""Process and normalize the index."""
if not isinstance(item, (slice, tuple)):
if not isinstance(item, int):
raise ValueError('The index should be a integer.')
item = (item,)
if not isinstance(item, tuple):
item = tuple([item])
starts, sizes ... |
def convert_min_to_sec(time_min):
"""Function to convert time in mins to secs"""
ans = time_min * 60
return ans |
def upper_keys(d):
"""Returns a new dictionary with the keys of `d` converted to upper case
and the values left unchanged.
"""
return dict(zip((k.upper() for k in d.keys()), d.values())) |
def probabilities (X) -> dict:
""" This function maps the set of outcomes found in the sequence of events, 'X', to their respective probabilty of occuring in 'X'.
The return value is a python dictionary where the keys are the set of outcomes and the values are their associated probabilities."""
# The set of outcomes... |
def parameter_dict_merge(log, param_dicts):
"""
Merge the param dicts into a single one.
If fail, return None
"""
merged_dict = {}
for param_dict in param_dicts:
for key, value in param_dict.items():
if key not in merged_dict:
merged_dict[key] = value
... |
def checkvars(myvars):
"""
Check variables to see if we have a COOP or DCP site
"""
for v in myvars:
# Definitely DCP
if v[:2] in ["HG"]:
return False
if v[:2] in ["SF", "SD"]:
return True
if v[:3] in ["PPH"]:
return False
return Fa... |
def day_of_year (yr, mn, dy) :
""" day serial number in year, Jan 01 as 1
args:
yr: year, 2 or 4 digit year
mn: month, 1 to 12
dy: day, 1 to 31, extended days also acceptable
returns:
day number in the year
"""
md = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, ... |
def make_a_level_list(N_colours):
""" Makes a list of levels for plotting """
list_of_levels = []
for i in range(N_colours):
list_of_levels.append(float(i))
return list_of_levels |
def encode_request(resource_request, module):
"""Structures the request as accountId + rest of request"""
account_id = resource_request['name'].split('@')[0]
del resource_request['name']
return {'accountId': account_id, 'serviceAccount': resource_request} |
def function_star(list):
"""Call a function (first item in list) with a list of arguments.
The * will unpack list[1:] to use in the actual function
"""
fn = list.pop(0)
return fn(*list) |
def clean(text, split=True):
"""cleans user input and returns as a list"""
if text:
if isinstance(text, str):
text = text.strip().lower()
if split:
text = text.split()
return text
else:
return [""] |
def cat_from(strlist, v, suf):
"""
Concatenate sublist of strings
:param strlist: list of strings
:param v: sublist starting position
:param suf: glue string
:return: concatenated string
"""
# return ''.join(map(lambda s: s + suf, strlist[v:]))
return suf.join(strlist[v:]) |
def t(string):
"""
add \t
"""
return (string.count(".")) * "\t" + string |
def fi(x, y, z, i):
"""The f1, f2, f3, f4, and f5 functions from the specification."""
if i == 0:
return x ^ y ^ z
elif i == 1:
return (x & y) | (~x & z)
elif i == 2:
return (x | ~y) ^ z
elif i == 3:
return (x & z) | (y & ~z)
elif i == 4:
return x ^ (y | ~... |
def add_array(arr1, arr2):
"""
function to add arrays
"""
return [i + j for i, j in zip(arr1, arr2)] |
def remove_important_elements(config_dict: dict) -> dict:
"""
Important elements are removed from the config file
so that you can't mistakenly set them to false.
Note: Some can still be sorted out, this will be done in the following versions.
"""
for key in ['BitsAllocated', 'BitsStored', 'High... |
def parser_args(argv):
"""
Parse Alfred Arguments
"""
args = {}
# determine search mode
if(argv[0].lower() == "--clipboard"):
args["mode"] = "clipboard"
args["query"] = argv[1].lower()
return args |
def _set_default_contact_form_id(contact_form_id: int, subcategory_id: int) -> int:
"""Set the default contact foem ID for switches.
:param contact_form_id: the current contact form ID.
:param subcategory_id: the subcategory ID of the switch with missing defaults.
:return: _contact_form_id
:rtype: ... |
def recurring_2(strg):
"""Hash map solution O(n)."""
counts = {}
for c in strg:
if c in counts:
return c
else:
counts[c] = 1
return None |
def bin_to_num(binstr):
"""
Convert a little endian byte-ordered binary string to an integer or long.
"""
# this will cast to long as needed
num = 0
for charac in binstr:
# the most significant byte is a the start of the string so we multiply
# that value by 256 (e.g. <<8) and ad... |
def _same_target(node1, node2, gens):
"""
Calcs fitness based on the fact that two nodes should share same target.
"""
shared_tg = None
for src in gens:
if shared_tg is None and src in [node1, node2]:
shared_tg = gens[src]
elif shared_tg is not None and gens[src] != share... |
def _cinterval(start,stop,step,center,balanced):
"""find start,stop,step to make a centered range or slice"""
if stop is None:
start,stop = 0,start
if center is None:
center = (start + stop)//2
#offset start to hit center
start += center - range(start,center,step)[-1]
if balanced... |
def patch_get_deferred_fields(model):
"""
Django >= 1.8: patch detecting deferred fields. Crucial for only/defer to work.
"""
if not hasattr(model, 'get_deferred_fields'):
return
old_get_deferred_fields = model.get_deferred_fields
def new_get_deferred_fields(self):
sup = old_get... |
def sort_012(arr):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
arr(list): List to be sorted
Returns:
(None)
"""
n = len(arr)
pos0 = 0
pos2 = n - 1
i = 0
while i <= pos2:
if arr[i] == 0:
a... |
def extract_dependencies(reg, assignments):
"""Return a list of all registers which directly
depend on the specified register.
Example:
>>> extract_dependencies('a', {'a': 1})
[]
>>> extract_dependencies('a', {'a': 'b', 'b': 1})
[]
>>> extract_dependencies('a', {'a'... |
def addToInventory(inventory, addedItems):
""" Add Items to inventory
Args:
inventory (dict): Inventory containing items and their counts
addedItems (list): Items to add to inventory
Returns:
updatedInventory (dict): Inventory containing updated items and their ... |
def falkner_skan_differential_equation(eta, f, beta):
"""
The governing differential equation of the Falkner-Skan boundary layer solution.
:param eta: The value of eta. Not used; just set up like this so that scipy.integrate.solve_ivp() can use this function.
:param f: A vector of 3 elements: f, f', and... |
def reduced_energy(temperature, potential):
"""Calculates reduced energy.
Arguments:
temperature - replica temperature
potential - replica potential energy
Returns:
reduced energy of replica
"""
kb = 0.0019872041
# check for division by zero
if temperature != 0:
beta = ... |
def havriliak_negami(x, de, logtau0, a, b, einf):
"""1-d HN: HN(x, logf0, de, a, b, einf)"""
return de / ( 1 + ( 1j * x * 10**logtau0 )**a )**b + einf |
def kill_procs(pids):
""" Kill a list of processes using their PIDs
Parameters
----------
pids : list
A list of process id's (processes that ought to be killed)
"""
return ' '.join( ['kill -9'] + [ str(pid) for pid in pids ] ) |
def sol2(arr):
"""
This comes out of the editorial. Complexity is n
"""
n = len(arr)
v = [-1 for i in range(256)]
m = 1
clen = 1
v[ord(arr[0])] = 0
for i in range(1, n):
lastIndex = v[ord(arr[i])]
if lastIndex == -1 or i-clen > lastIndex:
cle... |
def calc_rate(rate, rate_long, maturity):
"""Approximate a current interest rate.
Permforms linear interpolation based on the current
1-year and 10-year rates and the maturity of the
bond.
Parameters
----------
rate : float
1-year interest rate.
rate_long : float
10-yea... |
def correct_size_password(MAX_LEN):
"""Make sure that the password has a minimum of 5 character"""
if MAX_LEN < 5:
MAX_LEN = 5
else:
MAX_LEN = MAX_LEN
return MAX_LEN |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.