content stringlengths 42 6.51k |
|---|
def _index_by_primary_key(rows):
"""Return a dict of Rows indexed by the primary key."""
result = {}
for row in rows:
result[row.primary_key_value()] = row
return result |
def bound(index, l):
""" Helper function to get valid index of list
"""
if index >= len(l):
return len(l) - 1
elif index < 0:
return 0
else:
return index |
def progress_identifier(level_progresses):
"""
>>> progress_identifier([(0, 1)])
'0-1'
>>> progress_identifier([(0, 1), (2, 4)])
'0-1|2-4'
"""
return '|'.join('%d-%d' % lvl for lvl in level_progresses) |
def reverse(str):
"""
:param str: string
:return a: string
"""
if len(str) == 0:
a = ""
else:
a = str[-1] + reverse(str[:-1])
return a |
def cal_fps(raw_trajs_frequent_pattern: dict, sd_trajs_frequent_pattern: dict) -> float:
"""
calculate FPS
Args:
raw_trajs_frequent_pattern: frequent patterns of the original trajectory
sd_trajs_frequent_pattern : frequent patterns that generate trajectories
Returns:
... |
def process_country(x):
"""
:return: <continent/country>, <continent>, <country>
"""
# China: Shenzhen
# USA: WA
raw = x.split(': ')
if len(raw) == 1:
raw = x.split(':')
if len(raw) == 1:
raw = x.split('/')
if len(raw) == 1:
country = raw[0]
city = 'Un... |
def double_quotes(quote_str: str) -> str:
"""single quote to double quote mark in the string"""
list_str = list(quote_str)
new_list = list()
for x in list_str:
if x != '\'':
new_list.append(x)
else:
new_list.extend(['\'', '\''])
return ''.join(new_list) |
def common_reverse_rule(args):
""" Inverse valid rule """
replace_args = {
# Append
"-A": "-D",
"--append": "--delete",
# Insert
"-I": "-D",
"--insert": "--delete",
# New chain
"-N": "-X",
"--new-chain": "--delete-chain",
}
ret_ar... |
def parse_int(string:str) -> int:
"""
A function to parse string characters into int
-> string: str => a string of chars, ex : "abc12a3"
----
=> int: numbers present inside the string passed in, ex : 123
"""
if not isinstance(string, str):
raise TypeError('string must be a string')
... |
def avg(*args):
"""Returns the average of list of numeric values."""
return sum(args) / len(args) |
def decideHost(i, j, n):
"""
i: Row index on the original matrix.
j: Column index on the original matrix.
n: Target size of the new matrix.
Returns the sub-matrix and new row/column index.
"""
h = 2 if i >= n else 0
h = h+1 if j >= n else h
ni = abs(n - i) if i >= n else i
nj = a... |
def _parse_is_sub_array_assignment(line):
"""
:param line: String line
:returns: True if the statment is a sub array assignment. False otherwise.
>>> line = 'Map(:,:,1) = [1 2 3];'
>>> _parse_is_sub_array_assignment(line)
True
"""
lhs = line.split(' = ')[0].strip()
if '(' in lhs:
... |
def ComputeJaccardSimilarity(words_A, words_B):
"""
Title: Scraping 10-Ks and 10-Qs for Alpha
Author: Lucy Wu
Date: 2018
Code version: 1.0
Availability: https://www.quantopian.com/posts/scraping-10-ks-and-10-qs-for-alpha
"""
words_intersect = len(words_A.intersection(words_B))
words_... |
def temporal_segmentation(segments, min_time):
""" Segments based on time distant points
Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points
min_time (int): minimum required time for segmentation
"""
final_segments = []
for segment in segments:
final_... |
def remove_indices(ignore_indices, mets_found, start_IPP, end_IPP, config):
"""
Remoces indices where there's overlap
"""
remove_indices = []
if len(ignore_indices) < 1 or mets_found < 1:
return start_IPP, end_IPP
for index_1 in range(len(ignore_indices[0])):
for index_2 ... |
def parse_hex(string):
"""Parse a string as a hexadecimal value."""
return int(string, 16) |
def _check_table_name(table_name, base_table_name):
"""
Checks if (table_name == (base_table_name + "n")) where n is an integer
:param table_name: str
:param base_table_name: str
:return: bool
"""
# Split of last part of table_name
split_table_name = table_name.split('_')
table = "_"... |
def __equalAreaLine(A,B,C,D):
""" Returns two points on the line of symmetrical areal displacement.
Replacing points B & C with any point E on this line
will result in a new line feature AED whose displacement from ABCD
is symmetrical, i.e. equal areal displacement on either side of the original lin... |
def is_directives_header(s: str) -> bool:
"""
Checks whether passed string is a cython header line.
Ex: '# cython: infer_types=True'
:param s: str
:return: bool
"""
s = s.lstrip()
if not s[0] == '#':
return False
s = s[1:].lstrip()
return s.startswith('cython:') |
def handle_missing(row):
"""Removes the Place column from a row if result was a DNF/DNP/DQ.
"""
if any(row[col] == 1 for col in ['IsDnf', 'IsDNP', 'IsDQ']):
row.pop('Place')
return row |
def is_tree(item):
"""
Check if an item is a tree
"""
return item == "#" |
def check_block_merge(blocks, chrom):
""" A test run of this function on hg19 / mm9 indicates that a straightforward
merge of consecutive blocks is not possible (due to varying gap sizes)
Hence, this function is deprecated / useless and left here just as a reminder
:param blocks:
:param chrom:
... |
def gpsDecimalToDMS(decimal, loc):
"""Returns a GPS coordinate in DMS format.
Keyword arguments:
decimal -- a real number containing the lat or lon
loc -- an array of strings representing lat or lon
-- must be one of ["S", "N"] or ["W", "E"]
"""
if decimal < 0:
latlonRef = loc[0... |
def diff(list1, list2):
"""
Returns the list of entries that are present in list1 but not
in list2.
Args:
list1 A list of elements
list2 Another list of elements
Returns:
A list of elements unique to list1
"""
diffed_list = []
for item in list1:
if item not in list2:
diffed_list.... |
def _get_unique_name(port_name, oid_group_name):
"""Returns a unique name based on the port and oid group name."""
return port_name + '_' + oid_group_name |
def runge_kutta(f, x, u, dt):
"""Fourth order Runge-Kutta integration.
Keyword arguments:
f -- vector function to integrate
x -- vector of states
u -- vector of inputs (constant for dt)
dt -- time for which to integrate
"""
half_dt = dt * 0.5
k1 = f(x, u)
k2 = f(x + half_dt * k1... |
def has_keys(data, keys):
"""
Check whether a dictionary has all the given keys.
Parameters
----------
data: dict
Input dictionary.
keys: list
Expected keys to be found in the dictionary
Returns
-------
res: bool
True if all the keys are found in the dict, false o... |
def replica_keyword(replica_count, mirror_count):
"""Replica volume can be created using `replica` or `mirror` keyword."""
if replica_count > 0:
return "replica"
if mirror_count > 0:
return "mirror"
return "" |
def proper_prefixes(word):
""" Return a list of nonempty proper prefixes of
the given word (sorted in increasing length). """
return [word[:i] for i in range(1, len(word))] |
def normalize_cpu_arch(arch_specifier: str) -> str:
"""Normalize the string used for the CPU kernel architecture.
Different systems will report the CPU architecture differently and many software
downloads will expect one or the other formats. This function allows us to have a
single location for being... |
def lovelace_to_ada(value):
""" Take a value in lovelace and returns in ADA (str) """
# Define units
K = 1000
M = 1000000
B = 1000000000
units = {
'no': 1,
'K': K,
'M': M,
'B': B
}
# Calculate ADA from lovelaces
ada_int = value//M
# Select the b... |
def get_num_threads(profileDict):
"""
Returns the number of threads used in the given profile
Args:
profileDict (dict): Dictionary of the JSON format of a MAP profile
"""
assert isinstance(profileDict, dict)
# Assume that the number of OpenMP threads is the same on all processes, so
... |
def snake_to_camel_case(snake_input, uppercamel=False):
"""
Converts snake_case to camelCase (or CamelCase if uppercamel is ``True``).
Inspired by https://codereview.stackexchange.com/questions/85311/transform-snake-case-to-camelcase
:param str snake_input: The input snake_case string to convert to cam... |
def seq_mult_scalar(a, s):
"""Returns a list of the products of s with the values in list a."""
prod_as = []
for n in a:
prod_as.append(n*s)
return prod_as |
def valid_values_from_metdata(metadata, feat_name):
""" collect distinct set of values according to the JSON metada file """
return {
k: v for k, v in enumerate(list(range(metadata[feat_name]['maxval']+1)))} |
def triangular(n: int) -> int:
"""
Triangular Number
Conditions:
1) n >= 0
:param n: non-negative integer
:return: nth triangular number
"""
if not n >= 0:
raise ValueError
return n*(n+1)//2 |
def makeIntervals(evts):
"""From evts=[a,b,c], create a list of intervals: [(0,a), (b,c)]
From evts=[a,b,c,d], create a list of intervals: [(0,a), (b,c), (d,1)].
Assumes all values in evts are in (0,1)"""
if evts == []: return [(0.0, 1.0)]
evts.sort()
left = 0.0
intervals = []
for e in evts:
if left >= 0.0:
... |
def _value(ch, charset):
"""Decodes an individual digit of a base62 encoded string."""
try:
return charset.index(ch)
except ValueError:
raise ValueError("base62: Invalid character (%s)" % ch) |
def normalized_to_microseconds(normalized_setpoint: float, low: int, center: int, high: int) -> int:
"""
Converts a normalized setpoint (between -1.0 and 1.0) to a pulse width (in microseconds).
Positive and negative values are computed separately, as they can span different intervals in terms of pulse wid... |
def strtime(time):
"""Takes a number of seconds; returns a formatted duration string"""
years, days, hours, mins = 0, 0, 0, 0
timestr = ""
if time > 31536000:
years = int(time / 31536000)
time = time - (31536000 * years)
if time > 86400:
days = int(time / 86400)
time ... |
def pick_rarifaction_level(id_, lookups):
"""Determine which lookup has the appropriate key
id_ is a barcode, e.g., '000001000'
lookups is a list of tuples, e.g., [('10k',{'000001000':'000001000.123'})]
The order of the lookups matters. The first lookup found with the key will
be returned.
No... |
def pad(data: bytes, size: int, value: int = 0) -> bytes:
"""Padds given data with given value until its length is not multiple by size
Parameters:
data: bytes
Data to pad
size: int
Required size data length must be multiple to
value: int
Va... |
def basename(path: str) -> str:
"""
get '17asdfasdf2d_0_0.jpg' from 'train_folder/train/o/17asdfasdf2d_0_0.jpg
Args:
path (str): [description]
Returns:
str: [description]
"""
return path.split("/")[-1] |
def idealPalindrome(n):
"""Generates an array of length n with the character '9'"""
return ['9'] * n |
def find_eq_letters(chain_info, letter):
"""
Find chain letters with the same chain description
Parameters
----------
chain_info : dict
keys are chain descriptions and values are lists of letters
corresponding to that chain description
letter : string
letter whose equiva... |
def add_comma(integer):
"""E.g., 1234567 -> 1,234,567
"""
integer = int(integer)
if integer >= 1000:
return str(integer // 1000) + ',' + str(integer % 1000)
else:
return str(integer) |
def parse_pull_request_url(url: str):
"""
Parse the PR url to get the repo's owner, name and the pull request number.
:param url: The url of the pull request.
:return: A tuple with the repo's owner, name and the pull request number.
"""
owner, name, pr_number = '', '', ''
url_parts = url.sp... |
def fix_input_layer_shape(shape):
"""
tf.keras.models.load_model function introduced a bug that wraps the input
tensors and shapes in a single-entry list, i.e.
output_shape == [(None, 1, 28, 28)]. Thus we have to apply [0] here.
"""
if len(shape) == 1:
return shape[0]
return shape |
def is_affected(field):
"""field would be ["[one", "two", "three]"] if affected"""
if not isinstance(field, list):
return False
return any('[' in entry for entry in field) |
def calc_rms (values):
"""
calculate a root-mean-squared metric for a list of float values
"""
#return math.sqrt(sum([x**2.0 for x in values])) / float(len(values))
# take the max() which works fine
return max(values) |
def compute(string):
""" Simple Calculator.
Supports basic operators and floating point numbers
"""
values = string.split(' ')
num0 = float(values[0])
num1 = float(values[2])
operator = values[1]
if operator == '+':
return num0 + num1
elif operator == "-":
return num0... |
def varName(p, name_space = None):
"""
LEGACY CODE. Use file_management.nameof instead
Return name of the variable as a string
p: variable of any type
name_space: namespace of the variable to use
NOTE: must specify name_space = globals() when calling the function, should not be omitted
... |
def add_to_dict(d, key, base):
"""Function to add key to dictionary, either add base or start with base"""
if key in d:
d[key] += base
else:
d[key] = base
return d |
def min_dtuple(d1, d2):
"""return (min(d1_i, d2_i), ...)."""
d1_dict = dict(d1)
result = {}
for gen, exp in d2:
if gen in d1_dict:
result[gen] = min(exp, d1_dict[gen])
return tuple(sorted(result.items())) |
def _csv_dict_row(user, mode, **kwargs):
"""
Convenience method to create dicts to pass to csv_import
"""
csv_dict_row = dict(kwargs)
csv_dict_row['user'] = user
csv_dict_row['mode'] = mode
return csv_dict_row |
def page_not_found(e):
"""Return a custom 500 error."""
return 'Sorry, unexpected error: {}'.format(e), 500 |
def backward_substitution(matrix_u, matrix_y):
""" Backward substitution method for the solution of linear systems.
Solves the equation :math:`Ux = y` using backward substitution method
where :math:`U` is a upper triangular matrix and :math:`y` is a column matrix.
:param matrix_u: U, upper triangular ... |
def get_user_name(handle):
"""Returns the user name of the user executing the command, given 'handle'."""
return handle['user'] |
def qsify(_dict):
"""
converts a dict into a query string:
{{my_dict|qsify}}
"""
qs = '?'
try:
iterator = _dict.iterlists()
except AttributeError:
iterator = iter(list(_dict.items()))
for key, value in iterator:
if isinstance(value, list):
for v in v... |
def smart_division(a, b):
"""Not a really smart division, but avoid
to have ZeroDivisionError"""
try:
return float(a) / float(b)
except ZeroDivisionError:
return 0.0 |
def getFoodStores(food_id):
"""
#
---
GET method
pake path berupa id-nya food
"""
# Initialize data
data = {}
# Use Google Maps API for search store (Places)
# Refer to the docs here
# Set up console : https://developers.google.com/maps/documentation/places/web-service/cloud-s... |
def count_words(comment: str) -> int:
"""
Count how many words there are in a comment.
Args:
comment: The comment whose length to check.
Returns:
The number of words in the comment.
"""
return len(comment.split()) |
def p_(*args):
"""Get the name of tensor with the prefix (layer name) and variable name(s)."""
return '_'.join(str(arg) for arg in args) |
def class_ref(cls):
"""
Get Sphinx reference to a class
"""
return ":class:`~%s`" % (
cls.__module__ + '.' + cls.__name__
) |
def convertToIndexList(vertList):
""" convert components given to a list of indices
:param vertList: list of components
:type vertList: list
:return: list of integers representing the components values
:rtype: list
"""
indices = []
for i in vertList:
index = int(i[i.in... |
def pe48(limit=1000):
"""
>>> pe48()
9110846700
"""
s = 0
for i in range(1, limit+1):
s += i**i
return s % (10**10) |
def correct_barcodes_cutoff(barcodes_dict, cutoff=10):
"""
fillters keys,values from barcode dictionary where the number of reads
in the key is less than the cutoff
:param barcodes_dict:
:param cutoff:
:return:
"""
# output dict
error_corrected_barcode_dict = dict()
for k, v in... |
def _yql_queryMock(yql): # pylint: disable=invalid-name
"""Mock yahoo query language query."""
return ('{"query": {"count": 1, "created": "2017-11-17T13:40:47Z", '
'"lang": "en-US", "results": {"place": {"woeid": "23511632"}}}}') |
def cython_type_name(type_info):
"""Given a type instance parsed from ast, return the right python type"""
# print(type_info)
if type_info is None:
return "void"
ret = type_info.name
if type_info.templated_types:
return "{}<{}>".format(ret, cython_type_name(type_info.templated_types[... |
def popcount(n: int) -> int:
"""
Examples:
>>> popcount(0b1010)
2
>>> popcount(0b1100100)
3
>>> popcount(-1)
64
"""
n -= (n >> 1) & 0x5555555555555555
n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333)
n = (n + (n >> 4)) & 0x0F0F0F0F0F0... |
def _statistic_refine(statistic):
"""
Picking ingredients in order and count occur time of each sequence,
sequence are view as same if sequence == reversed sequence
"""
refined_statistic = {}
for key, value in statistic.items():
seq = list(key)
reversed_seq = seq.copy()
... |
def _search_line_for_cmd_start(line: str, start: int, valid_commands: dict) -> int:
"""Scan `line` for a string matching any key in `valid_commands`.
Start searching from `start`.
Commands escaped with `\` (E.g. `\DexLabel('a')`) are ignored.
Returns:
int: the index of the first character of t... |
def incon_replace(incon_file,blocks,incon_file_len):
"""It rewrite the incon file without the porosity, depending if it comes from .sav file or INCON generated with T2GEORES
Parameters
----------
incon_file : str
incon file to be rearange
blocks: str
Declares if the file has the block information on even or... |
def get_lightness(rgb):
"""Returns the lightness (hsl format) of a given rgb color
:param rgb: rgb tuple or list
:return: lightness
"""
return (max(rgb) + min(rgb)) / 2 / 255 |
def normalize_symbol_name(symbol_name):
"""
Change symbol names to a version which is known by write-math.com
Parameters
----------
symbol_name : str
Returns
-------
str
"""
if symbol_name == "\\frac":
return "\\frac{}{}" # noqa
elif symbol_name == "\\sqrt":
... |
def host_outdated(address, name):
"""Check if the entry for the virtual machine in /etc/hosts is outdated."""
hosts = open("/etc/hosts", "r")
for line in hosts:
if name in line:
if address not in line:
return True
return False |
def ceil(a, b):
"""
Returns the ceiling of a on b
"""
c = float(a) / float(b)
if c == int(c):
return int(c)
return int(c) + 1 |
def _stride(stride_spec):
"""Expands the stride spec into a length 4 list.
Args:
stride_spec: None, an integer or a length 1, 2, or 4 sequence.
Returns:
A length 4 list.
"""
if stride_spec is None:
return [1, 1, 1, 1]
elif isinstance(stride_spec, int):
return [1, stride_spec, stride_spec, 1... |
def get_family_subsets(family_subsets, gf_family):
"""Get all the valid subsets from the given family"""
valid_subsets = []
if family_subsets:
for subset in family_subsets:
if subset in gf_family['subsets']:
valid_subsets.append(subset)
return valid_subsets |
def factorial(n):
"""
Computes the factorial of n.
@type n: number
@rtype: number
@return: factorial of n
"""
n = int(n)
if n < 0:
raise ValueError("This factorial function is undefined for negative "
"numbers")
if n == 1:
return 1
retu... |
def escapeHTML(txt):
"""transform Unicode character -> DEC numerical entity"""
return txt.encode("ascii", "xmlcharrefreplace").decode() |
def is_po2(n) -> bool:
"""
Returns true iff n is a power of 2
"""
return not (n & (n - 1)) |
def is_context_manager(obj):
""" Check if the obj is a context manager """
# FIXME: this should work for now.
return hasattr(obj, '__enter__') and hasattr(obj, '__exit__') |
def get_categories(cat_str):
"""
Transform string with categories from cli into list of categories.
"""
if cat_str is None:
cat_list = ['gititized']
elif len(cat_str) == 0 :
cat_list = []
else:
cat_list = cat_str.split(',')
return cat_list |
def _populate_schema_names(schema):
"""Creates a list with the names that are inside of the schema.
Args:
schema: List[bigquery.SchemaField], a list of bigquery.SchemaField objects.
Returns:
A list containing the names of the schema.
"""
names = []
for name in schema:
names.append(name.name)
... |
def createExpressionList(string):
"""Creates a list of expression strings
Keyword arguments:
string -- String of semicolon-separated expressions
Takes the expression string and splits it with semicolon as delimiter
Returns list of single expression strings
"""
exprList = li... |
def _camelCase(base):
"""Convert a string to camelCase.
https://stackoverflow.com/a/20744956
"""
output = ''.join(x for x in base.title() if x.isalpha())
return output[0].lower() + output[1:] |
def extract_uuid_version_subscription_id(msg):
"""Extract uuid, version, subscription_id from message.
Args:
msg (dict): A dictionary of message contains bundle information.
Returns:
tuple: A tuple of (uuid, version, subscription_id). uuid is a string of the UUID of the bundle. version is ... |
def _channel_transf(channel):
"""Transform channel for luminance calculation."""
if channel < 0.03928:
return channel / 12.92
return ((channel + 0.055) / 1.055)**2.4 |
def filter60hz(A):
"""
Filters out 60hz noise from a signal.
In practice it is a sinc low pass filter with cutoff frequency of 50hz.
"""
# Filter designed in matlab
# Convolution math from http://www.phys.uu.nl/~haque/computing/WPark_recipes_in_python.html
filter=[0.0056, 0.0190, 0.0113, -0.... |
def local_cmp(a, b):
"""
compares with only values and not keys, keys should be the same for both dicts
:param a: dict 1
:param b: dict 2
:return: difference of values in both dicts
"""
diff = [key for key in a if a[key] != b[key]]
return len(diff) |
def cluster_spec(num_workers, num_ps):
"""
More tensorflow setup for data parallelism
"""
cluster = {}
port = 12222
all_ps = []
host = '127.0.0.1'
for _ in range(num_ps):
all_ps.append('{}:{}'.format(host, port))
port += 1
cluster['ps'] = all_ps
all_workers = []
for... |
def crc16(string, value=0):
"""CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1
@param string: Data over which to calculate crc.
@param value: Initial CRC value.
"""
crc16_table = []
for byte in range(256):
crc = 0
for bit in range(8):
if (byte ^ crc) & 1:
... |
def enlarge(n):
"""
This functions takes a number as an integer or float
and multiplies it by 100.
"""
return int(n)*100 |
def string_clean(s):
"""
Function will return the cleaned string
"""
return s.translate( s.maketrans("","","0123456789") ) |
def get_people_ids_based_on_role(assignee_role,
default_role,
template_settings,
acl_dict):
"""Get people_ids base on role and template settings."""
if assignee_role not in template_settings:
return []
template_... |
def compare_sets(a, b, name, limit=None):
"""
Given two sets, a and b, calculates the differences of each with respect to the other and prints the differences out.
:param limit: 'notus', 'notthem'
:param a: them
:param b: us
:param name: prefix in output
:return: String that summarizes the d... |
def reverse(s: str) -> str:
"""
For a string s return the reversed string s[::-1].
"""
return s[::-1] |
def _extract_class(name: str) -> str:
"""Extract a predicted class name from DAI column name.
Examples:
>>> _extract_class('target_column.class1')
'class1'
"""
return name.split('.')[-1] |
def _parse_query(q, required=False):
"""
Get the `q` query parameter and split it by comma into query parameters
for a schema query.
"""
if required and q is None:
raise ValueError('Missing query parameter')
# if no query parameter is provided, assume empty string
return q.split(','... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.