content stringlengths 42 6.51k |
|---|
def _split_to_slist(s):
"""Splits coverage language string to a list of strings. Here we
make sure that parentheses () will be separate items in list.
???Consider: it would be better to separate only those parentheses
which are not escaped with backslash; this would allow using
(escaped) parentheses... |
def IsStrictlyIncreasing(lst):
"""Returns true if the list is strictly increasing."""
return all([x < y for x, y in zip(lst, lst[1:])]) |
def _get_first_of(obj, *args):
"""
Helper function, returns first existing property of the object that is not None.
:param obj:
:param args: variadic, names of the properties
:return:
"""
for arg in args:
if hasattr(obj, arg):
prop = getattr(obj, arg)
if prop ... |
def perimeter_and_area(s1, s2):
"""prints the perimeter and returns the area"""
print(2*(s1+s2))
return (s1*s2) |
def dense_array(array, divide):
"""
delete inconsistent elements of 2D array and reduce its size by creating smaller array
:param
array: array to dense
:param
divide: number to divide the array size
:return:
2D divided array with consistent shape
"""
result = []
# get... |
def sort(lst, key=lambda x:x, p=""):
"""
sort(lst, key, p="")
key(ele): key function
p="r" -> reversed
"""
rev_flag = True if "r" in p else False
lst.sort(key=key, reverse = rev_flag)
return lst |
def sort_by_article_count(tags):
"""Return a number articles with the given tag."""
return sorted(tags, key=lambda tags: len(tags[1]), reverse=True) |
def num_water_bottles(num_bottles: int, num_exchange: int) -> int:
"""Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Return the maximum number of water bottles you c... |
def __eliminarDias(diasExcluidos):
"""
Funcion para devolver una lista con los dias de la semana excluyendo los que se pasan como parametro
"""
dias = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]
for ex in diasExcluidos:
if ex in dias:
dias.remove(ex)
return dias |
def get_telemetry_data(data):
""" Returns tuple of telemetry data"""
pos_x = float(data["telemetry"]["pos_x"])
pos_y = float(data["telemetry"]["pos_y"])
time = float(data["telemetry"]["time"])
velocity = float(data["telemetry"]["velocity"])
return pos_x, pos_y, time, velocity |
def get_switch_port_name (port):
"""
Get the name for the specified switch port.
Parameters:
port -- The port number to use when generating the same.
Return:
The internal name for the switch port.
"""
return "gi" + str (port) |
def subdict_by_prefix(flat, prefix, key=None):
"""
Put key-value pairs in `flat` dict prefixed by `prefix` in a sub-dict.
>>> flat = dict(
... prefix_alpha=1,
... prefix_beta=2,
... gamma=3,
... )
>>> assert subdict_by_prefix(flat, 'prefix_') == dict(
... prefix=dict... |
def compare(op_a: bytearray, op_b: bytearray) -> bool:
"""
Compare two byte arrays.
This function, in contrast to the simple comparison operation '==', is
performed in constant time to prevent timing attacks.
Args:
op_a: First array to compare.
op_b: Second array to compare.
R... |
def fromHexToInt(input):
"""
Transforms hexadecimal to decimal.
:param input: An hexadecimal number.
:return: An integer in base 10.
"""
return int(input, base=16) |
def elapsed_time(start, end):
"""
A function that calculate time difference between two times
:param start: the starting time
:param end: the ending time
:return: the time difference in readable format.
"""
hours, rem = divmod(end - start, 3600)
minutes, seconds = divmod(rem, 60)... |
def string_to_bytes(text):
"""converts a string to bytes
Args:
text: the text that should be converted
Returns:
the converted text
"""
return str.encode(str(text)) |
def getFileNameOnly(fileName):
"""
return the file name minus the trailing suffix
"""
return '.'.join(fileName.split('/')[-1].split('.')[:-1]) |
def level_to_rgb(level, background):
"""
Converts internal consept of level to a gray color for text in RGB
:param level: range from 1 to 15
:return: tuple referring to (R, G, B)
"""
#Level goes from 1 to 15, starting from level1:(30,30,30), and getting darker with 1 point
if level no... |
def evaluate(f, x ,y):
"""Uses a function f that evaluates x and y"""
return f(x, y) |
def isDoor(case):
"""Teste si la case est une porte"""
if "special_type" in case.keys():
return case['special_type'] == "door"
else:
return False |
def linear_disj(s, op='||'):
"""Return linear disjunction in prefix syntax."""
b = ' {op} '.format(op=op)
return b.join('({x})'.format(x=x) for x in s if x != '') |
def convert_size(number):
"""
Convert and integer to a human-readable B/KB/MB/GB/TB string.
:param number:
integer to be converted to readable string
:type number: ``int``
:returns: `str`
"""
for x in ['B', 'KB', 'MB', 'GB']:
if number < 1024.0:
string = "%3.1d%... |
def get_timedelta_in_seconds(time_interval):
"""Convert time delta as string into numeric value in seconds
:param time_interval: time interval as string in format HH:MM:SS.FFFFFF
:return: time interval in seconds
"""
if ":" not in time_interval:
return 0
(hours, minutes, sf) = time_inte... |
def myfunction( x , iterations):
""" using tylor series
x must be in range (-1,1]
"""
if x<=-1.0 or x >1.0 :
raise ValueError("x not in range (-1,1] ")
ans=0.0
multiply = -x
for i in range(1,iterations+1):
#print("i= ",i, " x= ",x," ans ",ans," multiply ",multiply)... |
def CByte(num):
"""Return the closest byte of a value"""
n = round(float(num))
if 0 <= n <= 255:
return int(n)
else:
raise ValueError("Out of range in CByte (%s)" % n) |
def create_bins(lower_bound, width, upper_bound):
"""
Creates bin if given the lower and upper bound
with the wirdth information.
"""
bins = []
for low in range(lower_bound, upper_bound, width):
bins.append([low, low + width])
return bins |
def _union(groupA, groupB):
"""Returns the union of groupA and groupB"""
elems = set(groupA)
elems.update(groupB)
return list(elems) |
def is_exception_class(obj):
"""Return whether obj is an exception class, or a tuple of the same.
>>> is_exception_class(ValueError)
True
>>> is_exception_class(float)
False
>>> is_exception_class(ValueError()) # An instance, not a class.
False
>>> is_exception_class((ValueError, KeyEr... |
def str_fraction(f):
"""Utility fonction to print fractions."""
return float(f) if f else 0.0 |
def resource_created(payload=None):
"""Return custom JSON if a resource is created but doesn't have output
:param payload: Customize the JSON to return if needed
:type payload: dict, optional
:return: A JSON dict with a message
:rtype: dict
"""
if payload is not None:
return payload... |
def findAll(needle, haystack):
"""Find all occurrances of 'needle' in 'haystack', even overlapping ones.
Returns a list of zero-based offsets.
"""
results = []
offset = 0
while True:
search = haystack[offset:]
if not search:
break
x = search.find(needle)... |
def sort_io_dict(performance_utilization: dict):
"""
Sorts io dict by max_io in descending order.
"""
sorted_io_dict = {
'io_all': dict(sorted(performance_utilization['io'].items(), key=lambda x: x[1], reverse=True))
}
performance_utilization.update({**sorted_io_dict})
del performanc... |
def was_last_response_B(last_keypress):
"""this function returns last_response_chose_delayed as True or False,
taking into account the location of the immediate and delayed rewards.
last_keypress is either 'left' or 'right'
"""
if last_keypress == "left":
last_response_chose_B = False
el... |
def get_effective_power(unit):
"""Get effective power of unit."""
return unit['count'] * unit['damage'] |
def reverse_words(str):
"""Reverse the order of letters in each word in a string."""
return " ".join(["".join(s[::-1]) for s in str.split(" ")]) |
def _validate_timeout(timeout, where):
"""Helper for get_params()"""
if timeout is None:
return None
try:
return int(timeout)
except ValueError:
raise ValueError('Invalid timeout %s from %s' % (timeout, where)) |
def statsGet(request, countType):
"""getSubsCount function return subscriber count
Args:
stats (dict): statistics dictionary
Returns:
int: [Subscriber Count]
"""
count = request['items'][0]['statistics'][countType]
print(f"{countType}: {count}")
return coun... |
def _hanoi(n: int, ls: list, src='A', aux='B', dst='C') -> list:
"""Recursively solve the Towers of Hanoi game for n disks.
The smallest disk, which is the topmost one at the beginning, is called 1,
and the largest one is called n.
src is the start rod where all disks are set in a neat stack in ascend... |
def largest_remaining_processing_time(evs, iface):
""" Sort EVs in decreasing order by the time taken to finish charging them at the EVSE's maximum rate.
Args:
evs (List[EV]): List of EVs to be sorted.
iface (Interface): Interface object.
Returns:
List[EV]: List of EVs sorted by re... |
def get_by_name(container, name, name_field="name"):
"""Return item from container by .name field if it exists, None otherwise"""
names = [getattr(x, name_field) for x in container]
try:
ind = names.index(name)
return container[ind]
except ValueError:
return None |
def pop_comments_gte(reply_stack, level_lte=0):
"""
Helper filter used to list comments in the <comments/list.html> template.
"""
comments_lte = []
try:
for index in range(len(reply_stack) - 1, -1, -1):
if reply_stack[index].level < level_lte:
break
co... |
def absolute_date(resolution, start, end):
"""Select an absolute date range for a location selector.
:keyword resolution: Time resolution specifier, e.g. ``hours`` or ``days``.
:keyword start: UTC start time in ISO 8601 format.
:keyword end: UTC end time in ISO 8601 format.
>>> from pprint import ... |
def _inputs_swap_needed(mode, shape1, shape2):
"""
If in 'valid' mode, returns whether or not the input arrays need to be
swapped depending on whether `shape1` is at least as large as `shape2` in
every dimension.
This is important for some of the correlation and convolution
implementations in t... |
def isBool( obj ):
"""
Returns a boolean whether or not 'obj' is of type 'bool'.
"""
return isinstance( obj, bool ) |
def find_index(text, pattern):
"""Return the starting index of the first occurrence of pattern in text,
or None if not found."""
text_index = 0 # start at beginning of text
if pattern == "": # check if pattern contains anything
return text_index
# as long as there are still letters to lo... |
def docs_with_doi(doi, docs):
"""look in document list for doi fields
and return project ids with the given doi
"""
return [p[1]['@id'] for p in docs if 'doi' in p[1] and doi in p[1]['doi']] |
def final_reclassifier(original_classifier, seq):
"""Reclassify the strategy"""
original_classifier["makes_use_of"].update(["length"])
original_classifier["memory_depth"] = max(
len(seq), original_classifier["memory_depth"]
)
return original_classifier |
def progressbar_colour(value: float):
"""Converts a percentage to a bootstrap label"""
if value > 99.5:
return "progress-bar-green"
elif value < 50.0:
return "progress-bar-red"
else:
return "progress-bar-yellow" |
def make_option_name(name):
"""
'poll_interval' -> '--poll-interval'
"""
return '--' + name.replace('_', '-') |
def concatenate(lists):
"""
This concatenates all the lists contained in a list.
:param lists: a list of lists.
:return:
new_list: concatenated list.
"""
new_list = []
for i in lists:
new_list.extend(i)
return new_list |
def map_types(params):
""" Takes a dict of params in the form i:{'value':'val','type':type} and maps them to i:value according to type """
type_map = {
'int':int,
'real':float,
'string':str,
'bool':bool
}
newparams = dict()
for p in params:
if params[p]['Value'] == "":
newparams[p] = None
cont... |
def folder_path_cleaning(folder):
"""
Modifies string file names from Windows format to Unix format if necessary
and makes sure there is a ``/`` at the end.
Parameters
----------
folder : string
The folder path
Returns
-------
folder_path : str
The folder path
"... |
def to_camel(s):
"""Convert an underscored title into camel case. 'PARENT_ORGANISATION_ID' => 'parentOrganisationId'"""
bits = [(x.lower() if i == 0 else x.title())
for (i, x) in enumerate(s.split("_"))]
return "".join(bits) |
def are_lists_identical(l1,l2):
"""
Quick function that asks if two lists are identical or not.
Parameters
-----------
l1 : list
First list
l2 : list
Second list
Returns
----------
bool
Returns True if they are identical, or False if not
"""
if... |
def ensure_tuple_of_ints(L):
"""This could possibly be done more efficiently with `tolist` if L is
np or pd array, but will stick with this simple solution for now.
"""
T = tuple([int(mm) for mm in L])
return T |
def get_confusion(pred, actual , data_map):
"""
Modify the actual classes according to the datamap, so we can look at the confusion matrix.
"""
result = []
for ac in actual:
for cl in data_map:
if ac in data_map[cl]:
result.append(cl)
for i in range(0, len(actual)):
if pred[i] != result[i]:
print(a... |
def _get_reaction_key(functional_groups):
"""
Return a key for :data:`._reactions`
Parameters
----------
functional_groups : :class:`iterable`
An :class:`iterable` of :class:`.GenericFunctionalGroup`.
The correct reaction must be selected for these functional
groups.
Re... |
def tower_build(n_floors=1):
"""
n_floors: number of floors for the tower
return: tower consisting of "*" from top to bottom layed out as a pyramid
"""
tower_list = ([" "*(n_floors-i) + "*"*(2*i-1) + " "*(n_floors-i) for i in range(1, n_floors+1)])
return tower_list |
def reindent(s, numspaces):
""" reinidents a string (s) by the given number of spaces (numspaces) """
leading_space = numspaces * ' '
lines = [leading_space + line.strip()for line in s.splitlines()]
return '\n'.join(lines) |
def contains_string(string,lines):
"""returns true if at least one of the lines contains the given string"""
for line in lines:
if string in line:
return True
return False |
def throttle_delay_set(session, delay):
"""Assign a new throttle delay to a session. The throttle delay
value, in seconds, is added to each request to avoid hitting
RESTCONF throttling limit.
:param session: Dictionary of session returned by :func:`login`.
:param delay: New delay to be assigned to ... |
def find_list_depth(a):
"""
Finds the depth of a list using recursion
Parameters
----------
a : list
list of arbitrary depth
Returns
-------
depth : integer
depth of list
"""
if isinstance(a, (list, tuple)):
depth = 1 + max(find_list_depth(item) ... |
def render_chart(word_list):
"""
Renders a bar chart to the console. Each row of the chart contains the frequency
of each letter in the word list.
Returns:
A dictionary whose keys are the letters and values are the freqency (N) of the
letter. The value is a string co... |
def _get_node_colors(nodes, path, colors):
"""For each node, assign color based on membership in path."""
node_colors = []
for x in nodes:
if x in path:
node_colors.append(colors['active'])
else:
node_colors.append(colors['inactive_node'])
return node_colors |
def fizzbuzz(n, fizz, buzz):
"""Compute fizzbuzz nth item given modulo values for fizz and buzz.
>>> fizzbuzz(5, fizz=3, buzz=5)
'buzz'
>>> fizzbuzz(3, fizz=3, buzz=5)
'fizz'
>>> fizzbuzz(15, fizz=3, buzz=5)
'fizzbuzz'
>>> fizzbuzz(4, fizz=3, buzz=5)
4
>>> fizzbuzz(4, fizz=4, bu... |
def tsk(basename, task, obj=None):
"""Merge in some defaults for task creation"""
if not obj: obj, task = task, None # argument order
return {
'basename': basename,
'name': task,
'title': lambda t: f'{t.name} -> {t.targets[0]}',
'clean': True,
**obj, # me... |
def fact_iter(n):
"""Assumes n is an int >= 0
* computes factorial
* number of steps:
* ignore additive constants
* ignore multplicative constants
"""
answer = 1
while n > 1:
answer *= n
n -= 1
return answer |
def question4c(T, r, n1, n2):
""" Find the least common ancestor between two nodes on a binary search tree """
# if three has less than three nodes, return None
if len(T)<=2:
return
# order search nodes
if n1<n2:
ln, rn = n1, n2
else:
ln, rn = n2, n1
while True:
... |
def max_clamp(val: int, limit: int) -> int:
"""Clamp int to limit."""
return min(val, limit) |
def convert_from_cammel_case_to_spaces(text):
"""
>>> convert_from_cammel_case_to_spaces('HelloWorld')
'Hello world'
>>> convert_from_cammel_case_to_spaces('helloMotto')
'hello motto'
"""
spaced_text = text[0]
for char in text[1:]:
if char == char.capitalize():
... |
def compress_runs(runs, incrementable):
"""
return a 2-tuple list (idx, run) filter out not incrementables
"""
return [(i, r) for i, r in enumerate(runs)
if r.analysis_type in incrementable] |
def split_reaction_identifier(rid):
""" SMIRKS-style reaction ID from reactant and product species IDs
"""
rct_str, prd_str = str.split(rid, '>>')
rct_sids = tuple(str.split(rct_str, '.'))
prd_sids = tuple(str.split(prd_str, '.'))
return (rct_sids, prd_sids) |
def gari( redchan, nirchan, bluechan, greenchan ):
"""
GARI: green atmospherically resistant vegetation index
gari( redchan, nirchan, bluechan, greenchan )
"""
redchan = 1.0*redchan
nirchan = 1.0*nirchan
bluechan = 1.0*bluechan
greenchan = 1.0*greenchan
result = ( nirchan - (greenchan-(bluechan - redchan))) / ... |
def compute_fsl_sigma(cutoff, TR, const=2):
"""Convert filter cutoff from seconds to sigma required by fslmaths"""
return cutoff / (TR*const) |
def get_cell_neighborhood(seq, pos):
"""
Return the neighborhood (a triple) of the cell in the specified
position of a sequence.
"""
cell = seq[pos]
left = seq[-1] if pos == 0 else seq[pos-1]
right = seq[0] if pos == (len(seq) - 1) else seq[pos+1]
return (left, cell, right) |
def closest_cruising_altitude(altitude):
"""
Calculate the closest cruising altitude to the given altitude.
Parameters
----------
altitude: float
An altitude [feet]
Returns
-------
The closest cruising altitude to the given altitude.
"""
return 1000 * ((altitude + 500) ... |
def result_string_to_dictionary(result_string: str) -> dict:
"""
Convert result string saved in a .csv file to a dictionary
:param result_string: string from .csv file
:return: dictionary with info from .csv file
"""
key_value_strings = result_string.split('\\')[0][2:-2].replace('\'', '').spli... |
def arg_range(arg, lo, hi):
"""
Given a string of the format `[int][-][int]`, return a list of
integers in the inclusive range specified. Open intervals are
allowed, which will be capped at the `lo` and `hi` values given.
If `arg` is empty or only contains `-`, then all integers in the
range `[... |
def SignToBool(inp):
"""Converts signed bits into boolean bits
-1 -> 0
1 -> 1"""
return (inp + 1) / 2 |
def b64encode(data):
"""Encodes data in base64 format.
Custom base64 function that is similar to Keycloaks base64url.js stringify function.
Used to conform with Keycloaks expected format, as Pythons base64 module seems
to produce unexpected output.
See https://github.com/keycloak/keycloak/blob/mast... |
def _make_body(mapping, source_key='source'):
"""
Given a dict mapping Keboola tables to aliases, construct the body of
the HTTP request to load said tables.
Args:
mapping(:obj:`dict`): Keys contain the full names of the tables to
be loaded (ie. 'in.c-bucker.table_name') and values ... |
def is_spotify(track):
""" Check if the input song is a Spotify link. """
status = len(track) == 22 and track.replace(" ", "%20") == track
status = status or track.find("spotify") > -1
return status |
def center_x(display_width: int, line: str) -> int:
"""
Find the horizontal center position of the given text line
Parameters:
display_width (int) : The character width of the screen/space/display
line (int) : Line of text
Returns:
(int): Horizontal character number
... |
def parse_capability_lists(cls_str):
"""Parse list of capability lists in --capabilitylistindex option
Input string of the form: uri,uri
"""
return(cls_str.split(',')) |
def url(search_string, date_string):
"""
date_string of the form ddMONyyyy e.g. 25OCT2018, 31JAN2019
When requesting options, must be in the future.
Must be a valid option expiration date for that stock.
return url
"""
base_url = 'https://www.nseindia.com'
query_prefix = '/live_market/dy... |
def is_in_list(num, lst):
"""
>>> is_in_list(4, [1, 2, 3, 4, 5])
True
>>> is_in_list(6, [1, 2, 3, 4, 5])
False
>>> is_in_list(5, [5, 4, 3, 2, 1])
True
"""
if not lst:
return False
else:
return lst[0] == num or is_in_list(num, lst[1:]) |
def parts_to_url(codechecker_cfg):
"""
Creates a product URL string from the test configuration dict.
"""
return codechecker_cfg['viewer_host'] + ':' + \
str(codechecker_cfg['viewer_port']) + '/' + \
codechecker_cfg['viewer_product'] |
def fib_3_iterative(n):
"""
Solution: Iterative solution.
Complexity:
Time: O(n)
Space: O(1)
"""
if n < 0:
raise ValueError('input must be a positive whole number')
x, y = 0, 1
for i in range(n):
x, y = y, x + y
return x |
def _get_creator(hardict):
"""
Get creator of HAR file.
"""
creator = hardict["log"]["creator"]
return "%s %s%s" % (creator["name"], creator["version"],
" (Comment: %s)" % creator["comment"] if creator.get("comment") else "") |
def _dummy_parameters(layer_group, n_in):
"""Return dummy parameters"""
return {'weights':[], 'bias':[], 'architecture':'dense'}, n_in |
def access_by_path(dic, path):
"""
Allows to access a nested dictionary using path to an entry, as if the nested
dictionary was a file system.
Parameters
----------
- dic: nested dictionary
- path: string with a path to a value within the dictionary (/key1/key2/key3)
R... |
def format_result(result, verbose):
"""
Common code to format the results.
"""
if verbose:
return f"line: {result['line_number']} - ({result['rule']}) {result['meta']['description']} - {result['line']}"
return f"line: {result['line_number']} - ({result['rule']}) {result['meta']['description'... |
def options_to_str(options_list):
"""
Helper method to create a sting out of a list of choice options.
"""
tmp_list = ["{} - {}".format(i + 1, o) for i, o in enumerate(options_list)]
return "\n".join(tmp_list) |
def count_send(link_counters):
"""Find the send count in the counters returned by a CommunicationLink."""
for processor in link_counters.values():
if 'send' in processor:
return processor['send'] |
def list_ascendant(input_list):
"""Function that orders a list on ascendant order using insertion sort
Args:
input_list (list): List with the values that we want to order
Returns:
list: The ordered list
"""
for i in range(1, len(input_list)):
j = i-1
next_element = ... |
def gen_hpack_huffman(data):
"""Generates the hpack_huffman array and returns a tuple with the length of the array and the content of the array both as strings"""
content = ""
for d in data:
content += " { " + str(d['bit_len']) + ", 0x" + d['LSB_hex'] + "u },\n"
# We remove the last comma and new line
return... |
def getFlattenDictionary(dd, separator='_', prefix=''):
"""
Args:
dd:
separator:
prefix:
Returns:
"""
return {prefix + separator + k if prefix else k: v
for kk, vv in dd.items()
for k, v in getFlattenDictionary(vv, separator, kk).items(... |
def _fix_links(md):
"""Change links in markdown to make them work in HTML."""
md = md.replace('(doc/', '(')
md = md.replace('.md)', '.html)')
return md |
def array_swap_transform_next_index_to_current_index(position, move):
"""Transforms the position depending on the move.
Works with the array_swap move type.
This function transforms the position so that it can be used as the indice
in the unaltered array, yet return the value it would have had if the m... |
def font_name(family, style):
"""
Same as ``full_name()``, but ``family`` and ``style`` names are separated by a hyphen instead of space.
"""
if style == 'Regular':
font_name = family
else:
font_name = family + '-' + style
return font_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.