content
stringlengths 42
6.51k
|
---|
def _type_check(variable_name: str, variable_type: str) -> str:
"""
Return the type check Python instruction.
If variable_type == int:
type(variable_name) == int
else:
isinstance(variable_name, variable_type)
:param variable_name: the variable name.
:param variable_type: the variable type.
:return: the Python instruction to check the type, in string form.
"""
if variable_type != "int":
return f"isinstance({variable_name}, {variable_type})"
else:
return f"type({variable_name}) is {variable_type}"
|
def _bool(val):
"""
Return ``True`` iff *val* is "1", "yes", or "true", otherwise ``False``.
>>> _bool('TRUE')
True
>>> _bool('nah')
False
"""
return val.lower() in ('1', 'yes', 'true')
|
def format_value_for_munin(value, zero_allowed=False):
"""
Convert value into a format that will be understood by Munin
@param value: value to write
@param boolean zero_allowed: if True, 0 will be reported as 0, otherwise as unknown ('U')
@return value
"""
return value if value or (zero_allowed and value == 0) else 'U'
|
def get_inverse_transform(transform):
"""Generates a transform which is the inverse of the provided transform"""
inverse_transform = [0] * len(transform)
for i in range(len(transform)):
inverse_transform[transform[i]] = i
return inverse_transform
|
def write_about(name, title, date, author):
"""
"""
return "* {} - {} * The {} is about {}. It has been writtent by {}, and published in {}.".format(name, title, name, title, author, date)
|
def _calculate_texture_sim(ri, rj):
"""
Calculate texture similarity using histogram intersection
"""
return sum([min(a, b) for a, b in zip(ri["texture_hist"], rj["texture_hist"])])
|
def val_to_dec(value, base=2):
""" base=2: [False, False, False, False, False, False, False, True] -> 128 """
res = 0
for idx, val in enumerate(value):
res += int(val) * base ** idx
return res
|
def topo_sorted(depmap):
"""Return list of items topologically sorted.
depmap: { item: [required_item, ...], ... }
Raises ValueError if a required_item cannot be satisfied in any order.
The per-item required_item iterables must allow revisiting on
multiple iterations.
"""
ordered = [ item for item, requires in depmap.items() if not requires ]
depmap = { item: set(requires) for item, requires in depmap.items() if requires }
satisfied = set(ordered)
while depmap:
additions = []
for item, requires in list(depmap.items()):
if requires.issubset(satisfied):
additions.append(item)
satisfied.add(item)
del depmap[item]
if not additions:
raise ValueError(("unsatisfiable", depmap))
ordered.extend(additions)
additions = []
return ordered
|
def generate(message: str) -> str:
"""Generate a string with 'Hello message' format.
Args:
message: A string to be added.
Returns:
Generated String.
"""
return 'Hello {}'.format(message)
|
def hello_guest(guest):
"""route for user privelege only"""
return 'Hello %s as Guest' % guest
|
def is_list_of_int(value):
"""
Check if an object is a list of integers
:param value:
:return:
"""
return bool(value) and isinstance(value, list) and all(isinstance(elem, int) for elem in value)
|
def invert(d):
"""Given a dictionary `d`, produce a dictionary that inverts its key-value relationship.
Warning:
If a value appears multiple times in `d` the resulting inverse dictionary will contain
only the last key that was encountered while iterating over `d` (which is, by definition,
undefined ;-).
"""
return {v: k for k, v in d.items()}
|
def strtoken(st,pos,sep):
"""Splits string and returns splitted substring. Returns "" if None
Args:
st: String to split
pos: Position to return. Can be negative
sep: Separator
"""
out = ""
s = st.split(sep)
if len(s) >= abs(pos) and pos != 0:
if pos > 0:
out = s[pos-1]
else:
out = s[len(s)+pos]
return out
|
def make_url_action(label, url, i18n_labels=None):
"""
make url action.
reference
- `Common Message Property <https://developers.worksmobile.com/jp/document/1005050?lang=en>`_
:param url: User behavior will trigger the client to request this URL.
:return: actions content
"""
if i18n_labels is not None:
return {"type": "uri", "label": label, "uri": url,
"i18nLabels": i18n_labels}
return {"type": "uri", "label": label, "uri": url}
|
def scale_loss(loss, loss_scale):
"""Scale loss by loss_scale."""
if callable(loss):
return lambda: loss() * loss_scale
return loss * loss_scale
|
def get_tag_value(tag_list, key):
"""
Given a list of dictionaries representing tags, returns the value of the given key, or None if the key
cannot be found.
"""
for tag in tag_list:
if tag["Key"] == key:
return tag["Value"]
return None
|
def dosta_Topt_volt_to_degC(T_optode_volt):
"""
Description:
Computes T_optode [degC], the DOSTA foil temperature as measured by its internal thermistor,
from the analog output of a DOSTA Aanderaa Optode connected to a SBE CTD's 0-5 volt analog
data channel.
Usage:
T_optode_degC = dosta_Topt_volt_to_degC(T_optode_volt)
where
T_optode_degC = optode foil temperature measured by an Aanderaa optode [degC].
T_optode_volt = optode foil temperature measured by an Aanderaa optode
that has been converted to volts for analog output.
Implemented by:
2015-08-04: Russell Desiderio. Initial Code.
Notes:
T_optode is preferred for calculating oxygen concentation from DOSTA Aanderaa optodes
because the permeability of the sensor's foil to oxygen is sensitive to temperature
and this measurement is situated directly at the sensor's foil.
References:
OOI (2012). Data Product Specification for Oxygen Concentration
from "Stable" Instruments. Document Control Number
1341-00520. https://alfresco.oceanobservatories.org/ (See:
Company Home >> OOI >> Controlled >> 1000 System Level
>> 1341-00520_Data_Product_SPEC_DOCONCS_OOI.pdf)
"""
# These coefficients to convert analog T_optode from volts to degC are universal
# for all Aanderaa optodes. Obtained from Shawn Sneddon at Xylem-Aanderaa.
T_optode_degC = -5.0 + 8.0 * T_optode_volt
return T_optode_degC
|
def convert_LengthUnit(len_unit1,len_unit):
"""
convert unit from [len_unit] => [len_unit1]
"""
if len_unit1 =="" or len_unit1 == len_unit:
return len_unit,1
#
dictC = {"ft_km":0.0003048, "kt_km": 1.852 , "mi_km":1.609344, "m_km":0.001, \
"km_ft":3280.8399, "km_kt": 0.53996, "km_mi":0.621371, "km_m":1000 , "km_km":1}
#
s1 = len_unit +"_km"
s2 = "km_"+len_unit1
val = dictC[s1] * dictC[s2]
#
return len_unit1, val
|
def _all_slots(T):
""" Return a list of all slots for a type, or object.
Args:
T: the type, or object to determine the slots for.
Returns:
The list of slot names, including those in base classes.
"""
if not isinstance(T, type):
T = type(T)
slots = []
def inner(T, slots):
if hasattr(T, '__slots__'):
slots += [s for s in T.__slots__]
for c in T.__bases__:
inner(c, slots)
inner(T, slots)
return slots
|
def full_name_natural_split(full_name):
"""
This function splits a full name into a natural first name, last name
and middle initials.
"""
parts = full_name.strip().split(' ')
first_name = ""
if parts:
first_name = parts.pop(0)
if first_name.lower() == "el" and parts:
first_name += " " + parts.pop(0)
last_name = ""
if parts:
last_name = parts.pop()
if (last_name.lower() == 'i' or last_name.lower() == 'ii'
or last_name.lower() == 'iii' and parts):
last_name = parts.pop() + " " + last_name
middle_initials = ""
for middle_name in parts:
if middle_name:
middle_initials += middle_name[0]
return first_name, middle_initials, last_name
|
def match_with_gaps(my_word, other_word):
"""
my_word: string with _ characters, current guess of secret word
other_word: string, regular English word
returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special
symbol _ , and my_word and other_word are of the same length;
False otherwise:
"""
my_word = my_word.replace('_ ', '_')
other_word_letters = []
non_other_word_letters = []
if len(my_word) != len(other_word):
return False
for index, letter in enumerate(my_word):
other_letter = other_word[index]
if letter == '_':
non_other_word_letters.append(other_letter)
if other_letter in other_word_letters:
return False
else:
other_word_letters.append(other_letter)
if letter != other_letter or letter in non_other_word_letters:
return False
return True
|
def get_year_and_day_of_year(year_and_day_of_year):
"""
Extract the year and day of year as separate values from a single integer containing both
:param year_and_day_of_year: An integer with format 'YYYYDDD' where YYYY is the year and DDD is the day
:return: A list of the year and day of year
"""
year = None
day_of_year = None
year_and_day_of_year_str = str(year_and_day_of_year)
if len(year_and_day_of_year_str) >= 5:
# must have at least 5 digits to get the year and day of year
year = int(year_and_day_of_year_str[:4])
day_of_year = int(year_and_day_of_year_str[4:])
return year, day_of_year
|
def reorder(mylist):
"""Reorder list from 0 degree -> 360 degree to -180 degree -> 180 degree.
Parameters
----------
mylist : list
old list
Returns
-------
list
new list
"""
old_mylist = mylist
mylist = old_mylist[180:]
mylist += old_mylist[:180]
return mylist
|
def get_arguments_str(arguments: dict) -> str:
""" takes the arguments dictionary of a proc_init and turns it into a nicely formatted string
"""
return ", ".join(["{}:{}".format(k, arguments[k]) for k in arguments])
|
def skeletonModuleName(mname):
"""Convert a scoped name string into the corresponding skeleton
module name. e.g. M1.M2.I -> M1__POA.M2.I"""
l = mname.split(".")
l[0] = l[0] + "__POA"
return ".".join(l)
|
def build_stats(history, eval_result, time_callback):
"""Normalizes and returns dictionary of stats.
Args:
history: Results of the training step. Supports both categorical_accuracy
and sparse_categorical_accuracy.
eval_output: Output of the eval step. Assumes first value is eval_loss and
second value is accuracy_top_1.
time_callback: Time tracking callback likely used during keras.fit.
Returns:
Dictionary of normalized results.
"""
stats = {}
if history and history.history:
train_history = history.history
stats['loss'] = train_history['loss'][-1]
if eval_result:
stats['eval_loss'] = eval_result[0]
stats['eval_hit_rate'] = eval_result[1]
if time_callback:
timestamp_log = time_callback.timestamp_log
stats['step_timestamp_log'] = timestamp_log
stats['train_finish_time'] = time_callback.train_finish_time
if len(timestamp_log) > 1:
stats['avg_exp_per_second'] = (
time_callback.batch_size * time_callback.log_steps *
(len(time_callback.timestamp_log)-1) /
(timestamp_log[-1].timestamp - timestamp_log[0].timestamp))
return stats
|
def query_api_url(count, start):
"""
Queries the Alexa API for top sites with a global scope
:param count: Number of sites to return in a response
:param start: Index of site to start from according to the Alexa API
:return: json
"""
return f'https://ats.api.alexa.com/api?Action=Topsites&Count={count}&ResponseGroup=Country&Start={start}&Output=json'
|
def hours_minutes(raw_table, base_index):
""" Convert raw value to hours """
return "%02d:%02d" % (raw_table[base_index],
raw_table[base_index + 1])
|
def extract_email(commit_email):
"""
Helper function!
Takes as parameter a string that contains between "<" and ">" an email that needs to be extracted.
The function uses find to search for the beginning of the email (that starts with "<") and adds the lengths of the
"<" so that returned email doesn't contain the "<" symbol and rfind to find the ending character ">". Both find and
rfind return the index where the carachters "<" and ">" are placed so when you do return commit_email with
[start_char_index:ending_char_index] the string shrinks to what's between the characters.
:param commit_email: String that contains an email
:return: String that contains only the email
"""
return commit_email[commit_email.find("<") + len("<"):commit_email.rfind(">")]
|
def version_split(s, delimiters={"=", ">", "<", "~"}):
"""Split the string by the version:
mypacakge<=2.4,==2.4 -> (mypacakge, <=2.4,==2.4)
In [40]: version_split("asdsda>=2.4,==2")
Out[40]: ('asdsda', ['>=2.4', '==2'])
In [41]: version_split("asdsda>=2.4")
Out[41]: ('asdsda', ['>=2.4'])
In [42]: version_split("asdsda")
Out[42]: ('asdsda', [])
"""
for i, c in enumerate(s):
if c in delimiters:
return (s[:i], s[i:].split(","))
return (s, [])
|
def is_scale_type(variable_type):
"""Utility method that checks to see if variable_type is a float"""
try:
float(variable_type)
return True
except ValueError:
return False
|
def _make_post_url(row):
"""
create the facebook post URL from ID
"""
post_url = "http://facebook.com/{0}".format(row['facebook_id'])
return post_url
|
def calc_price_exquisite_extract_of_nourishment(fine_price, masterwork_price, rare_price, exotic_price):
""" https://wiki.guildwars2.com/wiki/Exquisite_Extract_of_Nourishment """
return 5 * fine_price + 5 * masterwork_price + 5 * rare_price + 10 * exotic_price
|
def dotPlot(seqA: str, seqB: str) -> list:
"""Compare two DNA sequences using DotPlot method.
**Keyword arguments:**
seqA -- first sequence
seqB -- second sequence
"""
la = len(seqA)
lb = len(seqB)
M = [[' ' for n in range(la)] for m in range(lb)]
for i in range(lb):
for j in range(la):
if seqB[i] == seqA[j]:
M[i][j] = 'x'
return M
|
def _all_elements_equal(list_to_check:list) -> bool:
"""Private function to check whether all elements of
list_to_check are equal."""
# set() is not used here as some times the list
# elements are not hashable, e.g., strings.
if len(list_to_check) == 1:
return True
return all([
(list_to_check[i] == list_to_check[i+1])
for i in range(len(list_to_check)-1)
])
|
def process_path(module_path):
"""
Method to obtain module and class_name from a module path
Args:
module_path(String): path in the format module.class_name
Returns:
tuple containing class_name and module
"""
if module_path == 'numpy.ndarray':
return 'StorageNumpy', 'hecuba.hnumpy'
if module_path == 'StorageDict':
return 'StorageDict', 'hecuba.hdict'
last = 0
for key, i in enumerate(module_path):
if i == '.' and key > last:
last = key
module = module_path[:last]
class_name = module_path[last + 1:]
return class_name, module
|
def checksum(data):
"""
Calculate checksum on value string.
@retval checksum - base 10 integer representing last two hexadecimal digits of the checksum
"""
total = sum([ord(x) for x in data])
return total & 0xff
|
def _adjust_component(value: int) -> int:
""" Returns the midpoint value of the quadrant a component lies.
By Maitreyi Patel 101120534
>>>_adjust_component(43)
31
>>>_adjust_component(115)
95
>>>_adjust_component(154)
159
>>>_adjust_component(210)
223
"""
midpt = 0
if 255 >= value >=192:
midpt = 223
if 191 >= value >=128:
midpt = 159
if 127 >= value >=64:
midpt = 95
if 63 >= value >=0:
midpt = 31
return midpt
|
def simple(s):
"""Break str `s` into a list of str.
1. `s` has all of its peripheral whitespace removed.
1. `s` is downcased with `lower`.
2. `s` is split on whitespace.
3. For each token, any peripheral punctuation on it is stripped
off. Punctuation is here defined by `string.punctuation`.
Parameters
----------
s : str
The string to tokenize.
Returns
-------
list of str
"""
import string
punct = string.punctuation
final_toks = []
toks = s.lower().strip().split()
for w in toks:
final_toks.append(w.strip(punct))
return final_toks
|
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(n)
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
maxSum = 0
currentSum = 0
for i in range(len(nums)):
currentSum = max((nums[i] + currentSum), nums[i])
maxSum = max(currentSum, maxSum)
if maxSum <=0:
return max(nums)
return maxSum
|
def interfaces(data):
"""return a list of interfaces name"""
return [interface['nick'] for interface in data['interfaces']]
|
def generate_col_names(d):
"""Utility function to generate column names for the synthetic dataset """
assert (d >= 6)
pC = 2 # number of confounders
pP = 2 # number of outcome predictors
pI = 2 # number of exposure predictors
pS = d - (pC + pI + pP) # number of spurious covariates
col_names = ['A', 'Y'] + [f'Xc{i}' for i in range(1, pC + 1)] + [f'Xp{i}' for i in range(1, pP + 1)] + \
[f'Xi{i}' for i in range(1, pI + 1)] + [f'Xs{i}' for i in range(1, pS + 1)]
return col_names
|
def extract_features(row):
""" extract_features function
Taking one row, extracts all features deemed useful for logistic regression
and returns them as a list.
Args
----
row : dict
A single data point
Returns
-------
list
"""
pclass = float(row['Pclass']) if row['Pclass'] != '' else 0
sex = 1 if row['Sex'] == 'male' else 0
age = float(row['Age']) if row['Age'] != '' else 0
sibsp = float(row['SibSp']) if row['SibSp'] != '' else 0
parch = float(row['Parch']) if row['Parch'] != '' else 0
return [pclass, sex, age, sibsp, parch]
|
def _get_project_sync_url(sg_field_value, logger):
"""
Return sync url from Shotgun File/Link field.
:param sg_field_value: Shotgun File/Link field value as a dict or ``None``.
:param logger: Logger instance.
:returns: URL for sync as a str or ``None``.
"""
# We expect a File/Link field with a web link, something like:
# {
# 'name': 'SG Jira Bridge',
# 'url': 'http://localhost:9090',
# 'content_type': None,
# 'type': 'Attachment',
# 'id': 123456,
# 'link_type': 'web'
#
# }
# Default value if we can't retrieve a valid value
sync_url = None
if isinstance(sg_field_value, dict):
if sg_field_value.get("link_type") == "web":
sync_url = sg_field_value.get("url")
if sync_url and sync_url.endswith("/"):
sync_url = sync_url[:-1]
# There is a value in the sg_field_value but it's not what we expect.
if sync_url is None and sg_field_value:
logger.warning(
"Sync URL could not be extracted from %s. Expected a dictionary "
"representing a web link like {'link_type': 'web', 'url': "
"'https://<servername>/sg2jira/<settingsname>'}" % sg_field_value
)
return sync_url
|
def to_lowercase(words):
"""Convert all characters to lowercase from list of tokenized words"""
new_words = []
for word in words:
new_word = word.lower()
new_words.append(new_word)
return new_words
|
def xmltag_split(tag):
"""Return XML element bare tag name (without prefix)"""
try:
return tag.split('}')[1]
except:
return tag
|
def utf(val):
"""Little helper function which turns strings to utf-8 encoded bytes"""
if isinstance(val, str):
return val.encode('utf-8')
else:
return val
|
def is_instruction(func):
"""
Check the given function to see if it's an instruction.
A instruction is a function that is decorated with :func:`~ydf.instructions.instruction`.
:param func: Object to check
:return: `True` if object is an instruction function, `False` otherwise
"""
return callable(func) and hasattr(func, 'instruction_name')
|
def mirror_action(act):
"""
Mirror an action, swapping left/right.
"""
direction = (act % 18) // 6
act -= direction * 6
if direction == 1:
direction = 2
elif direction == 2:
direction = 1
act += direction * 6
return act
|
def _map_fn_to_mapcat_fn(fn, *args, **kwargs):
"""
takes in a function for mapping, and arguments to apply, and returns
a result for a mapcat
NOTE:
- this is a separate function for serializability
"""
res = fn(*args, **kwargs)
return [res]
|
def minDistance(s1, s2):
"""
:type s1: str
:type s2: str
:rtype: int
"""
len1 = len(s1)
len2 = len(s2)
dp = [[0 for _ in range(len2 + 1)] for _ in range(len1 + 1)]
for i in range(len1 + 1):
for j in range(len2 + 1):
if i > 0 and j == 0:
dp[i][j] = dp[i - 1][j] + 1
elif j > 0 and i == 0:
dp[i][j] = dp[i][j - 1] + 1
elif j > 0 and i > 0:
res1 = dp[i - 1][j] + 1
res2 = dp[i][j - 1] + 1
res3 = not s1[i - 1] == s2[j - 1] and dp[i - 1][j - 1] + 1 or dp[i - 1][j - 1]
dp[i][j] = min(res1, res2, res3)
return dp[len1][len2]
|
def _split_short_opt_list(short_opt_list):
"""Split short options list used by getopt.
Returns a set of the options.
"""
res = set()
tmp = short_opt_list[:]
# split into logical elements: one-letter that could be followed by colon
while tmp:
if len(tmp) > 1 and tmp[1] is ':':
res.add(tmp[0:2])
tmp = tmp[2:]
else:
res.add(tmp[0])
tmp = tmp[1:]
return res
|
def format_list(data, separator=', '):
"""Return a formatted strings
:param data: a list of strings
:param separator: the separator to use between strings (default: ', ')
:rtype: a string formatted based on separator
"""
if data is None:
return None
return separator.join(sorted(data))
|
def CharUnique(S: str) -> bool:
"""
>>> CharUnique('deacidified')
False
>>> CharUnique('keraunoscopia')
False
>>> CharUnique('layout')
True
>>> CharUnique('brand')
True
>>> CharUnique('texture')
False
>>> CharUnique('ovalness')
False
>>> CharUnique('unglove')
True
"""
#for i scan ahead for same char
for i in range(len(S)):
#c is the character that character i is compared against
for c in range(i + 1, len(S)):
if S[i] == S[c]:
return(False)
return(True)
|
def _seconds_to_time(seconds):
"""
Convert seconds into a time-string with the format HH:MM:SS. Seconds should
be an integer or float (rounded to nearest second and then cast to int).
"""
# Represent as integer
try:
if not type(seconds) is int:
seconds = int(round(seconds,0))
except TypeError:
err = "seconds must be able to be converted to an integer\n"
raise ValueError(err)
# Make sure the it is not too large to represent
max_value = 99*3600 + 59*60 + 59
if seconds > max_value:
err = "times longer than {} (99:59:59) cannot be represented in HH:MM:SS.\n".format(max_value)
raise ValueError(err)
# Convert seconds to hours, minutes, seconds
hours = seconds // 3600
leftover = seconds - hours*3600
minutes = leftover // 60
seconds = leftover - minutes*60
# Make sure the resulting time is sane.
try:
assert seconds >= 0 and seconds < 60
assert minutes >= 0 and minutes < 60
assert hours >= 0 and hours < 100
except AssertionError:
err = "time could not be converted to HH:MM:SS format.\n"
err += "gave: {} hours, {} minutes, {} seconds\n".format(hours,minutes,seconds)
raise RuntimeError(err)
return "{:02}:{:02}:{:02}".format(hours,minutes,seconds)
|
def _partition(array, low, high, pindex):
"""Sort values lower < pivot index < higher."""
# Place pivot in front
array[low], array[pindex] = array[pindex], array[low]
i = low + 1
for j in range(low + 1, high):
if array[j] < array[low]:
array[i], array[j] = array[j], array[i]
i += 1
# Place pivot in right place
pindex = i - 1
array[low], array[pindex] = array[pindex], array[low]
return pindex
|
def centroid(X):
"""
Calculate the centroid from a vectorset X
"""
C = sum(X)/len(X)
return C
|
def move(text, i, j):
"""Move operation.
move position X to position Y means that the letter which is at
index X should be removed from the string, then inserted such that it
ends up at index Y.
"""
chars = [t for t in text]
letter = chars[i]
chars.pop(i)
chars.insert(j, letter)
return "".join(chars)
|
def is_vlan(v):
"""
Check value is valid VLAN ID
>>> is_vlan(1)
True
>>> is_vlan(-1)
False
>>> is_vlan(4095)
True
>>> is_vlan(4096)
False
>>> is_vlan("g")
False
"""
try:
v = int(v)
return 1 <= v <= 4095
except ValueError:
return False
|
def listify(x):
"""Puts non-list objects into a list.
Parameters
----------
x: Object to ensure is list
Returns
----------
:obj:`list`
If ``x`` is already a list, this is returned. Otherwise, a list\
containing ``x`` is returned.
"""
if isinstance(x, list):
return x
else:
return [x]
|
def arg_keys(arg_name, keys):
"""Appends arg_name to the front of all values in keys.
Args:
arg_name: (string) String containing argument name.
keys: (list of strings) Possible inputs of argument.
Returns:
List of strings with arg_name append to front of keys.
"""
return ["{0}_{1}".format(arg_name, key) for key in keys]
|
def inherit_docstrings(cls):
"""Inherit docstrings from parent class"""
from inspect import getmembers, isfunction
for name, func in getmembers(cls, isfunction):
if func.__doc__:
continue
for parent in cls.__mro__[1:]:
if hasattr(parent, name):
func.__doc__ = getattr(parent, name).__doc__
return cls
|
def get_ids_from_list_of_dicts(lst):
"""Get all ids out of a list of objects and return a list of string ids."""
id_list = []
for item_dict in lst:
if "id" in item_dict:
id_list.append(item_dict["id"])
return id_list
|
def points_allowed_score(points: float) -> int:
"""The points allowed score logic generator based on standard D/ST fantasy
football scoring.
Args:
points (float): number of points allowed
Returns:
score (int): the score got for that number of points allowed
"""
if points == 0:
score = 10
elif points < 7:
score = 7
elif points < 14:
score = 4
elif points < 18:
score = 1
elif points < 28:
score = 0
elif points < 35:
score = -3
else:
score = -4
return score
|
def rotate(data, n):
"""
Create a method named "rotate" that returns a given array with the elements
inside the array rotated n spaces.
with array [1, 2, 3, 4, 5]
n = 7 => [4, 5, 1, 2, 3]
n = 11 => [5, 1, 2, 3, 4]
n = -3 => [4, 5, 1, 2, 3]
"""
if data:
k = len(data)
n = n % k
return data[k-n:] + data[:k-n]
return data
|
def is_autosomal(chrom):
"""Keep chromosomes that are a digit 1-22, or chr prefixed digit chr1-chr22
"""
try:
int(chrom)
return True
except ValueError:
try:
int(str(chrom.lower().replace("chr", "").replace("_", "").replace("-", "")))
return True
except ValueError:
return False
|
def clean_newline(line):
"""Delete newline characters at start and end of line
Params:
line (Unicode)
Returns:
line (Unicode)
"""
return_line = line.strip('\r\n')
if return_line != line:
return True, return_line
else:
return False, line
|
def args_to_int(args: list) -> tuple:
""" Convert augs to int or return empty """
try:
return tuple([int(i) for i in args])
except ValueError:
return ()
|
def swap(record):
""" Swap (token, (ID, URL)) to ((ID, URL), token)
Args:
record: a pair, (token, (ID, URL))
Returns:
pair: ((ID, URL), token)
"""
token = record[0]
keys = record[1]
return (keys,token)
|
def isplaceholder(sym):
"""
Checks whether a symbol in a structure is a placeholder for a representation
"""
if isinstance(sym, str):
return sym[0] == "#"
else:
return False
|
def big_number(int_in):
"""Converts a potentially big number into a lisible string.
Example:
- big_number(10000000) returns '10 000 000'.
"""
s = str(int_in)
position = len(s)
counter = 0
out = ''
while position != 0:
counter += 1
position -= 1
out = s[position] + out
if counter % 3 == 0 and position != 0:
out = " " + out
return (out)
|
def get_values_language():
"""Provide expected values - database table language."""
return [
None,
True,
"xxx_code_iso_639_3",
"xxx_code_pandoc",
"xxx_code_spacy",
"xxx_code_tesseract",
"xxx_directory_name_inbox",
"xxx_iso_language_name",
]
|
def init_feature(
chromosome_size: int,
organism: str,
mol_type: str = 'genomic DNA') -> str:
"""
Initialize a feature section of genbank file.
The feature section always start with the mandatory 'source' feature
"""
text = f'''\
FEATURES Location/Qualifiers
source 1..{chromosome_size}
/mol_type="{mol_type}"
/organism="{organism}"\n'''
return text
|
def calc_met_equation_cdd(case, t_min, t_max, t_base):
"""Calculate cdd according to Meteorological
Office equations as outlined in Day (2006): Degree-days: theory and application
Arguments
---------
case : int
Case number
t_min : float
Minimum daily temperature
t_max : float
Maximum dail temperature
t_base : float
Base temperature
Return
-------
case_nr : int
Case number
"""
if case == 1:
cdd = 0.5 * (t_max + t_min) - t_base
elif case == 2:
cdd = 0.5 * (t_max - t_base) - 0.25 * (t_base - t_min)
elif case == 3:
cdd = 0.25 * (t_max - t_base)
else:
cdd = 0
return cdd
|
def _get_column_val(column):
"""
Parameters
----------
column : float or tuple
gives the column or (column, unc) or (column, punc, munc)
Returns
-------
column: float
column value
"""
if isinstance(column, tuple):
return float(column[0])
else:
return float(column)
|
def get_md_link(text: str, link: str) -> str:
"""Get a link in Markdown format."""
return f"[{text}]({link})"
|
def make_tax_group_dict(taxonomic_groups):
"""Convert string to dictionary. Then check if all values are, in fact,
integers"""
tg = eval(taxonomic_groups)
if type(tg) == dict:
pass
else:
raise TypeError("Taxonomic groups can not be coerced into a"
"dictionary! Check `--taxonomic_groups` input!")
all_ints = all(type(value) == int for value in tg.values())
if all_ints == True:
return tg
|
def tarjans(complexes, products):
""" Tarjans algorithm to find strongly connected components.
Dirctly from the peppercornenumerator project.
"""
stack, SCCs = [], []
def strongconnect(at, index):
stack.append(at)
at.index = index
at.llink = index
index += 1
for to in products[at]:
if to.index is None:
# Product hasn't been traversed; recurse
strongconnect(to, index)
if to in stack:
# Product is in the current neighborhood
at.llink = min(at.llink, to.llink)
if at.index == at.llink:
# Back to the start, get the SCC.
scc = []
while True:
nc = stack.pop()
nc.llink == at.index
scc.append(nc)
if nc == at:
break
SCCs.append(scc)
for cplx in complexes:
cplx.index = None
for i, cplx in enumerate(complexes):
if cplx.index is None:
strongconnect(cplx, i)
return SCCs
|
def splitter(string, left=False, right=False):
"""Split 'domain\cn' or 'domain\computer' values and return left and/or right.
Can be used with tuple unpacking if left/right not set, but should be wrapped in
a try-except to catch ValueError in the case split returns 1 string.
"""
try:
split = string.split('\\')
if right:
return split[-1]
elif left:
return split[0]
else:
return split
except AttributeError:
return None if right or left else (None, None)
|
def filter_entity(org_name, app_name, collection_name, entity_data, source_client, target_client, attempts=0):
"""
This is an example handler function which can filter entities. Multiple handler functions can be used to
process a entity. The response is an entity which will get passed to the next handler in the chain
:param org_name: The org name from whence this entity came
:param app_name: The app name from whence this entity came
:param collection_name: The collection name from whence this entity came
:param entity: The entity retrieved from the source instance
:param source_client: The UsergridClient for the source Usergrid instance
:param target_client: The UsergridClient for the target Usergrid instance
:param attempts: the number of previous attempts this function was run (manual, not part of the framework)
:return: an entity. If response is None then the chain will stop.
"""
# return None if you want to stop the chain (filter the entity out)
if 'blah' in entity_data:
return None
# return the entity to keep going
return entity_data
|
def contingency_table(ys, yhats, positive=True):
"""Computes a contingency table for given predictions.
:param ys: true labels
:type ys: iterable
:param yhats: predicted labels
:type yhats: iterable
:param positive: the positive label
:return: TP, FP, TN, FN
>>> ys = [True, True, True, True, True, False]
>>> yhats = [True, True, False, False, False, True]
>>> tab = contingency_table(ys, yhats, 1)
>>> print(tab)
(2, 1, 0, 3)
"""
TP = 0
TN = 0
FP = 0
FN = 0
for y, yhat in zip(ys, yhats):
if y == positive:
if y == yhat:
TP += 1
else:
FN += 1
else:
if y == yhat:
TN += 1
else:
FP += 1
return TP, FP, TN, FN
|
def WORK(config, task):
"""
The work to be done for each task
Parameters
----------
config : dict
task : dict
Returns
-------
status : Boolean
"""
status = False
return(status)
|
def endswith(string, target):
"""
Description
----------
Check to see if the target string is the end of the string.
Parameters
----------
string : str - string to check end of\n
target : str - string to search for
Returns
----------
bool - True if target is the end of string, False otherwise
Examples
----------
>>> endswith('Sample string', 'ing')
-> True
>>> endswith('abcabcabc', 'abcd')
-> False
"""
if not isinstance(string, str):
raise TypeError("param 'string' must be a string")
if not isinstance(target, str):
raise TypeError("param 'target' must be a string")
return string[len(target) * -1 :] == target
|
def prep_ingr(ingredients):
"""preprocess formatting of the list of ingredients
will remove string 'and' and '&' if present
Args:
ingredients (list of strings): list of ingredients
Returns:
list: list of formatted ingredients
"""
toreturn = []
for ingr in ingredients:
# remove 'and' or '&' if exsits
if "and" in ingr or "&" in ingr:
ingr = ingr.replace("and", "").replace("&","") #remove
ingr = ingr.split(" ")
# remove empty strings
while "" in ingr:
ingr.remove("")
for i in ingr:
toreturn.append(i)
else:
toreturn.append("_".join(ingr.split(" ")))
return toreturn
|
def validate_input(crop_size, crop_center): # validates the input of the ex4 function
"""
:param image_array: A numpy array containing the image data in an arbitrary datatype and shape (X, Y).
:param crop_size:A tuple containing 2 odd int values. These two values specify the size
of the rectangle that should be cropped-out in pixels for the two spatial dimensions X and Y.
:param crop_center:A tuple containing 2 int values. These two values are the position of the
center of the to-be cropped-out rectangle in pixels for the two spatial dimensions X and Y.
"""
valid = True
distance = 20
x, y = crop_center
dx, dy = crop_size
# integer division
dx, dy = dx // 2, dy // 2
dimx, dimy = (100, 100)
if any(x < distance for x in [x - dx, dimx - (x + dx + 1), y - dy, dimy - (y + dy + 1)]):
valid = False
return valid
|
def doublecolon_tail(string):
"""return the last (rightmost) part of a namespace or namespace-qualified proc"""
last_colons = string.rfind("::")
if last_colons >= 0:
return string[last_colons + 2 :]
return string
|
def same_keys(a, b):
"""Determine if the dicts a and b have the same keys in them"""
for ak in a.keys():
if ak not in b:
return False
for bk in b.keys():
if bk not in a:
return False
return True
|
def gfrcalc_alt(guide, distneg_med, distpos_med):
"""
Determines guide field ratio, the ratio of the PIL-parallel component of
magnetic field to the PIL-perpendicular component, a proxy for the magnetic
shear.
Parameters
----------
guide_left : arr
Guide field strength, right-hand side.
guide_right : arr
Guide field strength, left-hand side.
distneg_med : arr
Distance from negative ribbon to PIL for each time step; from code for
separation.
distpos_med : arr
Distance from positive ribbon to PIL for each time step; from code for
separation.
Returns
-------
left_gfr : arr
Guide field ratio, left edge of ribbons.
right_gfr : arr
Guide field ratio, right edge of ribbons.
"""
gfr = guide/(distneg_med+distpos_med)
return gfr
|
def is_executable(permission_int):
"""Takes a number containing a Unix file permission mode (as reported by RPM utility)
and returns True if the file has executable bit set.
NOTE: for some reason the modes returned by RPM utility are beyond 777 octal number...
so we throw away the additional bits
"""
executable_flag = 0x49 # 0x49 is equal to 0111 octal number, which is the flag for executable bits for USER,GROUP,OTHER
return (permission_int & executable_flag) != 0
|
def is_odd(x: float):
"""Function checking if a number is odd.
Args:
x (float): Number to check.
Returns:
bool: True if the number is odd, False otherwise.
"""
return x % 2 == 1
|
def mod_inv(a, n):
"""Computes the multiplicative inverse of a modulo n using the extended Euclidean algorithm."""
t, r = 0, n
new_t, new_r = 1, a
while new_r != 0:
quotient = r // new_r
t, new_t = new_t, t - quotient * new_t
r, new_r = new_r, r - quotient * new_r
if r > 1:
raise Exception("a is not invertible")
if t < 0:
t = t + n
return t
|
def build_settings_dictionary(id_string, start_time, redis_connection_string, shared_memory_max_size,
ordered_ownership_stop_threshold, ordered_ownership_start_threshold):
"""
Builds the settings dictionary which peers use to pass settings information back and forth.
"""
# Build.
settings_dict = dict()
settings_dict["id"] = id_string
settings_dict["start_time"] = start_time
settings_dict["sm_connection"] = redis_connection_string
settings_dict["sm_max"] = shared_memory_max_size
settings_dict["oq_stop"] = ordered_ownership_stop_threshold
settings_dict["oq_start"] = ordered_ownership_start_threshold
# Return.
return settings_dict
|
def is_anagram(word_1, word_2):
"""
Test if the parameters are anagram of themselves.
:param word_1: 1st word
:param word_2: 2nd word
:return: True if the parameters are anagram, False if not
"""
word_1.lower()
word_2.lower()
return sorted(word_1) == sorted(word_2)
|
def func_g(a, n, p, x_i):
"""
a_(i+1) = func_g(a_i, x_i)
"""
if x_i % 3 == 2:
return a
elif x_i % 3 == 0:
return 2*a % n
elif x_i % 3 == 1:
return (a + 1) % n
else:
print("[-] Something's wrong!")
return -1
|
def v3_state_away_json():
"""Return a /v1/ss3/subscriptions/<SUBSCRIPTION_ID>/state/away."""
return {
"success": True,
"reason": None,
"state": "AWAY",
"lastUpdated": 1534725096,
"exitDelay": 120
}
|
def sanitize_dest(path):
"""Ensure the destination does have a trailing /"""
return path if path.endswith('/') else path + '/'
|
def list_difference(l1, l2, key1=None, key2=None):
"""Like set difference method, but list can have duplicates. If l1 has two
identical items, and l2 has one of that item, res will have 1 of that item
left. Sets would remove it"""
if not key1:
key1 = lambda x: x
if not key2:
key2 = lambda x: x
res = list(l1)
keys = list(map(key1, res))
for x in l2:
try:
i = keys.index(key2(x))
del(keys[i])
del(res[i])
except ValueError:
continue
return res
|
def _cleanup_eval(body):
"""Removes code blocks from code."""
if body.startswith('```') and body.endswith('```'):
return '\n'.join(body.split('\n')[1:-1])
return body.strip('` \n')
|
def parseDBXrefs(xrefs):
"""Parse a DB xref string like HGNC:5|MIM:138670 to a dictionary"""
#Split by |, split results by :. Create a dict (python 2.6 compatible way).
if xrefs == "-": return {}
return dict([(xrefParts[0], xrefParts[2])
for xrefParts in (xref.partition(":")
for xref in xrefs.split("|"))])
|
def int_to_little_endian(n: int, length: int) -> bytes:
"""
Represents integer in little endian byteorder.
:param n: integer
:param length: byte length
:return: little endian
"""
return n.to_bytes(length, 'little')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.