content stringlengths 42 6.51k |
|---|
def sanitize(some_tuple):
"""
Parameters
----------
some_tuple : tuple
Delete some symbols like "-", "(" and space in elements of tuple.
Returns
-------
clean_string : tuple
A string without the symbols.
"""
clean_string = () # initialize
for st in s... |
def _process_transcript(transcript):
"""
Removes tags found in AN4.
"""
extracted_transcript = transcript.split('(')[0].strip("<s>").split('<')[0].strip().upper()
return extracted_transcript |
def iter_range(items):
""" returns a zero based range list for iteration in templates """
return range(0,items) |
def validate_pooling_params(pooling_params):
""" Helper to supported sqlalchemy pooling options """
supported = ("max_overflow", "pool_recycle", "pool_size", "pool_timeout")
if not pooling_params:
return {}
if not isinstance(pooling_params, dict):
raise ValueError(f"Invalid pooling par... |
def word_and_pattern_fixed(word, pattern):
"""Get word and a pattern and return True if they are fixed (equal letters or '_')
False otherwise"""
for i in range(len(pattern)):
if pattern[i] == "_":
continue
else:
if pattern[i] != word[i]:
return False
... |
def fix_content_to_append(content):
"""
Needed when appending files
If there is no line feed at the end of content, adds line feed at the end
"""
if content:
if content[-1] != "\n":
content += "\n"
return content |
def nuclideIDFromNucleusID( nucleusID ) :
""" The nuclide id is computed from nucleus id by converting 1st letter to upper case """
return( nucleusID[0].upper( ) + nucleusID[1:] ) |
def is_permutation(string1, string2):
""" check if string1 is permutation of string2 """
return len(string1) == len(string2) and sorted(string1) == sorted(string2) |
def is_even(n):
"""
return true if n is even; false otherwise
"""
return n%2 == 0 |
def css(name, e=None, styles=None, default=None):
"""Answers the named style values. Search in optional style dict first,
otherwise up the parent tree of styles in element e. Both e and style can
be None. In that case None is answered. Note that this is a generic
"Cascading style request", outside the r... |
def func_args(func):
"""Return a flatten list of function argument names.
Correctly detect decorated functions"""
if hasattr(func, 'wrapped'):
w = func.wrapped
r = w.args
if w.varargs:
r.append(w.varargs)
if w.keywords:
r.append(w.keywords)
ret... |
def index(l, i):
"""return a set of indexes from a list
>>> index([1,2,3],(0,2))
(1, 3)
"""
return tuple([l[x] for x in i]) |
def _inject_conn_arg(conn, arg, args, kwargs):
"""
Decorator utility function. Takes the argument provided to the decorator
that configures how we should inject the pool into the args to the callback
function, and injects it in the correct place.
"""
if isinstance(arg, int):
# Invoked po... |
def _parse_mail_options(mail, mail_on_begin, mail_on_abort, mail_on_terminate):
""" Generate the qsub options for sending email.
"""
options = []
if mail :
if isinstance(mail, (list, tuple)) :
mail = ",".join(mail)
options.extend(["-M", mail])
if True in [mail_on... |
def closedLoopController (time, robot_state, desired_pose, desired_vel):
"""
The closed loop pd-controller for the robot paddle implemented
in the previous section.
"""
K_px = 100
K_py = 100
K_pth = 10
K_dx = 50
K_dy = 50
K_dth = 20
# the output signal
x,y,th, ... |
def _err(msg=None):
"""To return a string to signal "error" in output table"""
if msg is None:
msg = 'error'
return '!' + msg |
def length (value, val_length):
"""
Receives `value`, truncates to length (used primarily for storage fees/volume)
:param value: Value to truncate
:param val_length: Length to truncate after the decimal
:return:
"""
if not value:
return '0.00'
else:
_length = int(val_leng... |
def rename(a):
"""
method_site -> method
"""
return [s.split('_')[0] for s in a] |
def _get_return_value_name_from_line(line_str: str) -> str:
"""
Get the return value name from the target line string.
Parameters
----------
line_str : str
Target line string. e.g., 'price : int'
Returns
-------
return_value_name : str
Return value name. If colon charac... |
def _menutitlestring (ARG_title: str) -> str:
"""Returns a suitable title string that is uppercase, and ends in 'MENU', and is less than or equal to 70 characters long.
Parameters
----------
ARG_title : str
A string to be used as the basis for the title string.
Returns
-------
str
... |
def getMaxSymStrFromCenterOdd(_string, cur_len):
"""Get The Max Symmetry String of @_string from center.
Return the start, end index of the Symmetry-String."""
pos_center = cur_len >> 1
offset = 1
while offset <= pos_center and _string[pos_center - offset] == _string[pos_center + offset]:
of... |
def get_atomic_charge(atom, atomic_valence_electrons, BO_valence):
"""
"""
if atom == 1:
charge = 1 - BO_valence
elif atom == 5:
charge = 3 - BO_valence
elif atom == 15 and BO_valence == 5:
charge = 0
elif atom == 16 and BO_valence == 6:
charge = 0
else:
... |
def parse_request(message):
"""
Accept request from client.
Verify content and return appropriate error or URI.
"""
request_parts = message.split()
if len(request_parts) <= 4:
raise ValueError('400 Bad Request')
if request_parts[0] == 'GET':
if request_parts[2] == 'HTTP/1.1'... |
def split_cdl_line(line):
"""
Splits a line of a "cdl" file into fields taking into account "{" and "}"
brackets.
>>> split_cdl_line("define WL_bank 0")
['define', 'WL_bank', '0']
>>> split_cdl_line("define_WL_bank 0 -range {0 310}")
['define_WL_bank', '0', '-range', ['0', '310']]
>>> s... |
def get_max_core(ph):
"""
Max Core Allocations in Each Phase (ph)
"""
core = [0,16,12,24,32,48]
if ph == 0:
return 0
return core[ph] |
def build_gnab_feature_id(gene_label, genomic_build):
"""
Creates a GNAB v2 feature identifier that will be used to fetch data to be rendered in SeqPeek.
For more information on GNAB feature IDs, please see:
bq_data_access/data_types/gnab.py
bq_data_accvess/v2/gnab_data.py
Params:
gene... |
def list_items(list):
"""Returns a string with a listing of all the items
in the list."""
string = ""
for i in list:
string += str(i) + " "
return string |
def unescape_single_quote(escaped):
"""
Unescape a string which uses backslashes to escape single quotes.
:param str escaped: The string to unescape.
:return: The unescaped string.
:rtype: str
"""
escaped = escaped.replace('\\\\', '\\')
escaped = escaped.replace('\\\'', '\'')
return escaped |
def is_pythagorean_triplet(a, b, c):
"""Determine whether the provided numbers are a Pythagorean triplet.
Arguments:
a, b, c (int): Three integers.
Returns:
Boolean: True is the provided numbers are a Pythagorean triplet, False otherwise.
"""
return (a < b < c) and (a**2 + b**2 == ... |
def binomial_cofficient(m, k):
"""Binomial coefficien of m taking k.
Note there is a recursion relationship for binomial coefficients:
C(m, k) = C(m - 1, k - 1) + C(m - 1, k)
which represents C(m, k) is the sum of selecting and not selecting m.
Apply bottom-up dynamic programming.
Time comple... |
def compact(iterable, generator=False):
""" Returns a list where all None values have been discarded. """
if generator:
return (val for val in iterable if val is not None)
else:
return [val for val in iterable if val is not None] |
def GetReleaseSpecs(data=None):
"""parse out the release information from the json object.
This assumes data release specified in data as a dictionary
"""
if not isinstance(data, dict):
raise TypeError("Wrong input data type, expected list")
specs = {}
try:
specs['release_notes... |
def fix_projection(shape, axes, limits):
"""Fix the axes and limits for data with dimension sizes of 1.
If the shape contains dimensions of size 1, they need to be added
back to the list of axis dimensions and slice limits before calling
the original NXdata 'project' function.
Parameters
-----... |
def is_rotation(list1, list2):
"""
Time: O(n)
Space: O(1)
"""
if len(list1) != len(list2):
return False
list1index = 0
list2index = -1
if list1[0] in list2:
list2index = list2.index(list1[0])
if list2index == -1:
return False
while list1index < len(li... |
def canonize(line):
"""
A rudimentary C/C++ line canonizer that strips whitespace and squiggly
brackets
"""
return line.strip(' \r\n\t{}') |
def likelihood_from_chi_squared_and_noise_normalization(
chi_squared, noise_normalization
):
"""Compute the likelihood of each masked 1D model-simulator fit to the dataset, where:
Likelihood = -0.5*[Chi_Squared_Term + Noise_Term] (see functions above for these definitions)
Parameters
----------
... |
def _union(lst_a, lst_b):
""" return the union of two lists """
return list(set(lst_a) | set(lst_b)) |
def dict_key_lookup(the_dict, key):
"""
Checks if the given key exists in given dict
:param the_dict:
:param key:
:return: str
"""
return the_dict.get(key, '') |
def fom_harmonization(fom, units, power, life):
"""
Harmonization of Fixed Operation and Management costs
:param units: Reported units of the data point
:param power: Power of the powerplant if availible, otherwise None.
:param life: Lifespan of the powerplant
:return: Harmonized cost value
... |
def _get_prefix_and_full_hash(repo_data, kernel_partial_hash):
"""Find the prefix and full hash in the repo_data based on the partial."""
kernel_partial_hash_lookup = 'u\'%s' % kernel_partial_hash
for line in repo_data.splitlines():
if kernel_partial_hash_lookup in line:
prefix, full_hash = line.split('... |
def relative_difference_by_min(x, y):
"""Calculate relative difference between two numbers."""
return (x - y) / min(x, y) |
def formolIndex (NaOH_volume, NaOH_molarity, NaOH_fc, grams_of_honey):
"""
Function to calculate the formol index in honey
"""
number_of_NaOH_mols = NaOH_volume * NaOH_molarity * NaOH_fc
volume = number_of_NaOH_mols / NaOH_molarity
formol_index = (volume * 1000) / grams_of_honey
return formo... |
def intcode_four(parameter_list, code_list):
""" Prints item in parameter_list[0] place in code_list. Returns True. """
print(parameter_list[0])
return True |
def fixHoles(img, gradImg, backgroundVal):
"""prox = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)]
for y in range(len(img)):
for x in range(len(img[0])):
if(img[y][x] ... |
def _get_alphanum_cell_index(row, col):
"""
Convert a (row, col) cell index to a AB123 style index.
"""
# Convert the column number to the corresponding alphabetic index.
# Taken from https://stackoverflow.com/questions/181596/how-to-convert-a-column-number-e-g-127-into-an-excel-column-e-g-aa
d... |
def sanitize_xml(text):
""" Removes forbidden entities from any XML string """
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace('"', """)
text = text.replace("'", "'")
return text |
def getGantryInfoFromPath(filepath):
"""Get dataset info from path."""
parts = filepath.split("/")
# First check whether immediate parent folder is a timestamp or a date
if parts[-2].find("__") > -1:
# raw_data/scanner3DTop/2016-01-01/2016-08-02__09-42-51-195/file.json
j_timestamp = part... |
def search_log(log_list, search_string):
"""Search through a log list for lines containing the `search_string`.
Returns a list of the matched lines."""
return [log_line for log_line in log_list if search_string in log_line] |
def check_cprofile(dump):
"""check to cProfile module's data or profile module's data."""
signature = "sprof.Profiler".encode()
return True if dump.find(signature) > 0 else False |
def factorial(n):
"""
Returns n!
"""
if(n == 0):
return 1;
else:
return n * factorial(n-1) |
def read_gff_attributes(attribute_column: str) -> dict:
"""
Parse attributes for a GFF3 record. Attributes with pre-defined meaning are parsed according to their
specification (e.g. Dbxref usually has multiple values which are split up: 'GeneID:1234,Genbank:NM_9283').
:param attribute_column: Attribut... |
def clamp(val, min, max):
"""Clamp the value between min and max."""
if val <= min:
return min
elif val >= max:
return max
return val |
def get_network_size(netmask):
"""Get cidr size of network from netmask"""
b = ''
for octet in netmask.split('.'):
b += bin(int(octet))[2:].zfill(8)
return str(len(b.rstrip('0'))) |
def median(x):
"""Return the median of a list of values."""
m, r = divmod(len(x), 2)
if r:
return sorted(x)[m]
return sum(sorted(x)[m - 1:m + 1]) / 2 |
def compression_level(compression, level):
"""
Validate compression and compression's level user arguments.
This function return appropriate compression level for any `zipfile.Zipfile`
supported values.
Check: https://docs.python.org/3/library/zipfile.html#zipfile-objects
to see possible value... |
def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by replacing
all `T` to `U`
"""
bp_dict={'A':'T','T':'A','C':'G','G':'C'}
seq="".join([bp_dict[x] for x in list(seq)])
return seq.replace('T','U') |
def get_normalized_progress(current_progress, start_ndist):
"""
Return normalized current progress with respect to START LINE of the track.
Args:
current_progress: current_progress to normalize (0 - 100)
start_ndist: start_ndist to offset (0.0 - 1.0)
Returns:
normalized current... |
def isstring(obj):
"""Test if an object is a string for different python versions."""
# Early Python only had one string type
# if type(obj) is str
# Middle-aged Python had several:
# if type(obj) in types.StringTypes
# Modern python has one again
# if type(obj) is str
return type(obj) i... |
def twos_comp(per_bytes, bits):
"""compute the 2's complement of int value val"""
if (per_bytes & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
per_bytes = per_bytes - (1 << bits) # compute negative value
return per_bytes |
def ljust(string, amt):
"""Left-align the value by the amount specified.
Equivalent to Djangos' ljust.
Args:
string (str): The string to adjust.
amt (int): The amount of space to adjust by.
Returns:
str: The padded string.
"""
return string.ljust(amt) |
def urwid_to_click_bold(color):
"""convert urwid color name to click bold attribute
"""
col = color.split()[0]
if col == 'brown':
return False
return col == 'light' or col == 'yellow' |
def metric_to_keys(metric):
"""Returns the associated key for the specified metric."""
switcher = {
"averageSpeed": "GHS av",
"averageSpeed5s": "GHS 5s",
"chainFailures": "chain_acs[i]",
"chainsActive": "chain_acs[i]",
"chipTemp": "temp2_[i]",
"errorRate": "Device... |
def ravel_index(indices, shape):
"""Flatten the index tuple to 1D
Parameters
----------
indices : tuple of int or tvm.tir.IntImm
The input coordinates
shape : tuple of int
Shape of the tensor.
Returns
-------
idx : int or Expr
The index after flattening
"""... |
def split_trace_event_line(line):
"""
Split a trace-cmd event line into the preamble (containing the task, cpu id
and timestamp), the event name, and the event body. Each of these is
delimited by a ': ' (optionally followed by more whitespace), however ': '
may also appear in the body of the event a... |
def to_seconds(days=None, hours=None):
""" Convert given day/hours to seconds and return
:param int days: days to be converted
:param int hours: hours to be converted
"""
#only either days or hours should be speciefied, but atleast one should be specified
if days and hours:
rais... |
def greet(name):
"""Return special hello for Johnny, normal greeting for everyone else."""
if name == "Johnny":
return "Hello, my love!"
return "Hello, {}!".format(name) |
def max_difference(L):
"""max difference will accept a list and return the largest difference in which the
larger value must come after the smaller one
output will be a string with the first argument being the location of the small
value and the second argument being the location of the l... |
def _HasIOSTarget(targets):
"""Returns true if any target contains the iOS specific key
IPHONEOS_DEPLOYMENT_TARGET."""
for target_dict in targets.values():
for config in target_dict['configurations'].values():
if config.get('xcode_settings', {}).get('IPHONEOS_DEPLOYMENT_TARGET'):
return True
r... |
def adder(first, second):
"""We can map functions with arguments.
All named capture groups (this is a capture group named first: (?P<first>\d+)) are passed as keyword-arguments to
function. So make sure the names of your capture groups fit the names of your function arguments.
Unnamed capture groups as... |
def unifyLists(list1, list2):
"""
This function performs union between two lists.
:param list1: A list.
:param list2: A list.
:return: the union of list1 and list2.
"""
return [x for x in list1 + list2 if len(x) > 0]
# return list(set(list1) | set(list2))
|
def get_current_weather_icon(data):
"""Get WWO's weather icon.
:param data:
:return: image to include in the email
"""
return data['current_condition'][0]['weatherIconUrl'][0]['value'] |
def safe_read(sensor, sensor_name, attribute_name, errors):
"""Reads I2C sensor while catching errors."""
if sensor is None:
# There was an error initialising the sensor, can't even try to read it.
return None
else:
try:
value = getattr(sensor, attribute_name)
exc... |
def K(x, y):
"""K code generator ex: K(28, 5) is COM Symbol"""
return (y << 5) | x |
def unexpo(intpart, fraction, expo):
"""Remove the exponent by changing intpart and fraction."""
if expo > 0: # Move the point left
f = len(fraction)
intpart, fraction = intpart + fraction[:expo], fraction[expo:]
if expo > f:
intpart = intpart + '0'*(expo-f)
elif expo < 0... |
def parse_asset_data(get_asset_data):
""" parsing get_asset_data JSON object
containing video asset data, specifically for mp4 source URL """
for index, item in enumerate(get_asset_data):
mp4_url = 0
# look for the dictionary in the API response (type(get_source)==list)
# that contai... |
def weight_combination(entropy, contrast, visibility, alpha1, alpha2, alpha3):
"""
Combining the entropy, the contrast and the visibility to build a weight layer
:param entropy: The local entropy of the image, a grayscale image
:param contrast: The local contrast of the image, a grayscale image
:pa... |
def findpop(value, lst):
""" Return whether `value` is in `lst` and remove all its occurrences """
if value in lst:
while True: # remove all instances `value` from lst
try:
lst.pop(lst.index(value))
except ValueError:
break
return True # ... |
def parse_match(ref_index, read_index, length, read_sequence, ref_sequence):
"""
Process a cigar operation that is a match
:param alignment_position: Position where this match happened
:param read_sequence: Read sequence
:param ref_sequence: Reference sequence
:param length: Length of the operat... |
def create_image_uri(region, framework, instance_type, py_version='py2', tag='1.0', account='520713654638'):
"""Return the ECR URI of an image.
Args:
region (str): AWS region where the image is uploaded.
framework (str): framework used by the image.
instance_type (str): EC2 instance typ... |
def pop_sequence(dic, protected):
"""
Remove an entry in the dictionary that has multiple values
"""
for k, v in dic.items():
try:
len(v)
if not k in protected:
dic.pop(k)
return (k, v)
except:
pass
return ('', [... |
def normalize_whitespace(s):
"""
Remove leading and trailing whitespace, and convert internal
stretches of whitespace to a single space.
"""
return ' '.join(s.split()) |
def _symbol_to_url(sym: str) -> str:
"""
:param sym: A symbol of a CBOE published index
:return: the URL to download the index historical data from.
Works for some of the CBOE indexes.
You can find a variety of indexes using the CBOE global index search.
https://ww2.cboe.com/index and even m... |
def WriteColouredDiff(file, diff, isChanged):
"""helper to write coloured text.
diff value must always be computed as a unit_spec - unit_generic.
A positive imaginary part represents advantageous trait.
"""
def cleverParse(diff):
if float(diff) - int(diff) < 0.001:
return str(in... |
def distance_clean(distance):
"""
This part seems to have some issues with spacing. Lets fix that
:param distance:
:return: cleaned distance! (string)
"""
distance = distance.replace("(", " (")
distance = distance.replace("miles", "miles ")
distance = distance.replace("off", "off ")
... |
def _remove_duplicates(objects):
"""Remove duplicate objects.
Inspired by http://www.peterbe.com/plog/uniqifiers-benchmark
"""
seen = set()
result = []
for item in objects:
marker = id(item)
if marker in seen:
continue
seen.add(marker)
result.append(... |
def is_in_dict(searchkey, searchval, d):
"""
Test if searchkey/searchval are in dictionary. searchval may
itself be a dict, in which case, recurse. searchval may be
a subset at any nesting level (that is, all subkeys in searchval
must be found in d at the same level/nest position, but searchval
... |
def rhombus_area(diagonal_1, diagonal_2):
"""Returns the area of a rhombus"""
return (diagonal_1 * diagonal_2) / 2 |
def SanitizeDomain(s):
"""Sanitize a domain name to ch aracters suitable for use in code.
We only want text characters, digits, and '.'. For now, we only allow ASCII,
characters but we may revisit that in the future if there is demand from
Endpoints customers.
Since the pattern 'my-custom-app.appspot.com' i... |
def get_value_str(value, type_val):
"""Convert the value from the csv file to the correct str according to the type
Parameters
----------
value : str
value to convert
type_val : str
Type to convert to
Returns
-------
value : str
Value updated to match the type
... |
def _rgba_to_int(red, green, blue, alpha=255):
""" Return the color as an Integer in RGBA encoding """
r = red << 24
g = green << 16
b = blue << 8
a = alpha
rgba_int = sum([r, g, b, a])
if rgba_int > (2 ** 31 - 1): # convert to signed 32-bit int
rgba_int = rgba_int - 2 ** 32
re... |
def shape(x):
"""Change str to List[int]
>>> shape('3,5')
[3, 5]
>>> shape(' [3, 5] ')
[3, 5]
"""
# x: ' [3, 5] ' -> '3, 5'
x = x.strip()
if x[0] == "[":
x = x[1:]
if x[-1] == "]":
x = x[:-1]
return list(map(int, x.split(","))) |
def area_rating(area):
"""Display a graphic indicator showing the area
"""
areas = list()
missing_areas = list()
for a in range(0, area - 1):
areas.append(a)
for a in range(0, 6 - area):
missing_areas.append(a)
return {
'areas': areas,
'missing_areas': miss... |
def _scale_mapper(x, y):
"""maps coordinates to google coordinates
Arguments:
x,y: coordinates
Returns:
new_x,new_y: Google env coordinates
Raises:
"""
# Takes our x,y and maps it into google's (x,y)
new_x = (x / 100.0 - 0.5) * 2
new_y = -(y / 100.0 - 0.5) * 2
return (new... |
def check_win(player, board):
"""Checks if the inputted player has won"""
# These are all the winning lines/combinations
lines = [
(0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6),
]
# For each on... |
def split_filter(li, cond, op=lambda x:x):
"""
takes in list and conditional
returns [[False], [True]] split list in O(n) time
"""
retval = [[],[]]
for elm in li:
index = cond(elm)
retval[index].append(op(elm) if index else elm)
return retval |
def bytesToHex( byteStr ):
"""
from http://code.activestate.com/recipes/510399-byte-to-hex-and-hex-to-byte-string-conversion/
Convert a byte string to its hex string representation e.g. for output.
"""
# Uses list comprehension which is a fractionally faster implementation than
# the altern... |
def check_valid_column(observation):
"""
Validates that our observation only has valid columns
Returns:
- assertion value: True if all provided columns are valid, False otherwise
- error message: empty if all provided columns are valid, False otherwise
"""
valid... |
def collect_consecutive_values(seq):
"""Given a sequence of values, output a list of pairs (v, n) where v is a
value and n is the number of consecutive repetitions of that value.
Example:
>>> collect_consecutive_values([53, 92, 92, 92, 96, 96, 92])
[(53,1), (92,3), (96,2), (92,1)]
"""
... |
def get_factors_(number, printed=False):
"""Get the factors of a number."""
factors = []
for x in range(1, number+1): # For each number from 1 to the given number.
if number % x == 0: # If number divided by x has a remainder of 0.
factors.append(x) # Then it is a factor of the given numb... |
def createDictForPath2Yang(gatherPaths):
"""
Provide dict to find yang path from proto path
"""
d = {}
for g in gatherPaths:
d[g['path']] = g['gather_path']
return d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.