content stringlengths 42 6.51k |
|---|
def get_urls(page_links):
"""Insert page links, return list of url addresses of the json"""
urls = []
for link in page_links:
link1 = link.replace('v3', 'VV')
game_id = ''.join([char for char in link1 if char in list(map(str, list(range(10))))])
json_url = f'http://www.afa.com.ar/dep... |
def _is_true(string):
"""
Check if something is truthy.
"""
return str(string.lower().strip()) in ['true', '1', 'yes', 'y'] |
def raw_list(name, value, prev):
"""create list of raw values"""
if prev is None:
prev = []
prev.append(value)
return prev |
def reverseString(string: str):
"""Reverses a string."""
return string[::-1] |
def GetSubmoduleName(fullname):
"""Determines the leaf submodule name of a full module name.
Args:
fullname: Fully qualified module name, e.g. 'foo.bar.baz'
Returns:
Submodule name, e.g. 'baz'. If the supplied module has no submodule (e.g.,
'stuff'), the returned value will just be that module name ... |
def exponentiation_by_squaring(n, exp):
""" Fast way to do exponentiation
Args:
n -- int
exp -- int -- the exponent
return n**exp
"""
y = 1
while exp > 1:
if exp % 2 == 1:
y *= n
n *= n
exp = (exp-1) // 2
else:... |
def sequence_remove(sequence, possible_triplet):
"""
To remove the elements of a set of triplets ie [1,2,3] from the sequence
ie. if triplets is [1,2,3], then sequence [4,1,3,2] should return [4]
"""
sequencex = sequence.copy()
for integer in possible_triplet:
sequencex.remove(integer)
... |
def get_request_type(data: bytearray) -> int:
""":returns: the message request type"""
return int(chr(data[1])) |
def queue_table(sai_id):
"""
:param sai_id: given sai_id to cast.
:return: COUNTERS table key.
"""
return b'COUNTERS:' + sai_id |
def get_angular_speed(linear_vel, turn_rad):
"""Relates path to the angular velocity."""
if turn_rad != 0:
return linear_vel / turn_rad
else:
return 0 |
def compare_overlaps_greedy(context, synsets_signatures):
"""
Calculate overlaps between the context sentence and the synset_signature
and returns the synset with the highest overlap.
Note: Greedy algorithm only keeps the best sense, see http://goo.gl/OWSfOZ
Only used by original_lesk(). K... |
def read_str_num(string, sep=None):
"""Returns a list of floats pulled from a string.
Delimiter is optional; if not specified, uses whitespace.
Parameters
----------
string : str
String to be parsed.
sep : str, optional
Delimiter (default is None, which means consecutive whites... |
def get_coordinates_from_kml(coordinates):
"""Returns list of tuples of coordinates.
Args:
coordinates: coordinates element from KML.
"""
if coordinates:
return [tuple(float(x.strip()) for x in c.split(',')) for c in str(coordinates[0]).split(' ') if c.strip()] |
def add4(a, h):
"""
This function helps us to add datatype.
a: Give same datatype values for a and b.
b: Give same datatype values for a and b.
"""
print("Value of a:", a)
print("Value of h:", h)
return a+h |
def baseBToNum(n, b):
"""makes a number in base b to decimal"""
if n == "":
return 0
return (int(n[0]))*(b**(len(n)-1))+baseBToNum(n[1:], b) |
def convert(vertical_lists):
"""rotate a given list of lists
converts a list as if it was a matrix
interchanges 'row' and 'columns'
Args:
vertical_lists: list of lists to be rotated
Returns:
list: list of lists
contains the same elements as original
except t... |
def boolean_labels(names, idx, mapping={True: 'AND', False: 'NOT'},
strip='AND_'):
"""
Creates labels for boolean lists.
For example:
>>> names = ['exp1', 'exp2', 'exp3']
>>> idx = [True, True, False]
>>> boolean_labels(names, idx)
'exp1_AND_exp2_NOT_exp3'
Parameter... |
def calc_Distance_from_Magnitudes(M,m):
"""
m: apparent magnitude
M: absolute magnitude
"""
return 10**(m+5-M)/5 |
def reverse_order(order_value):
"""Reserve ordering of order value (asc or desc).
:param order_value: Either the string ``asc`` or ``desc``.
:returns: Reverse sort order of order value.
"""
if order_value == 'desc':
return 'asc'
elif order_value == 'asc':
return 'desc'
retur... |
def matching(graph):
"""
Find maximum cardinality matching of a bipartite graph (U,V,E).
The input format is a dictionary mapping members of U to lists
of their neighbors in V. The output is a triple (M,A,B) where M is a
dictionary mapping members of V to their matches in U, A is the part
of th... |
def Prepare_Suffix_List(suffix_list):
"""
Adds regular expression parts to given suffixes
"""
new_suffix_list = []
for suffix in suffix_list:
regex_suffix = r"(?<=\w)" + suffix + r"(?=\s)"
new_suffix_list = new_suffix_list + [regex_suffix]
return new_suffix_list |
def zotero_collection_map(zotero_item_list, collection=""):
"""
params:
zotero_item_list, [{},{},...]
collection, str.
return: zotero_collection_list, []
"""
#
zotero_collection_list = []
#
for zotero_item in zotero_item_list:
zotero_item["collections"] = []
zote... |
def validate_path(ip=None):
"""Give a valid path return absolute
If the provided relative or absoltue path is invalide, raise
RuntimeError exception
If none is provided, use current working directory
:param str ip: absolute or relative path
:rtype: str
"""
import os
if ip is Non... |
def edit_diff(start, goal, limit):
"""A diff function that computes the edit distance from START to GOAL.
>>> edit_diff("ash", "hash")
1
>>> edit_diff("roses", "arose") # roses -> aroses -> arose
2
>>> edit_diff("tesng", "testing") # tesng -> testng -> testing
2
>>> edit_diff("rlog... |
def getTrueAnnotationType(annotation):
"""
Resolve the supertype of an annotation type possibly created using the typing module.
:param annotation: A type object.
:return: The original object or its supertype.
"""
return getattr(annotation, '__supertype__', annotation) |
def job_flow_has_pending_steps(job_flow):
"""Return ``True`` if *job_flow* has any steps in the ``PENDING``
state."""
steps = getattr(job_flow, 'steps', None) or []
return any(getattr(step, 'state', None) == 'PENDING'
for step in steps) |
def compare_seq_counts(db_counts, fa_counts):
"""
Compares the number of sequences per family in full_region table with
the number of sequences written in the distinct fasta files
db_counts: A dictionary with the number of sequences per family as
found in full_region (e.g. {'RFXXXXX':N... |
def get_name(test):
"""Gets the name of a test.
PARAMETERS:
test -- dict; test cases for a question. Expected to contain a key
'name', which either maps to a string or a iterable of
strings (in which case the first string will be used)
RETURNS:
str; the name of the test
... |
def default_list_format(index: int, in_str: object) -> str:
"""
Makes the first character in the given string uppercase
Also shows the position of the item in the list (1-based)
:param index: The index of the item (0-based)
:type index: int
:param in_str: The string to forma... |
def range_filter(value):
"""
Filter - returns a sequence containing range made from given value
Example:
{% for i in 3|range %}
{{ i }}
{% endfor %}
Result:
0
1
2
Example:
{% for i in (0,10,2)|range %}
{{ i }}
{% endfor %}
Result:
0
2
4... |
def getTopKSimilarUser(user, records, numK = 200):
"""
Args:
user: id of a user
records: [(user_sim, similarity, number of common ratings)]
numK: number of similar users we want to keep track of
Returns:
(user, [(user_sim, similarity, number of common ratings)])
"""
l... |
def get_by_lcp_name(yaml, lcpname):
"""Returns the interface or sub-interface by a given lcp name, or None,None if it does not exist"""
if not "interfaces" in yaml:
return None, None
for ifname, iface in yaml["interfaces"].items():
if "lcp" in iface and iface["lcp"] == lcpname:
r... |
def worker(num):
"""Thread worker."""
print('Worker #{0}'.format(num))
return True |
def runnable(config):
"""Is this logger configuration runnable? (Or, e.g. does it just have
a name and no readers/transforms/writers?)
"""
return config and ('readers' in config or 'writers' in config) |
def y_ss(n, s, t):
"""Spin observable: y-direction
"""
if s == t:
return 0
else:
return 1.j * (-1)**t |
def _decrement_version(lambda_config):
"""Decrement the Lambda version, if possible.
Args:
lambda_config (dict): Lambda function config with 'current_version'
Returns:
True if the version was changed, False otherwise
"""
current_version = lambda_config['current_version']
if cur... |
def count_units(units):
"""Count total number of units."""
return sum(unit['count'] for _, unit in units.items()) |
def format_unit(unit: str) -> str:
""" Add a space before the unit if necessary, e.g. 'LOC' -> ' LOC', but '%' -> '%'. """
return ' ' + unit if unit and unit != '%' and not unit.startswith(' ') else unit |
def total_graded(parsed_list):
"""
This function finds the total number of individuals that were graded.
:param parsed_list: the parsed list of the grades
:return: the total number of people graded
"""
number_graded = len(parsed_list)
return number_graded |
def is_line_in_file(filename: str, line: str) -> bool:
"""
Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match)
"""
assert "\n" not in line
with open(filename, "r") as file:
for fileline in file:
... |
def is_numeric(arg):
"""
purpose:
check if the arg is a number
arguments:
arg: varies
return value: Boolean
"""
try:
float(arg)
return True
except Exception:
return False |
def dict_merge_pair(d1, d2):
"""
Recursively merges values from d2 into d1.
"""
for key in d2:
if key in d1 and isinstance(d1[key], dict) and \
isinstance(d2[key], dict):
dict_merge_pair(d1[key], d2[key])
else:
d1[key] = d2[key]
return d1 |
def get_vehicle_max_acceleration(_):
"""
Get the maximum acceleration of a carla vehicle
default: 3.0 m/s^2: 0-100 km/h in 9.2 seconds
:param vehicle_info: the vehicle info
:type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo
:return: maximum acceleration [m/s^2 > 0]
:rtype: float64
... |
def pairs_to_counts(original_poly: str, poly_pairs: dict) -> dict:
"""For parm dictionary of polymer pairs, return dictionary of counts of each elements letter.
Most letters are 'double counted'. For example, consider the polymer 'ABC'. 'B' is in the pairs 'AB' and 'BC'.
Except the first and last letters of... |
def return_list_of(cls, data):
"""
Returns a list of instances of the class type found in the response.
:param cls: class
The class type we want to instantiate
:param data: list
The data containing the list of the dictionaries we want to return as objects
:return:
A list of ... |
def rgbToStrhex(r, g, b):
"""r (int), g (int), b (int): rgb values to be converted
Returned value (str): hex value of the color (ex: #7f866a"""
return '#%02x%02x%02x' % (r, g, b) |
def remove_duplicates(array: list) -> list:
"""
:param array: a list of words
:return: a list without duplicates
"""
return list(dict.fromkeys(array)) |
def is_ball_recovery(event_list, team):
"""Returns if event list has a ball recovery in the front"""
recovery = False
for e in event_list[:1]:
if e.type_id == 49:
recovery = True
return recovery |
def _check_shape_matadd(mat):
"""
Determines matrix shape of given matrix (as defined in matmul) 'mat'
Args:
mat - A list/list of lists representing a vector/matrix (see 'matmul')
Returns:
m, n - The shape of mat
"""
if isinstance(mat[0],list):
... |
def get_text(tag):
"""return text from hashtags
Args:
tag (object): object with hashtags
Returns:
string: the text from a hashtag
"""
return tag.get('text').lower() |
def parse_hdf5_version(vers):
""" Split HDF5 version string X.Y.Z into a tuple. ValueError on failure.
"""
try:
vers = tuple(int(x) for x in vers.split('.'))
if len(vers) != 3:
raise ValueError
except Exception:
raise ValueError("Illegal value for HDF5 version")
... |
def render_js(url, defer=False):
"""Render tag to include Javascript resource"""
return '<script type="text/javascript" src="%s"%s></script>' % \
(url, ' defer' if defer else '') |
def slice_array_on_limit(array, limit):
"""
If array contains more items than the limit, return an array containing items up until the limit
:param array:
:limit: integer
"""
if array and len(array) > limit:
return array[0:limit]
return array |
def remove_ex(line):
"""
Replaces '#ex in any string with an empty string.'
"""
return line.replace('#ex', '') |
def S_VAR_DEC(dec, ident):
"""Evaluates an S_STATEMENT node"""
return "var " + ident; |
def Max(a, b) :
"""Max define as algrebraic forumal with 'abs' for proper computation on vectors """
return (a + b + abs(a - b)) / 2 |
def get_list(value, sep=','):
"""Get a list from value"""
if not value:
return []
if isinstance(value, str): # single or comma separated
return value.strip().strip(sep).split(sep)
return value |
def _hide_num_nodes(shape):
"""Set the first dimension as unknown
"""
shape = list(shape)
shape[0] = None
return shape |
def mapdict_keys(function, dic):
"""
Apply a function to a dictionary keys,
creating a new dictionary with the same values
and new values created by applying the function
to the old ones.
:param function: A function that takes the dictionary key as argument
and returns a n... |
def list_to_str(inp: list) -> str:
"""
joins list to string
"""
return ' ' .join(
['' if e != e or type(e) is not str
else str(e) for e in inp]) |
def constant(val, dtype='float'):
"""A literal value
>>> from emlearn import cgen
>>> cgen.constant(3.14)
"3.14f"
"""
if dtype == 'float':
return "{:.6f}f".format(val)
else:
return str(val) |
def convert_compile_gcc(test):
"""compile-*gcc-auto superseded by compile-gcc"""
if 'and-run' in test['type']:
test['args']['run'] = True
test['type'] = 'compile-gcc'
if 'cflags' in test['args']:
test['args']['cflags'] = ' '.join(test['args']['cflags'])
return test |
def unlimited_dish(string, unlimited_dishes):
"""
Checks if a dish is part of the unlimited dishes list.
Parameters
----------
string : str
Dish to check.
unlimited_dishes : list
List of unlimited dishes.
Returns
-------
bool
True if dish is part of the unli... |
def time_string(t):
""" Return a string of format 'hh:mm:ss', representing time t in seconds
Result rounded to nearest second.
"""
seconds = int(round(t))
h,rsecs = divmod(seconds,3600)
m,s = divmod(rsecs,60)
return str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2) |
def os_path_norm(diroot):
"""function os_path_norm
Args:
diroot:
Returns:
"""
diroot = diroot.replace("\\", "/")
return diroot + "/" if diroot[-1] != "/" else diroot |
def set(bit):
"""Set the specifeid bit (1-indexed) eg. set(8) == 0x80"""
return 1 << (bit - 1) |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
divlist = []
counter = 0
for item in range(1, num + 1):
if num % item == 0:
divlist.append(item)
counter = count... |
def value_map_corner_values_from_coverage(coverage: str):
"""
get location of lon/lat box:
:param coverage:
:return:
"""
lon_low = lon_up = lat_low = lat_up = -999
if coverage == 'reunion':
lon_low, lon_up, lat_low, lat_up = 54.75, 56.25, -21.75, -20.25
if coverage == 'swio':
... |
def get_key(dictionary, value):
""" Funtion to return the key that match with the passed value
>>> get_key({'py' : 3.14, 'other' : 666}, 3.14)
'py'
"""
values = list(dictionary.values())
keys = list(dictionary.keys())
return (keys[
values.index(value)
]) |
def _build_res(key, match, lhs, rhs):
"""
Builds a result tuple object for CouchDB.
"""
return key, match[0], lhs, rhs |
def lerp(first, second, mu):
"""Linear Interpolation between values of two lists
Parameters
----------
first : tuple or list
first list of values
second : tuple or list
second list of values
mu : float
Interpolation factor [0,1]
Returns
-------
list
... |
def parallel(lines):
"""
Helper for using multiproccesing for parallel execution
"""
for line in lines:
line.analyze()
line.readLetters()
return lines |
def min_sub1(A):
"""
:param A:List[int]
:return: List[(int,int,int)]
"""
def sub_min(start, end):
"""
:param start: int
:param end: int
:return: List[(int,int,int)]
"""
if start == end:
return [(A[start], start, end)]
else:
... |
def getting_students_sum(marks):
"""Getting sums of students marks"""
return [(i, j[0][2]) for i, j in zip([sum([task[0] for task in tasks])
for tasks in marks], marks)] |
def average_color(colors):
"""
Returns average for the list, or None of the list is empty. Each element is
an inner list of 4 numbers.
"""
count = len(colors)
if count == 0:
return None
totals = [0, 0, 0, 0]
for color in colors:
for i in range(0, 4):
totals[i]... |
def isbool(s):
"""
Checks whether the string ``s`` represents a boolean.
The string requires Python capitalization (e.g. 'True', not 'true').
:param s: the candidate string to test
:type s: ``str``
:return: True if s is the string representation of a boolean
:rtype: ``bool``... |
def is_int(s):
"""Check whether an object is an integer.
Parameters
----------
s: NA
Object to be checked
"""
try:
int(s)
return True
except ValueError:
return False |
def sqrt(number=None):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number is None or number < 0:
return None
low = 1
high = number
while low <= high:
... |
def ToHex(data):
"""Return a string representing data in hexadecimal format."""
s = ""
for c in data:
s += ("%02x" % ord(c))
return s |
def check_native_segwit(script):
"""
Checks wether a given output script is a native SegWit type.
:param script: The script to be checked.
:type script: str
:return: tuple, (True, segwit type) if the script is a native SegWit, (False, None) otherwise
:rtype: tuple, first element boolean
"""... |
def post_processing(call, func):
"""Post processes decorated function result with func."""
return func(call()) |
def identify_unique_asset_codes(raw_data):
"""Identify unique asset codes in the data block
Args:
raw_data : data block retrieved from the Storage layer that should be evaluated
Returns:
unique_asset_codes : list of unique codes
Raises:
"""
unique_asset_codes = []
for row... |
def detect_overlap_1d(first, first_length, second, second_length):
"""Detects overlap between two lines in one dimensional space.
Args:
first (int): Beginning of the first one dimensional line.
first_length (int): The length of the first line.
second (int): Beginning of the second one d... |
def is_hidden(name):
"""Check if object is active or no"""
if len(name) < 2:
return False
if name.startswith('t_'):
return True
return False |
def convert_dB_to_W(dB_value):
""" Function that converts dB values into Watts!"""
_ = 10 ** (dB_value / 10)
return _ |
def log(msg, ip=None, output=None, suppress=False):
"""
Logging function.
"""
import time
message = f"[{time.strftime('%Y/%m/%d %H:%M:%S')}] :: %s{msg}\n" % (
f"({ip}) " if ip != None else "")
# Write to a file if filename is provided.
if output:
with open(output, "a+") as f:
f.write(message)
# Outpu... |
def symmetric_residue(a, m):
"""Return the residual mod m such that it is within half of the modulus.
>>> from sympy.ntheory.modular import symmetric_residue
>>> symmetric_residue(1, 6)
1
>>> symmetric_residue(4, 6)
-2
"""
if a <= m // 2:
return a
return a - m |
def isIpAddrValid(sIpAddr):
"""
Checks if a IPv4 address looks valid. This will return false for
localhost and similar.
Returns True / False.
"""
if sIpAddr is None: return False;
if len(sIpAddr.split('.')) != 4: return False;
if sIpAddr.endswith('.0'): retu... |
def _sum(array):
""" Recursively find the sum of array"""
if len(array) == 1:
return array[0]
else:
return array[0] + _sum(array[1:]) |
def get_prefered_gpu(gpu_indices, prefered):
"""Move prefered GPU on a first position if it is available."""
if prefered in gpu_indices:
gpu_indices.remove(prefered)
return [prefered, ] + gpu_indices
return gpu_indices |
def _iszipfile(filename):
"""
Determine if filename is a zip file. Zip files either
(1) end with '.zip', or
(2) are located in a subdirectory '/zip/' for files downloaded from
the ICGEM web site.
"""
if '/zip/' in filename:
return True
elif filename[-4:] == '.zip'... |
def key( *args ):
"""
join the arguments in the format of donkey
Arguments
---------
args: list of string
Examples
--------
>>>key( 'a', 'b', 'c' )
'a__b__c'
"""
return '__'.join( args ) |
def parse_split(value):
"""Decodes the split value.
Returns a tuple (type, value) where type is either perc, num or dir set.
"""
assert isinstance(value, (int, str))
if isinstance(value, int):
return ('num', value)
elif value.endswith("%"):
return ('perc', float(value.rstri... |
def mergebagdiff(xs, ys):
""" merge lists xs and ys. Return a sorted result """
result = []
xi = 0
xs.sort() # sort clause unneeded if lists already sorted (as in instructions), but added for generalising
ys.sort()
while True:
if xi == len(xs): # If xs list is finished,
... |
def html_bescape(s, quote=False, crlf=False):
"""html.escape but bytestrings"""
s = s.replace(b"&", b"&").replace(b"<", b"<").replace(b">", b">")
if quote:
s = s.replace(b'"', b""").replace(b"'", b"'")
if crlf:
s = s.replace(b"\r", b" ").replace(b"\n", b" ")
... |
def cabs2(x):
"""Fast abs^2 for complex numbers which returns a contiguous array."""
return x.real**2 + x.imag**2 |
def get_container_network_metrics(all_conns, lsof_result):
""" return in_byte, out_byte of container """
if all_conns is None or lsof_result is None:
return 0, 0
in_byte = 0
out_byte = 0
for container_pid, container_conns in lsof_result.items():
for conn in container_conns:
... |
def remove_spaces_from_sentences(sents):
"""
Makes sure every word in the list of sentences has SpaceAfter=No.
Returns a new list of sentences
"""
new_sents = []
for sentence in sents:
new_sentence = []
for word in sentence:
if word.startswith("#"):
n... |
def _base_directory(username):
"""Get the directory where the file that needs to be read or written is."""
return 'exports/{}'.format(username) |
def console_output(access_key_id, secret_access_key, session_token, session_token_expiry, verbose):
""" Outputs STS credentials to console """
if verbose:
print("Use these to set your environment variables:")
exports = "\n".join([
"[default]",
"aws_access_key_id=%s" % access_key_id,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.