content stringlengths 42 6.51k |
|---|
def get_tin_npi_list(decoded_messages):
"""Decode messages and return lists of npis and tins."""
if not decoded_messages:
return (None, None)
return zip(*[(provider.get('tin'), provider.get('npi')) for provider in decoded_messages]) |
def get_pair(value=None, val_1_default=None, val2_default=None, name="value"):
"""
>>> v1, v2 = get_pair(9)
>>> assert v1 == 9
>>> assert v2 == 9
>>> value = (8, 1)
>>> v1, v2 = get_pair(value=value)
>>> assert v1 == 8
>>> assert v2 == 1
>>> v1, v2 = get_pair(val_1_default=3, val2_... |
def calc_beta_mode(a: int, b: int) -> float:
"""
This function calculate the mode (i.e. the peak) of the beta distribution.
:param a: First shape parameter of the Beta distribution
:param b: Second shape parameter of the Beta distribution
:return: The mode
"""
return (a-1)/(a+b-2) |
def dict_diff(d1, d2):
"""
Assumes dicts of dicts or tensors and that dicts have same structure.
"""
out = {}
for k in d1.keys():
if isinstance(d1[k], dict):
out[k] = dict_diff(d1[k], d2[k])
else:
out[k] = d1[k] - d2[k]
return out |
def intersection(collection_a, collection_b):
"""
The intersection between two collections considered
as sets (duplicated items will be removed).
"""
set_a = set(collection_a)
set_b = set(collection_b)
return set_a.intersection(set_b) |
def _to_df(point, level=0):
"""Transfrom point to dataframe dict layout.
Args:
point (dict): Point
level (int, optional): Defaults to 0. Level
Returns:
dict
"""
data = {
'Label': [point['label']],
'Time': [point['difference_time']],
'Memory': [point[... |
def count_communication_primitives(hlo_ir: str,
ignore_scalar_all_reduce: bool = False):
"""Count the communication primitives in a HLO IR."""
total = hlo_ir.count("channel_id")
all_reduce = hlo_ir.count("all-reduce(") + hlo_ir.count("all-reduce-start(")
all_gather = h... |
def image_shape_to_hw(image_shape):
"""Extract the height and width of the image from HW, HWC or BHWC"""
img_size = (-1, -1)
if len(image_shape) == 2:
img_size = image_shape
elif len(image_shape) == 3:
img_size = image_shape[:2]
elif len(image_shape) == 4:
img_size = image_sh... |
def get_bytes_asset_dict(
data: bytes, target_location: str, target_name: str,
):
"""Helper function to define the necessary fields for a binary asset to
be saved at a given location.
Args:
data: the bytes to save
target_location: sub-directory to which file will
be written,... |
def volume_dialogs(context, request, volume=None, volume_name=None, instance_name=None, landingpage=False,
attach_form=None, detach_form=None, delete_form=None):
"""Modal dialogs for Volume landing and detail page."""
ng_attrs = {'model': 'instanceId', 'change': 'getDeviceSuggestion()'}
#... |
def month_letter(i):
"""Represent month as an easily graspable letter (a-f, o-t)."""
# return ('abc' 'def' 'opq' 'rst')[i-1]
# return ('abc' 'ijk' 'pqr' 'xyz')[i-1]
return ('abc' 'def' 'uvw' 'xyz')[i-1] |
def package_file(*args):
"""Return the filename of a file within this package."""
import os
return os.path.join(
os.path.dirname(__file__),
*args
) |
def is_under_replicated(num_available, expected_count, crit_threshold):
"""Calculates if something is under replicated
:param num_available: How many things are up
:param expected_count: How many things you think should be up
:param crit_threshold: Int from 0-100
:returns: Tuple of (bool, ratio)
... |
def _dump_filename(config):
"""Give the name of the file where the results will be dumped"""
return (config['out'] + '/' + config['target']['name'] + '_' +
str(config['target']['spectrum']) + '_' +
str(int(0.5+config['time']['tmin'])) + '_' +
str(int(0.5+config['time']['tmax'... |
def int2bin(n, digits=8):
"""
Integer to binary string
"""
return "".join([str((n >> y) & 1) for y in range(digits - 1, -1, -1)]) |
def strip(text):
"""
Strings a string of surrounding whitespace.
"""
return text.strip() |
def get_order_category(order):
"""Given an order string, return the category type, one of:
{"MOVEMENT, "RETREATS", "DISBANDS", "BUILDS"}
"""
order_type = order.split()[2]
if order_type in ("X", "D"):
return "DISBANDS"
elif order_type == "B":
return "DISBANDS"
elif order_type ... |
def parse_lines(s):
"""
parser for line-separated string fields
:s: the input string to parse, which should be of the format
string 1
string 2
string 3
:returns: tuple('string 1', ...)
"""
return tuple(map(lambda ss: ss.strip... |
def create_non_compliance_message(violations):
"""Create the Non Compliance Message."""
message = "Violation - The following EC2 IAM Role is in violation of security compliance \n\n"
for violation in violations:
message += violation + "\n"
return message |
def is_leap_year(year):
"""
Is the current year a leap year?
Args:
y (int): The year you wish to check.
Returns:
bool: Whether the year is a leap year (True) or not (False).
"""
if year % 4 == 0 and (year % 100 > 0 or year % 400 == 0): return True
return False |
def slugify(name):
"""
Derpi has some special slugifying rules.
"""
RULES = {
":": "-colon-",
".": "-dot-",
}
r = name
for k, v in RULES.items():
r = r.replace(k, v)
return r |
def sum_even_fibonacci(limit: int) -> int:
"""
Sums even terms in the Fibonacci sequence.
:param limit: Limit for the sequence, non-inclusive.
:return: Sum of even terms in the Fibonacci sequence.
"""
term_a = 1
term_b = 2
result = 0
while term_b < limit:
if not term_b % 2:
... |
def dead_check(d_age):
"""Deze functie controleert of de tamagotchi dood is. Dit hangt af\
van de leeftijd van de tamagotchi."""
if -1 < d_age < 7:
return 6
elif d_age < 14:
return 12
elif d_age < 21:
return 18
elif d_age < 25:
return 24
else:
... |
def human_size(sz):
"""
Return the size in a human readable format
"""
if not sz:
return False
units = ('bytes', 'Kb', 'Mb', 'Gb', 'Tb')
if isinstance(sz, str):
sz=len(sz)
s, i = float(sz), 0
while s >= 1024 and i < len(units)-1:
s /= 1024
i += 1
retur... |
def line_p(x, p):
"""
Straight line: :math:`a + b*x`
Parameters
----------
x : float or array_like of floats
independent variable
p : iterable of floats
parameters (`len(p)=2`)
- `p[0]` = a
- `p[1]` = b
Returns
-------
float
function valu... |
def convert_cfg_markdown(cfg):
"""Converts given cfg node to markdown for tensorboard visualization.
"""
r = ""
s = []
def helper(cfg):
s_indent = []
for k, v in sorted(cfg.items()):
seperator = " "
attr_str = " \n{}:{}{} \n".format(str(k), seperator, str(v... |
def _create_vn_str(novice_status):
"""Creates varsity-novice status string from the integer pseudo-enum used by the model"""
if novice_status is 0: return "varsity"
if novice_status is 1: return "novice"
return novice_status |
def check_win(guess_word):
"""
Returns True if the player has won.
The player has won if there are no underscores left to guess.
Args:
guess_word: the current state of the guess word
Returns:
True in case of win, False otherwise.
"""
return not "_" in guess_word |
def checkEqual(lst):
"""
Utility function
"""
return lst[1:] == lst[:-1] |
def namespacer(plugin_group, plugin, name):
"""
* `plugin_group` - `string`. The name of the plugin directory
* `plugin` - `string`. The name of the plugin
* `name` - `string`. An attribute key name
A helper to enforce DRY. Used in the two places that namespace attribute keys which are
appended to the attributes ... |
def pickaparc(files):
"""Return the aparc+aseg.mgz file"""
aparcs = []
for s in files:
if 'aparc+aseg.mgz' in s:
aparcs.append(s)
if aparcs == []:
raise Exception("can't find aparc")
return aparcs[0] |
def title(sen):
"""
Turn text into title case.
:param sen: Text to convert
:return: Converted text
"""
new_text = ""
for i in range(0, len(sen)):
if i == 1:
new_text += sen[i].upper()
continue
if sen[i - 1] == " ":
new_text += sen[i].upper... |
def ceildiv(a, b):
"""
Ceiling division, used rounding up page size numbers
:param a: numerator
:param b: denominator
:return: integer
"""
return -(-a // b) |
def adjust(f, i, xs):
"""Applies a function to the value at the given index of an array, returning a
new copy of the array with the element at the given index replaced with the
result of the function application"""
return [f(x) if i == ind else x for ind, x in enumerate(xs)] |
def num_of_sample_of_different_label(training_samples):
"""
:param training_samples: data of all training samples, the format are shown in load_training_data function.
:return num_of_each_label: number of samples of each kind of label, a dictionary.
eg: {'good': 8, 'bad': 9}
"""
# get ... |
def count_letters(data):
"""
The following function counts the number of letters in the string by applying isalpha method
which returns true when the i'th' character of the particular string is an alphabet.
"""
countLetters = 0
for character in data:
if (character.isalpha()): # check ... |
def knownvalues(caselen):
"""Insert known bad values"""
values = []
values.append(
("01"*(caselen * 2))[:caselen]
)
values.append(
("10"*(caselen * 2))[:caselen]
)
return values |
def robust_l1(x):
"""Robust L1 metric."""
return (x**2 + 0.001**2)**0.5 |
def isVideo(link):
""" Returns True if link ends with video suffix """
suffix = ('.mp4', '.webm')
return link.lower().endswith(suffix) |
def check_number_validity(number, previous_numbers):
"""Return true if two numbers of previous_numbers sum up exactly to number"""
for candidate in previous_numbers:
if number - candidate in previous_numbers:
return True
return False |
def find_first_tag(tags, entity_type, after_index=-1):
"""Searches tags for entity type after given index
Args:
tags(list): a list of tags with entity types to be compared to
entity_type
entity_type(str): This is he entity type to be looking for in tags
after_index(int): the st... |
def logstash_processor(_, __, event_dict):
"""
Adds @version field for Logstash.
Puts event in a 'message' field.
Serializes timestamps in ISO format.
"""
if 'message' in event_dict and 'full_message' not in event_dict:
event_dict['full_message'] = event_dict['message']
event_dict['m... |
def verify_gender(gender_input: str) -> bool:
"""
A helper function to make verifying gender strings easier
Parameters
----------
gender_input: str
The single letter gender string to be verified.
Valid inputs are: 'm', 'f', 'o'
Returns
----------
bool: Returns true if t... |
def remove_leading_number(string):
"""
Will convert 8 Alex Ovechkin to Alex Ovechkin, or Alex Ovechkin to Alex Ovechkin
:param string: a string
:return: string without leading numbers
"""
newstring = string
while newstring[0] in {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}:
n... |
def check_state(state, max_len, pad_token):
"""Check state and left pad or trim if necessary.
Args:
state (list): list of of L decoder states (in_len, dec_dim)
max_len (int): maximum length authorized
pad_token (int): padding token id
Returns:
final (list): list of L padded... |
def simplify_title(title: str):
"""
Takes in an anime title and returns a simple version.
"""
return ''.join(
i for i in title if i.isalpha() or i==' '
).lower().strip() |
def apply_column_rule(row, rule):
"""
Given a cell value and a rule, return a format name. See `create_cell_formats` for more detail.
"""
rule_type = rule['type']
if rule_type == 'all':
return rule['format']
if rule_type == 'boolean':
if rule['function'](row):
return ... |
def _format_lineno(session, line):
"""Helper function to format line numbers properly."""
if session == 0:
return str(line)
return "%s#%s" % (session, line) |
def specified_users(users_arg, users):
"""Parse a comma-separated list of users
Check that all specified users are valid, and return them as a list
Parameters
----------
users_arg : str
Comma-separated list of users
users : container
Container of valid users
Re... |
def euler_problem_2(n=4000000):
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four milli... |
def getSSC(rawEMGSignal, threshold):
""" Number of times the slope of the EMG signal changes sign.::
SSC = sum(f( (x[i] - x[i-1]) X (x[i] - x[i+1]))) for i = 2 --> n-1
f(x){
1 if x >= threshold
0 otherwise
}
* Input:
* raw EM... |
def lagrange2(N, i, x, xi):
"""
Program to calculate Lagrange polynomial for order N
and polynomial i [0, N] at location x at given collacation points xi
(not necessarily the GLL-points)
"""
fac = 1
for j in range(-1, N):
if j != i:
fac = fac * ((x - xi[j + 1]) / (xi[i +... |
def calc_TS(Sal):
"""
Calculate total Sulphur
Morris, A. W., and Riley, J. P., Deep-Sea Research 13:699-705, 1966:
this is .02824.*Sali./35. = .0008067.*Sali
"""
a, b, c = (0.14, 96.062, 1.80655)
return (a / b) * (Sal / c) |
def isReplacementNeeded(config):
"""
Check if we need to clean some junk from the source code files path
:param config: configuration of the flask app
:return (should_replace_path, new_src_dir)
"""
should_replace_path = False
if 'REPLACE_KERNEL_SRC' in config:
should_replace_path = c... |
def is_alphanumeric(text:str) -> bool:
""" whole string is a-z,A-Z,0-9 """
# ord values [48-57, 65-90, 97-122, ]
# return all((48 <= ord(c) <= 57 or 65 <= ord(c) <= 90 or 97 <= ord(c) <= 122) for c in text)
for c in text:
o = ord(c)
if not (48 <= o <= 57 or 65 <= o <= 90 or 97 <= o <= 122): return False
return... |
def stringList(listItems):
"""Convert a list into string list"""
return [str(node) for node in listItems] |
def key_with_maxval(d):
"""Get the key with maximum value in a dictionary
Paramerers:
d (dictionary)
"""
try:
v=list(d.values())
k=list(d.keys())
return k[v.index(max(v))]
except:
return 9999 |
def endpoint(line, x=0, y=0):
"""
>>> endpoint('nwwswee')
(0, 0)
"""
if line == "":
return x, y
if line.startswith("nw"):
return endpoint(line[2:], x, y - 1)
if line.startswith("ne"):
return endpoint(line[2:], x + 1, y - 1)
if line.startswith("sw"):
return... |
def validate_input(name):
"""Check that the user supplied name conforms to our standards.
A name should be between 1-10 characters (inclusive) and composed of all
alphabetic characters.
Args:
name (str): The name to be validated.
Returns:
An error message if the name is invalid, o... |
def float_if_not_none(value):
"""
Returns an float(value) if the value is not None.
:param value: None or a value that can be converted to an float.
:return: None or float(value)
"""
return None if value is None else float(value) |
def deepmerge(source, destination):
"""
Merge the first provided ``dict`` into the second.
:param dict source: The ``dict`` to merge into ``destination``
:param dict destination: The ``dict`` that should get updated
:rtype: dict
:returns: ``destination`` modified
"""
for key, value in s... |
def sublime_line_endings_to_serial(text, line_endings):
"""
Converts the sublime text line endings to the serial line ending given
:param text: the text to convert line endings for
:param line_endings: the serial's line endings setting: "CR", "LF", or "CRLF"
:return: the new text
"""
... |
def scrapyd_url(ip, port):
"""
get scrapyd url
:param ip: host
:param port: port
:return: string
"""
url = 'http://{ip}:{port}'.format(ip=ip, port=port)
return url |
def round_base(num, base=1):
"""
Returns a number *num* (*int* or *float*) rounded to an arbitrary *base*. Example:
.. code-block:: python
round_base(7, 3) # => 6
round_base(18, 5) # => 20
round_base(18., 5) # => 20. (float)
"""
return num.__class__(base * round(float(num) ... |
def calc_group_rel_ratios(rel_pow_low, rel_pow_high):
""" Calculates relative ratio of power within two bands.
Parameters
----------
rel_pow_low : float or list of floats
Low band power or list of low band powers
rel_pow_high : float or list of floats
High band power or list of high... |
def gender_similarity_scorer(gender_1: str, gender_2: str):
"""Compares two gender strings, returns 0 if they match, returns penalty of -1 otherwise.
Conservative assumption: if gender is nil or empty string, consider it a match against the comparator.
"""
if gender_1 == gender_2:
return 0
... |
def rotate(arr, n):
"""
Right side rotation of an array by n positions
"""
# Storing the length to avoid recalculation
arr_len = len(arr)
# Adjusting the value of n to account for Right side rotations and cases where n > length of the array
n = arr_len - (n % arr_len)
# Splitting the array into two parts and me... |
def brackets(string: str) -> str:
"""Wraps a string with a pair of matching brackets."""
if len(string) != 0:
return "[" + string + "]"
else:
return "" |
def checkOutputFormat(output_len):
"""check if output length is word count or percentage ratio of the original text"""
if float(output_len) < 1:
outputFormat = "ratio"
else:
outputFormat = "word_count"
return outputFormat |
def deep_sort(obj):
"""Recursively sort list or dict of nested lists."""
if isinstance(obj, dict):
_sorted = dict()
for key in sorted(obj):
_sorted[key] = deep_sort(obj[key])
elif isinstance(obj, list):
new_list = []
for val in obj:
new_list.append(dee... |
def flatten(cmd, path="", fc={}, sep="."):
"""
Convert a nested dict to a flat dict with hierarchical keys
"""
fcmd = fc.copy()
if isinstance(cmd, dict):
for k, v in cmd.items():
k = k.split(":")[1] if ":" in k else k
fcmd = flatten(v, sep.join((path, k)) if path else... |
def str2list(str):
"""Convert string to a list of strings."""
return str.split('\n') |
def turn(n):
"""Formula from WIkipedia.
n could be numpy array of integers
"""
return (((n & -n) << 1) & n) != 0 |
def period_to_int(period):
"""
Convert time series' period from string representation to integer.
:param period: Int or Str, the number of observations per cycle: 1 or "annual" for yearly data, 4 or "quarterly"
for quarterly data, 7 or "daily" for daily data, 12 or "monthly" for monthly data, 24 or "hou... |
def frames(string):
"""Takes a comma separate list of frames/frame ranges, and returns a set containing those frames
Example: "2,3,4-7,10" => set([2,3,4,5,6,7,10])
"""
def decode_frames(string):
print('s', string)
if '-' in string:
a = string.split('-')
start, en... |
def validate_product_data(product):
""" this funtion validates the product data """
# Check for empty product_name
if product['product_name'] == '':
return {'warning': 'product_name is a required field'}, 400
# Check for empty product_category
elif product['product_category'] == '':
... |
def parse_people_data(data):
""" Handle :PeopleData
Reduces the length of the returned data somewhat.
"""
lines = data.split('\n')
return '. '.join(lines[:min(len(lines), 3)]) |
def get_ssl(database):
"""
Returns SSL options for the selected engine
"""
# Set available keys per engine
if database['engine'] == 'postgresql':
keys = ['sslmode', 'sslcert', 'sslkey',
'sslrootcert', 'sslcrl', 'sslcompression']
else:
keys = ['ssl_ca', 'ssl_c... |
def validate(config):
"""
Validate the beacon configuration
"""
if not isinstance(config, list):
return False, ("Configuration for telegram_bot_msg beacon must be a list.")
_config = {}
list(map(_config.update, config))
if not all(
_config.get(required_config) for required_... |
def shouldIgnore(s):
"""Should we ignore the key s?
(Right now, returns true if s takes the form
"__xxxxx...", prepended by two '_' chars
"""
return len(s) > 1 and s[:2] == "__" |
def get_nx_standard_epu_mode(mode):
"""
Define polarization as either
cir. right, point of view of source,
cir. left, point of view of source, or
linear. If the linear case is selected, there is an additional value in degrees for
the angle (number is meaningless if circul... |
def lowercase_first_segment(apitools_collection_guess):
"""First segment of collection should be lowercased, handle acronyms."""
acronyms = ['HTTPS', 'HTTP', 'SSL', 'URL', 'VPN', 'TCP']
found_acronym = False
for acronym in acronyms:
if apitools_collection_guess.startswith(acronym):
apitools_collection... |
def endpoint_not_found(e):
"""
Fallback request handler
"""
return "Endpoint not found.", 404 |
def nag_function_is_output(name):
"""
Check wether a NAG function name is of type output
"""
if name[0:1] == 'o':
return True
else:
return False |
def flatten_dictionary(dictionary):
"""
Input: a request's JSON dictionary output with nested dictionary
Output: a flattened dictionary (format: key1.key2 = value2)
"""
flattenedDictionary = dict()
for key, value in dictionary.items():
if isinstance(value, dict):
for subkey, ... |
def padBlock(block, dur):
"""Adjusts the block for the proper timing interval"""
nBlock = []
for i, b in enumerate(block):
if i == 0:
nBlock.append(b)
else:
j = i - 1
prev = block[j]
ev = b + dur + prev
nBlock.append(ev)
return ... |
def qmag2(q):
"""
Returns the euclidean length or magnitude of quaternion q squared
"""
return (sum(e*e for e in q)) |
def attr_is_not_inherited(type_, attr):
"""
returns True if type_'s attr is not inherited from any of its base classes
"""
bases = type_.__mro__[1:]
return getattr(type_, attr) not in (getattr(base, attr, None) for base in bases) |
def traverse_table(time_step, beam_indx, back_pointers, elems_table,
format_func=None):
"""
Walks back to construct the full hypothesis by traversing the passed table.
:param time_step: the last time-step of the best candidate
:param beam_indx: the beam index of the best candidate in... |
def sanitize(string):
"""removes the added identification prefix 'caffe_layer_'
"""
return int(string[12:]) |
def api_file_url(url_or_id):
"""Converts the Google Drive file ID or "Get link" URL to an API URL.
from https://drive.google.com/file/d/<ID>/view?usp=sharing
to https://www.googleapis.com/drive/v3/files/<ID>?alt=media
"""
if '/' in url_or_id:
gid = url_or_id.split('/')[-2]
else:
... |
def rename_to_text(file_path):
"""
Appends a .txt to all files run since some output files do not have an extension
:param file_path: input file path
:return: .txt appended to end of file name
"""
import os
file = file_path.split('/')[-1]
if file.endswith('.txt') is False:
new_f... |
def binding_string_to_dict(raw_value):
"""Convert comma-delimted kwargs argument into a normalized dictionary.
Args:
raw_value: [string] Comma-delimited key=value bindings.
"""
kwargs = {}
if raw_value:
for binding in raw_value.split(','):
name, value = binding.split('=')
if value.lower()... |
def refMEMReplacements(tex):
"""
Searches through the tex for any reference that specifically points to
the memory model and replaces that sentence with a hard-coded string.
Processing the section that was in the original text is not an option
because the reference the Latex file does not apply to... |
def merge(*objs):
"""
Create a ``dict`` merged with the key-values from the provided dictionaries such that each next
dictionary extends the previous results.
Examples:
>>> item = merge({'a': 0}, {'b': 1}, {'b': 2, 'c': 3}, {'a': 1})
>>> item == {'a': 1, 'b': 2, 'c': 3}
True
... |
def sort_priority_use_nonlocal(numbers, group):
""" add nonlocal keyword to assign outter value
:param numbers:
:param group:
:return:
"""
found = False
def helper(x):
if x in group:
nonlocal found
found = True
return 0, x
return 1, x
... |
def flatten(l):
"""
Flattens a list.
Written by Bearophile as published on the www.python.org newsgroups.
Pulled into Topographica 3/5/2005.
"""
if type(l) != list:
return l
else:
result = []
stack = []
stack.append((l,0))
while len(stack) != 0:
... |
def string_to_boolean(value, true_values, false_values):
"""Find value in lists and return boolean,
else returns the original value string.
"""
clean_value = value.strip().lower()
if clean_value in true_values:
return True
if clean_value in false_values:
return False
return v... |
def get_dimensions(line):
"""
Parse and extract X, Y and Z dimensions from string
Parameters
----------
full_prefix: string
shot full prefix (e.g R8O3IL08C25_Y10Z15)
returns: Tuple of (bool, string, string)
True if ok, False and file name and SHA1 if signat... |
def encodeStop(sreg):
"""final step: returns the BCH code from the shift register state"""
sreg ^= 0xFF # invert the shift register state
sreg <<= 1 # make it the 7 most sign. bits
return (sreg & 0xFE) # filter the 7 most sign bits |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.