content stringlengths 42 6.51k |
|---|
def fixup_name(name):
"""Fixes up the name."""
name = name.replace(' ', '-')
return name.lower() |
def str_key(dic):
"""
Apply str to the keys of a dict.
This must be a applied to a dict in order to transform it into json.
:param dic: a dict
:return: the dict with keys as strings.
"""
return {str(k): v for k, v in dic.items()} |
def coin_possibility(a, b, n, S):
"""
a is the number of n coins
b is the number of 1 coins
S is the total sum required to pay
"""
total_sum_available = a*n + b
if total_sum_available < S:
return 'NO'
if b < (S % n):
return 'NO'
return 'YES' |
def ComposeAdUserName(domainName, userName):
"""
Examples:
composedUserName = "{0}@{1}".format(userName, domainName), when using userName@domainName
"""
composedUserName = "{0}.{1}".format(domainName, userName)
return composedUserName |
def rectangle_w(x, N, ft_compensated=False):
"""
Rectangle FT window function.
"""
return x*0+1 |
def not_found_xml(item):
"""
Return XML representation of CLB item not found.
"""
return (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<itemNotFound xmlns="http://docs.openstack.org/loadbalancers/api/v1.0" code="404">'
'<message>{0} not found</message></itemNotFoun... |
def move_left(loc):
"""increments the location for leftward movement.
"""
return (loc[0] - 1, loc[1]) |
def _collect_column_constraints(column, unique):
"""
Collect constraints for a column.
Use column information as well as unique constraint information.
Note: for a unique constraint on a single column we set
column / constraints / unique = True
(and store all multicolumn uniques in ... |
def dump_datetime(value):
"""Deserialize datetime object into string form for JSON processing."""
if value is None:
return None
return [value.strftime("%Y-%m-%d")] |
def get_dimensions6(o_dim, ri_dim):
""" Get the orientation, real/imag, height and width dimensions
for the full tensor (6 dimensions)."""
# Calculate which dimension to put the real and imaginary parts and the
# orientations. Also work out where the rows and columns in the original
# image were
... |
def camel_to_snake(s):
""" used for converting CSS Attributes from Python style to CSS style """
buff, l = '', []
for ltr in s:
if ltr.isupper():
if buff:
l.append(buff)
buff = ''
buff += ltr
l.append(buff)
return '-'.join(l).lower() |
def _bowtie2_args_from_config(config):
"""Configurable high level options for bowtie2.
"""
qual_format = config["algorithm"].get("quality_format", "")
if qual_format.lower() == "illumina":
qual_flags = ["--phred64-quals"]
else:
qual_flags = []
num_cores = config["algorithm"].get(... |
def parse_limit(parses):
"""
parse the limit number
:param parses:
:return:
"""
if "limit" in parses.keys():
if type(parses["limit"]) is not int:
raise Exception("SQL limit incorrect")
else:
return " LIMIT " + str(parses["limit"])
return "" |
def _distribute(d, number):
"""
Generates amounts based on distribution and total number and minimizes rounding error
Parameters
----------
d : dict
The distribution used for generating amounts.
Keys : str
Values : float
Number between 0 and 1. The sum over all v... |
def count(gen):
"""Simple function to count the number of elements returned by a generator."""
return sum(1 for _ in gen) |
def update_gender_count(gender, movie_id, movie_map):
"""Given gender, movieID, and a dictionary, returns an updated dictionary
reflecting an increase in the gender count for the input gender.
Parameters:
gender: a string that is either 'female_count' or 'male_count'.
movie_id: a string rep... |
def combine_values(d, v):
"""Helper function used in call to .aggregateByKey
Args:
d (dict): python dictionary to be aggregated into
v (tuple): tuple of key, value to be inserted into d
Returns:
dict: updated python dictionary from v
"""
key, value = v
d[key] = value
retu... |
def json_maker(topic='', questions_list=[]):
"""
Gets list of questions, topic and generates final version of JSON.
:type questions_list: list
:param topic: topic which question covers.(str)
:param questions_list: list containing all the questions.(list)
:return: final version of the question.(... |
def _append_resource(subnets, project, name_id):
"""Append subnets to resources."""
resources = []
out = {}
for subnet in subnets:
policy_name = 'iam-subnet-policy-{}'.format(subnet[name_id])
resources.append({
'name': policy_name,
# https://cloud.google.com/compu... |
def get_top_counts(data, field, limits):
"""show the values in descending order"""
arr = data[field]
arr.sort(key=lambda x: -x[1])
return arr[:limits] |
def terminatesLabel(treeString, offset):
"""Return True if treeString+offset is empty or starts w/char that would terminate a label"""
return (offset == len(treeString) or treeString[offset] == ',' or treeString[offset] == ')' or
treeString[offset] == ';' or treeString[offset] == ':') |
def calc_oxygen_generator_rating(lines):
"""
Calculate oxygen generator rating
:param lines: List of lines from file
:returns: Oxygen generator rating
"""
# oxygen generator rating
filtered_lines = lines.copy()
index = 0
while len(filtered_lines) > 1 and index < len(filtered_lines[0... |
def _conceal_amqp_password(url):
"""
replace the broker password in the url before printing it
"""
before_password = url[:url.find(':', 5)]
after_password = url[url.find('@'):]
final = before_password + ':***' + after_password
return final |
def check_mirc_exploit(proto) -> bool:
"""Verifies that the nickname portions of the protocol
does not contain any binary data.
Vars:
:proto: The text before the second : hopefully a nickname.
:returns: True if there is binary data and False if it is clean.
"""
for let i... |
def itemize(x):
"""
Extract item from a list/tuple with only one item.
>>> itemize([3])
3
>>> itemize([3, 2, 1])
[3, 2, 1]
>>> itemize([])
[]
:param list|tuple x: An indexable collection
:return: Return item in collection if there is only one, else
returns the co... |
def valid_imo(imo=0):
"""Check valid IMO using checksum.
Arguments
---------
imo : integer
An IMO ship identifier
Returns
-------
True if the IMO number is valid
Notes
-----
Taken from Eoin O'Keeffe's `checksum_valid` function in pyAIS
"""
try:
str_imo ... |
def cpu_units(value):
"""Converts CPU string into numeric in BMIPS"""
norm = str(value).upper().strip()
if norm.endswith('%'):
return int(norm[:-1])
else:
return int(norm) |
def rem_num_of_lines(in_filename, start_string):
"""
Returns the number of lines that is remaining in the given file starting
from the first appearance of the given start string.
---------
PARAMETERS:
<in_filename> Input filename
<start_string> Start string to be search in <in_file>.
-... |
def is_property(obj, attribute):
""" Check if object attribute is a property
:param obj:
:param attribute:
:return:
"""
try:
return isinstance(type(obj).__getattribute__(obj, attribute), property)
except AttributeError:
return False |
def generateCSV(package_exports):
"""
Create a CSV file based on the exported data
It expects to receive a list of objects with the following keys:
- package
- name
- type
"""
csv_content = ""
for package_export in package_exports:
csv_content += "%s,%s,%s\n"%(
... |
def is_valid_host(host):
""" Check if host is valid.
Performs two simple checks:
- Has host and port separated by ':'.
- Port is a positive digit.
:param host: Host in <address>:<port> format.
:returns: Valid or not.
"""
parts = host.split(':')
return len(parts) == 2 or par... |
def is_valid(
move, # type: tuple[int, int]
player):
"""
Check a move for common mistakes, and throw a (hopefully) helpful error message if incorrect.
:param move:
:param player:
"""
if move == "Late":
return False
if not type(move) is tuple:
print('Bot {} ... |
def compute_score_of(winner: list) -> int:
"""Compute score of winning deck."""
return sum((idx + 1) * card for idx, card in enumerate(winner[::-1])) |
def pick(dct, *keys):
"""Pick a subset of a dict."""
return {k: v for k, v in dct.items() if k in keys} |
def update_submit_attrs(entry_information, attr, submit_attr):
"""Update submit attribute according to produced attribute if submit attribute is not defined
Args:
entry_information (dict): a dictionary of entry information from white list file
attr (str): attribute name
submit_attr (str... |
def mohr_c(stress_x, stress_y, shear):
"""
inputs
stress_x: int or float
stress_y: int or float
shead: int or float
mohr_c() outputs two values for the circle, center, and radius
output:
C, R
C is the x-value of the circle center
R is the radius of the c... |
def calculate_win_loss_ratio(total_wins, total_losses):
"""
Calculate the average for a list of items.
"""
if total_wins == 0:
return 0
activity_average = total_wins / total_losses
return round(activity_average, 2) |
def split_list(input_list, n):
"""
Takes a list and splits it into smaller lists of n elements each.
:param input_list:
:param n:
:return:
"""
n = max(1, n)
return [input_list[i:i + n] for i in range(0, len(input_list), n)] |
def fitness_score_distance(id1, id2, to_consider, distance):
"""A value to choose between two resources considering the distance"""
return max(distance(id1,to_consider), distance(to_consider, id2))/distance(id1,id2) |
def is_untracked(untracked_files):
"""Function: is_untracked
Description: Method stub holder for git.Repo.git.is_untracked().
Arguments:
"""
status = True
if untracked_files:
return status
else:
return True |
def tabulate_summary(certificates, kubeconfigs, etcd_certs, router_certs, registry_certs):
"""Calculate the summary text for when the module finishes
running. This includes counts of each classification and what have
you.
Params:
- `certificates` (list of dicts) - Processed `expire_check_result`
dicts with fill... |
def Flatten(li):
""" Returns a generator that is a flattened out version of the original
list.
Example:
Flatten([1, 2, [3, 4]]) -> [1, 2, 3, 4]
Flatten([[1, [2]], [3, 4]]) -> [1, 2, 3, 4]
"""
flat = []
for x in li:
if type(x) == list:
flat.extend(Flatten(x))
else:... |
def bin_search_iter(arr: list, key: int) -> int:
"""Iterative Binary Search"""
left = 0
right = len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == key:
return mid
elif arr[mid] < key:
left = mid + 1
else:
... |
def clean_string(strng):
"""Function used for replaceing characters that are different
from 0 and 1 in a given string"""
for char in strng:
if char not in "01":
strng = strng.replace(char, "")
return strng |
def contains(script, keywords):
"""Performs DFS on the script to determine if keyword exists."""
# The keyword must be the first item in a list.
if type(script) != list or not script:
return False
if script[0] in keywords:
return True
# Iterate over all children.
return any(co... |
def dup_strip(f):
"""
Remove leading zeros from ``f`` in ``K[x]``.
Examples
========
>>> from sympy.polys.densebasic import dup_strip
>>> dup_strip([0, 0, 1, 2, 3, 0])
[1, 2, 3, 0]
"""
if not f or f[0]:
return f
i = 0
for cf in f:
if cf:
brea... |
def temp_ftoc(temp_f):
"""Convert fahrenheit degrees to celsius.
Prometheus expects SI units, but some sensors return F.
"""
return (temp_f - 32.0) * (5.0 / 9.0) |
def simplest_gini(x):
"""Return computed Gini coefficient of inequality. This function was found at http://econpy.googlecode.com/svn/trunk/pytrix/utilities.py """
#note: follows basic formula
#see: `calc_gini2`
#contact: aisaac AT american.edu
x = sorted(x) # increasi... |
def human_bytes(n):
"""
convert bytes to human readable format
'borrowed' from https://github.com/giampaolo/psutil/blob/master/scripts/ifconfig.py
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10... |
def are_all_kws_present(kws, word_freq):
""" Check if all the kws are found in word_freq """
not_found = []
for kw in kws:
if kw not in word_freq:
not_found.append(kw)
return not_found |
def set_bit(val: int, bitNo: int) -> int:
"""
Set a specified bit to '1'
"""
return val | (1 << bitNo) |
def coerce(string):
"""When appropriate, coerce `string` into some type.
Supports floats, ints, booleans and strings."""
if string == "True": return True
if string == "False": return False
try: return int(string)
except Exception:
try: return float(string)
except Exception: return string |
def split_commands(commands):
"""Split command arguments into an arg_list obect to be passed to uncompress
function"""
out = []
for c in commands:
splitted = c.split(",")
if len(splitted) == 4:
out.append(
{
"taglbl": int(splitted[0]),
... |
def dataToString(var, data):
"""Given a tuple of data, and a name to save it as
returns var <- c(data)
"""
#convert data to strings
d = [str(d) for d in data]
return "%s <- c(%s)" % (var, ",".join(d)) |
def before_breadcrumb(crumb, hint):
"""
fake method to experiment sentry custom before_breadcrumb function.
"""
print(hint) if hint else None
return crumb |
def merge_dicts(list_of_dicts):
"""
Merge multipe dictionaries together.
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
Args:
dict_args (list): a list of dictionaries.
Returns:
dict
"""
merge_dict... |
def arepr(terms, l, r):
""" Concatenate str representations with commas and left and right
characters. """
return l + ', '.join(map(str, terms)) + r |
def _is_aaaaaah(word: str) -> bool:
"""
Check if a word contains at least three of the same letters after each other and no non-letter characters
:param word: Word for which we check if it is 'aaaaah'-like
:returns: Boolean indicating if word is 'aaaaah'-like
>>> _is_aaaaaah('aaaaaaah')
True
... |
def valid_ip(ip):
"""
:type ip: str
:rtype: str
"""
def is_v4(s):
try:
return str(int(s)) == s and 0 <= int(s) <= 255
except:
return False
def is_v6(s):
if len(s) > 4:
return False
try:
return int(s, 16) >= 0 and s[... |
def _switch_case_letter(ch):
"""switch the case of the character"""
return ch.swapcase() |
def addDummyVariable(allVariables):
"""Create, add, and return a new dummy variable name.
Specifically, the set allVariables is a set of all current
variable names. We find a new variable name of the form d1, d2,
d3, ... which is not in the given set. The new name is added to
the set, and the new n... |
def string_date_to_ints(bday):
"""Split mm/dd/yy(yy) into separate m, d, and y fields."""
try:
month, day, year = [int(num) for num in bday.split('/')]
return month, day, year
except:
return None, None, None |
def load_federated_extensions(federated_extensions):
"""Load the list of extensions"""
extensions = []
for name, data in federated_extensions.items():
build_info = data['jupyterlab']['_build']
build_info['name'] = name
extensions.append(build_info)
return extensions |
def parse_host_port(address):
"""
Given a string address with host/port, build a tuple(host, port)
Parameters
----------
address: string address to parse
Returns
-------
tuple with host and port info : tuple(host, port)
"""
if '://' in address:
address = address.rsplit(... |
def element_counts(msTuple):
"""
Docstring for function pykrev.element_counts
====================
This function takes an msTuple and gives atomic counts for C,H,N,O,P & S for each formula in the formula list.
Use
----
element_counts(Y)
Returns a list of len(Y) in which each element, i , is a dict... |
def row_width(width: int) -> int:
"""Calculates the width in bits of each row in the output font bitmaps from the actual witdth of a character in pixels."""
# NOTE: Lines in BDF BITMAPs are always stored in multiples of 8 bits
# (https://stackoverflow.com/a/37944252)
return -((-width) // 8) * 8 |
def find_nesting_levels(string, beg, end, fst, snd):
"""Find the nesting level of beg and end."""
beg_level = 0
end_level = 0
for i in range(beg, end):
if string[i] == fst:
end_level += 1
if string[i] == snd:
if end_level > 0:
end_level -= 1
... |
def shrink_nested_list(nest, limit=5000):
"""
The last element from the largest list in
the nested list is removed until the
total length of the nest is <= limit.
"""
nest_len = sum([len(l) for l in nest])
while nest_len > limit:
biggest = max(enumerate(nest), key=lambda tup: len(tup... |
def DOTlabel(model, shapes, debug, name):
"""
Function creating labels for dot graphs and nodes
"""
if debug:
# We indicate if Keras Input/Output is available
if model.kerasInput is None:
inputState = ' (Keras-Not Computed)'
else:
inputState = ' (Keras-Com... |
def one_only(l):
"""
Return None if `l` empty, raise exception if `len(l) > 1`, otherwise `l[0]`.
"""
if len(l) == 1:
return l[0]
elif len(l) == 0:
return None
raise Exception('filter matched too many: {}'.format(len(l))) |
def generate_report(rates_to_watch):
""" Generates a report on tracked rates and emails them.
:param rates_to_watch: A list of CurrencyTrackers.
:param email: The email to send report to.
:param password: The password for the email account.
"""
# Create email report.
complete_report = ""
... |
def as_bytes(x: int) -> bytes:
""" cast int into bytes
Parameters
----------
x: int
an integer to be cast into bytes
Returns
-------
b: bytes
"""
return x.to_bytes(1, "little") |
def letter_count(word):
"""How many charaters in `word` satisfy `str.isalpha()`?"""
return sum(map(str.isalpha, word)) |
def safe_index(l, e):
"""Gets the index of e in l, providing an index of len(l) if not found"""
try:
return l.index(e)
except:
return len(l) |
def application_error(e):
"""Return a custom 500 error."""
return 'Sorry, unexpected error because I messed up: {}'.format(e), 500 |
def relativedatacsvpath(datacsvfilename):
"""
relative data csv path
:param datacsvfilename:
:return:
"""
return 'datacsv/' + datacsvfilename + '.csv' |
def fix_join(path, *paths):
"""Fix joined path.
This workaround function is used in pipelines like DWIPreprocessing* or PETVolume. In the workflow.connect part,
you can use some function that are used as string, causing an import error
"""
import os
return os.path.join(path, *paths) |
def valid_state(state: str) -> bool:
"""Test if a state is valid."""
return len(state) < 256 |
def inr(r,s,t):
"""r is in range of s and t left inclusive"""
return (r < t) and (r >= s) |
def _to_http_url(url: str) -> str:
"""Git over SSH -> GitHub https URL."""
if url.startswith("git@github.com:"):
_, repo_slug = url.split(':')
return f"https://github.com/{repo_slug}"
return url |
def _get_repositories_to_use(context, rhsm_info, target_repositories):
"""
Filters the available repositories based on the target_repositories passed.
:param context: An instance of a mounting.IsolatedActions class
:type context: mounting.IsolatedActions class
:param rhsm_info: An instance of a RHS... |
def getBinaryRep(n, numDigits):
"""Assumes n and numDigits are non-negative ints
Returns a str of length numDigits that is a binary
representation of n"""
result = ''
while n > 0:
result = str(n%2) + result
n = n//2
if len(result) > numDigits:
raise ValueError('not enough digit... |
def overWriteDict(dict1, dict2):
"""
merges dict2 into dict1 by inserting and overwriting values
"""
if dict2 is not None and len(dict2) > 0:
for p in dict2:
if p in dict1:
dict1[p].update(dict2[p])
else:
dict1[p] = dict2[p]
return dict1 |
def parse_combo_results(results, var_names):
"""
"""
if var_names is not None and (isinstance(var_names, str) or
len(var_names) == 1):
results = (results,)
return results |
def _partition_products_by_language(products):
""" Partitions the given product models into language buckets of product id's.
:param products: a list of product models.
:returns: a map {language: set of product_id's}.
"""
products_by_language = {}
for product in products.values():
... |
def int_or_none(x):
"""
A helper to allow filtering by an integer value or None.
"""
if x.lower() in ("null", "none", ""):
return None
return int(x) |
def check_correctness_number_of_args_mode(argv_):
"""return bool"""
return len(argv_) >= 4 and len(argv_) <= 7 |
def _get_version_string(version_number):
"""Produces a three char string that corresponds to the desired db folder"""
version_string = str(version_number)
while len(version_string) < 3:
version_string = '0' + version_string
return version_string |
def allelic_balance(gt):
"""Return allelic balance from genotype value."""
if not gt.get("dp"):
return 0.0
else:
return gt.get("ad") / gt.get("dp") |
def is_palindrome(string: str) -> bool:
"""
Check if a string is a palindrome.
"""
string = string.replace(" ", "").lower()
return string == string[::-1] |
def _create_signature_key(signature, rev):
"""Given a signature ID and revision, build the key we use to look up the signature in the redis db."""
return f'{signature}:{rev}' |
def active_ceased_lists(filing):
"""Create active/ceased director lists based on a filing json."""
ceased_directors = []
active_directors = []
for filed_director in filing['filing']['changeOfDirectors']['directors']:
if filed_director.get('cessationDate'):
ceased_directors.append(fil... |
def isAnalysisJob(trf):
""" Determine whether the job is an analysis job or not """
if (trf.startswith('https://') or trf.startswith('http://')):
analysisJob = True
else:
analysisJob = False
return analysisJob |
def delete_line_breaks(text, joiner):
""" Deletes line breaks and joins split strings in one line
:param text: string
:param joiner: string used to join items [" " for abs or "" for title]
:return: joined text
"""
text = text.split('\n')
text = joiner.join(text)
return text |
def fibonacciIt(num):
"""this function returns True if a number is in
the fibonacci sequence and False if otherwise"""
a=1
b=2
n = 10000
list_sequence = [1, 2]
for i in range(0, n+1):
b=a+b
a=b-a
list_sequence.append(b)
if num < 0:
return "Wrong input"
... |
def COL_DISTINF(col1, col2):
"""
Computes inf-distance between two RGB vectors, i.e.
= max(abs(r), abs(g), abs(b))
"""
r, g, b = (col1[i] - col2[i] for i in range(0, 3))
return max(abs(r), abs(g), abs(b)) |
def solution(limit: int = 1_000_000) -> int:
"""
Returns an integer, the solution to the problem
>>> solution(10)
31
>>> solution(100)
3043
>>> solution(1_000)
304191
"""
phi = [i - 1 for i in range(limit + 1)]
for i in range(2, limit + 1):
if phi[i] == i - 1:
... |
def is_pj_los(value):
""" Is the given value a PyJSON Listof Species+?
:param value: The value being checked
:type value: Any
:return: True if the given value is a PyJSON Listof Species+
:rtype: Boolean
"""
return isinstance(value, list) |
def robuste_issubclass(cls1, cls2):
"""
function likes issubclass but returns False instead of raise type error
if first parameter is not a class.
"""
try:
return issubclass(cls1, cls2)
except TypeError:
return False |
def minimum_swap(arr):
"""
Takes an array and finds the minimum swaps needed
The input is first reduced into the subtracted index equivalent format then if the index is equal to the value things remains unchanged
otherwise the value is swapped with the index of that value.
arr: array to find... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.