content stringlengths 42 6.51k |
|---|
def _recall(conf_mat):
"""
Compute the recall score, i.e. the ratio of true positives to true positives and false negatives.
Answers the question: "Which share of the pixels that are actually slum was identified by the model as such?"
:param conf_mat: Confusion matrix produced by conf_mat().
:retu... |
def swap_dict_key_and_values(d):
"""
Given a dictionary, return a dictionary with the keys and values of the original dictionary swapped
"""
d2 = {}
for key, value in d.items():
if type(value)==int:
d2[int(value)] = key
else:
d2['{}'.format(value)] = key
... |
def snake_to_camel(word: str) -> str:
"""Converts string in snake case to camel case.
For example, "test_string" becomes "TestString"
"""
return ''.join(x.capitalize() or '_' for x in word.split('_')) |
def _str_fmt_dct(dct):
"""Assumes dict mapping str to float."""
return " | ".join("%s: %.4g" % (k, v) for k, v in dct.items()) |
def get_number(num):
"""Return the number one less than the given positive number.
If the number is nonpositive, return a string "Enter a positive number!".
Arguments:
num -- an integer.
Return values:
An integer one less than the input number.
"""
return "Enter a positive number!" if... |
def long_birth(well, origin, irid):
"""If the well is empty and the well h distance away is an xantophore, create a melanophore"""
if (well == 'S') & (origin == 'X') & (~ irid):
return 'M'
else:
return well |
def attribute_hex(x):
"""return a python code string for a hex value"""
if x is None:
return 'None'
return '0x%x' % x |
def prodtypes_remediation(rule_obj, r_type):
"""
For a rule object, check if the prodtypes match between the YAML and the
remediations of type r_type.
"""
rule_id = rule_obj['id']
rule_products = set(rule_obj['products'])
if not rule_products:
return
remediation_products = set... |
def get_theta(pressure, temperature):
"""calculate potential temperature profile"""
# standard reference pressure [Pa]
ref_pressure = 1e5
# gas constant [kg m**2 s**-2 K**-1 mol*-1]
gas_constant = 8.3144598
# specific heat capacity at constant pressure for air
spec_heat_capacity = 29.07
... |
def cleanup_ip(ip):
"""
Given ip address string, it cleans it up
"""
ip = ip.strip().lower()
if (ip.startswith('::ffff:')):
return ip.replace('::ffff:', '')
return ip |
def is_integer(obj):
"""
Return True if *obj* is an int, False otherwise.
"""
return isinstance(obj, int) |
def writeBenchScript(dir, benchmark_name, size, synthetic):
"""
This method creates a script in dir which will be eventually
passed to the simulated system (to run a specific benchmark
at bootup).
"""
input_file_name = '{}/run_{}_{}'.format(dir, benchmark_name, size)
if (synthetic):
... |
def is_not_excluded_type(file, exclude_types):
"""Return False if file type excluded, else True"""
if exclude_types:
for exclude_type in exclude_types:
if file.lower().endswith(exclude_type.lower()):
return False
return True |
def url_parse_server_protocol(settings_dict):
"""Return the public HTTP protocol, given the public base URL
>>> url_parse_server_protocol({'USE_SSL': True})
'https'
>>> url_parse_server_protocol({'USE_SSL': False})
'http'
"""
return "https" if settings_dict["USE_SSL"] else "http" |
def chunks_alignment_sequence(alignment_sequence_pairs, min_length):
"""Yield successive n-sized chunks from l."""
chunks = []
for i in range(0, len(alignment_sequence_pairs), min_length):
chunks.append(alignment_sequence_pairs[i:i + min_length])
return chunks |
def generate_parallelogrammatic_board(width=5, height=5):
"""
Creates a board with a shape of a parallelogram.
Width and height specify the size (in fields) of the board.
"""
return [[1] * height for _ in range(width)] |
def freezedicts(obj):
"""Recursively iterate over ``obj``, supporting dicts, tuples
and lists, and freeze ``dicts`` such that ``obj`` can be used
with hash().
"""
if isinstance(obj, (list, tuple)):
return type(obj)([freezedicts(sub) for sub in obj])
if isinstance(obj, dict):
retu... |
def get_tags_from_message(message):
"""
Given a message string, extracts hashtags and returns a comma-separated list
:param message: a Hipchat message body
"""
tags = {word.strip('#') for word in message.split() if word.startswith('#')}
return ','.join(tags) |
def _convert_index(index, pos, m=None, is_start=True):
"""Converts index."""
if index[pos] is not None:
return index[pos]
n = len(index)
rear = pos
while rear < n - 1 and index[rear] is None:
rear += 1
front = pos
while front > 0 and index[front] is None:
front -= 1
... |
def anagrams(S): # S is a set of strings
"""group a set of words into anagrams
:param S: set of strings
:returns: list of lists of strings
:complexity:
:math:`O(n k log k)` in average, for n words of length at most k.
:math:`O(n^2 k log k)` in worst case due to the us... |
def window_bounds(i, n, wn):
"""Start and stop indices for a moving window.
Parameters
----------
i : int
Current index
n : int
Total number of points
wn : int, odd
Total window size
Returns
-------
start : int
Start index
stop : int
Stop... |
def trc2id(t, row, col, grid_dim):
"""
Convert row, col, cell type to state id
"""
s_id = (t * grid_dim[0] * grid_dim[1] + row * grid_dim[1] + col) // 1
return s_id |
def _help_message(msgs, tag=None, vals=None):
""" extend a basic help message with a tag and a list of possible argument
values
"""
msgs = list(msgs)
if vals is not None:
msgs.append('options: {:s}'.format(', '.join(map(str, vals))))
help_msg = '; '.join(msgs)
if tag is not None:
... |
def split_slack(kp):
""" Computes the expected value and
Args:
kp:
Returns:
"""
s = (1 + 1 / kp) ** kp
base = 1 + 1 / kp
k = - (base ** (kp) - 1) * base
k = k + (base ** (kp + 1) - 1 - base) * (kp + 3)
k = k - 2 * kp * (base ** (kp + 2) - (5 * kp ** 2 + 7 * kp + 2) / (2 * ... |
def makeWennerArray(numElectrodes=32, id0=0):
"""
creates a schedule (A,B,M, N) for a Wenner array of length numElectrodes
"""
schedule=[]
for a in range(1, (numElectrodes+2)//3):
for k in range(0, numElectrodes-3*a):
schedule.append((k+id0, k+3*a+id0, k+1*a+id0, k+2*a+id0))
... |
def type_name(type_: type) -> str:
"""Convert a type object to a string in a consistent manner.
:param type_: the type object to convert
:return: a string with the type name
"""
type_qualname = type_.__qualname__
type_module = type_.__module__
if type_module not in ("__main__", "builtins"):... |
def make_balanced_tree(size):
"""Make a balanced binary tree with size nodes, where size is a power of 2."""
if size <= 1:
return 0
return (make_balanced_tree(size/2), make_balanced_tree(size/2)) |
def rejectBranchUsage(err=''):
""" Prints the Usage() statement for this method """
m = ''
if len(err):
m += '%s\n\n' %err
m += 'This script will reject a Task Branch (TB) on Salesforce.\n'
m += '\n'
m += 'Usage:\n'
m += ' rejectbranch -s <stream> -b <b... |
def rec_sum_digits(num):
"""rec_sum_digits(int) -> int
Recursive function which takes an integer and computes
the cumulative sum the individual digits of that integer.
>>> sum_digts(4321)
10
"""
if not isinstance(num, int):
raise TypeError("Must be a positive int")
# Base Case... |
def config(path):
"""
Set CONFIG_FILE, the path to the configuration JSON file,
to the given path, and return the new path.
No error or sanity checking is performed.
"""
global CONFIG_FILE
CONFIG_FILE = path
return CONFIG_FILE |
def isfile(string):
"""
Is string an existing file?
:param string: path
:return: abspath or raise FileNotFoundError if is not a dir
"""
import os
if os.path.isfile(string):
return os.path.abspath(string)
else:
raise FileNotFoundError(string) |
def has_duplicates(s):
"""Returns True if any element appears more than once in a sequence.
s: string or list
returns: bool
"""
t = list(s)
t.sort()
for i in range(len(t)-1):
if t[i] == t[i+1]:
return True
return False |
def extract_mac_address(scanlist):
"""
Extracts MAC address from the scan output.
"""
if "Address:" in "".join(scanlist):
mac_address_index = scanlist.index("Address:") + 1
mac_address = scanlist[mac_address_index]
return mac_address.strip()
else:
return "Unknown" |
def IsPakFileName(file_name):
"""Returns whether the given file name ends with .pak or .lpak."""
return file_name.endswith('.pak') or file_name.endswith('.lpak') |
def strToRange(s):
""" Convert string to range
"""
return [int(i) for i in s.split(',')] |
def tf_shape_to_list(shape):
"""Get shape from tensorflow attr 'shape'."""
dims = None
try:
if not shape.unknown_rank:
dims = [int(d.size) for d in shape.dim]
except: # pylint: disable=bare-except
pass
return dims |
def _header(string):
"""Make API REQUEST strings human readable."""
# Example: volume_space -> Volume Space
camelized = []
split = string.split('_')
for word in split:
word = word.lower()
camel = word[0].upper() + word[1:]
camelized.append(camel)
return ' '.join(camelized... |
def _container_name(kata):
"""Calculate the name of the container for a given kata.
"""
# Important: this accounts for docker's limitation that container names
# can only be lower case. The user might (and probably will) include
# upper-case letters in their kata id. We lower-case those here.
re... |
def maj_jud_median_calc(totals_array):
"""The array contains totals for every judgment.
An array like [12,32,45,67] means:
12 votes of 0
32 votes of 1
45 votes of 2
67 votes of 3
"""
n = len(totals_array)
element_count = 0
for i in totals_array:
element_count = element_c... |
def _quadratic_poly_coef_from_3_values(x1, x2, x3, n1, n2, n3):
"""
Returns the coeficients a, b and c of a quadratic polynomial of the form
n = a*x**2 * b*x + c from 3 known points.
Parameters
----------
x1, x2, x3 : float
The positions of the values.
n1, n2, n3 : float
The... |
def validate_input(user_input, input_map):
""" Checks user_input for validity and appends any validation errors to
return data.
Input:
- user_input: Dictionary containing the following input keys: values
- amount: float
- prefix: string
- type: string
... |
def make_sns_raw_record(topic_name, sns_data):
"""Helper for creating the sns raw record"""
raw_record = {
'EventSource': 'aws:kinesis',
'EventSubscriptionArn': 'arn:aws:sns:us-east-1:123456789012:{}'.format(topic_name),
'Sns': {
'MessageId': 'unit test message id',
... |
def calc_GC(seq):
"""
Calc. seq G+C content
"""
gc = {'G', 'C', 'g', 'c'}
return len([x for x in seq if x in gc]) / float(len(seq)) * 100 |
def scale(x, min_value, max_value):
"""
scale x to values between 0 and 1
"""
domain = max_value - min_value
x = (x - min_value) / domain
return x |
def command_line_option_to_keyword(option):
""" Convert the command line version of the option to a keyword.
Parameters
----------
option: string
The "long" command line option version
Returns
-------
keyword: string
The "keyword" version of the option. Namely, the initial ... |
def coding_problem_19(house_costs):
"""
A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost
while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and
kth column represents the cost to ... |
def idx_to_array_index(idx: int, idxpos0: int):
"""
Converts a nucleotide index to an 0-included array index
:param idx: The index to convert
:param idxpos0: The start index
:return: The index of the element in the array
>>> idx_to_array_index(10, 5)
5
>>> idx_to_array_index(10, -200)
... |
def sec_dev(f, x, h=1e-6):
"""
Calculates the second derivative of a function at a given x, given a small h
"""
return (f(x - h) - 2 * f(x) + f(x + h)) / float(h**2) |
def write_vcf(lines, vcf):
"""Create a file from the provided list"""
with open(vcf, "w") as vcf_handle:
vcf_handle.write('\n'.join(lines))
return vcf |
def merge_intervals(intervals, delta= 0.0):
"""
A simple algorithm can be used:
1. Sort the intervals in increasing order
2. Push the first interval on the stack
3. Iterate through intervals and for each one compare current interval
with the top of the stack and:
A. If current interval... |
def tzdel(dt):
""" Create timezone naive datetime from a timezone aware one by removing
the timezone component.
>>> from plone.event.utils import tzdel, utctz
>>> from datetime import datetime
>>> dt = utctz().localize(datetime(2011, 05, 21, 12, 25))
Remove the timezone:
>>> tzdel(dt)
... |
def get_volume_fn_from_mask_fn(mask_filename):
"""Extract volume path from mask path"""
return mask_filename.replace("S-label", "") |
def check_clip_len(options, duration):
"""
Function to determine the number of clips of a specified duration.
Parameters
----------
options : list of 2-item tuples or lists
start and stop times to evaluate
duration : numeric (int or float)
minimum desired clip duration
Ret... |
def wiki_title(name):
"""Like title(), except it never lowercases a letter."""
return ''.join(min(x,y) for x,y in zip(name, name.title())) |
def val_coding_ht_path(build):
"""
HT of coding variants for validating callset data type. HT written using
hail-elasticsearch-pipelines/download_and_create_reference_datasets/v02/hail_scripts/write_dataset_validation_ht.py
"""
return f"gs://seqr-reference-data/GRCh{build}/validate_ht/common_coding_... |
def get_name_receipt_without_extention(receipt_name):
""" get the name of the file without the extension so we can store the json file with the same name """
index = receipt_name.index(".")
return receipt_name[0:index] |
def maybe_unwrap_results(results):
"""
Gets raw results back from wrapped results.
Can be used in plotting functions or other post-estimation type
routines.
"""
return getattr(results, '_results', results) |
def route_error_500(error):
"""Handle server-side errors."""
return 'Internal server error', 500 |
def format_map(m):
"""pleasing output for dc name and node count"""
keys = sorted(m)
items = []
for key in keys:
count = m[key]
items.append("%s: %s" % (key, count))
if not m:
return "N/A"
return "{ %s }" % ", ".join(items) |
def lowercase_list(l):
"""Transform list items to string type and convert to lowercase
Args:
l: List of specification values
"""
return [str(i).lower() for i in l] |
def rgb2hsv(rgb):
"""Converts RGB to HSV.
Note that H may be None when S is 0 (for grey colors).
"""
r, g, b = rgb
minimum = min(r, g, b)
maximum = max(r, g, b)
v = maximum
delta = maximum - minimum
if delta != 0:
s = delta / maximum
else:
# h is undefined
... |
def sum(lst):
"""
Returns: the sum of all elements in the list
Example: sum([1,2,3]) returns 6
sum([5]) returns 5
Parameter lst: the list to sum
Precondition: lst is a nonempty list of numbers
(either floats or ints)
"""
result = 0 # Accumulator
for x in lst:
... |
def get_file_type(command: str) -> str:
"""
Used to understand if a command run uses a .msi or a .exe installer / uninstaller
#### Arguments
command (str): The command to infer the installer type from
Returns:
str: The filetype of the installer infered from the command
"""
# msi... |
def markAvgMedian(marks):
"""
markAvgMedian (marks) - returns the average median of the top 6 marks in the list of marks given
"""
top6 = []
for x in marks:
if len(top6) >= 6:
if x > min(top6):
top6.pop(top6.index(min(top6)))
top6.append(x)
... |
def quotify(comment, username):
"""
Converts 'Foo\nbar' to:
@username
> Foo
> bar
\n\n
"""
header = "@%s" % username
lines = comment.splitlines()
quote = "\n> ".join(lines)
quote = "%(header)s\n> %(quote)s\n\n" % ({'header': header, 'quote': quote})
return quote |
def any7(nums):
"""Are any of these numbers a 7? (True/False)"""
# YOUR CODE HERE
for loop_num in nums:
if loop_num == 7:
return True
return False |
def bytes_ljust(x: bytes, width: int, fill: bytes) -> bytes:
"""Given a bytes object, a line width, and a fill byte, left-justifies the bytes object within the line.
Compiling bytes.ljust compiles this function.
This function is only intended to be executed in this compiled form.
Checking the fill leng... |
def overlap(e1_start: int, e1_end: int, e2_start: int, e2_end: int) -> bool:
"""
Check if two spans overlap with each other
Args:
e1_start (int): span 1 begin offset
e1_end (int): span 1 end offset
e2_start (int): span 2 begin offset
e2_end (int): span 2 end offset
Retu... |
def calc_x_for_contact_depth(m, c, contact):
"""Calculate x for contact depth
Args:
m: slope from `last_base_slope`
c: intercept from `c0`
"""
return 1 / m * (contact - c) |
def rectangles_overlap(rectangle1, rectangle2):
"""
True when two rectangles overlap.
"""
from_x1, from_y1, to_x1, to_y1 = rectangle1
from_x2, from_y2, to_x2, to_y2 = rectangle2
def overlap_1d(from1, from2, to1, to2):
return from1 < to2 and to1 > from2
return (overlap_1d(from_x1, f... |
def find_largest_digit_helper(n, l):
"""
helper function
base case: n//10 == 0
n//10 => remove the units digit of n
n%10 => get the units digit of n
:param n: (int) the number which units digit are removing.
:param l: (int) the stored largest digit so far
"""
if n//10 == 0: # base case: no more digits after r... |
def MaybeToNumber(instance):
"""Convert to an int or float if possible."""
if isinstance(instance, (float, int)) or instance is None:
return instance
try:
return int(instance)
except (TypeError, ValueError):
pass
try:
return float(instance)
except (TypeError, ValueError):
pass
retur... |
def to_css_length(x):
"""
Return the standard length string of css.
It's compatible with number values in old versions.
:param x:
:return:
"""
if isinstance(x, (int, float)):
return '{}px'.format(x)
else:
return x |
def _ExtractCLPath(output_of_where):
"""Gets the path to cl.exe based on the output of calling the environment
setup batch file, followed by the equivalent of `where`."""
# Take the first line, as that's the first found in the PATH.
for line in output_of_where.strip().splitlines():
if line.startswith('LOC:'... |
def vm_to_mm(verbal_model):
""" Convert VM to MM. Time information will be lost.
>>> a = VerbalModels.Prop(name="a", neg=False, identifying=False, t=123)
>>> non_b = VerbalModels.Prop(name="b", neg=True, identifying=False, t=456)
>>> vm = [VerbalModels.Individual(props=[a], t=789), VerbalModels.Individ... |
def sort_by_month(orders: list) -> tuple:
"""
A function which sorts the contents of the CSV file into months.
:param orders: List
:return: tuple
"""
jan: list = []
feb: list = []
mar: list = []
apr: list = []
may: list = []
jun: list = []
jul: list = []
... |
def deindent(s):
"""
>>> print(deindent('''
... bepa
... apa
...
... cepa
... '''))
<BLANKLINE>
bepa
apa
<BLANKLINE>
cepa
<BLANKLINE>
"""
lines = s.split('\n')
chop = 98765
for line in lines:
if line.strip():
m... |
def B(A: int, D: int) -> int:
"""Function that should become part of the graph - B"""
return A * A + D |
def pad_data(data, pad_amount, pad_value=b"\x00", start_at=0):
""" Pad a piece of data according to the padding value and returns the
result. Use start_at to specify an offset at the starting point. """
end_position = len(data) + start_at
if end_position % pad_amount != 0:
pad_size = pad_amount ... |
def _is_max_limit_reached(current: int, maximum: int = -1) -> bool:
"""Check if the limit has been reached (if enabled).
Args:
current: the current value
maximum: the maximum value (or -1 to disable limit)
Returns:
bool: whether the limit has been reached
"""
return maximum... |
def py3to2_remove_raise_from(content):
"""
Removes expression such as: ``raise Exception ("...") from e``.
The function is very basic. It should be done with a grammar.
@param content file content
@return script
"""
lines = content.split("\n")
r = None
for i... |
def families_dipoles():
"""."""
return ['B'] |
def check_is_number(s):
"""Summary
Args:
s (TYPE): Description
Returns:
TYPE: Description
"""
try:
float(s)
return True
except ValueError:
return False |
def ship_new(name):
"""Create a new ship
name: The name to attribute to the ship
"""
return "Created ship {0}".format(name) |
def cast_vanilla(value, cur): # pylint: disable=unused-argument
"""Vanilla Type caster for psycopg2
Simply returns the string representation.
"""
if value is None:
return None
else:
return str(value) |
def write_readmap(fh, rmap, namedic=None):
"""Write a read map to a tab-delimited file.
Parameters
----------
fh : file handle
Output file.
rmap : dict
Read-to-taxon(a) map.
namedic : dict, optional
Taxon name dictionary.
"""
# sort subjects by count (high-to-low... |
def hard_label(ypred, thresh=0.5):
"""
Hard assign label after prediction of Keras model
Args:
ypred (int): Percentage that the label will be 0 or 1.
thresh (float): Default=0.5 Threshold to assign labels.
Returns:
Label 0 if smaller than threshold and label 1 if larger... |
def map_encoding(encoding):
"""Replace specific unwanted encodings with compatible alternative."""
encoding_map = { None : 'utf-8',
'' : 'utf-8',
'ascii' : 'utf-8' }
lower_encoding = (encoding or '').lower()
return encoding_map.get(lower_encoding) or lo... |
def grid_coordinates(roi, x_divisions, y_divisions, position):
"""
Function that returns the grid coordinates of a given position.
To do so it computes, for a given area and taking into account
the number of x and y divisions which is the total amount of cells.
After that it maps the given position to the cell it ... |
def pad(input: str, spaces: int) -> str:
"""Pads the input lines with spaces except for the first line.
We don't need opts here because the default mode will always be a single line so we'll never invoke this.
"""
lines = input.splitlines()
pad = " " * spaces
return f"\n{pad}".join(lines) |
def get_correct_ids(hgnc_symbol, alias_genes):
"""Try to get the correct gene based on hgnc_symbol
The HGNC symbol is unfortunately not a persistent gene identifier.
Many of the resources that are used by Scout only provides the hgnc symbol to
identify a gene. We need a way to guess what gene is p... |
def bps_mbps(val: float) -> float:
"""
Converts bits per second (bps) into megabits per second (mbps).
Examples:
>>> bps_mbps(1000000)
1.0
>>> bps_mbps(1129000)
1.13
Args:
val (float): The value in bits per second to convert.
Returns:
Returns val i... |
def foo(param):
"""Simple foo function that returns a string with an exclamation point
Parameters
----------
param : str
Param string to pass in
Returns
-------
str
A str with a passed in param concat with an exclamation point
"""
param = param + '!'
return ... |
def reverse_list_valued_dict(dict_obj):
"""Reverse a list-valued dict, so each element in a list maps to its key.
Parameters
----------
dict_obj : dict
A dict where each key maps to a list of unique values. Values are
assumed to be unique across the entire dict, on not just per-list.
... |
def _color_for_labels(label_color, default_color, seq_index):
"""Helper function to get a color for a label with index `seq_index`."""
if label_color is None:
if hasattr(default_color, '__getitem__'):
c = default_color[seq_index]
else:
c = default_color
else:
... |
def split_float_colons(string_values):
"""
Uses numpy-ish syntax to parse a set of two floats. Blanks are interpreted as None.
Parse the following:
1:10
1:
:100
1.1:200
1:300.
"""
if string_values:
assert ',' not in string_values, string_values
sl... |
def float_replication(field, old_field):
"""*4., *(11.5)"""
msg = 'field=%r; expected *(1.), *2., ..., *11.' % field
assert field[0] == '*', msg
assert '.' in field, msg
assert len(field) >= 3, msg
if '(' in field:
assert field[1] == '(', msg
assert field[-1] == ')', msg
... |
def fix_spans_due_to_empty_words(action_dict, words):
"""Return modified (action_dict, words)"""
def reduce_span_vals_gte(d, i):
for k, v in d.items():
if type(v) == dict:
reduce_span_vals_gte(v, i)
continue
try:
a, b = v
... |
def euler191(nb_days=4):
"""Solution for problem 191."""
# 0 late : a, b, c for 0, 1, 2 consecutive absences
# 1 late : d, e, f for 0, 1, 2 consecutive absences
a, b, c, d, e, f = 1, 0, 0, 0, 0, 0
for _ in range(nb_days + 1): # 1 more iteration to have the res in d
a, b, c, d, e, f = a + b ... |
def extract_tty_phone(service_center):
""" Extract a TTY phone number if one exists from the service_center
entry in the YAML. """
tty_phones = [p for p in service_center['phone'] if 'TTY' in p]
if len(tty_phones) > 0:
return tty_phones[0] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.