content stringlengths 42 6.51k |
|---|
def linear_sieve(max_n):
"""Computes all primes < max_n and lits of
all smallest factors in O(max_n) time
Returns
-------
primes: list of all primes < max_n
smallest_factors: list such that if q = smallest_factors[n],
then n % q == 0 and q is minimal.
"""
smallest_factors = [0] ... |
def eval_if_exist_else_none(name, global_symbol_table):
"""
Args:
name([str]): Expression passed into `eval`.
local_symbol_table(dict): Specified from `globals()`. DO NOT use `locals()`,
because all STATIC_CONVERT_VAR_SHAPE_SUFFIX vars is
... |
def flatten(xs):
"""Flatten list of lists to a list."""
return sum(xs, []) |
def __convert_sec_to_time(seconds):
"""Convert sec to time format"""
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return hour, minutes, seconds |
def cell_id(i,j,k,nx,ny):
"""
Get the cell Id given i,j,k indexes.
* --- * --- * --- *
| 0,2 | 1,2 | 2,2 | <- Cell id 6,7,8
* --- * --- * --- *
| 0,1 | 1,1 | 2,1 | <- Cell id 3,4,5
* --- * --- * --- *
| 0,0 | 1,0 | 2,0 | <- Cell id 0,1,... |
def set_publish_logistic_regression_args(args):
"""Set args to publish logistic regression
"""
public_logistic_regression = {}
if args.public_logistic_regression:
public_logistic_regression = {"private": False}
if args.model_price:
public_logistic_regression.update(price=arg... |
def calc_position(dimension, distance):
"""
Define a function to calculate the ratio of the solid's dimension to the distance.
:param dimension: The dimension that we're interested in
:param distance: The distance to the face of the solid.
:return:
"""
return dimension / 2 / distance |
def hex2bytes(hex_str):
"""
Converts spaced hexadecimal string (output of ``bytes2hex()``) function to an array of bytes.
Parameters
----------
hex_str: str
String of hexadecimal numbers separated by spaces.
Returns
-------
bytes
Array of bytes (ready to be unpicked).
... |
def convert_content_type_to_extension(content_type):
"""Convert image extension to Content-Type
Args:
content_type: Content-Type
Returns:
str: extension
"""
if content_type == "image/jpeg":
extension = "jpg"
elif content_type == "image/png":
extension = "png"
e... |
def GetShortAmountOfBeer(amount):
"""Returns a shortened string for an volume in cL."""
if amount >= 999.5:
return 'DED'
if amount >= 99.5:
return '{0:>3d}'.format(int(round(amount)))
return '{0:3.2g}'.format(amount) |
def getAttr(argAttrName, argAttrs):
"""Extract and return the value of a particular attribute from a list
of (attributeName, attributeValue) pairs. If the attribute does
not exist in the list, return None.
"""
for attr in argAttrs:
if attr[0] == argAttrName: return attr[1]
return None |
def to_pascal_case(s):
"""
Converts snake_case to PascalCase
"""
parts = s.split('_')
return ''.join([x.title() for x in parts]) |
def _find(seq, val):
"""
Search sequence 'seq' for val. This behaves like str.find(): if not found,
-1 is returned instead of throwing an exception.
Args:
seq: The sequence to search
val: The value to search for
Returns:
int: The index of the value if found, or -1 if not f... |
def encode_ber(value, ber_length=0):
"""
Encodes an integer to BER
The length of the encoded BER value (in bytes) can be optionally specified
"""
if not ber_length:
if value < 127:
return [value]
elif value < 256:
ber_length = 2
elif value < 256 * 256:... |
def removeprefix(s: str, prefix: str, ignore_case: bool = False) -> str:
"""Replacement for str.removeprefix() (Py3.9+) with ignore_case option."""
if ignore_case:
if not s.lower().startswith(prefix.lower()):
return s
else:
if not s.startswith(prefix):
return s
re... |
def sec2msec(sec):
"""Convert `sec` to milliseconds."""
return int(sec * 1000) |
def generate_hasura_error_payload(error_message, error_code):
"""
Generate a standard error payload for Hasura.
Ref: https://hasura.io/docs/latest/graphql/core/actions/action-handlers.html
**Parameters**
``error_message``
Error message to be returned
``error_code``
Error code ... |
def RenamePredicate(e, old_name, new_name):
"""Renames predicate in a syntax tree."""
renames_count = 0
if isinstance(e, dict):
if 'predicate_name' in e and e['predicate_name'] == old_name:
e['predicate_name'] = new_name
renames_count += 1
# Field names are treated as predicate names for funct... |
def invert(n, p):
"""Compute inverse mod p."""
if n % p == 0:
raise ZeroDivisionError()
a = n, 1, 0
b = p, 0, 1
while b[0]:
q = a[0] // b[0]
a = a[0] - q*b[0], a[1] - q*b[1], a[2] - q*b[2]
b, a = a, b
assert abs(a[0]) == 1
return a[1]*a[0] |
def ranktofar(rankine):
""" This function converts Rankine to fahrenheit, with Rankine as parameter."""
fahrenheit = rankine - 459.67
return fahrenheit |
def matrix_divided(matrix, div):
"""Divides all elements in the matrix by div"""
if type(matrix) is not list:
raise TypeError(
"matrix must be a matrix (list of lists) of integers/floats")
size = None
for l in matrix:
if type(l) is not list:
raise TypeError(
... |
def flatten_list(list_obj):
"""
flatten array objects.
:param list_obj:
:return:
"""
return tuple([item for sublist in list_obj for item in sublist]) |
def varReplacements(tex, keyString):
"""
Convert every VAR/VARTH macro with the bolded argument string
(.I <argument>).
-- Special consideration to any periods after the macro, since a
period at the beginning of a line denotes a comment and the
entire line will not appear.
(.IR <argument>... |
def combine_edgesets(edgesets):
"""
Takes a collection of sets of edges and returns their union.
The return type is a Python set, and thus unordered.
:param edgesets: collection of sets of edges
:return: a set of edges covered by all sets given
"""
return set().union(*edgesets) |
def Color(red, green, blue, white=0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (red << 16)| (green << 8) | blue |
def enableDisableEquipment(enable, names):
"""Enables or disables a Tuple of equipment connections from a
script.
Args:
enable (bool): Set to True to enable equipment connections, or
set to False to disable them.
names (tuple[str]): A Tuple of Strings. Each String should match
... |
def make_string(seq):
"""
Don't throw an exception when given an out of range character.
"""
# todo: this can be done way more efficiently!!
new_string = ''
for c in seq:
# Screen out non-printing characters
if 32 <= c < 256:
new_string += chr(c)
# If no p... |
def frequency_analysis(most_frequent_letters: list,
most_frequent_count: int) -> str:
"""
analysis of the data in human-readable form
:param most_frequent_letters: the most frequent letters
:param most_frequent_count: the most frequent count
:return: string
"""
letter... |
def extract_task_ids(project_data):
"""
Extract from project data the list of task id
:param project_data: Dictionary of project data of a HOT tasking manager project
:return:
"""
tasks_ids = list()
for feature in project_data['tasks']['features']:
tasks_ids.append(feature['propertie... |
def calculate_confidence(inspected, expected, percentage):
"""
Generate a confidence value possibly confirming or denying data parity.
A positive return value indicates the amount of bytes past the confidence
interval. A negative value indicates the missing amount required to pass.
Args:
i... |
def escape_html(s: str)-> str:
"""
Escape html
:param str s: string
:return: replaced html-string
"""
s = s.replace('&','&')
s = s.replace('<','<')
s = s.replace( '>','>')
s = s.replace('"','"')
s = s.replace("'", ''')
return s |
def check_for_empty_tasks(task_assignments):
"""Convenience function that checks for empty processor/MPI worker
assignments.
Args:
``task_assignments``: List of task assignments.
Returns:
``empty_tasks``: ``True`` if any processor/MPI worker has no tasks,
otherwise ``False``.
... |
def _solve_method_1(magazine, note):
"""This method works on small inputs but produced a timeout. It doesn't
use dictionaries ironically."""
magazine = magazine.split()
note = note.split()
for w in note:
if not w in magazine:
return False
else:
magazine.remo... |
def dict_element_of_list(my_dict_list, dict):
""" description:
Check if <dict> is part of dict list <my_dict_list>
usage:
ui_utils.dict_element_of_list(my_dict_list, dict)
tags:
ui, android, helper, dict, list
"""
for el in my_dict_list:
eq = Tru... |
def get_raw_base_qual(alignment: bytes,
len_read_name: int,
number_cigar_operations: int,
len_sequence: int, ) -> bytes:
"""Extract the raw base qualities from a BAM alignment bytestring
Parameters
----------
alignment : bytes
A ... |
def list_distinct(l):
"""Return a the distinct version of the input list, perserve order
"""
uniq_list = []
seen = set()
for x in l:
if x not in seen:
seen.add(x)
uniq_list.append(x)
return uniq_list |
def month_name(value):
"""Return month name for a month number."""
from calendar import month_name
return month_name[value] |
def format_name(name):
""" Konwertuje z 'Imie Nazwisko' na 'imie.nazwisko' """
return name.replace(' ', '.').lower() |
def cli_env(tracking_server_uri):
"""Provides an environment for the MLflow CLI pointed at the local tracking server."""
cli_env = {
"LC_ALL": "en_US.UTF-8",
"LANG": "en_US.UTF-8",
"MLFLOW_TRACKING_URI": tracking_server_uri,
}
return cli_env |
def map_bin(x, bins, na_bin):
"""
Initializes CategoricalBin objects in Pandas Series
cache is used to prevent duplicates
:param x: feature value
:param bins: bins object
:param na_bin: bin object to fill NA values
:return: dict of bin's share and target rate
"""
for b in bins:
... |
def get_mesh_index(glTF, name):
"""
Return the mesh index in the glTF array.
"""
if glTF.get('meshes') is None:
return -1
index = 0
for mesh in glTF['meshes']:
if mesh['name'] == name:
return index
index += 1
return -1 |
def get_concepts(gt_concepts, ex_index, num_samples):
""" Given [(gt_concept, start_i, end_i)...]
Return the ground truth occuring at a given index."""
gt_concept = None
for gt_c, s_i, e_i in gt_concepts:
if s_i <= ex_index < e_i:
gt_concept = gt_c
break
return (... |
def standardize_sizes(sizes):
"""
Removes trailing ones from a list.
Parameters
----------
sizes: List
A list of integers.
"""
while (sizes[-1] == 1) and len(sizes)>2:
sizes = sizes[0:-1]
return sizes |
def printnum(num, total=6, after=2):
"""prints a number with after digits after the decimal point and
taking up total spaces. Padded on the front if need be"""
formstr = "%." + str(after) + "f"
new = formstr % num
return (total - len(new)) * ' ' + new |
def add_address(x, y):
"""Returns a string representation of the sum of the two parameters.
x is a hex string address that can be converted to an int.
y is an int.
"""
return "{0:08X}".format(int(x, 16) + y) |
def sign(x):
""" Returns the sign of float x.
"""
if abs(x) == x:
return 1.
else:
return -1. |
def select_anno(annotations):
"""
Description
-----------
Function to assign the hierarchically right choice of annotation
Parameters
----------
annotations : list, List of annotations to choose the preferred one
Returns
-------
STR, The preferred annotation
"""
if ... |
def distance(begin, destination, graph, weight, weightCounts):
"""Deze functie berekent de afstand tussen 2 vertex.Wanneer weightCounts True is
houd hij de Heuristiek ook rekening met het gewicht van de paketten om zo brandstof te besparen"""
if weightCounts:
totalWeigt = sum(weight)
package... |
def get_rpm_properties(input_file: str):
"""
Summary:
processes the structured name of the rpm file to get the
arch, release, version, and name
Parameters:
input_file (str): the file
Returns:
dictionary containing arch, release, version, and name
"""
#get prope... |
def brillance(p, g, m = 255):
"""
p < 0 : diminution de la brillance
p > 0 : augmentation de la brillance
"""
if (p + g < m + 1) and (p + g > 0):
return int(p + g)
elif p + g <= 0:
return 0
else:
return m |
def list_to_comma_string(val, file_format):
"""
Handle array fields by converting them to a comma-separated string.
Example:
['1','2','3'] -> 1,2,3
"""
if val is None:
# If a field is empty we must replace it with an empty string for tsv/csv exports and leave it as None for json ex... |
def polyval(p, x):
""" Takes a sequence p representing a polynomial and a number x and
returns the value of p at x. This version is Numba-compatible; NumPy's
version is not. """
val = 0
ii = len(p) - 1
for i in range(len(p) - 1):
val += p[i] * (x ** ii)
ii -= 1
... |
def calculate_interest_years(starting_amount, requested_amount, interest_rate, stipend_rate):
"""
If I want X in the bank, how long will it take?
:param starting_amount: The amount of money the bank has to start with.
:type starting_amount: double
:param requested_amount: The amount requested in the... |
def PolygonArea(corners):
"""
Area of polygon given a list of vertices
This result is due to a nifty theorem often called the Shoelace Theorem!
"""
n = len(corners) # of corners
area = 0.0
for i in range(n):
j = (i + 1) % n
area += corners[i][0] * corners[j][1]
area -... |
def make_dictionary(duration, voltage_extremes, num_beats, mean_hr_bpm, beats):
"""This function returns a dictionary of ECG metric data
This function makes a dictionary containing all of the ECG metric data,
which is passed into the function as the function's input parameters.
Args:
duration ... |
def process_confidence_threshold(netblock_list, threshold):
"""Returns results that are greater than given threshold.
Args:
netblock_list: A list of netblocks with identifying information.
threshold: The threshold at which confidence scores lower than
this number should be exc... |
def get_blue_green_from_app(app):
"""
Returns the blue_green object if exists and it's color field if exists
>>> get_blue_green_from_app({})
(None, None)
>>> get_blue_green_from_app({'blue_green': None})
(None, None)
>>> get_blue_green_from_app({'blue_green': {}})
(None, None)
>>... |
def in_permissions(permissions, value):
"""
Given a permissions mask, check if the specified permission value is within those permissions.
:param permissions: permissions set as integer mask
:param value: permission value to look for
:type permissions: int
:type value: int
:return: is val... |
def validate_password(password):
"""Validate user password value."""
errors = []
if not isinstance(password, str):
errors.append("Password must be string type.")
return errors
if len(password) < 8:
errors.append("Password must have minimum 8 characters.")
password_chars = se... |
def _isIPv6Addr(strIPv6Addr):
"""Confirm whether the specified address is an IPv6 address.
:param str strIPv6Addr: IPv6 address string that adopted the full
represented.
:return: True when the specified address is an IPv6 address.
:rtype: bool
Example::
strIPv6Addr ... |
def Ignore_Long_Sentence(tokenized_sentence, max_tokens):
"""
Determines if tokenized_sentence should be ignored, if it has more than max_tokens
"""
if len(tokenized_sentence) > max_tokens:
return True
else:
return False |
def parse_coverage_list(coverage_list):
"""
Given a coverage_list (structured as a list of coverage statements (which
are strings) that define the poset, parses them into a dictionary.
Parameters
----------
coverage_list : `list`
list of coverage statements defining a poset, e.g.:
... |
def get_oxygen(data, index=0):
"""
Determines the oxygen rating by recursively removing all values with the least sum per bit for each bit.
:param data: Array of binary numbers as Stings.
:param index: Starting index for the recursion.
:return: The last remaining binary number of the complete input... |
def get_main_entity_from_question(question_object):
"""
Retrieve the main Freebase entity linked in the url field
:param question_object: A question encoded as a Json object
:return: A list of answers as strings
>>> get_main_entity_from_question({"url": "http://www.freebase.com/view/en/natalie_port... |
def parse_slice(slice_string):
"""
Parse a slice given as a string.
Parameters
----------
slice_string : str
String describing the slice. Format as in fancy indexing: 'start:stop:end'.
Returns
-------
slice
Examples
--------
Everything supported in fancy index... |
def _safe_division(numerator, denominator):
"""Returns none if you'd get a ZeroDivisionError else divides"""
if denominator == 0:
return None
return numerator / denominator |
def enforce_shell_extension_security(on=0):
"""Forcar Seguranca nas Extensoes Shell
DESCRIPTION
Esta restricao pode ser usada para limitar o sistema a somente executar
arquivos que tem uma extensao shell aprovada.
COMPATIBILITY
Todos.
MODIFIED VALUES
Enfor... |
def request_headers(auth_token):
"""Return request headers using the provided authorization token."""
headers = {
"Accept": "application/vnd.heroku+json; version=3",
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(auth_token),
}
return headers |
def listify(x):
"""
Returns [] if x is None, a single-item list consisting of x if x is a str or bytes, otherwise returns x.
listify(None) -> []
listify("string") -> ["string"]
listify(b"bytes") -> [b"bytes"]
listify(["foo", "bar"]) -> ["foo", "bar"]
:param x: What to listify.
:return:... |
def split_jaspar_id(id):
"""
Utility function to split a JASPAR matrix ID into its component base ID
and version number, e.g. 'MA0047.2' is returned as ('MA0047', 2).
"""
id_split = id.split('.')
base_id = None
version = None
if len(id_split) == 2:
base_id = id_split[0]
... |
def compress(num: int) -> bytearray:
"""
Compresses a integer into a variable integer inside a bytearray.
:param num: The integer to compress.
:return: A bytearray containing the variable integer.
"""
sign = num < 0
out = bytearray(1)
if sign:
# Swap all bits.
num = ~nu... |
def find_start_end(grid):
"""
Finds the source and destination block indexes from the list.
Args
grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf)
Returns
start: <int> source block index in the list
end: <int> destination block index... |
def Convert2mAhg(c, mass=1.0):
"""Converts capacity in Ah to capacity in mAh/g.
Args:
c (float or numpy array): capacity in mA.
mass (float): mass in mg.
Returns:
float: 1000000 * c / mass
"""
return 1_000_000 * c / mass |
def find_key_endswith(arg_list, key, value):
"""Checks '--key prefix_<value>' is in arg_list."""
for i in range(len(arg_list)):
if arg_list[i] == key and arg_list[i + 1].endswith(value):
return True
return False |
def latest(scores):
"""
Get the most recent score.
:param scores list - List of scores
:return int - Most recent score.
"""
return scores[len(scores) - 1] |
def _concatenate(*elements):
"""Concatenates all arguments with no delimiters."""
return ''.join(elements) |
def offset(offset, inArr):
"""offset column of data
Input:
- inMat, 1d numpy array with return True np.isnans()
Output:
- Mat with offset applied to column of data
Example:
>>> outArray = offset(offset, col, inMat)
"""
#for i in range(0, len(inArr)):
# inArr[i] = ... |
def _range_overlap(a_min: float, a_max: float, b_min: float, b_max: float) -> float:
"""Neither range is completely greater than the other
"""
return (a_min <= b_max) and (b_min <= a_max) |
def queryAnnotations(paths, startTime=None, endTime=None, types=None):
"""Queries user stored annotations from the tag history system for a
set of paths, for a given time range.
Args:
paths (list[str]): A list of tag paths to query. The paths are
equivalent to what would be used ofr a t... |
def map_utensils(materials):
"""
Get following material, if available
:param materials: list with checked materials, can be empty
:return: converted list with device names, e.g. TACX R--> trek-rad. Can be an empty string
"""
if len(materials) < 1:
return ""
return ", ".join(material... |
def no_save_settings(on=0):
"""Desabilitar Salvamento de Configuracoes ao Sair
DESCRIPTION
Quando o Windows e desligado, ele normalmente salva o layout do
Desktop, incluindo a localizacao dos icones, aparencia e outros parametros.
Este ajuste descarta quaisquer alteracoes feitas anter... |
def trim(src_str):
"""
It returns the trimmed value of the given string.
A string with null value is considered as an empty string.
"""
if not src_str:
return ""
# May not behave like java, their documentation is unclear what
# types of whitespace they strip..
return src_str.stri... |
def _add_thumb(s):
"""
Modifies a string (filename, URL) containing an image filename, to insert
'.thumb.jpg' at the end.
"""
return s + ".thumb.jpg" |
def _FormatHash(h):
"""Return a string representation of a hash.
The hash is a sha1 hash. It is computed both for files that need to be
pushed to App Engine and for data payloads of requests made to App Engine.
Args:
h: The hash
Returns:
The string representation of the hash.
"""
return '%s_%s_... |
def _EscapeForMacro(s):
"""Escapes a string for use as an argument to a C++ macro."""
paren_count = 0
for c in s:
if c == '(':
paren_count += 1
elif c == ')':
paren_count -= 1
elif c == ',' and paren_count == 0:
return '(' + s + ')'
return s |
def _link_attach_and_doi(
items: list, attach_key: str, parent_doi: dict,
on_no_dois: str = 'ignore') -> str:
"""
Matches given `attach_key` in `items` to corresponding DOI name
linked via parent ID in `parent_doi` dictionary.
Args:
items (list): List of Zotero items.
at... |
def line_to_position(reports, diff):
"""
The actual source file line number in report is different from what we need to send to github as review payload.
This function converts the clang-tidy generated error or warning line numbers to position in diff,
so that review can be made for position relevant t... |
def _parse_decision_node_line(line):
"""
Return feature index and threshold given the string representation of a decision node.
"""
substr = line[line.find('[') + 1: line.find(']')]
feature_str, border_str = substr.split('<')
feature_ndx = int(feature_str[1:])
border = float(border_str)
... |
def miles_to_kilometers(miles):
"""
Convert from units of miles to kilometers
PARAMETERS
----------
miles: float
A distance value in units of miles
RETURNS
-------
kilometers: float
A distance value in units of kilometers
"""
#convert miles to km:
return mil... |
def _multiindex(_, show, on, **kwargs):
"""
Multiindexing --- disabled currently
"""
if not show or len(show) < 2:
return True, False
return False, on |
def count_missing (vect):
"""Count the number of missing values in a vector;
missing values assumed to be 'NA'."""
return vect.count('NA') |
def bar1s(ep,ed):
"""
Compute element force in spring element (spring1e).
:param float ep: spring stiffness or analog quantity
:param list ed: element displacements [d0, d1]
:return float es: element force
"""
k = ep
return k*(ed[1]-ed[0]); |
def replace_X_end_month(month):
"""Find the latest legitimate month."""
month = month.lstrip('-')
if month == 'XX' or month == '1X':
return '12'
if month == 'X0':
return '10'
if month == '0X':
return '09'
if month[1] in ['1', '2']:
# 'X1' or 'X2'
return mo... |
def StripTypeInfo(rendered_data):
"""Strips type information from rendered data. Useful for debugging."""
if isinstance(rendered_data, (list, tuple)):
return [StripTypeInfo(d) for d in rendered_data]
elif isinstance(rendered_data, dict):
if "value" in rendered_data and "type" in rendered_data:
retu... |
def vdotw(v, w):
"""
Vector-vector dot product
"""
return sum(v[i] * w[i] for i in range(len(v))) |
def humanized_bytes(size, precision=2):
"""
Returns a humanized storage size string from bytes
"""
unit = ""
for x in ["", "KB", "MB", "GB", "TB"]:
if size < 1000.0:
unit = x
break
size /= 1000.0
return f"{size:.{precision}f} {unit}" |
def _token_to_int(t, token_list, token_cache, size_limit=float('inf')):
"""Return the int which represents a token, with caching.
Throws a ValueError if token t is not in the token_list. There MUST
be a _UNK token at the beginning of your vocab, or this may not halt.
"""
if t not in token_cache:
... |
def whitespace_tokenize(text):
"""
Runs basic whitespace cleaning and splitting on a piece of text.
:param text:
:return:
"""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens |
def priv_level_formatter(level):
"""Format privilege level"""
level = level.lower()
if level == "administrator":
level = "admin"
return level |
def get_iso_format(date):
"""Convert the date (a DateTime object from DB, or NULL) to ISO format YYYY-MM-DD HH:MM:SS."""
if date:
return date.strftime('%Y-%m-%d %H:%M:%S') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.