content
stringlengths 42
6.51k
|
|---|
def clear_tables(data):
"""
Function clears table if rows are not valid (dasen't hold jumper data).
:param data: raw data from the pdf tables
:return: cleared raw data
"""
table_raw_content_list = []
# clean rows for pdfs with tables
data_to_skip = ['Jury', 'RACE', 'Club', 'Rank', 'Name', 'Fini', 'not ', 'Disq', 'Code', 'PRAG', 'NOC ',
'Not ', 'TIME', 'WIND', 'Fina', 'GATE', 'No. D', 'Comp', 'Worl', 'FIS ', 'Hill']
data_to_skip = list(x.lower() for x in data_to_skip)
for lines in data:
for line in lines:
for row in line:
if row[0] is None:
continue
if row[0][0:4].lower() in data_to_skip:
continue
if row[0] in ['Weather Information', 'Statistics', '1st Round', 'Did Not Start', 'Qualification']:
break
if row[0][0:18] == 'Technical Delegate':
break
if row[0][0:4] in ['Note', 'NOTE']:
break
# DSQ row
if row[0] == '1st Round':
continue
if row[0] == '' or row[0].split()[0] in ['DNS', 'DSQ']:
continue
if 'SCE' in row or 'ICR' in row[2] or 'SCE' in row[2]:
continue
table_raw_content_list.append(row)
return table_raw_content_list
|
def get_total_price_of_items(pizzas, kebabs, drinks):
"""Calculates and returns the total price of items provided.
arguments:
pizzas - list of pizzas
kebabs - list of kebabs
drinks - list of drinks
"""
total = 0.0
for p in pizzas:
total += float(p.price_without_dollar_sign())
for k in kebabs:
total += float(k.price_without_dollar_sign())
for d in drinks:
total += float(d.price_without_dollar_sign())
return total
|
def format_status(items, symbol_success='success', symbol_failed='failed'):
"""Format the status field of pipeline jobs."""
result = {}
for name, content in items.items():
result[name] = content
if content['status'] == 'success':
result[name]['status'] = symbol_success
if content['status'] == 'failed':
result[name]['status'] = symbol_failed
return result
|
def e_s(msg):
"""Return a string, with reserved characters escaped"""
msg = msg.replace(".", "\\.")
msg = msg.replace("=", "\\=")
msg = msg.replace("-", "\\-")
msg = msg.replace("(", "\\(")
msg = msg.replace(")", "\\)")
msg = msg.replace("]", "\\]")
msg = msg.replace("!", "\\!")
return msg
|
def curies_runtime(base):
""" base is .e.g https://api.blackfynn.io/datasets/{dataset_id}/ """
return {
'local': base,
'contributor': base + 'contributors/',
'subject': base + 'subjects/',
'sample': base + 'samples/',
}
|
def mean(data):
"""Compute the mean of the provided data."""
n = len(data)
try:
return [float(sum(l))/len(l) for l in zip(*data)]
except TypeError:
return sum(data)/n
|
def get_link_type(link: str) -> str:
"""
Analyzes the given link and returns the type of download type required.
(track for individual song, album for an album URL and playlist if given
a the Spotify link of a playlist).
"""
# a spotify link is in the form of: open.spotify.com/<type>/<id>
# we only need the type part
link_type = link.split("/")
return link_type[len(link_type) - 2]
|
def discrete_uniform_expval(lower, upper):
"""
Expected value of discrete_uniform distribution.
"""
return (upper - lower) / 2.
|
def is_set(object):
"""Check the given object is a set"""
return isinstance(object, set)
|
def clean_exchanges(data):
"""Make sure all exchange inputs are tuples, not lists."""
def tupleize(value):
for exc in value.get("exchanges", []):
exc["input"] = tuple(exc["input"])
return value
return {key: tupleize(value) for key, value in data.items()}
|
def text_to_title(value):
"""when a title is required, generate one from the value"""
title = None
if not value:
return title
words = value.split(" ")
keep_words = []
for word in words:
if word.endswith(".") or word.endswith(":"):
keep_words.append(word)
if len(word) > 1 and "<italic>" not in word and "<i>" not in word:
break
else:
keep_words.append(word)
if len(keep_words) > 0:
title = " ".join(keep_words)
if title.split(" ")[-1] != "spp.":
title = title.rstrip(" .:")
return title
|
def billions(x, pos):
"""The two args are the value and tick position."""
return '${:1.0f}B'.format(x*1e-9)
|
def get_identifier(recipe):
"""Return identifier from recipe dict. Tries the Identifier
top-level key and falls back to the legacy key location."""
try:
return recipe["Identifier"]
except (KeyError, AttributeError):
try:
return recipe["Input"]["IDENTIFIER"]
except (KeyError, AttributeError):
return None
except TypeError:
return None
|
def to_solution(parameters, columns):
"""Convert a solution given as a list pairs of column indices and values to
a solution given as a list of pairs of columns and values."""
return [(parameters.columns[column_id], value)
for column_id, value in columns]
|
def map_schema(line, schema):
"""
cleans the message msg, leaving only the fields given by schema, and casts the appropriate types
returns None if unable to parse
:type line : str message to parse
:type schema: dict schema that contains the fields to filter
:rtype : dict message in the format {"field": value}
"""
try:
msg = line.split(schema["DELIMITER"])
msg = {key:eval("%s(\"%s\")" % (schema["FIELDS"][key]["type"],
msg[schema["FIELDS"][key]["index"]]))
for key in schema["FIELDS"].keys()}
except:
return
return msg
|
def text_to_sentences(text, terminators = (".", "?", "!", '."', '?"', '!"'), exclude = ("Mr.", "Ms.", "Mrs.", "Dr.", "e.g.", "i.e.")):
"""
Break text into a list of sentences.
This is a highly imperfect function that takes a passage of text and
breaks it into a list of sentences. The main stumbling block for the
function is that there are numerous words that could indicate either the
end of a sentence or the end of an abbreviation. I do not know of an
effective solution to this problem.
NB: The assumption is made that line breaks always denote the end of a
sentence, regardless of the preceding character.
Parameters:
text: the passage to break into sentences.
Keyword Parameters:
terminators: strings that denote the end of a sentence.
exclude: exceptions to the terminators.
Returns:
sentences: a list of sentences in text.
"""
sentences = []
text_as_paragraphs = text.split("\n")
paragraphs_as_words = []
for paragraph in text_as_paragraphs:
paragraph = paragraph.strip()
if not paragraph:
# This is a blank line.
paragraphs_as_words.append([])
# Go to the next paragraph:
continue
words = paragraph.split(" ")
paragraphs_as_words.append(words)
for paragraph in paragraphs_as_words:
if not paragraph:
# This is a blank line.
sentences.append("")
continue
sentence = ""
for word in paragraph:
# Add word to sentence, along with a leading space if necessary:
if sentence:
sentence = sentence+" "+word
else:
sentence = word
# Check whether word ends with a terminator:
try:
ends_with_terminator = word.endswith(terminators)
except TypeError:
# terminators is probably a list rather than a tuple.
# str.endswith() requires a tuple.
terminators = tuple(terminators)
ends_with_terminator = word.endswith(terminators)
if ends_with_terminator and word not in exclude:
# This ends the sentence.
sentences.append(sentence)
sentence = ""
# Check for a dangling sentence:
if sentence:
sentences.append(sentence)
return sentences
|
def div(numer, denom):
"""PFA division behavior: inf and -inf for a finite number divided by zero and nan for 0/0.
Also ensures that return type of any two numbers (including integers) is floating point.
:type numer: number
:param numer: the numerator
:type denom: number
:param denom: the denominator
:rtype: float
:return: fraction, including non-numeric possibilities
"""
try:
return numer / float(denom)
except ZeroDivisionError:
if numer > 0.0:
return float("inf")
elif numer < 0.0:
return float("-inf")
else:
return float("nan")
|
def min_max_indexes(seq):
"""
Uses enumerate, max, and min to return the indices of the values
in a list with the maximum and minimum value:
"""
l = sorted(enumerate(seq), key=lambda s: s[1])
return l[0][0], l[-1][0]
|
def _build_pure_transition_impl(settings, attr):
"""
Transition that enables pure, static build of Go binaries.
"""
return {
"@io_bazel_rules_go//go/config:pure": True,
"@io_bazel_rules_go//go/config:static": True,
}
|
def av_good_mock(url, request):
"""
Mock for availability, best case.
"""
return {'status_code': 301, 'text': 'Light side'}
|
def upsample_kernel_size_solver(
in_size, out_size, stride=1, padding=0, output_padding=0, dilation=1,
):
"""
Returns kernel size needed to upsample a tensor of some input size to
a desired output size.
The implementation solves for kernel size in the equation described the
the "Shape" section of the pytorch docs:
https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose1d.html
"""
x = out_size - 1 - output_padding - (in_size - 1) * stride + 2 * padding
x = int(x / dilation + 1)
return (x, )
|
def addr_to_text(mac_addr, big_endian=False, sep=""):
"""Convert a mac_addr in bytes to text."""
return sep.join(["{:02x}".format(b)
for b in (mac_addr if big_endian else reversed(mac_addr))])
|
def get_core_identifier(cpu_identifier, sensor_identifier):
"""
a cpu has many sensors. some of them for cores. cores themselves don't have identifiers.
thus, we use the identifier of the sensor to infer to which core it belongs.
:param cpu_identifier: e.g. /intelcpu/0
:param sensor_identifier: e.g. /intelcpu/0/load/1 - i.e. the load sensor for core #1 of CPU #0.
:return: a core identifier e.g. /intelcpu/0/1
"""
core_number = sensor_identifier.split('/')[-1]
return cpu_identifier + "/" + core_number
|
def parse_bool(value):
"""Attempt to parse a boolean value."""
if value in ("true", "True", "yes", "1", "on"):
return True
if value in ("false", "False", "None", "no", "0", "off"):
return False
return bool(int(value))
|
def convert_values_to_string(variables):
"""
Converts the values in the dictionary to the string type.
:param variables: the variables dictionary
:rtype: dict[str, object]
:return: the variables dictionary with string values
:rtype: dict[str, str]
"""
if not variables:
return {}
return dict((k, str(v)) for k, v in variables.items())
|
def chunk(arr:list, size:int=1) -> list:
"""
This function takes a list and divides it into sublists of size equal to size.
Args:
arr ( list ) : list to split
size ( int, optional ) : chunk size. Defaults to 1
Return:
list : A new list containing the chunks of the original
Examples:
>>> chunk([1, 2, 3, 4])
[[1], [2], [3], [4]]
>>> chunk([1, 2, 3, 4], 2)
[[1, 2], [3, 4]]
>>> chunk([1, 2, 3, 4, 5, 6], 3)
[[1, 2, 3], [4, 5, 6]]
"""
_arr = []
for i in range(0, len(arr), size):
_arr.append(arr[i : i + size])
return _arr
|
def parseVectors(nodes):
""" Parses a list of nodes (inputs, outputs, regs, wires, etc.) and encodes them based on whether they
are a bus like [127:0]sk, or a single bit value like [1234] or 'a'.
Args:
nodes (list(string)): list of nodes to parse
Returns:
dict(string : int): dictionary encoding the inputted nodes
"""
visited = []
vectors = dict()
for node in nodes:
vec = node.split('~')
if len(vec) == 1:
visited.append(vec[0])
vectors[vec[0]] = 0
else:
vName, vIdx, _ = vec
if vName not in visited:
visited.append(vName)
vectors[vName] = int(vIdx)
elif int(vIdx) > vectors[vName]:
vectors[vName] = int(vIdx)
return vectors
|
def score(word):
"""
Calculate score for a word
"""
result = 0
for char in word.upper():
if char in "AEIOULNRST":
result += 1
elif char in "DG":
result += 2
elif char in "BCMP":
result += 3
elif char in "FHVWY":
result += 4
elif char == "K":
result += 5
elif char in "JX":
result += 8
else:
result += 10
return result
|
def get_symmetric_key():
"""Returns symmetric key bytes
16 bytes that were randomly generated. Form a 128 bit key.
"""
symmetric_key = (
b'\x92\xcf\x1e\xd9\x54\xea\x30\x70\xd8\xc2\x48\xae\xc1\xc8\x72\xa3')
return symmetric_key
|
def is_remove(list, object):
"""remove objects from a list using is equivalence instead
of comparison equivalence"""
result = []
for e in list:
if object is not e:
result.append(e)
return result
|
def overlap(range1, range2):
""" Checks whether two ranges (f.e. character offsets overlap)
This snippet by Steven D'Aprano is from the forum of
www.thescripts.com.
Keyword arguments:
range1 -- a tuple where range1[0] <= range1[1]
range1 -- a tuple where range2[0] <= range2[1]
Returns:
True (ranges overlap) or False (no overlap)
"""
assert(range1[0] <= range1[1]), (range1, range2)
assert(range2[0] <= range2[1]), (range1, range2)
# Fully overlapping cases:
# x1 <= y1 <= y2 <= x2
# y1 <= x1 <= x2 <= y2
# Partially overlapping cases:
# x1 <= y1 <= x2 <= y2
# y1 <= x1 <= y2 <= x2
# Non-overlapping cases:
# x1 <= x2 < y1 <= y2
# y1 <= y2 < x1 <= x2
return not (range1[1] <= range2[0] or range2[1] <= range1[0])
|
def build_history_object(metrics):
"""
Builds history object
"""
history = {"batchwise": {}, "epochwise": {}}
for matrix in metrics:
history["batchwise"][f"training_{matrix}"] = []
history["batchwise"][f"validation_{matrix}"] = []
history["epochwise"][f"training_{matrix}"] = []
history["epochwise"][f"validation_{matrix}"] = []
return history
|
def has_straight(h):
"""
Straight: All cards are consecutive values.
return: (hand value, remaining cards) or None
"""
values = {value for value, _ in h}
if len(values) == 5 and max(values) - min(values) == 4:
return max(values), []
else:
return None
|
def float_fraction(trainpct):
""" Float bounded between 0.0 and 1.0 """
try:
f = float(trainpct)
except ValueError:
raise Exception("Fraction must be a float")
if f < 0.0 or f > 1.0:
raise Exception("Argument should be a fraction! Must be <= 1.0 and >= 0.0")
return f
|
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red'
return 'color: %s' % color
|
def mapset(mapping, oldset):
"""
Applies a mapping to a set.
Args:
mapping:
oldset (set):
Returns:
"""
newset = set()
for e in oldset:
newset.add(mapping[e])
return newset
|
def _estimate_correlation_length(bins, averages):
"""Estimate the correlation length of a spatial velocity correlation
function. The correlation length is typically defined as the radial
distance at which the correlation first becomes zero.
"""
n_point = len(bins)
for i in range(0, n_point-1):
bottom = averages[i]
top = averages[i+1]
if bottom > 0.0 and top < 0.0:
return (bins[i]+bins[i+1])/2.0
return None
|
def bound_ros_command(bounds, ros_pos, fail_out_of_range_goal, clip_ros_tolerance=1e-3):
"""Clip the command with clip_ros_tolerance, instead of
invalidating it, if it is close enough to the valid ranges.
"""
if ros_pos < bounds[0]:
if fail_out_of_range_goal:
return bounds[0] if (bounds[0] - ros_pos) < clip_ros_tolerance else None
else:
return bounds[0]
if ros_pos > bounds[1]:
if fail_out_of_range_goal:
return bounds[1] if (ros_pos - bounds[1]) < clip_ros_tolerance else None
else:
return bounds[1]
return ros_pos
|
def percents_to_pixels(image_width, image_height, row_percent, col_percent, width_percent, height_percent):
"""
Convert from percents of image to pixel values
Args:
image_width:
image_height:
row_percent:
col_percent:
width_percent:
height_percent:
Returns:
(int, int, int, int): row, col, height width in pixels.
"""
row = int(image_height * row_percent)
col = int(image_width * col_percent)
width = int(image_width * width_percent)
height = int(image_height * height_percent)
return row, col, height, width
|
def strip_position(pos):
"""
Stripes position from +- and blankspaces.
"""
pos = str(pos)
return pos.strip(' +-').replace(' ', '')
|
def get_texture_declaration(texture):
"""Return the GLSL texture declaration."""
declaration = "uniform sampler%dD %s;\n" % (texture["ndim"], texture["name"])
return declaration
|
def add_trailing_slash(directory_path):
"""
Add trailing slash if one is not already present.
Argument:
directory_path -- path to which trailing slash should be confirmed.
"""
# Add trailing slash.
if directory_path[-1] != '/':
directory_path=str().join([directory_path, '/'])
# Return directory_path with trailing slash.
return directory_path
|
def h3(text):
"""Heading 3.
Args:
text (str): text to make heading 3.
Returns:
str: heading 3 text.
"""
return '### ' + text + '\r\n'
|
def change_key_in_dict(d, old_key, new_key):
"""Change the key of the entry in `d` with key `old_key` to `new_key`. If
there is an existing entry
Returns:
The modified dict `d`.
Raises:
KeyError : If `old_key` is not in `d`.
"""
d[new_key] = d.pop(old_key)
return d
|
def get_min_rooms(lectures):
"""
Given an array of start and end times for lectures,
find the minimum number of classrooms necessary.
"""
starts = sorted(start for start, _ in lectures)
ends = sorted(end for _, end in lectures)
num_rooms = 0
current_overlap = 0
start_idx, end_idx = 0, 0
while start_idx < len(starts) and end_idx < len(ends):
if starts[start_idx] < ends[end_idx]:
current_overlap += 1
num_rooms = max(num_rooms, current_overlap)
start_idx += 1
else:
current_overlap -= 1
end_idx += 1
return num_rooms
|
def find_active_firmware(sector):
"""Returns a tuple of the active firmware's configuration"""
for i in range(8):
app_entry = sector[i * 32 : i * 32 + 32]
config_flags = int.from_bytes(app_entry[0:4], "big")
active = config_flags & 0b1 == 0b1
if not active:
continue
app_address = int.from_bytes(app_entry[4 : 4 + 4], "big")
app_size = int.from_bytes(app_entry[8 : 8 + 4], "big")
return app_address, app_size, i
return None, None, None
|
def f_exists(fname):
"""
checks if a file exists
:param fname:
:return:
"""
try:
with open(fname) as f:
return True
except IOError:
return False
|
def shorten_name(name, max_length = 10):
"""
Makes a string shorter, leaving only certain quantity of the last characters, preceded by '...'.
@param name: The string to shorten.
@param max_length: Maximum length of the resulting string.
@return: A string with max_lenght characters plus '...'
"""
if len(name) > max_length:
return "..."+name[-max_length:]
else:
return name
|
def perlin_noise_1d(count, seed, octaves, bias):
"""
Return a noise 1d array
"""
perlin_noise = [0.0] * count
for x in range(count):
noise = 0.0
scale = 1.0
scale_accumulate = 0.0
for o in range(octaves):
n_pitch = count >> o
if n_pitch == 0:
continue
n_sample1 = (x / n_pitch) * n_pitch
# this helps with tessellation
n_sample2 = (n_sample1 + n_pitch) % count
# return value between 0 and 1
blend = float(x - n_sample1) / float(n_pitch)
sample = (1.0 - blend) * seed[
n_sample1] + blend * seed[n_sample2]
noise += sample * scale
# half the scale so the noise is less strong
scale_accumulate += scale
scale /= bias
perlin_noise[x] = noise / scale_accumulate
return perlin_noise
|
def multi_gpu_load_single_gpu_model(checkpoint):
""" Use the single gpu trained model in multi gpus.
"""
new_state_dict = {}
for k, v in checkpoint.items():
# remove prefix 'module'.
name = 'module.' + k
new_state_dict[name] = v
# Use 'load_state_dict' to load parameters.
return new_state_dict
|
def add_sequences(seq1: list, seq2: list):
"""
A function to add two sequences and return the result
seq1: A list of integers
seq2: A list of integers
returns: seq1 + seq2 as a list
"""
if len(seq1) == len(seq2):
return [x + y for x, y in zip(seq1, seq2)]
elif len(seq1) == 0 or len(seq2) == 0:
return []
else:
smaller_length = len(seq1) if len(seq1) < len(seq2) else len(seq2)
seq1 = seq1[0:smaller_length]
seq2 = seq2[0:smaller_length]
return [x + y for x, y in zip(seq1, seq2)]
|
def wrappable_range_overlaps(start, end, test,
wrap_after=59, wrap_to=0,
overlap=False
):
"""Figure out whether a range of numbers (specified by 'start' and
'end') has any overlap with the set of numbers in the set 'test'.
The numbers in the range may wrap (e.g., the 60th minute wraps to
the 0th or the 12th month wraps to the 1st); where the wrap occurs
is governed by 'wrap_after' (default 59) and where it wraps is
governed by 'wrap_to' (default 0). If 'overlap' is true, the
start and end must simply overlap with the test set, otherwise it
must be completely contained within it.
"""
if not isinstance(test, set):
raise ValueError("Type of 'test' must be 'set'")
if wrap_to >= wrap_after:
raise ValueError("Unusuable wrap values.")
if not ( (wrap_to <= start <= wrap_after)
and (wrap_to <= end <= wrap_after) ):
raise ValueError("Start and end must be in [%d..%d]" \
% (wrap_to, wrap_after))
ranges = []
if end >= start:
ranges.extend(list(range(start, end+1)))
else:
ranges.extend(list(range(start, wrap_after+1)))
ranges.extend(list(range(0, wrap_to+1)))
ranges = set(ranges)
return bool(test.intersection(ranges)) if overlap \
else ranges.issubset(test)
|
def check_lammps_sim(out_file, verbose=True):
"""
Check if LAMMPS simulation is finished.
"""
FINISHED = False
try:
with open(out_file, 'r') as f:
lines = f.readlines()
if 'Total wall time' in lines[-1]:
FINISHED = True
except Exception as e:
if verbose:
print(e)
# print(lines[-1])
return FINISHED
|
def _tf(word_occured_in_doc: int, total_words_in_doc: int) -> float:
"""Term frequency of a word in certain document.
See: https://bit.ly/3zEDkMn
"""
assert word_occured_in_doc <= total_words_in_doc
return word_occured_in_doc / total_words_in_doc
|
def getid(obj):
"""Extracts object ID.
Abstracts the common pattern of allowing both an object or an
object's ID (UUID) as a parameter when dealing with relationships.
"""
try:
return obj.id
except AttributeError:
return obj
|
def call_req(obj_name, method, params):
"""Construct message used when sending API calls to CtrlServer.
:param obj_name: Name of API-exported system that owns the given method.
:type obj_name: string
:param method: API-exported method to call on the given object.
:type method: string
:param params: Params to pass to the given method.
:type params: dict
:returns: Constructed call_req dict, ready to be sent over the wire.
"""
return {
"type": "call_req",
"obj_name": obj_name,
"method": method,
"params": params
}
|
def subtract(v1, v2):
""" Subtracts v2 from v1. """
return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]]
|
def divide(intf, ints):
"""
overpython.divide(intf, ints)
Divide intf by ints. Raises ValueError if intf/ints is a string.
"""
try:
return float(intf) / float(ints)
except ValueError:
raise ValueError("%s/%s is not a number" % (intf, ints))
|
def parse_keqv_list(l):
"""Parse list of key=value strings where keys are not duplicated."""
parsed = {}
for elt in l:
k, v = elt.split('=', 1)
if v[0] == '"' and v[-1] == '"':
v = v[1:-1]
parsed[k] = v
return parsed
|
def dico_add(*dicos):
""" dictionnaries addition, with (shallow) copy """
if len(dicos) == 0:
return {}
res = dicos[0].__class__()
for dico in dicos:
res.update(dico)
return res
|
def hr_range_formatter(start, end, step):
"""Format a range (sequence) in a simple and human-readable format by
specifying the range's starting number, ending number (inclusive), and step
size.
Parameters
----------
start, end, step : numeric
Notes
-----
If `start` and `end` are integers and `step` is 1, step size is omitted.
The format does NOT follow Python's slicing syntax, in part because the
interpretation is meant to differ; e.g.,
'0-10:2' includes both 0 and 10 with step size of 2
whereas
0:10:2 (slicing syntax) excludes 10
Numbers are converted to integers if they are equivalent for more compact
display.
Examples
--------
>>> hr_range_formatter(start=0, end=10, step=1)
'0-10'
>>> hr_range_formatter(start=0, end=10, step=2)
'0-10:2'
>>> hr_range_formatter(start=0, end=3, step=8)
'0-3:8'
>>> hr_range_formatter(start=0.1, end=3.1, step=1.0)
'0.1-3.1:1'
"""
if int(start) == start:
start = int(start)
if int(end) == end:
end = int(end)
if int(step) == step:
step = int(step)
if int(start) == start and int(end) == end and step == 1:
return '{}-{}'.format(start, end)
return '{}-{}:{}'.format(start, end, step)
|
def get_insert_many_query(table_name: str) -> str:
"""Build a SQL query to insert several RDF triples into a PostgreSQL table.
Argument: Name of the SQL table in which the triples will be inserted.
Returns: A prepared SQL query that can be executed with a list of tuples (subject, predicate, object).
"""
return f"INSERT INTO {table_name} (subject,predicate,object) VALUES %s"
|
def to_bytes(something, encoding='utf8'):
"""
cast string to bytes() like object, but for python2 support
it's bytearray copy
"""
if isinstance(something, bytes):
return something
if isinstance(something, str):
return something.encode(encoding)
elif isinstance(something, bytearray):
return bytes(something)
else:
raise TypeError("Not a string or bytes like object")
|
def frequencies(seq):
""" Find number of occurrences of each value in seq
>>> frequencies(['cat', 'cat', 'ox', 'pig', 'pig', 'cat']) #doctest: +SKIP
{'cat': 3, 'ox': 1, 'pig': 2}
See Also:
countby
groupby
"""
d = dict()
for item in seq:
try:
d[item] += 1
except KeyError:
d[item] = 1
return d
|
def cage_correlations_summing(target_species_hit, transcript_id, target_cages, tf_cages, cage_correlations_dict, cage_corr_weights_dict):
"""
Extract correlation values between CAGEs associated with a predicted TFBS protein,
and CAGEs associated with the current gene.
"""
corr_weights_ls = []
corr_weight_sum = 0
# cages for all transcripts of the predicted TFBS's proteins
tf_name = target_species_hit[0]
for target_cage in target_cages:
if target_cage in cage_correlations_dict:
for tf_cage in tf_cages:
if tf_cage in cage_correlations_dict[target_cage]:
cage_correlation = cage_correlations_dict[target_cage][tf_cage]
cage_corr_weight = cage_corr_weights_dict[abs(cage_correlation)]
corr_weights_ls.append(cage_corr_weight)
# take strongest correlation weight score
if len(corr_weights_ls) > 0:
corr_weights_ls.sort()
corr_weight_sum = corr_weights_ls[-1]
return corr_weight_sum
|
def func_extract_all_project_ids(project_version_mapping):
"""
:param project_version_mapping:
:return: project id list
"""
ids = []
for _ in project_version_mapping.keys():
ids.append(_.id)
return ids
|
def uniq_arr(arr):
"""Remove repeated values from an array and return new array."""
ret = []
for i in arr:
if i not in ret:
ret.append(i)
return ret
|
def line_intersect(pt1, pt2, ptA, ptB):
"""
Taken from https://www.cs.hmc.edu/ACM/lectures/intersections.html
Returns the intersection of Line(pt1,pt2) and Line(ptA,ptB).
"""
import math
DET_TOLERANCE = 0.00000001
# the first line is pt1 + r*(pt2-pt1)
# in component form:
x1, y1 = pt1
x2, y2 = pt2
dx1 = x2 - x1
dy1 = y2 - y1
# the second line is ptA + s*(ptB-ptA)
x, y = ptA
xB, yB = ptB
dx = xB - x
dy = yB - y
DET = -dx1 * dy + dy1 * dx
if math.fabs(DET) < DET_TOLERANCE:
return None
# now, the determinant should be OK
DETinv = 1.0 / DET
# find the scalar amount along the "self" segment
r = DETinv * (-dy * (x - x1) + dx * (y - y1))
# find the scalar amount along the input line
s = DETinv * (-dy1 * (x - x1) + dx1 * (y - y1))
# return the average of the two descriptions
xi = (x1 + r * dx1 + x + s * dx) / 2.0
yi = (y1 + r * dy1 + y + s * dy) / 2.0
if r >= 0 and 0 <= s <= 1:
return xi, yi
else:
return None
|
def merge_dict_recursive(base, other):
"""Merges the *other* dict into the *base* dict. If any value in other is itself a dict and the base also has a dict for the same key, merge these sub-dicts (and so on, recursively).
>>> base = {'a': 1, 'b': {'c': 3}}
>>> other = {'x': 4, 'b': {'y': 5}}
>>> want = {'a': 1, 'x': 4, 'b': {'c': 3, 'y': 5}}
>>> got = merge_dict_recursive(base, other)
>>> got == want
True
>>> base == want
True
"""
for (key, value) in list(other.items()):
if (isinstance(value, dict) and
(key in base) and
(isinstance(base[key], dict))):
base[key] = merge_dict_recursive(base[key], value)
else:
base[key] = value
return base
|
def tickets(people):
"""
Determines whether Vasya can sell a ticket to all people in the queue.
:param people: an array integers ranging from numbers 25, 50, and 100.
:return: YES, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that
moment. Otherwise return NO.
"""
a,b = 0, 0
for x in range(len(people)):
if people[x] == 25:
a += 1
elif people[x] == 50 and a > 0:
a -= 1
b += 1
elif people[x] == 100 and a > 0 and b > 0:
a -= 1
b -= 1
elif people[x] == 100 and a > 2:
a -= 3
else:
return "NO"
return "YES"
|
def is_object(x):
"""Returns True if x has a __dict__ attribute.
This function is intended to determine if its argument is an object
in the "classic" sense--that is, one belonging to a type created by the
"class" construct, and excluding such built-in types as int, str, and
list, which are, strictly speaking, also objects in a general sense.
This function also returns True if x is a class or module.
"""
return hasattr(x, "__dict__")
|
def cleanArrayForKey(lst):
"""
This method will clean out so that only the kh will contain 0,1,2,3,4,5,6,7
"""
array = []
temp = []
for i, x in enumerate(lst):
if x[1] == 0:
temp = [i, x[1]]
array.append(temp)
elif x[1] == 1:
temp = [i, x[1]]
array.append(temp)
elif x[1] == 2:
temp = [i, x[1]]
array.append(temp)
elif x[1] == 3:
temp = [i, x[1]]
array.append(temp)
elif x[1] == 4:
temp = [i, x[1]]
array.append(temp)
elif x[1] == 5:
temp = [i, x[1]]
array.append(temp)
elif x[1] == 6:
temp = [i, x[1]]
array.append(temp)
elif x[1] == 7:
temp = [i, x[1]]
array.append(temp)
return array
|
def _esc_var(name):
"""Returns a valid and unique Python identifier derived from name.
Just returns name with the "_" appended. This is enough to ensure there's
no collisions with any keyword or built-in or import.
Args:
name (string): The name to escape.
Returns:
string: A name which is a valid and unique Python identifier.
"""
return name + '_'
|
def normalise(val, minimum, maximum):
"""
Normalise a value between two values
:param val: value to normalise
:param minimum: minimum boundary
:param maximum: maximum boundary
:return: value between 0 and 1
"""
return (val - minimum) / float(maximum - minimum)
|
def bubblesort(l):
"""
Runtime: O(n^2)
"""
last = len(l)-1
for i in range(last):
for j in range(i+1, last):
if l[i] > l[j]:
l[i], l[j] = l[j], l[i]
return l
|
def join_dots(*inputs):
"""['123', '456', '789'] -> '123.456.789'"""
return '.'.join([item for item in inputs])
|
def wallis_product(n_terms):
"""Implement the Wallis product to compute an approximation of pi.
See:
https://en.wikipedia.org/wiki/Wallis_product
XXX : write Parameters and Returns sections as above.
"""
# XXX : The n_terms is an int that corresponds to the number of
# terms in the product. For example 10000.
pi = 2
if n_terms > 0:
for n in range(1, n_terms+1):
pi *= (4*n**2)/(4*n**2 - 1)
return pi
|
def format_datetime(datetime_):
"""Convert datetime object to something JSON-serializable."""
if datetime_ is None:
return None
return datetime_.strftime('%Y-%m-%dT%H:%M:%SZ')
|
def disbursal(from_acc, amount, from_pass, bank):
""" Withdraws a desired amount of money from a user's account
If a user's account is verified, using the account name and password, the desired amount of money is withdrawn from
the user's account.
:param from_acc: user's account number
:param amount: user's desired amount of money
:param from_pass: user's account password
:param bank: dictionary consisting of all the bank-related data (mainly the clients' data)
:return: if the user's account is verified, returns clients' data after the withdrawal has taken place, and
otherwise, returns a string value of "Invalid Disbursal"
"""
clients_data = []
for client in bank["clients"]:
clients_data.append(client)
balance = client.get("balance")
if client.get("account_number") == from_acc and float(balance) > amount and client.get(
"password") == from_pass:
name = client.get('name')
password = client.get("password")
acc_num = client.get("account_number")
balance = str(float(balance) - amount)
updated_cli = {"name": name, "password": password, "account_number": acc_num, "balance": balance}
clients_data.remove(client)
clients_data.append(updated_cli)
return clients_data
return "Invalid Disbursal"
|
def str2bool(x):
""" Convert a string to a boolean. """
return x.lower() in ("true", "1")
|
def fill_space(s, i, j):
"""
Replace [i to j) slice in a string with empty space " "*len
"""
return s[:i] + " " * (j - i) + s[j:]
|
def make_spec(repos, slack_user_id, author_name):
""" Format and return spec specifying what to analyze
Convenience method: spec used by several other methods here
Args:
repos: list of repo names, which should have their logs jumped to json already in logs2hours/logs/git
start_date: datetime start
end_date: datetime end
slack_user_id: id of desired user, not their name - str
look in the dumps to find this
author_name: git author name
Returns:
spec
"""
spec = {
'repos': repos,
'slack_uid': slack_user_id,
'author_name': author_name
}
return spec
|
def first_missing_positive_naive(a):
"""
O(n) time and O(n) space.
"""
n = len(a)
flag = [False]*n
for x in a:
if x < 1 or x > n:
continue
flag[x-1] = True
for i, f in enumerate(flag):
if not f:
return i+1
|
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'firstact': ['install'],
'secondact': ['install'],
}
|
def djfrontend_h5bp_html(lang):
""" Returns HTML tag according to chosen language.
Included in HTML5 Boilerplate.
"""
output=[
'<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="%s"> <![endif]-->' % lang,
'<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="%s"> <![endif]-->' % lang,
'<!--[if IE 8]> <html class="no-js lt-ie9" lang="%s"> <![endif]-->' % lang,
'<!--[if gt IE 8]><!--> <html class="no-js" lang="%s"> <!--<![endif]-->' % lang,
]
return '\n'.join(output)
|
def tslash(apath):
"""Add a trailing slash to a path if it needs one.
Doesn't use os.sep because you end up jiggered on windoze - when you
want separators for URLs.
"""
if (apath and
apath != '.' and
not apath.endswith('/') and
not apath.endswith('\\')):
return apath + '/'
else:
return apath
|
def escape_markdown(text: str):
"""
return text escaped given entity types
:param text: text to escape
:param entity_type: entities to escape
:return:
"""
# de-escape and escape again to avoid double escaping
return text.replace('\\*', '*').replace('\\`', '`').replace('\\_', '_')\
.replace('\\~', '~').replace('\\>', '>').replace('\\[', '[')\
.replace('\\]', ']').replace('\\(', '(').replace('\\)', ')')\
.replace('*', '\\*').replace('`', '\\`').replace('_', '\\_')\
.replace('~', '\\~').replace('>', '\\>').replace('[', '\\[')\
.replace(']', '\\]').replace('(', '\\(').replace(')', '\\)')
|
def guess_index_name(name: str) -> str:
"""Guess index name for a preferred name.
Naive calculation of "Family Name, Given Name"
"""
return ', '.join(list(reversed(name.split(maxsplit=1))))
|
def decode_cigar(cigar):
"""Return a list of 2-tuples, integer count and operator char."""
count = ""
answer = []
for letter in cigar:
if letter.isdigit():
count += letter # string addition
elif letter in "MIDNSHP=X":
answer.append((int(count), letter))
count = ""
else:
raise ValueError("Invalid character %s in CIGAR %s" % (letter, cigar))
return answer
|
def removePrefix(str, prefix):
"""Removes prefix of str."""
return str[len(prefix):] if str.startswith(prefix) else str
|
def naive_2mm(p, t):
"""Return a naive string match allowing up to 2 mismatches."""
occurrences = []
for i in range(len(t) - len(p) + 1): # loop over alignments
match = True
mismatch = 0
for j in range(len(p)): # loop over characters
if t[i+j] != p[j]: # compare characters
mismatch += 1 # increment mismatch
if mismatch > 2: # mismatches > 2 makes it a mismatch
match = False
break
if match:
occurrences.append(i) # all chars matched; record
return occurrences
|
def basis_function_ders_one(degree, knot_vector, span, knot, order):
""" Finds the derivative of one basis functions for a single knot.
Implementation of Algorithm A2.5 from The NURBS Book by Piegl & Tiller.
:param degree: degree
:type degree: int
:param knot_vector: knot_vector
:type knot_vector: list, tuple
:param span: span of the knot
:type span: int
:param knot: knot
:type knot: float
:param order: order of the derivative
:type order: int
:return: basis function derivatives values
:rtype: list
"""
ders = [0.0 for _ in range(0, order + 1)]
# Knot is outside of span range
if (knot < knot_vector[span]) or (knot >= knot_vector[span + degree + 1]):
for k in range(0, order + 1):
ders[k] = 0.0
return ders
N = [[0.0 for _ in range(0, degree + 1)] for _ in range(0, degree + 1)]
# Initializing the zeroth degree basis functions
for j in range(0, degree + 1):
if knot_vector[span + j] <= knot < knot_vector[span + j + 1]:
N[j][0] = 1.0
# Computing all basis functions values for all degrees inside the span
for k in range(1, degree + 1):
saved = 0.0
# Detecting zeros saves computations
if N[0][k - 1] != 0.0:
saved = ((knot - knot_vector[span]) * N[0][k - 1]) / (knot_vector[span + k] - knot_vector[span])
for j in range(0, degree - k + 1):
Uleft = knot_vector[span + j + 1]
Uright = knot_vector[span + j + k + 1]
# Zero detection
if N[j + 1][k - 1] == 0.0:
N[j][k] = saved
saved = 0.0
else:
temp = N[j + 1][k - 1] / (Uright - Uleft)
N[j][k] = saved + (Uright - knot) * temp
saved = (knot - Uleft) * temp
# The basis function value is the zeroth derivative
ders[0] = N[0][degree]
# Computing the basis functions derivatives
for k in range(1, order + 1):
# Buffer for computing the kth derivative
ND = [0.0 for _ in range(0, k + 1)]
# Basis functions values used for the derivative
for j in range(0, k + 1):
ND[j] = N[j][degree - k]
# Computing derivatives used for the kth basis function derivative
# Derivative order for the k-th basis function derivative
for jj in range(1, k + 1):
if ND[0] == 0.0:
saved = 0.0
else:
saved = ND[0] / (knot_vector[span + degree - k + jj] - knot_vector[span])
# Index of the Basis function derivatives
for j in range(0, k - jj + 1):
Uleft = knot_vector[span + j + 1]
# Wrong in The NURBS Book: -k is missing.
# The right expression is the same as for saved with the added j offset
Uright = knot_vector[span + j + degree - k + jj + 1]
if ND[j + 1] == 0.0:
ND[j] = (degree - k + jj) * saved
saved = 0.0
else:
temp = ND[j + 1] / (Uright - Uleft)
ND[j] = (degree - k + jj) * (saved - temp)
saved = temp
ders[k] = ND[0]
return ders
|
def build_completed_questions_feedback(actor_name, quiz_name, course_name, score, feedback):
"""
Build the feedback when an user has completed the quiz and has failed the quiz.
:param actor_name: Name of the user that has completed the quiz.
:type actor_name: str
:param quiz_name: Name of the quiz.
:type quiz_name: str
:param course_name: Name of the course.
:type course_name: str
:param score: Result of the user.
:type score: str
:param feedback: String with the feedback.
:type feedback: str
:return: String of the message.
:rtype: str
"""
if feedback == '':
return ''
message = f'Hi {actor_name},\n You have completed the quiz "{quiz_name}" for the course "{course_name}". ' \
f'You did not answer every question correct. For information about the topics of the questions ' \
f'you answered wrong, please take a look at: {feedback}'
return message
|
def italReplacements(tex):
"""
Replace the Latex command "\\textit{<argument>}" with just
argument
"""
while (tex.find("\\textit{") != -1):
beg = tex.find("\\textit{")
sbrace = tex.find("{", beg)
ebrace = tex.find("}", sbrace)
tex = tex[:beg] + tex[sbrace+1:ebrace] \
+ tex[ebrace+1:]
return tex
|
def toFloat (str, default=None):
"""toFloat(str[, default]) -> float | default
Converts the given string to a floating-point value. If the
string could not be converted, default (None) is returned.
NOTE: This method is *significantly* more effecient than
toNumber() as it only attempts to parse floating-point numbers,
not integers or hexadecimal numbers.
Examples:
>>> f = toFloat("4.2")
>>> assert type(f) is float and f == 4.2
>>> f = toFloat("UNDEFINED", 999.9)
>>> assert type(f) is float and f == 999.9
>>> f = toFloat("Foo")
>>> assert f is None
"""
value = default
try:
value = float(str)
except ValueError:
pass
return value
|
def nest_toc_tokens(toc_list):
"""Given an unsorted list with errors and skips, return a nested one.
[{'level': 1}, {'level': 2}]
=>
[{'level': 1, 'children': [{'level': 2, 'children': []}]}]
A wrong list is also converted:
[{'level': 2}, {'level': 1}]
=>
[{'level': 2, 'children': []}, {'level': 1, 'children': []}]
"""
ordered_list = []
if len(toc_list):
# Initialize everything by processing the first entry
last = toc_list.pop(0)
last['children'] = []
levels = [last['level']]
ordered_list.append(last)
parents = []
# Walk the rest nesting the entries properly
while toc_list:
t = toc_list.pop(0)
current_level = t['level']
t['children'] = []
# Reduce depth if current level < last item's level
if current_level < levels[-1]:
# Pop last level since we know we are less than it
levels.pop()
# Pop parents and levels we are less than or equal to
to_pop = 0
for p in reversed(parents):
if current_level <= p['level']:
to_pop += 1
else: # pragma: no cover
break
if to_pop:
levels = levels[:-to_pop]
parents = parents[:-to_pop]
# Note current level as last
levels.append(current_level)
# Level is the same, so append to
# the current parent (if available)
if current_level == levels[-1]:
(parents[-1]['children'] if parents
else ordered_list).append(t)
# Current level is > last item's level,
# So make last item a parent and append current as child
else:
last['children'].append(t)
parents.append(last)
levels.append(current_level)
last = t
return ordered_list
|
def ordinal(n):
"""If n is a cardinal, ordinal function will return it's ordinality"""
return "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])
|
def argsparselist(txt):
"""
Validate a list of txt argument.
:param txt: argument with comma separated int strings.
:return: list of strings.
"""
txt = txt.split(",")
listarg = [i.strip() for i in txt]
return listarg
|
def tn_rate(TN, neg):
"""
Gets true positive rate.
:param: TP: Number of true negatives
:type TN: `int`
:param: pos: Number of negative labels
:type neg: `int`
:return: true negative rate
:rtype: `float`
"""
if neg == 0:
return 0
else:
return TN / neg
|
def possible_bipartition(dislikes):
""" Will return True or False if the given graph
can be bipartitioned without neighboring nodes put
into the same partition.
Time Complexity: O(n^2)
Space Complexity: O(n)
"""
visited = [False] * len(dislikes)
color = [-1] * len(dislikes)
def dfs(v, c):
visited[v] = True
color[v] = c
for u in dislikes[v]:
if not visited[u]:
dfs(u, 1 - c)
for i in range(len(dislikes)):
if not visited[i]:
dfs(i, 0)
for i in range(len(dislikes)):
for j in dislikes[i]:
if color[i] == color[j]:
return False
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.