content stringlengths 42 6.51k |
|---|
def abbreviate(x):
"""
A small routine to automatically derive an abbreviation from the long name.
"""
try:
first,last = x.split(' ')
if len(last)>2:
return "%s%s"%(first[0],last[0:3])
elif len(last)==1:
return "%s%s"%(first[0:3],last[0])
... |
def merge_json(data1, data2):
"""merge lists in two json data together
Args:
data1 (json or None): first json data
data2 (json): 2nd json data
Returns:
TYPE: merged data
"""
if not data1:
return data2
else:
for i in data2['list']:
data1['list... |
def is_passphrase_valid_extended(phrase):
"""
each list item is alphabetically sorted,
and again the value is added to the set uniquely
"""
word_list = phrase.split(" ")
word_set = set(map(lambda v: ''.join(sorted(v)), word_list))
return len(word_list) == len(word_set) |
def _build_self_message(msg, start, end, batch_size, total):
"""Creates a JSON object for batch processing.
The function builds the message with all the details to be able to process the
batch data when received. The aim of this message is this very same cloud
function.
Args:
msg: A JSON object represen... |
def _validate_subdomain(subdomain):
"""
Validates the given subdomain.
Parameters
----------
subdomain : `None` or `str`
Subdomain value.
Returns
-------
subdomain : `None` or `str`
The validated subdomain.
Raises
------
TypeError
If `subdomain` was... |
def get_state_salue(view, option):
"""Get selected values stored at the state element"""
element_value = ""
for element in view["state"]["values"]:
element_value = view["state"]["values"][element].get(option, None)
if element_value is not None:
if element_value.get("selected_opt... |
def adjust_detector_length(requested_detector_length,
requested_distance_to_tls,
lane_length):
""" Adjusts requested detector's length according to
the lane length and requested distance to TLS.
If requested detector length is negative, the resu... |
def encodeDict(items):
""" Encode dict of items in user data file
Items are separated by '\t' characters.
Each item is key:value.
@param items: dict of unicode:unicode
@rtype: unicode
@return: dict encoded as unicode
"""
line = []
for key, value in items.items():
item = u'%... |
def is_insert(line):
"""
Returns true if the line begins a SQL insert statement.
"""
return line.startswith(b'INSERT INTO') or False |
def hex_byte_to_bits(hex_byte):
"""
Interpret a single hex character as bits.
This function will accept a hex byte (two characters, 0-F)
and cast it to a list of eight bits. Credit to StackOverflow
user: "Beebs" for concise function implementation.
Parameters
----------
hex_byte: str... |
def index_of_first_zero_bit_moving_right_to_left(ii):
"""
Return the first the index of the first zero bit of the integer ii
when moving right to left. Returns index in [0,...,nbits(ii)-1]
# x >> y Returns x with the bits shifted to the right by y places.
# This is the same as //'ing x by 2**y.
... |
def camel2snake(s):
"""Convert a camelCase name to snake_case"""
o = ''
lastcap = False
for letter in s:
lc = letter.lower()
if not lc.isalpha():
lastcap = True
if lc == '-':
lc = '_'
lastcap = True
elif not lc.isalpha():
la... |
def complemento_base (base):
"""
(str)-> (str)
Programa para complementar la base dada
>>> complemento_base('T')
'AT'
>>> complemento_base('G')
'CG'
>>> complemento_base('C')
'GC'
:param base: base a complementar
:return: base complementada
"""
comp_base = ''
... |
def escape(s: str) -> str:
"""Escape HTML entity characters."""
s = s.replace('&', '&')
s = s.replace('<', '<')
s = s.replace('>', '>')
s = s.replace('"', '"')
return s.replace('\'', ''') |
def get_filenames(i):
"""Returns the filepaths for the output MusicXML and .png files.
Parameters:
- i: unique identifier for the score
Returns:
- (sheet_png_filepath, musicxml_out_filepath)
"""
output_folder_prefix = "dataset/"
sheet_png_out_filepath = output_folder_prefix + "{}-s... |
def front_back(str_: str) -> str:
"""Swap the first and last characters of a string."""
if len(str_) > 1:
return f'{str_[-1]}{str_[1:-1]}{str_[0]}'
return str_ |
def precedes(layers, n1, n2):
"""
Helper function to determine whether node n1 is in
a layer that immediately precedes the layer of node n2.
"""
i = [k for k in range(len(layers)) if n1 in layers[k]][0]
j = [k for k in range(len(layers)) if n2 in layers[k]][0]
return i + 1 == j |
def parse_string(string: str):
"""function to convert a string into a int list
Example:
Input: parse_string("64-64")
Output: [64, 64]
"""
string_arr = string.split("-")
int_list = []
for string in string_arr:
try:
int_list.append(int(string))
except:
... |
def _pkg_shortname(package):
"""
Strips out the package's namespace and returns its shortname.
"""
return package.split('/')[1] |
def get_value(path, obj):
"""Returns the value of key in a nested data structure
:param path: The path to the value to be returned
:type path: str
:param obj: Source of the data to return a value from
:type obj: obj
:return: Value based on the path or None
:rtype: object
"""
try:
... |
def distance(point1, point2):
"""Return the calculated distance between the points.
Manhattan distance.
"""
x0, y0 = point1
x1, y1 = point2
return abs(x1 - x0) + abs(y1 - y0) |
def is_mode_correct(mode_no):
"""The function checks the correctness of the game mode (number range from 1 to 2)."""
try:
num = int(mode_no)
if num < 1 or num > 2:
return False
except ValueError:
return False
return True |
def _bpe_to_words(sentence, delimiter='@@'):
"""Convert a sequence of bpe words into sentence."""
words = []
word = ''
delimiter_len = len(delimiter)
for subwords in sentence:
if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter:
word += subwords[:-delimit... |
def create_table(table_headers, table_rows):
"""Given array of table headers, and an array of arrays for each row, format as table"""
ths = [{'value': header_name} for header_name in table_headers]
trs = [{
'tds': [{
'value': col_val
} for col_val in row]
} for row in table_rows]
return... |
def get_tags_for_deliverable(team_data, team, name):
"""Return the tags for the deliverable owned by the team."""
if team not in team_data:
return set()
team_info = team_data[team]
dinfo = team_info['deliverables'].get(name)
if not dinfo:
return set()
return set(dinfo.get('tags',... |
def business_rule_2(account: int, use_br: bool, threshold: int) -> bool:
"""
Account sends >= threshold transactions within a day. Only works for scatter-gather.
:param account: number of involved accounts
:param use_br: whether to use this br
:param threshold: the threshold
:return: True when ... |
def checkToken(aToken):
"""
Used by pickColumns, below:
"""
if ( aToken.find(';') >= 0 ):
aList = aToken.split(';')
aList.sort()
newT = ''
for bToken in aList:
newT += bToken
if ( len(newT) > 0 ): newT += ';'
if ( newT[-1] == ';' ): newT = ... |
def str_to_int(exp):
""" Convert a string to an integer """
sum = 0
for character in exp:
sum += ord(character)
return sum |
def _convert_paths_to_flask(transmute_paths):
"""
convert transmute-core's path syntax (which uses {var} as the
variable wildcard) into flask's <var>.
"""
paths = []
for p in transmute_paths:
paths.append(p.replace("{", "<").replace("}", ">"))
return paths |
def set_roles(db, roles):
"""
Add roles to a key-value store db
:return: db
"""
db['roles'] = roles
return db |
def findXCoordinateFromDirection(direction):
""" Returns delta X, when given a direction value """
if direction in (1, 5):
return 0
elif direction in (2, 3, 4):
return 2
elif direction in (6, 7, 8):
return -2
else:
error_template = "Unexpected direction value of: {0}"... |
def dimensions(paths):
"""
Calculate the dimensions of a set of paths (i.e. minumum box)
Returns (left, top, right, bottom) as a box.
"""
min_x = float('inf')
min_y = float('inf')
max_x = float('-inf')
max_y = float('-inf')
for path in paths:
for point in path:
... |
def stepAndRepeat(singleExpansion, singleSpikePattern, step, repeat):
""" Given a single instance of the expansion pattern and corresponding spike patter,
plus the stepping distance between patterns and a repeat count,
copy the expansion pattern to the 'repeat' number of
places, separated by 'step'... |
def hide_toolbar(notebook):
"""
Finds the display toolbar tag and hides it
"""
if 'celltoolbar' in notebook['metadata']:
del(notebook['metadata']['celltoolbar'])
return notebook |
def _preprocess_image(image, return_debug_images=False):
"""Pre-process an image before comparing it to others.
This should be done both to input images when classifying,
and tile data images when importing. This function currently
does nothing, but is kept to make it easier to experiment.
Paramet... |
def parse_commandline_args(args):
"""
Parse command line arguments
:param args: list of arguments
:return: parameter names and values
"""
assert len(args) == 7, f'ERROR: pass exactly 7 arguments to launch the simulation, not {len(args)}.'
expected_par_names = ['lambda', 'tau', 'delta']
... |
def class_name(obj):
"""Returns the class name of the specified object.
"""
return obj.__class__.__name__ |
def generate_unsafe_ingress_entry(ingress_entry: dict, unsafe_ip: str) -> dict:
"""
Generates a dictionary from an unsafe ingress entry to the analysis
response
"""
unsafe_ingress = {
"IpProtocol": ingress_entry["IpProtocol"],
"CidrIp": unsafe_ip,
"Status": "warning",
}
... |
def extract(node, path):
"""Pull bits of data out of the ecs bag structure"""
ptr = node
for item in path:
if hasattr(ptr, item):
ptr = getattr(ptr, item)
else:
return None
return ptr |
def bitsize(a):
"""
Compute the bitsize of an element of Z (not counting the sign).
"""
val = abs(a)
res = 0
while val:
res += 1
val >>= 1
return res |
def getUVPins(faces, borders, uvFaces, uvBorders, pinBorders):
"""Find which uvBorders are also mesh borders"""
if uvFaces is None: return set()
if pinBorders:
return set(uvBorders)
pinnit = set()
for face, uvFace in zip(faces, uvFaces):
for i in range(len(face)):
f = face[i]
pf = face[i-1]
... |
def blockReward(height):
"""
https://docs.decred.org/advanced/inflation/
I think this is actually wrong for height < 4096
"""
return 31.19582664*(100/101)**int(height/6144) |
def join2(xseries, sep=',', final_sep=' or '):
"""Regular "join", but with a special separator before the last item. Example: join2([a,b,c,d], ',', ' and ') --> 'a, b, c and d' """
return sep.join(xseries[:-1]) + final_sep + ''.join(xseries[-1:]) |
def yielder(it):
"""
Yield from generator.
Adapted from:
https://stackoverflow.com/a/40701031
"""
try:
return next(it)
except StopIteration:
return None |
def pbb_to_dict(pbb_all):
""" Function that takes the pbb_all array and turns
it into a dictionary to be used and added to the
pyart radar object. """
pbb_dict = {}
pbb_dict['coordinates'] = 'elevation azimuth range'
pbb_dict['units'] = '1'
pbb_dict['data'] = pbb_all
pbb_dict['standard_n... |
def flatten_dictionaries(input):
""" Flatten a list of dictionaries into a single dictionary, to allow flexible YAML use
Dictionary comprehensions can do this, but would like to allow for pre-Python 2.7 use
If input isn't a list, just return it.... """
output = dict()
if isinstance(input, list):... |
def PerpProduct2D(a,b):
"""Computes the the 2D perpendicular product of sequences a and b.
The convention is a perp b.
The product is:
positive if b is to the left of a
negative if b is to the right of a
zero if b is colinear with a
left right defined as shortest a... |
def GetValueFromListList(values,iteration):
"""
Function generating the random sample; in this case, we return a value from an input
"""
value = values[iteration]
return value |
def curvature(dx, dy, ddx, ddy):
"""
Compute curvature at one point given first and second derivatives.
:param dx: (float) First derivative along x axis
:param dy: (float)
:param ddx: (float) Second derivative along x axis
:param ddy: (float)
:return: (float)
"""
return (dx * ddy - ... |
def retrive_sequence(contig_lst, rec_dic):
"""
Returns list of sequence elements from dictionary/index of SeqIO objects specific to the contig_lst parameter
"""
contig_seqs = list()
#record_dict = rec_dic
#handle.close()
for contig in contig_lst:
contig_seqs.append(rec_dic[contig].se... |
def normalize(rendered):
"""Return the input string without non-functional spaces or newlines."""
out = ''.join([line.strip()
for line in rendered.splitlines()
if line.strip()])
out = out.replace(', ', ',')
return out |
def recursive_len(item: list):
""" Return the total number of elements with a potentially nested list """
if type(item) == list:
return sum(recursive_len(subitem) for subitem in item)
else:
return 1 |
def hexString(s):
"""
Output s' bytes in HEX
s -- string
return -- string with hex value
"""
return ":".join("{:02x}".format(ord(c)) for c in s) |
def subseq( seq, index ):
"""numpy-style slicing and indexing for lists"""
return [seq[i] for i in index] |
def extend_dictionary(d1, d2):
"""
Helper function to create a new dictionary with the contents of the two
given dictionaries. Does not modify either dictionary, and the values are
copied shallowly. If there are repeats, the second dictionary wins ties.
The function is written to ensure Skulpt comp... |
def get_host_values(field, db_object):
"""Retrieves the list of hosts associated with peer."""
result = []
for entry in getattr(db_object, 'hosts', []):
result.append(entry.hostname)
return result |
def decodeBits (len, val):
""" Calculate the value from the "additional" bits in the huffman data. """
return val if (val & (1 << len - 1)) else val - ((1 << len) - 1) |
def reverseBits(m):
"""
:param m: integer to reberse bits
:return: integer with reverse bits and number of bits in m
"""
mRev = 0
n = 0
while m > 0:
mRev <<= 1
mRev += m % 2
m >>= 1
n += 1
return mRev, n |
def policy_threshold(threshold, belief, loc):
"""
chooses whether to switch side based on whether the belief on the current site drops below the threshold
Parameters
----------
threshold (float): the threshold of belief on the current site,
when the belief is lower than the... |
def split_and_strip(sep, s):
"""
Split input `s` by separator `sep`, strip each output segment with empty
segment dropped.
"""
return [y for y in (x.strip() for x in s.split(sep)) if len(y) > 0] |
def suppConfiguration(cfg):
"""Load the default pipeline configuration and adjust as necessary
"""
#Edit the input configuration with things specific to this task.
cfg['debug'] = False
# tasks = """dpp.checkDirExistTask dpp.serveTask dpp.extractLightcurveFromTpfTask
# dpp.computeCentroidsTa... |
def in_order_traversal(root):
"""
@ input: root of lcrs tree
@ output: integer list of id's in-order
"""
node_list = []
if root:
node_list = in_order_traversal(root.child) # Left tree
node_list.append(root.id) # Root of tree
node_list = node_list + in_order_traversal... |
def td_rotate_90ccw(txtdict, wout, hout):
"""Rotate 90 CCW"""
# y: x
# x: w - y - 1
ret = {}
for y in range(hout):
for x in range(wout):
xin = hout - y - 1
yin = x
try:
val = txtdict[(xin, yin)]
except KeyError:
... |
def _convert_rho_to_krho(rho, size_ds: int):
"""
Converts the parameter ``rho`` (also noted: math:`\\varrho`) between :math:`0 < \\varrho < 1` in a value between 0 and the size of the reference game.
:param list rho: The values (s) of :math:`\\varrho` to convert
:param int size_ds: The size of the refe... |
def process_opt_with_defn(process, key, defns, values):
""" Use the map of option definitions provided (defns) and map of
project/user-selected preferences (values) to produces appropriate
command line arguments for the given key (key).
In all current cases, the proc_fn in the defns map will either
... |
def format_latex(ss):
"""
Formats a string so that it is compatible with Latex.
:param ss: The string to format
:type ss: string
:return: The formatted string
:rtype: string
"""
tt = (str(ss).replace('_', ' ')
.replace('%', '\%')
)
r... |
def mergeDict(master, other):
"""Merge the given two dictionaries recursively and return the
result."""
if isinstance(master, dict) and isinstance(other, dict):
for key, value in other.items():
if isinstance(value, dict):
if key not in master:
master[k... |
def content_type(content_type_str):
"""Returns the actual type, as embedded in an xml ContentType attribute; application and version are disregarded."""
if content_type_str is None:
return None
if 'type=' in content_type_str:
return content_type_str[content_type_str.rfind('type=') + 5:]
... |
def get_diff(old, new, value):
""" Get the difference between old and new osu! user data. """
return float(new[value]) - float(old[value]) |
def fizz_buzz_one( start, end ):
""" Note: This method returns a long string not a list. """
fizzbuzz = ''
# range is NOT inclusive of the 2nd number, so add 1 to include it.
# range(1,4) > 1,2,3. range(1, 4 + 1) > 1,2,3,4.
for i in range(start,end+1):
if i%3 == 0:
fizzbuzz += "f... |
def get_ending_datetime_of_timetable(timetable):
"""
Get the ending_datetime of a timetable, which corresponds to
the arrival_datetime of the last timetable entry.
:param timetable: timetable_document
:return: None (Updates timetable)
"""
timetable_entries = timetable.get('timetable_entries... |
def list_to_dict(seq):
"""
Take list and insert value in dict
Using values from list as keys and index from list as values in BST.
"""
d = {}
for v, k in enumerate(seq):
d[k] = v
return d |
def time2s(t):
""" t: "hh:mm:ss" """
h, m, s = t.split(":")
return int(h)*3600 + int(m)*60 + int(s) |
def red(string):
""" Use ascii escape sequences to turn `string` in red color.
Parameters
----------
string : str
String to add red color to.
Returns
-------
red_string: str
`string` with ascii escape codes added that will make it show up as red.
"""
return "\033[9... |
def evaluate_accuracy(labels, predictions):
"""
Input: Arrays of labels and predictions, each containing either '0' or '1'
Output: The fraction of predictions that correctly match the label
"""
# Make sure that the lengths of both arrays is equal
assert(len(labels) == len(predictions))
# Score will count ... |
def base_taskname(taskname, packagename=None):
"""
Extract the base name of the task.
Many tasks in the `drizzlepac` have "compound" names such as
'drizzlepac.sky'. This function will search for the presence of a dot
in the input `taskname` and if found, it will return the string
to the right o... |
def rawlist(*args):
"""Build a list of raw IRC messages from the lines given as ``*args``.
:return: a list of raw IRC messages as seen by the bot
:rtype: list
This is a helper function to build a list of messages without having to
care about encoding or this pesky carriage return::
>>> ra... |
def name_paths(name_dataset):
"""
provide article type
make the needed files
"""
name_src = str(name_dataset + '_src_query')
name_dst = str(name_dataset + '_dst_query')
name_summary = str(name_dataset + '_sum')
name_unique = str(name_dataset + '_unique_df')
plot_unique = s... |
def generate_model_config(name, n_filters, nonlinearity='relu'):
""" Generates a spec describing how to build the model
Args:
name: name for this model config
n_filters: list of num filters for each layer - [n_layers]
Returns:
model_spec
"""
model_config = {
'name': name... |
def extract(text, startText, endText):
"""
Extract the first occurence of a string within text that start with startText and end with endText
Parameters:
text: the text to be parsed
startText: the starting tokem
endText: the ending token
Returns the string found between st... |
def traverse_list_forward(head):
"""Traverse the LinkedList in forward direction"""
if head is None:
return -1
curr = head
arr = []
while curr:
arr.append(curr.data)
curr = curr.next
return ' '.join(map(str, arr)) |
def string_contains_environment_var(string):
"""Determines whether or not there is a valid environment variable in the string"""
parts = string.split("$")
# If there are no $ then there is no possiblity for there to be
# an environment variable
if len(parts) == 1:
return False
for inde... |
def duration_str(s):
"""
s: number of seconds
Return a human-readable string.
Example: 100 => "1m40s", 10000 => "2h46m"
"""
if s is None:
return None
m = int(s / 60)
if m == 0:
return "%.1fs" % s
s -= m * 60
h = int(m / 60)
if h == 0:
return "%dm%ds"... |
def is_blank_or_comment(x):
"""Checks if x is blank or a FASTA comment line."""
return (not x) or x.startswith('#') or x.isspace() |
def clamp(value, abs_max):
"""clamp value"""
value = max(-abs_max, value)
value = min(abs_max, value)
return value |
def month_num(month_name: str):
"""Returns the number of a month, with January as month number 1. It;s case insensitive."""
months = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',... |
def partition(s):
"""Returns: a list splitting s in two parts
Precondition: s is a string."""
first = ""
second = ""
# for x in s:
# pos = s.find(x)
# print(pos)
# if pos % 2 == 0:
# first += x
# else:
# second += x
for pos in range(len(s))... |
def _check_nested_floats(thelist):
"""
Returns True if thelist is a (nested) list of floats
INTERNAL HELPER
If thelist recursively contains anything other than a list, tuple, int, or float,
this function returns false.
:param message: A custom error message (OPTIONAL)
:type me... |
def drawBorder(grid: list) -> list:
"""Draw a border around the maze"""
for i, x in enumerate(grid): # Left and Right border
x[0] = x[len(grid)-1] = (20,20,20)
grid[i] = x
grid[0] = grid[len(grid)-1] = [(20,20,20) for x in range(len(grid))] # Top and Bottom border
return grid |
def is_word_capitalized(word):
"""
Check if word is capitalized.
Args:
word (str): Word.
Returns:
(boole): True f word is capitalized. False otherwise.
"""
if not word:
return False
first_letter = word[0]
return first_letter == first_letter.upper() |
def isPerfectSquare(num: int) -> bool:
"""Okay. Solution is O(1)."""
r = int(num ** 0.5)
return r * r == num |
def params(kernels, time, target, target_frame, observer, corr):
"""Input parameters from WGC API example."""
return {
'kernels': kernels,
'times': time,
'target': target,
'target_frame': target_frame,
'observer': observer,
'aberration_correction': corr,
} |
def getHostIP(url='www.google.com'):
"""Returns the (external) host ip for this machine"""
import socket
s = socket.socket()
try:
s.connect((url, 80))
return s.getsockname()[0]
except Exception:
return socket.gethostbyname(socket.gethostname()) |
def append(base, suffix):
"""Append a suffix to a string"""
return f"{base}{suffix}" |
def _insert_statement(name, d):
"""Generate an insert statememt.
ex) insert into foo values (:a, :b, :c, ...)
"""
keycols = ', '.join(":" + c.strip() for c in d)
return "insert into %s values (%s)" % (name, keycols) |
def font_bold(mystring):
"""
Formats the string as bold, to be used in printouts.
"""
font_bold = "\033[1m"
font_reset = "\033[0;0m"
return font_bold + mystring + font_reset |
def humanize_list(l):
"""Return a human-readable list."""
if len(l) == 1:
return l[0]
elif len(l) == 2:
return "{0} and {1}".format(l[0], l[1])
else:
return ", ".join(l[:-1]) + ", and " + l[-1] |
def storable(obj):
"""
Remove fields that can't / shouldn't be stored.
"""
def get_data(a):
if a.startswith('linked_'):
return getattr(getattr(obj, a), 'uuid', None)
else:
return getattr(obj, a)
return {
a:get_data(a) for a in dir(obj)
if n... |
def add_if_missing(add_this, path_list_str):
"""
if a path is missing in a path list separated by ';',
append it
"""
path_list = path_list_str.split(';')
if add_this in path_list:
pass
else:
path_list.append(add_this)
return ';'.join(path_list) |
def normalized_device_coordinates_to_image(image):
"""Map normalized value from [-1, 1] -> [0, 255].
"""
return (image + 1.0) * 127.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.