content stringlengths 42 6.51k |
|---|
def _solve_method_3(N, queries):
"""Me manually trying to mimic/perform/do the "slope" method."""
arr = [0] * N
for query in queries:
a, b, k = query[0], query[1], query[2]
arr[a-1] += k
arr[b] -= k
largest = -1
for i in arr:
if i > largest:
largest = i
... |
def get_hkld_from_matching_id(hkld_ids: dict) -> dict:
"""
given a list of h,k,l, or d values from a place where the list contains values from multiple phases,
return only those values corresponding to the given phase id
:param hkld_ids: dictionary of h,k,l,d,id values
:return: a list containing the... |
def add_wdpp(articles, wdpp):
"""Join in Wikidata page protection information to articles."""
pid_to_qid = {pid:articles[pid]['pageprops']['wikibase_item'] for pid in articles}
for pid, qid in pid_to_qid.items():
found = False
for item in wdpp:
if item['title'] == qid:
... |
def part2(input_data):
"""
>>> part2(["abc"])
3
>>> part2(["a\\nb\\nc"])
0
>>> part2(["ab\\nac"])
1
>>> part2(["a\\na\\na\\na"])
1
>>> part2(["b"])
1
"""
total_count = 0
for group in input_data:
ppl = group.split('\n')
yes_questions = {}
fo... |
def white_spaces(x):
"""
Blank Spaces
"""
x -= 2
espac = ' ' * x
return espac |
def hexstr_to_int(value, base=16):
"""
Convert hex string to int.
:param value:
:param base:
:return:
"""
return int(value, base=base) |
def dot2object(dotted_dict):
"""
Create a object based on a dict that use
dot notation keys.
"""
obj = {}
for k in dotted_dict:
keys = k.split(".")
new_key = keys[0]
if not new_key in obj:
obj[new_key] = {}
obj[new_key][".".join(keys[1:])] = dotted_dic... |
def binary_search(query, numbers, left, right):
"""
The contents of this method are either influenced by or directly copied from "Assemblytics_uniq_anchor.py"
written by Maria Nattestad. The original script can be found here:
https://github.com/MariaNattestad/Assemblytics
And the publication assoc... |
def find_sub_indexes(s: str, sub: str):
"""
Returns all the indexes where the "sub" string appears in "s".
"""
indexes_list = []
counter = 0
while counter < len(s):
temp = s[counter:].find(sub)
if temp == -1:
return indexes_list
# counter += temp
# pri... |
def hms_to_sec(hms: str) -> float:
"""Convert HH:mm:ss.SSS to seconds."""
h, m, s, ms = map(int, hms.replace('.', ':').split(':'))
sec = 3600 * h + 60 * m + s + .001 * ms
return sec |
def fmt_union(type_strings):
"""
Returns a union type of the given types.
"""
return '|'.join(type_strings) if len(type_strings) > 1 else type_strings[0] |
def generate_wf_name(projectid, subjectid, sessionid, processing_phase):
"""
This function...
:param projectid:
:param subjectid:
:param sessionid:
:processing_phase:
:return:
"""
return (
"WF_"
+ str(subjectid)
+ "_"
+ str(sessionid)
+ "_"
... |
def slice_shrink(xp,x,interval):
"""
NAME:
slice_shrink
PURPOSE:
shrink the interval in slice sampling (Mackay 2003)
INPUT:
xp - proposed sample
x - current sample
interval - the current interval
OUTPUT:
new interval
REVISION HISTORY:
... |
def hangman_display(guessed, secret):
""" This sets up the hangman display"""
#guessed = letters guessed so far
#secret = full secret word/phrase
secret_list = list(secret)
guess_list = list(guessed)
new_list = []
for i in secret_list:
if i in guess_list:
new_list.append(... |
def multiply_two(arg1, arg2):
""" (float, float) -> float
multiplies two numbers (arg1 * arg2)
Returns the product
"""
try:
return arg1 * arg2
except TypeError:
return 'Unsupported operation: {0} * {1} '.format(type(arg1), type(arg2)) |
def replace_dict(d0, d1):
"""
Returns a dictionary whose keys are the intersection of d0 and d1, and
whose values are from d1.
"""
ret = {}
for (name, val) in d1.items():
if name in d0.keys():
ret[name] = val
return ret |
def f(n):
"""
Parameters
----------
n : integer, n >= 0
Returns
-------
integer
"""
if n == 0:
return 1
else:
return n * f(n - 1) |
def key_to_link(key: int):
"""Returns a URL containing the unique key for the survey."""
return 'http://localhost:5000/forms/validate/' + str(key) |
def convert_tf_to_crowdsourcing_format(images, detections):
"""
Args:
images: dictionary {image_id : image info} (images from Steve's code)
detections: detection output from multibox
Returns:
dict : a dictionary mapping image_ids to bounding box annotations
"""
image_annotation... |
def is_regex(obj):
"""Cannot do type check against SRE_Pattern, so we use duck typing."""
return hasattr(obj, 'match') and hasattr(obj, 'pattern') |
def human_readable_timedelta(duration):
"""Timedelta as a human readable string.
:param duration: timedelta values from timedelta_to_dict()
:type duration: dict
:returns: Human readable string
"""
if not duration:
return ""
assert isinstance(duration, dict)
# format duration s... |
def string(
value,
shortest=None,
longest=None,
cut=False,
lower=False,
upper=False,
strip=False,
pad=False,
align="<",
):
"""Returns back a string from the given value"""
value = str(value)
if shortest is not None and len(value) < shortest:
if pad:
va... |
def rivers_with_station(stations) -> set:
"""returns a set of rivers"""
DuplicateRivers = []
for station in stations:
DuplicateRivers.append(station.river)
Rivers = set(DuplicateRivers)
return Rivers |
def remove_bots(members):
"""Removes bots from a list of members"""
bots = []
for member in members:
if member.bot:
bots.append(member)
for bot in bots:
members.remove(bot)
return members |
def hex_to_rgb(hexx):
"""
Utility function to convert hex to (r,g,b) triples.
http://ageo.co/1CFxXpO
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
tuple: The equivalent RGB triple, in the range 0 to 255.
"""
h = hexx.strip('#')
l = len(h)
retu... |
def calc_distance(original, closest):
"""
Parameters
----------
original : Numpy array
The coordinates where you want to know the distance to the closest surface
closest : TYPE
The closest point to the points of interest
Returns
-------
distance : Numpy array
... |
def process_file(data: list) -> list:
"""Changes the string-digits into integers"""
election_data = [i.split(' ') for i in data]
# Change string-digits to integers:
for i, candidate in enumerate(election_data):
for j, field in enumerate(candidate):
if field.isdigit():
... |
def align2local(seq):
"""
Returns list such that
'ATG---CTG-CG' ==> [0,1,2,2,2,3,4,5,5,6,7]
Used to go from align -> local space
"""
i = -1
lookup = []
for c in seq:
if c != "-":
i += 1
lookup.append(i)
return lookup |
def string_to_list(text, separator=' '):
""" Converts a string to a list of 'letters' using the (optional) separator
:param str text: Text to split
:param str seperator: [Optional] Separator to split string by
:return: List of split string elements
:rtype: list
"""
return text.split(separ... |
def force_bytes(s, encoding='utf-8', errors='strict'):
"""
Return a bytestring version of s.
:param s: string to coerce
:param encoding: encoding to use
:return: bytestring version of s
"""
if isinstance(s, bytes):
if encoding == 'utf-8':
return s
else:
... |
def getid(obj):
"""Return id if argument is a Resource.
Abstracts the common pattern of allowing both an object or an object's ID
(UUID) as a parameter when dealing with relationships.
"""
try:
if obj.uuid:
return obj.uuid
except AttributeError:
pass
try:
... |
def extractLeafsAndIntBranches( nt, options, leafDict ):
"""Given a newick tree object, it returns a dict of
leaf and internal branch objects. Operates recursively.
"""
if nt is None:
return None
nt.distance = 0
if nt.right is None and nt.left is None:
# leaf
leafDict[ nt... |
def div_imglst_by_name(image_list):
"""divide image list by frame name
:param image_list
:output img_lists
"""
image_list.sort()
code_list = [path.split('\\')[-1].split('.')[0] for path in image_list]
def get_seg_ind(name):
return int(name[:4])
seg_cell = []
start_i... |
def _split_work(load, workers, proc_id):
"""
Uniformly distributes load over the dimension.
Remaining load is assigned in reverse round robin manner
Parameters
----------
load : int
load size to be assigned
workers : int
total processing elements work will be assigned to
... |
def pad_line_and_add_pipe(line, width, last=False):
"""
Pads to width or truncate, adding the | in the start
"""
l = width - len(line)
last_pipe = '|' if last else ''
if l > 0:
return '|' + line + ' ' * l + last_pipe
else:
return '|' + line[:width] + last_pipe |
def recover_escape(text: str) -> str:
"""Converts named character references in the given string to the corresponding
Unicode characters. I didn't notice any numeric character references in this
dataset.
Args:
text (str): text to unescape.
Returns:
str: unescaped string.
"""
return text.replace('&', '... |
def convertosides(polypointsx, polypointsy):
"""
Takes polypoints describing the corners of a polygon and returns list of quadruples describing sides of polygon
Input:
polypointsx (list of float): corners of the polygon in a consecutive order, any format, x
polypointsy (list of float): corners of t... |
def format_currency(int_amount):
""" Format the input currency in a human readable way """
if int_amount is None:
return '$---'
amount_str = '${:0,.2f}'.format(abs(float(int_amount)/100))
if int_amount < 0:
amount_str = '-' + amount_str
return amount_str |
def getPositiveCoordinateRangeOverlap(uStart1, uEnd1, uStart2, uEnd2):
"""@return: If the two coordinate ranges overlap on the same strand
returns the overlap range. If no overlap it returns None.
"""
if uEnd1 < uStart2 or uEnd2 < uStart1:
return None
l = [ uStart1, uEnd1, uStart2, uEnd2 ]
... |
def report_new_event(json_obj):
"""
Generates new event message.
Args:
json_obj (obj): JSON obj.
Returns:
string: Message.
"""
name = json_obj['Dogodek']
event_start = json_obj['Od']
event_stop = json_obj['Do']
location = json_obj['Lokacija']
country = json_obj[... |
def calc_arc_extent(day: int, hour: int, minutes: int) -> int:
"""
Returns the value, in degrees, to use to draw the arc representing the current minutes. It is negative to run
clockwise.
Hour and day are passed to handle the hedge cases.
:param day: current day
:param hour: current hour
:p... |
def string_contrast(ss):
"""From an array of strings, *ss*, returns maximum common prefix
string, maximum common suffix string, and array of middles.
"""
s = [item + 'q' for item in ss if item is not None]
short = min(s, key=len)
for ib in range(len(short)):
if not all([mc[ib] == short[... |
def escape_html(raw_string):
"""Escape html content
Note: only use for short strings
"""
return raw_string.replace('&', '&').replace('<', '<').replace('>', ">") |
def largest_prime_factor_naive(number):
"""
Let the given number be n and let k = 2, 3, 4, 5, ... .
For each k, if it is a factor of n then we divide n by k and completely divide out each k before moving to the next k.
It can be seen that when k is a factor it will necessarily be prime, as all smaller... |
def round_to(x: int, to: float = 1.0) -> float:
"""Rounds a number down to the nearest multiple of `to`"""
return to * (x // to) |
def parse_file_name(image_name):
"""
Parse image file names including possible extensions.
Parameters
----------
image_name : str
An image file name and (optionally) extension specification,
e.g.: ``'j1234567q_flt.fits[1]'``, ``'j1234568q_flt.fits[sci,2]'``,
etc.
Return... |
def get_leader_and_non_leaders(status):
"""Get the leader and non-leader Juju units.
This function returns a tuple that looks like:
({
'unit/1': juju.Unit,
},
{
'unit/0': juju.Unit,
'unit/2': juju.unit,
})
The first entry of this tuple is the leader, and the second... |
def contains(items, value, key, casefold=False):
"""
Return if a value is found in a key.
Parameters
----------
items : the list.
value : the value.
key : the key.
Return if a value is found for the specified key in the list.
"""
if casefold:
value = str(value)... |
def get_expressions_out(
raw_expressions, descriptors, source, expression_type, group_by
):
"""Return expressions output."""
return {
"raw_expressions": raw_expressions,
"descriptors": descriptors,
"source": source,
"expression_type": expression_type,
"group_by": grou... |
def format_action_as_text(field):
"""
Given an instance (ie from "numpy_to_instance") convert it into text
:param field:
:param object_id: which object
:param convert_ids: Whether to convert numbers like "distance: 3" into the names
:return: text representation
"""
txt = ['Action: {}'.fo... |
def build_metrics(region, values):
"""Build"""
dash_values = {
'Metric': values,
'Region': region,
'TitlePrefix': {
'us-east-1': 'NA',
'eu-west-1': 'EU',
'ap-southeast-2': 'AU'
}
}
return dash_values |
def format_package_list(packages):
"""
Take the package list provided by salt and
format it as spacewalk expects it.
"""
# FIXME: Fake data needs to be sourced correctly
def frmt_pkg(name, version):
return {'name': name, 'version': version,
'epoch': '', 'release': 'unknow... |
def get_current_hessian_penalty_loss_weight(max_lambda, hp_start_iter, t, T):
"""
Computes the current loss weighting of the Hessian Penalty.
max_lambda: Maximum loss weighting for the Hessian Penalty
hp_start_iter: the first training iteration where we start applying the Hessian Penalty
t: current... |
def bool_type(argument):
"""
Implement conversion of boolean input parameters since
arparse (or bool, depending on the point of view), do not
handle bool as a type in an intuitive fashion.
:param argument: The argument to be parsed to a boolean
:return: The converted value
"""
try:
... |
def bazed_ulid(n):
""" recode number in ULID format """
baza = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
bl = len(baza)
res = ''
if n == 0:
return '0'
while n:
r = n % bl
n //= bl
res = baza[r] + res
return res |
def largest_prime_factor(n: int) -> int:
"""https://stackoverflow.com/questions/15347174/python-finding-prime-factors"""
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
return n |
def _get_age_label(days_birth, ranges):
""" Return the age group label (int). """
age_years = -days_birth / 365
for label, max_age in enumerate(ranges):
if age_years <= max_age:
return label + 1
else:
return 0 |
def dest(side):
"""Given a side, give the destination of the triangle"""
return (side - 1) % 3 |
def get_hall_url(hall_id):
""" Builds the URL for the menu of a specific dining hall """
url = 'http://dining.columbia.edu/?quicktabs_homepage_menus_quicktabs='
url = url + str(hall_id)
url = url + '#quicktabs-homepage_menus_quicktabs'
return url |
def extractNetmaskFromIPAddress(ipv4WithNetmask) :
"""
:param ipv4WithNetmask:
:return
"""
# We receive in parameter an ipv4 address and mask as "192.168.10.11 255.255.255.0"
# We will extract only the netmask from ip parameter
# There is not check in this function
print("=============... |
def has_duplicates(anylist):
"""Returns a boolean whether a list contains duplicates values
It does this by comparing the length of the list to the length
of the set of the list. A set will only include unique values.
"""
if not isinstance(anylist, list):
raise ValueError(
"has_d... |
def highlight_status(status):
""" a little filter to colour our status entires in project lists.
"""
status_colours = {"Cancelled": "red", "Ongoing": "blue", "Complete": "green"}
return status_colours.get(status, "black") |
def replace_line(data, my_array):
"""
Args: data : data to replace
my_array : replace data in this array
Return: new array with new data
"""
new_list = []
for line in my_array:
for idx, value in data.items():
line = line.replace(idx, value)
new_list.append(... |
def _theoretical_logit_grad(x):
"""Reference implementation for the gradient of the logit function."""
return 1 / (x * (1.0 - x)) |
def int_to_bytes_str(value: int) -> bytes:
"""
Converts a int value to a bytes array containing the numeric character.
Ex: 123 -> b'123'
:param value: int value to convert
:return: bytes array
"""
return str(value).encode("utf-8") |
def getStructName(sig):
"""Get the class name from a signature or '', if signature is not a class."""
sig = sig.strip()
pos1 = sig.rfind(' ')
if pos1 < 0: return ""
while (pos1 > 0) and (sig[pos1] == ' '): pos1 -= 1
if ((pos1 >= 5) and (sig[pos1-5:pos1+1] == 'struct')) or ((pos1 >= 4)... |
def exam_grade(score):
"""Students in a class receive their grades as Pass/Fail. Scores of 60 or more
(out of 100) mean that the grade is "Pass". For lower scores, the grade is
"Fail". In addition, scores above 95 (not included) are graded as "Top Score".
This function receives the score and returns the proper grad... |
def split_key_path_to_hive_and_path(key_path):
"""Return a (hive, path) tuple given a full key path"""
path_parts = key_path.split("\\")
hive = path_parts[0]
path = "\\".join(path_parts[1:])
return hive, path |
def get_table_id(meta):
"""
meta types:
- table_caption_18
- cell_18_1_1
- header_cell_18_0_0
"""
if meta.startswith("table_caption"):
return meta.split("_")[-1]
if meta.startswith("header_cell") or meta.startswith("cell"):
return meta.split("_")[-3] |
def ghc_cc_program_args(cc):
"""Returns the -pgm* flags required to override cc.
Args:
cc: string, path to the C compiler (cc_wrapper).
Returns:
list of string, GHC arguments.
"""
args = [
# GHC uses C compiler for assemly, linking and preprocessing as well.
"-pgma",
... |
def slices_union(seq):
"""Sort 2-tuples and combine them as if right-open intervals."""
out = []
for (start, end) in sorted(seq):
if len(out) < 1 or out[-1][1] < start:
out.append((start, end))
else:
out[-1] = (out[-1][0], end)
return out |
def iter_or_list(val):
"""Return val if iterable else None"""
try:
if any(True for _ in val):
return val
return []
except Exception:
return [
val,
] |
def simpleInterest(p, r, t):
"""Simple interest
Returns: interest value
Input values:
See 'Simple interest future value' below
"""
i = p * r * t
return i |
def nand(arg1: bool, arg2: bool):
"""
Performs a nand (not and) operation on two booleans
:param arg1: boolean 1
:param arg2: boolean 2
:return: not (arg1 and arg2)
"""
return not (arg1 and arg2) |
def scaleto100(value):
"""Scale to IPX800 value."""
return max(0, min(100, round((value * 100.0) / 255.0))) |
def gen_anytext(*args):
"""
Convenience function to create bag of words for anytext property
"""
bag = []
for term in args:
if term is not None:
if isinstance(term, list):
for term2 in term:
if term2 is not None:
bag.a... |
def make_cup_prefix(radUnit, outerCup, innerCupSer, innerCupNum):
"""
Makes filename prefix given RU, OC, IC info
Parameters
----------
radUnit: string
radiation unit
outerCup: string
outer cup info
innerCupSer: string
inner cup serial line... |
def glyphicon(icon):
""" Shorthand for bootstrap glyphicon markup
:param icon: the icon to present, gets appended to glyphicon-{{ icon }}
:return: the template context
"""
return {'icon': icon} |
def _fabric_network_name(fabric_name, network_type):
"""
:param fabric_name: string
:param network_type: string (One of the constants defined in NetworkType)
:return: string
"""
return '%s-%s-network' % (fabric_name, network_type) |
def guess_type(col_values):
""" Find the most frequent data type in col_values """
highest_freq = 0
ret_type = None
values = [cell_value for cell_value in col_values]
type_list = [type(cell_type) for cell_type in col_values]
values_types = zip(values, type_list)
for cell_value, cell_typ... |
def parse_page_metadata(item):
"""Parse out page attributes from the raw page metadata construct."""
_id = item[0]
page_idx = item[1]
_page_nums = item[2]
ix = item[3]
obj = {'id': _id,
'page_idx': page_idx, # Maintain our own count, just in case; should be page_leaf_num-1
... |
def plugin_reconfigure(handle, new_config):
""" Reconfigures the plugin, it should be called when the configuration of the plugin is changed during the
operation of the South device service.
The new configuration category should be passed.
Args:
handle: handle returned by the plugin ini... |
def node_value(data):
"""
>>> node_value([0, 1, 7])
(7, 3)
>>> node_value([0, 3, 1, 0, 5])
(6, 5)
>>> node_value([1, 1, 0, 1, 8, 1])
(8, 6)
>>> node_value([1, 4, 0, 1, 8, 1, 1, 0, 9])
(16, 9)
"""
child_count = data[0]
metadata_count = data[1]
index = 2
children =... |
def apply_mask(xy):
"""
Apply bitmask to value.
Args:
xy: A tuple with the bit of the mask
and the bit to mask (mask, value).
Returns:
The bit after being masked.
"""
if xy[0] == 'X':
return xy[0]
elif xy[0] == '1':
return xy[0]
else:
return xy[1] |
def build_transmitter_name(network_name, site_name):
"""
Return a string that is the network name with spaces removed followed
by an underscore followed by the site name with spaces removed.
EXAMPLES:
>>> build_transmitter_name('Slap hAppy', 'Go go ')
'SlaphAppy_Gogo'
"""
return netwo... |
def distance(a, b):
"""Fonction qui retourne la distance entre deux points
:param a: Point a (x_a, y_a)
:param b: Point b (x_b, y_b)
:return: float
"""
return ((a[0] - b[0])**2 + (a[1] - b[1])**2)**0.5 |
def col(col_no) -> slice:
"""Returns slice object for appropriate column.
Note: Can this be memoised? Would it help in any way?
"""
start = col_no
step = 9
return slice(start, None, step) |
def makeScalarProduct(vector1, vector2):
"""
calculating the scalar product vector1 x vector2
"""
return vector1[0]*vector2[0] + vector1[1]*vector2[1] + vector1[2]*vector2[2] |
def listToString(inputList):
"""Converts a list of integers into an ASCII string."""
return ''.join([chr(i) for i in inputList]) |
def index_to_letter(index):
""" Convert a 1-index to a letter in the alphabet: 1 -> a,... """
return chr(ord('a') + index - 1) |
def dict_flatten(dic: dict):
"""
d = {'a': range(10), 'b': range(20)}
[(k, i) for k, v in d.items() for i in v]
:param dic:
:return:
"""
return [(k, i) for k, v in dic.items() for i in v] |
def splitGtfId(gtfIds):
""" extracts transcript and gene name from last column in gtf"""
splitids = gtfIds.split('"')
return splitids[1], splitids[3] |
def _get_discussion_styles(_helper_cfg):
"""This function defines (when present in the configuration) the enabled discussion styles in the environment.
:param _helper_cfg: The configuration parsed from the helper configuration file
:type _helper_cfg: dict
:returns: List of enabled discussion styles in ... |
def ratio(leechs, seeds):
""" computes the torrent ratio"""
try:
ratio = float(seeds) / float(leechs)
except ZeroDivisionError:
ratio = int(seeds)
return ratio |
def standardize_sample_or_class_weights(x_weight,
output_names,
weight_type):
"""Maps `sample_weight` or `class_weight` to model outputs.
# Arguments
x_weight: User-provided `sample_weight` or `class_weight` argument.
... |
def count_tilings(n: int) -> int:
"""Returns the number of unique ways to tile a row of length n >= 1."""
if n < 5:
# handle recursive base case
return 2**(n - 1)
else:
# place each tile at end of row and recurse on remainder
return (count_tilings(n - 1) +
cou... |
def benchmark_id(request):
"""Benchmark id of the benchmark to test."""
return request.param if hasattr(request, 'param') else None |
def v7_add(matrix1, matrix2):
"""Add corresponding numbers in given 2-D matrices.
One-liner solution =}
"""
return [[n+m for n, m in zip(r1, r2)] for r1, r2 in zip(matrix1, matrix2)] |
def first_arg_equals(e, t):
"""
Return true if the first args are equal in both
"""
return e.args[0] == t.args[0] |
def citep(body:str):
"""
Change
\cite
to
\citep
"""
body = body.replace(r'\cite',r'\citep')
return body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.