content stringlengths 42 6.51k |
|---|
def set_to_list(obj):
"""
Helper function to turn sets to lists and floats to strings.
"""
if isinstance(obj, set):
return list(obj)
if isinstance(obj, float):
return str('%.15g' % obj)
raise TypeError |
def _collect_facts(resource):
"""Transform cluster information to dict."""
facts = {
'identifier': resource['ClusterIdentifier'],
'status': resource['ClusterStatus'],
'username': resource['MasterUsername'],
'db_name': resource['DBName'],
'maintenance_window': resource['Pr... |
def escape_spaces(text):
"""
Escape spaces in the specified text
.. note:: :func:`pipes.quote` should be favored where possible.
"""
return text.replace(' ', '\ ') |
def add_main_category(row, categories_dict):
"""
Add the item's main category to the row
:param row: A dict containing metadata for one item
:param categories_dict: A dict mapping subcategories to main categories, as
a Spark broadcast variable
:return: A dict containing the original data plus th... |
def filter_content(response: dict) -> str:
"""Assign correct output label to a response according to OpenAI guidelines
Args:
response (dict): response dictionary
Returns:
str: output label after logprob correction
"""
output_label = response["choices"][0]["text"]
# This is th... |
def cast(s):
""" Function which clarifies the implicit type of
strings, a priori coming from csv-like files.
Example
-------
>>> cast('1')
1
>>> cast('1.')
1.0
>>> cast('1E+0')
1.0
>>> cast('1E+1')
10.0
>>> cast('one')
'one'
>>> cast('One')
... |
def shunt(infix):
"""Return the infix regular expression in postfix.
Parameter:
infix(string): The regular expression to be shunted from infix to postfix
:returns
The postfix stack of operators.
"""
infix = list(infix)[::-1]
# Operator stack.
opers, postfix = [], []
# Operator... |
def calculate_zoo_I0(sizes):
"""initializes allometric parameters based on array of sizes (ESD)"""
return 26 * sizes ** -0.4 |
def spammer_cmd_header(username):
"""Return formatted text for spammer command header.
Args:
username (str): DeviantArt username.
Returns:
str: Formatted text for spammer command header.
"""
return '\n'.join([
'REPORT LINK: https://contact.deviantartsupport.com/en?subOption... |
def strip_string(string):
"""
:param string:
:return:
"""
return string.strip() |
def construct_console_connect_url(instance_id: str, region: str = "us-east-1") -> str:
"""Assemble the AWS console instance connect url with the current instance id and region."""
instance_connect_url = f"https://console.aws.amazon.com/ec2/v2/home?region={region}#ConnectToInstance:instanceId={instance_id}" # n... |
def get_subfield(_dict, field, subField):
"""checks to see if a field in a dictionary exists, if it does, `.get` a specified subfield"""
print(_dict)
print(field)
print(subField)
if _dict[field] is not None:
return _dict[field].get(subField, '')
return '' |
def create_annotationlist_v2(manifest_info, annolist_id, annotation_infos, add_context=False):
"""
Return V2 AnnotationList structure from annotation_infos
"""
annolist = {
'@type': 'sc:AnnotationList',
'@id': annolist_id,
'within': manifest_info['id']
}
if add_context:
... |
def mySub(a, b):
"""
Find the absolute difference between the two inputs
Parameters
----------
a : int or float
First number
b : int or float
Second number
Returns
-------
int or float
Returns the difference between the two inputs
"""
diff = 0
if... |
def merge(left, right):
""" Merge two lists by the following method:
1. Begin iterating through both halves simultaneously
2. Compare the currently indexed value of each half
3. Add the smaller value to the final, merged list, increment
"""
worklist = []
lindex = 0
rindex = 0
wh... |
def to_bool(data):
"""Convert truthy strings to boolean."""
return str(data).lower() == "true" |
def parser_multilingual_network_name_Descriptor(data,i,length,end):
"""\
parser_multilingual_network_name_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "multilingual_network_name", "contents" : unpa... |
def parser_transport_stream_Descriptor(data,i,length,end):
"""\
parser_transport_stream_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "transport_stream", "contents" : unparsed_descriptor_contents }
... |
def find_first(mylist, item):
""" Returns index of the first occurence of item in mylist, returns -1 if not found """
try:
idx = mylist.index(item)
except ValueError:
idx = -1
return idx |
def process_secondary_inputs(dict_):
"""
This functions processes the secondary input parameters.
Parameters
----------
dict_: dict
Estimation dictionary. Returned by grmpy.read(init_file).
Returns
-------
trim: bool, default True
Trim the data outside the common suppor... |
def model_names():
"""Provides a list containing the 8 bad-measurement model names, sorted in order of increasing dimensionality"""
return ['all-good','P_bad-flat','free-n_all-bad','free-Q_all-bad','free-F_all-bad', 'free-n', 'free-Q', 'free-F'] |
def resnet_params(model_name):
""" Map resnet_pytorch model name to parameter coefficients. """
params_dict = {
# Coefficients: res,dropout
"resnet20": (32, 0.2),
"resnet32": (32, 0.2),
"resnet44": (32, 0.2),
"resnet56": (32, 0.2),
"resnet110": (32, 0.2),
... |
def create_dicts_same_nodes(my_set, neighbors_dict, node, dict_out, dict_in):
"""
A function to create useful dictionaries to represent connections between nodes that have the same type, i.e between
nodes that are in the embedding and between nodes that aren't in the embedding. It depends on the input.
... |
def clamp(val, minVal=0.0, maxVal=1.0):
""" clamp value between min and max
:param val: value to clamp
:type val: float
:param minVal: minimum value
:type minVal: float
:param maxVal: maximum value
:type maxVal: float
:return: the clamped value
:rtype: float
"""
... |
def task2(rows, cols):
"""
Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array.
The element value in the i-th row and j-th column of the array should be i*j.
Example:
Suppose the following inputs are given to the program: 3, 5.
Then, the output of the program ... |
def concat(*items):
"""
Turn each item to a string and concatenate the strings together
"""
sep = ""
if len(items) == 1 and (
isinstance(items[0], (list, tuple, set)) or hasattr(items[0], "as_list")
):
items = items[0]
sep = ", "
return sep.join(map(str, items)) |
def get_package_url(data):
"""Get the url from the extension data"""
# homepage, repository are optional
if "homepage" in data:
url = data["homepage"]
elif "repository" in data and isinstance(data["repository"], dict):
url = data["repository"].get("url", "")
else:
url = ""
... |
def aks_test (n):
"""
AKS primality test using (x-1)^n - (x^n - 1)
to prove primality of n, or in other words
the nth row of pascals triangle minus the leading
and trailing 1s must be divisible by n.
Arguments:
n (:int) - the integer in question
Returns:
(:bool) - approximate primality of n
Example:
>>>... |
def calc_desired_torque1(laser_data, steering_percentage, max_velocity, delta_time_seconds, previous_torque_percentage):
"""
:param laser_data:
:param steering_percentage:
:return: previous_torque_percentage, time_last_run
"""
if previous_torque_percentage > 0:
# Running Time
if ... |
def timestamp(seconds):
"""
returns an approximate time that has been formatted to read more nicely for long runs
Inputs:
seconds: the number of seconds
Outputs:
a string representation of the time, as expressed in days, hours, minutes, and seconds
Notes:
in order to incre... |
def max_pyr_path_sum(p):
"""returns max adjacent path sum top->down through pyramid p"""
f = [[0 for j in range(i)] for i in range(1,len(p)+1)]
for i in range(len(p)):
for j in range(len(p[i])):
sigma = []
if i == 0:
f[i][j] = p[i][j]
... |
def _xor_block(a, b):
""" XOR two blocks of equal length. """
return ''.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)]) |
def check_degenerate(E):
"""E is a set of node-edge incidences corresponding to a single edge"""
E_distinct = set([e.nid for e in E])
return len(E_distinct) != len(E) |
def update_tile_data_from_redis(previousData, newData):
""" update value of tile with new data """
if isinstance(newData, str):
previousData['text'] = newData
return previousData
for key, value in newData.items():
if isinstance(value, dict) and key != 'data' and key in previousData a... |
def show_fact_sheet_a(responses, derived):
"""
If the claimant is claiming special extraordinary expenses, Fact Sheet A is
indicated.
"""
return responses.get('special_extraordinary_expenses', '') == 'YES' |
def group_by(l, column, comp_margin = None):
"""
Groups list entities by column values.
"""
sorted_values = []
result_list = []
current_value = None
for i in range(0, len(l)):
x = l[i]
if x[column][0:comp_margin] in sorted_values or x[column][0:comp_margin] == current_value:... |
def modulo(arr, val):
""" Modulo division of array by value. """
return [i % val for i in arr] |
def encodeList(items):
""" Encode list of items in user data file
Items are separated by '\t' characters.
@param items: list unicode strings
@rtype: unicode
@return: list encoded as unicode
"""
line = []
for item in items:
item = item.strip()
if not item:
co... |
def can_convert(s1, s2):
"""Convert 2 strings of same length by doing zero or more conversions"""
if s1 == s2:
return True
dp = {}
for i, j in zip(s1, s2):
if dp.setdefault(i, j) != j:
return False
return len(set(s2)) < 26 |
def CompareVersions(first_version_list, second_version_list):
"""Compares two lists containing version parts.
Note that the version parts can contain alpha numeric characters.
Args:
first_version_list: the first list of version parts.
second_version_list: the second list of version parts.
Returns:
... |
def build_key(*segment) -> str:
"""build a key of S3 objects"""
path = "/".join(segment)
path = path.replace("//", "/")
if len(path) > 1 and path[0] == "/":
path = path[1:]
return path |
def get_conn_args(database="mydb", user="user", password="password", host="mydb", port="5432"):
"""
Get arguments for the connection to the PostgreSQL database server
Parameters
----------
database: str
String of the database (default: "mydb")
user: str
String of the user (defau... |
def build_uri(base, *parts):
"""
This method helps to generate a URI based on a list of words
passed as a parameter
:param base: The URI base e.g.: http://examples.com
:param parts: List of elementos for generatig the URI e.g.: [oooooslc,service,catalog]
:return: The URI formed with the base and... |
def program_prefix(hint: str, *, return_program: bool = False, return_prefix: bool = False) -> str:
"""Translate between CMS package name and method prefix."""
pkgprefix = {
"p4": "Psi4",
"c4": "CFOUR",
"d3": "DFTD3",
"nwc": "NWChem",
"gms": "GAMESS",
}
lookup =... |
def finish_point(row, shown, results, obstacles, completed):
"""Extract a failure point (i.e., which obstacle) from a given row.
Args:
shown (str): "S", "PS" or "NS".
results (int): The number of completed obstacles.
completed (bool): True if the course was completed and False otherwise... |
def getAllBoxes( predictions):
"""
Params:
predictions - list of predictions
Returns - obtains list of all bounding box, softmax_scores tuples.
"""
boxes = []
scores = []
for prediction in predictions:
boxes += prediction['boxes']
scores += prediction['s... |
def protocol_replace(text):
"""
Replaces text name resolutions from domain names
Arguments:
text: string of domain with resolved port name
Results:
string value with resolved port name in decimal format
"""
replacements = [(':https', ':443'),
(':http', ':80')... |
def el_to_list(data, key1, key2, key3):
"""
Extracts a value from the third layer of a dictionary given the
three keys and converts it to a list if it is not a list
"""
val = data[key1].get(key2, dict()).get(key3, [])
if isinstance(val, list):
return val
else:
return [val] |
def customized_sort(list_like, compare_func, reverse=False):
"""
:param reverse:
:param list_like: iterative object
:param compare_func: takes two element, a, b as input, return -1 or 1.
if a > b return 1 and reverse is False, the sort is Increasing.
:return:
"""
from functools import ... |
def generate_annotation(x, y, text, color='black', fsize=12, textangle=0, xref='paper',
yref='paper', align='left'):
"""
Generates a plotly annotation in the form of dictionary.
It can be directly be appended to the layout.annotations.
:param x: x coordinate in plot
:param y: ... |
def region_from(ctg_name, ctg_start=None, ctg_end=None):
"""
1-based region string [start, end]
"""
if ctg_name is None:
return ""
if (ctg_start is None) != (ctg_end is None):
return ""
if ctg_start is None and ctg_end is None:
return "{}".format(ctg_name)
return "{}... |
def generateJson(samples):
"""Convert results to JSON
Creates a JSON object as a sting for each feature.
At the end of the function, JSON objects are concatenated and the resulting
string is returned.
Arguments:
samples (dict): of predicted-Samples
"""
j_objs = []
for s in sam... |
def is_prime(n):
"""
Decide whether a number is prime or not.
>>> is_prime(2)
True
>>> is_prime(8)
False
"""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
maxi = n**0.5 + 1
while i <= maxi:
if n % i =... |
def from_h(s):
"""Returns list of bytes corresponding to hex string `s`"""
assert len(s) % 2 == 0
return [int(s[2 * i: 2 * i + 2], 16) for i in range(len(s) // 2)] |
def powMod(p,k,N):
"""
powMod computes p^k mod N using rapid modular exponentiation.
Args:
p (int): The number to be exponentiated.
k (int): The exponental.
N (int): The modulus.
Returns:
The integer result.
"""
acc = 1
r = 0
for s in range(0,65):
... |
def build_config_xml(xmlstr):
"""build_config_xml"""
return '<config> ' + xmlstr + ' </config>' |
def color_tuple_to_hsl(three_tuple):
"""
Converts a (h, s, l) to a valid CSS value.
h: hue
s: saturation (in %)
l: lightness (in %)
"""
return 'hsl({}, {}%, {}%)'.format(*three_tuple) |
def anchor(computer, name, values):
"""Compute the ``anchor`` property."""
if values != 'none':
_, key = values
anchor_name = computer['element'].get(key) or None
computer['target_collector'].collect_anchor(anchor_name)
return anchor_name |
def f_to_c(f) -> float:
"""Converts Fahrenheit degrees to Celsius degrees."""
return (f - 32) * 5/9 |
def fixDelex(filename, data, data2, idx, idx_acts):
"""Given system dialogue acts fix automatic delexicalization."""
try:
turn = data2[filename.strip('.json')][str(idx_acts)]
except:
return data
if not isinstance(turn, str): # and not isinstance(turn, unicode):
for k, act in tu... |
def cluster_length_to_bin(len_list, num):
"""compute bin bound
"""
avg_bin_len = len(len_list) // num
sort_list = sorted(len_list)
bin_bound = []
for i in range(num):
if i == (num - 1):
bin_bound.append((sort_list[i * avg_bin_len], 1e5))
else:
bin_bound... |
def is_active(instance):
"""
:param instance: a nova instance,normally is a dict
"""
if isinstance(instance, dict):
return instance['server']['status'] == 'ACTIVE' \
if "server" in instance.keys() \
else instance['status'] == "ACTIVE"
else:
return False |
def get_error_codes(err_code_file):
"""Function to retrieve all block numbers from the `run-tests-codes.sh`
file to maintain backwards compatibility with the `run-tests-jenkins`
script"""
with open(err_code_file, 'r') as f:
err_codes = [e.split()[1].strip().split('=')
for e... |
def pairs_to_dict(items: list) -> dict:
"""Example: ['MESSAGES', '3', 'UIDNEXT', '4'] -> {'MESSAGES': '3', 'UIDNEXT': '4'}"""
if len(items) % 2 != 0:
raise ValueError('An even-length array is expected')
return dict((items[i * 2], items[i * 2 + 1]) for i in range(len(items) // 2)) |
def position_to_variant_id(
chromosome: str, position: int, ref_allele: str, alt_allele: str
) -> str:
"""EPACTS-format variant ID, with human-readable comma delimiters"""
return f"{chromosome}:{position:,}_{ref_allele}/{alt_allele}" |
def block_cyclic_size(dim_data):
""" Get a size from a block-cyclic dim_data. """
global_size = dim_data['size']
block_size = dim_data.get('block_size', 1)
grid_size = dim_data.get('proc_grid_size', 1)
grid_rank = dim_data.get('proc_grid_rank', 0)
global_nblocks, partial = divmod(global_size, b... |
def _identify_bool_attributes_with_defaults(
attributes, attr_name, attr_value, default=True
):
"""For boolean attributes that have default values in the ONNX specification
checks to see if they are present in `attributes`, and assigns the
default if not present and appropriate value if present. Note `a... |
def get_request_path(environ: dict) -> str:
"""
Returns a path part of the HTTP request.
:param environ: WSGI environment
:return: request path
"""
path = environ["PATH_INFO"]
return path |
def shortText(a,b):
"""Returns a short portion of the text that shows the first difference
a: the first text element
b: the second text element
"""
a = repr(a)
b = repr(b)
displayLen = 20
halfDisplay = displayLen//2
if len(a)+len(b) < displayLen:
return a+" "+b
firstDiff = -1
i = 0
while i <... |
def to_text(value, encoding='utf-8', errors='ignore'):
"""Convert value to unicode, default encoding is utf-8
:param value: Value to be converted
:param encoding: Desired encoding
"""
if not value:
return ''
if isinstance(value, str):
return value
if isinstance(value, bytes)... |
def files_with_suffix(files, suffix):
"""Filter files with given suffix."""
return [f for f in files if f.endswith(suffix)] |
def _unpack_tuples(my_list):
"""Convert from a list of tuples containing one string each to
simply a list of strings.
"""
results_processed = [tup[0] for tup in my_list]
return results_processed |
def get_adjacent_line_number(segment_number, i):
"""
Returns the next segment number + i.
Segment numbers have the form "pN.sM", where N/M are positive integers.
"""
split = segment_number.split('s')
adj = int(split[1]) + i
return split[0] + 's' + str(adj) |
def getDigit(num, n, base=10):
"""
return nth least-significant digit of integer num (n=0 returns ones place)
in specified base
"""
return int(num / base**n) % base |
def I2(Q,dfg):
"""
Computes the I^2 value, ie, percent of variation due to heterogeneity rather than chance
By convention, Q = 0 if Q < k-1, so that the precision of a random effects summary estimate
will not exceed the precision of a fixed effect summary estimate
See Higgins & Thompson 2002; DOI: 1... |
def size_of(num, suffix='B'):
"""
Generates human readable file sizes. Accepts a value then returns a human readable file size in a string variable
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1... |
def linear_decay(now_step, total_step, final_value):
"""linear decay scheduler"""
decay = (1 - final_value) / total_step
return max(final_value, 1 - decay * now_step) |
def get_mrns_from_database(results):
"""Accepts json request and posts new patient heart rate
to server database.
Method curated by Braden Garrison
json request should contain a dict formatted as follows:
{
"patient_id": int, # Should be patient MRN
"heart_rate_average_since": str ... |
def get_major_versions(versions):
"""
Return only the major version (i.e x.0.0)
:param versions: A list of valid semver strings.
"""
majors = []
for version in versions:
major, minor, patch = version.split('.')
if minor == '0' and patch == '0':
majors.append(version... |
def hyphenate(value, arg):
"""Concatenate value and arg with hyphens as separator, if neither is empty"""
return "-".join(filter(None, [str(value), str(arg)])) |
def azimu_half(degrees: float) -> float:
"""
Transform azimuth from 180-360 range to range 0-180.
:param degrees: Degrees in range 0 - 360
:return: Degrees in range 0 - 180
"""
if degrees >= 180:
degrees = degrees - 180
return degrees |
def size_in_bytes(n):
""" Convert to human readable bytes size K,M,G, etc
>>> size_in_bytes(123)
'123B'
>>> size_in_bytes(1234)
'1.2K'
>>> size_in_bytes(1280)
'1.3K'
>>> size_in_bytes(12345)
' 12K'
>>> size_in_bytes(123888)
'124K'
... |
def TailSet(start_point, listing):
"""Returns set of object name tails.
Tails can be compared between source and dest, past the point at which the
command was done. For example if test ran {cp,mv,rsync}
gs://bucket1/dir gs://bucket2/dir2, the tails for listings from bucket1
would start after "dir", while the... |
def get_bond_payout(bond_price, market_value_asset):
"""
Arguments
---------
ohm_price: The price of the bond in USD.
market_value_asset: The market value in USD of the assets used to pay for
the bond.
Returns
-------
bond_payout: The number of OHMs sold to a bon... |
def analyze_connectivity(map_, key):
"""Analyze the connectivity of a given map using the key value.
:param map: map to analyze
:type map: dict
:param key: key value
:type key: str
:return: list of connected values to the key
:rtype: list
"""
clist = []
keys = [key]
wh... |
def find_slack_handle(socials: dict):
"""Search social media values for slack
:param socials:
:return:
"""
if 'slack' in socials:
return socials['slack']
else:
return 'marty331' |
def _remove_nulls(managed_clusters):
"""
Remove some often-empty fields from a list of ManagedClusters, so the JSON representation
doesn't contain distracting null fields.
This works around a quirk of the SDK for python behavior. These fields are not sent
by the server, but get recreated by the CLI... |
def quintic_ease_in(p):
"""Modeled after the quintic y = x^5"""
return p * p * p * p * p |
def num_examples_per_epoch(split):
"""Returns the number of examples in the data set.
Args:
split: name of the split, "train" or "validation".
Raises:
ValueError: if split name is incorrect.
Returns:
Number of example in the split.
"""
if split.lower().startswith('train'):
re... |
def _convertToBashStyle(strCommand):
"""
Strip escape windows chars for the command line
in the end they won't be used in a shell
the resulting command is bash/zh like
Args:
strCommand (str): command generated by mkvtoolnix-gui
Returns:
str:
cli command converted to ba... |
def _get_google_project_ids_from_service_accounts(registered_service_accounts):
"""
Return a set of just the google project ids that have registered
service accounts.
"""
google_projects = set([sa.google_project_id for sa in registered_service_accounts])
return google_projects |
def makeFullName(parScope, parName):
""" Create the fully-qualified name (inclues scope if used) """
# Skip scope (and leading dot) if no scope, even in cases where scope
# IS used for other pars in the same task.
if parScope:
return parScope+'.'+parName
else:
return parName |
def to(*items, **kwargs):
"""call `.to()` on all items that have a `to()` method, skips ones that don't"""
return tuple(x.to(**kwargs) if hasattr(x, 'to') else x for x in items) |
def tokenize_chinese_chars(text):
"""Adds whitespace around any CJK character."""
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Uni... |
def is_numeric(value):
"""
Check if a var is a single element
:param value:
:return:
"""
return isinstance(value, (int, float)) |
def extract_description(page, default=None):
""" Extracts civil case description. Usually it is used for a docket """
_page = page.upper()
desc = None
for _m in ('PERSONAL INJURY/PROPERTY DAMAGE - NON-VEHICLE', 'PERSONAL INJURY/PROPERTY DAMAGE', 'PROPERTY DAMAGE - NON-VEHICLE',
'PERS... |
def clean_dict(source, keys=[], values=[]):
"""Removes given keys and values from dictionary.
:param dict source:
:param iterable keys:
:param iterable values:
:return dict:
"""
dict_data = {}
for key, value in source.items():
if (key not in keys) and (value not in values):
... |
def create_body_dict(name, schema):
""" Create a body description from the name and the schema."""
body_dict = {}
if schema:
body_dict['in'] = 'body'
body_dict['name'] = name
body_dict['schema'] = schema
if 'description' in schema:
body_dict['description'] = schem... |
def string_cleaning(entity):
"""Handle punctuations and tokenizes entity string.
Removes punctuation characters from the string and performs
string tokenization.
Args:
entity: A string.
Returns:
A list of string tokens, without any punctuation,
based on the input string.
... |
def check_if_package_exists(package, packages):
"""Check if a package exist in the given packages
If packages is equals to False then return always True because it means
that the user did not provide packages to specify from which packages
wants to find new versions.
Returns:
bool
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.