content stringlengths 42 6.51k |
|---|
def beautify_bash_oneliner(command, replacements={}):
"""Makes a one-line bash command more immediate by adding indentation.
It also can replace tags with a specific string"""
cmd_lines = []
jumpit = False
nl = ""
for c in command:
if c != ";":
nl += c
elif c == ";" ... |
def _index_bam_cmd(i_bam_fn, nproc=1):
"""Index *.bam and create *.bam.bai"""
return 'samtools index %s -@ %s' % (i_bam_fn, nproc) |
def get_api_url(repo_url):
"""Return the GitHub API URL for the respository."""
api_url = None
# If the remote url is set for SSH keys
if repo_url[:3] == "git":
api_url = ("https://api.github.com/repos/" +
repo_url[repo_url.index(":") + 1: -3])
# If the remote url is set f... |
def data_merge(a, b):
"""
Merges b into a and return merged result.
see http://stackoverflow.com/a/15836901
NOTE: tuples and arbitrary objects are not handled as it is totally
ambiguous what should happen.
"""
if b is None:
return a
key = None
try:
#if a is None or ... |
def filter_list_of_dictionary_submission(submission_list, min_comments):
"""filters the list of submission dictionaries to only include submissions with more than min_comments comments"""
filtered_submission_list = []
# filter submission_list for submissions with > min_comments # comments
for submission... |
def splitter(s, split_list):
""" Splits string into smaller substring according to a list. """
# Note: This function won't work correctly if there exists splittable substrings of other splittable strings
# An example would be if 'banana' was a split string and 'nana' also was one.
# However there is no ... |
def policy_with_role(policies, role):
"""Returns the policy with the given name."""
matches = [x for x in policies if x['role'] == role]
if matches:
return matches[0]
else:
raise Exception('No policy matching role {}'.format(role)) |
def LeakyRELU(x, alpha=0.3):
"""Leaky Rectified Linear Unit. It allows a small gradient when the unit is not active.
`f(x) = alpha * x for x < 0, f(x) = x for x >= 0`
Args:
x (list or np.array): Input list or array.
alpha (float): Scale factor.
Returns:
np.array: The Le... |
def incrementSparseVector(v1, scale, v2):
"""
Given two sparse vectors |v1| and |v2|, perform v1 += scale * v2.
This function will be useful later for linear classifiers.
"""
# BEGIN_YOUR_CODE (our solution is 2 lines of code, but don't worry if you deviate from this)
for k, val in v2.items():
... |
def step_learning_rate(base_lr, epoch, step_epoch, multiplier=0.1):
"""Sets the learning rate to the base LR decayed by 10 every step epochs"""
lr = base_lr * (multiplier ** (epoch // step_epoch))
return lr |
def get_group_num(group_size, num_participants, additional_group=True):
"""Returns the number of groups required.
Args:
group_size: The size each group should have.
num_participants: The total number of participants (teams).
additional_group: True if an additional group should be create... |
def getObjID(objName, objList):
"""
Returns an object's ID (int) given its 'objName' (str) and a reference 'objList' (list)
Format of 'objList' is [['name_1',id_1], ['name_2',id_2], ...]
"""
for i in range(0, len(objList)):
if objList[i][0] == objName:
return objList[i][1] |
def parse_artist(data):
"""parse artist data in to message"""
return "%s - %s followers" % (data["name"], data["followers"]["total"]) |
def _signature_get_bound_param(spec):
""" Private helper to get first parameter name from a
__text_signature__ of a builtin method, which should
be in the following format: '($param1, ...)'.
Assumptions are that the first argument won't have
a default value or an annotation.
"""
assert spec... |
def hasCapitalLetters(passW):
"""
checks if password has Capital Letters
"""
count = 0
for i in passW:
if(i.isupper()):
count+=1
return count |
def find_abs_min(arr):
"""
Finds minimum value of the array where each element is absoluted
:param arr: the input array
:return: minimum value and its first index
"""
min_val, min_index = (abs(arr[0]), 0)
for i in range(len(arr)):
if min_val > abs(arr[i]):
min_val, min_in... |
def int_validator(inp, ifallowed):
"""
Test whether only (positive) integers are being keyed into a widget.
Call signature: %S %P
"""
if len(ifallowed) > 10:
return False
try:
return int(inp) >= 0
except ValueError:
return False
return True |
def is_almost_zero(
x: float,
num_of_exponents: int = 6) -> bool:
"""Checks if a num is almost 0 taking into account tiny mistake by python.
Sometimes in adding, division and etc. some mistakes are introduced by
python. This funcions checks whether a number is 0 taking into account
... |
def int_to_bytes(value: int) -> bytes:
"""
Convert an integer value to bytes in big endian representation
"""
return value.to_bytes((value.bit_length() + 7) // 8, byteorder="big") |
def template_subst(template, subs, delims=('<', '>')):
""" Perform substitution of content into tagged string.
For substitutions into template input files for external computational
packages, no checks for valid syntax are performed.
Each key in `subs` corresponds to a delimited
substitution tag t... |
def get_unit(scale):
"""
Convert scale term to unit label
"""
scale2unit = { 1e-9: 'nm',
1e-6: u'\N{MICRO SIGN}m', #or hex id (lookup): u'\u00B5'
1e-3: 'mm',
0.01: 'cm',
0.1:'dm',
1:'m',
100... |
def cast_type(cls, val, default):
"""Convert val to cls or return default."""
try:
val = cls(val)
except Exception:
val = default
return val |
def calc_y(f, t):
"""Calc y coordinate by params.
:param f: the interp params
:type f: dict
:param t: the accumulation of steps
:type t: int
:return: y coordinate
:rtype: float
"""
return f['a_y'] + f['b_y'] * t + f['c_y'] * t * t + f['d_y'] * t * t * t |
def strip_ns(ref):
"""
strip the namespace prefix from ``ref``
:param str ref: one word, colon delimited string, such as *nx:groupGroup*
:returns str: the part to the right of the last colon
"""
return ref.split(":")[-1] |
def function_namespace(f):
"""
Attempts to returns unique namespace for function
"""
if hasattr(f, 'im_func'):
return '%s.%s.%s' % (f.__module__, f.im_class.__name__, f.__name__)
else:
return '%s.%s' % (f.__module__, f.__name__) |
def configureXRayAccumulators(xrts, charAccum=True, charFluorAccum=False, bremFluorAccum=False, printRes=False):
"""configureXRayAccumulators(xrts, charAccum = True, charFluorAccum = False, bremFluorAccum = False, printRes=False)
Configures the x-ray accumulators for characteristic and both bremsstrahlung and c... |
def _is_qualified_name(value):
"""Tests if the given value looks like a schema-qualified name."""
return isinstance(value, list) and len(value) == 2 and all(isinstance(item, str) for item in value) |
def js_rename(jscode, cur_name, new_name):
""" Rename a function or class in a JavaScript code string.
Parameters:
jscode (str): the JavaScript source code
cur_name (str): the current name
new_name (str): the name to replace the current name with
Returns:
jscode (st... |
def kron_delta(a:float, b:float) -> int:
"""Cannonical Kronecker Delta function.
Returns 1 if inputs are equal returns 0 otherwise.
Args:
(:obj:`float`): First input argument
(:obj:`float`): Second input argument
Returns:
(:obj:`int`) Kronecker delta result {0, 1}
"""
... |
def _get_ngrams(n, text):
"""Calculates n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams
"""
ngram_set = set()
text_length = len(text)
max_index_ngram_start = text_length - n
for i in range(max_index_ngram_start + 1):
... |
def ordered(obj):
"""Sort json dicts and lists within."""
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj |
def _exclude(term):
"""
Returns a query item excluding messages that match the given query term.
Args:
term (str): The query term to be excluded.
Returns:
The query string.
"""
return f"-{term}" |
def as_signed(value, bits):
"""Converts an unsigned integer to a signed integer."""
s = 32 - bits
mask = (1 << s) - 1
return (value & mask) - (value & (mask << s)) |
def marker_delay(session, Type='Real64', RepCap='', AttrID=1150061, buffsize=0, action=['Get', '']):
"""[Marker Delay]
"""
return session, Type, RepCap, AttrID, buffsize, action |
def deep_update_dict(dct1, dct2, delete_entries=False):
""" Updates the value from a given recursive dictionary with those from a
second one.
"""
for key, value in dct2.items():
if delete_entries and value == "delete" and key in dct1:
del dct1["key"]
elif key.startswith(... |
def addition(a, b=10): # <-- Don't forget to fill out the function arguments!
"""
Simple function to become familiarized with function structure, paramaters, and return
statements. This function will sum to numbers together.
Parameters:
a (any int or float number): A number to be summed
... |
def boolToYes(b):
"""Convert a Boolean input into 'yes' or 'no'
Args:
b (bool): The Boolean value to be converted
Returns:
str: 'yes' if b is True, and 'no' otherwise.
"""
if b:
return "yes"
else:
return "no" |
def as_unicode(b):
"""
Convert a byte string to a unicode string
:param b: byte string
:return: unicode string
"""
try:
b = b.decode()
except (AttributeError, UnicodeDecodeError):
pass
return b |
def matrix_to_string(matrix, row_headers=None, col_headers=None, fmtfun=lambda x: str(int(x))):
"""Takes a 2D matrix (as nested list) and returns a string.
"""
ret = []
if col_headers:
ret.append('\t' if row_headers else '' + '\t'.join(col_headers))
if row_headers:
ret += [rh + '\t' ... |
def group_type(type_string):
"""
Surround a type with parentheses as needed.
"""
return (
'(' + type_string + ')'
if '|' in type_string else
type_string
) |
def __one_both_open(x, y, c = None, l = None):
"""convert coordinates to zero-based, both strand, open/closed coordinates.
Parameters are from, to, is_positive_strand, length of contig.
"""
return x - 1, y - 1 |
def _aisc_table(metric, version):
"""
Returns the name of the AISC table matching the criteria.
Parameters
----------
metric : bool
If True, searches for the name in the metric shape database. Otherwise,
searches for the name in the imperial shape database.
version : {'15.0'}
... |
def form_to_dict(urlencoded: str):
"""Decode a form of the structure foo=bar&baz=qux&zap=zazzle"""
return {obj.split('=')[0]: obj.split('=')[1] for obj in urlencoded.split('&')} |
def parallelz(*args):
"""
parallelz Function:
This function is designed to generate the total parallel
impedance of a set (tuple) of impedances specified as real
or complex values.
Parameters
----------
Z: tuple of complex
The tupled input set of impedances, ma... |
def get_size(lx, ly):
""" Gets columns with maximum and minimum length.
Args:
lx (:obj:`float`): X-axis length.
ly (:obj:`float`): Y-axis length.
Returns:
Column indexes with maximum and minimum length, respectively.
"""
if lx > ly:
max_size = 1
min_size = 2... |
def linkify(link_template, item):
"""Formats a strings into a URL using string replacement
Paramters
---------
link_template : str
The template for the URL.
item : list or tuple of str
The strings that will be inserted into the template
"""
return link_template.format(*item) |
def search_req(req_id, ni_url, http_host, http_index, form_params,
file_name, tempdir):
"""
@brief Perform a NetInf 'search' on the http_host using the form_params.
@param req_id integer sequence number of message containing request
@param ni_url None for earch requests
@param http_ho... |
def angular_escapes(value):
"""Provide a basic filter to allow angular template content for Angular.
Djangos 'escapejs' is too aggressive and inserts unicode.
It provide a basic filter to allow angular template content to be used
within javascript strings.
Args:
value: a string
Return... |
def move(pos, mov):
"""Change a position (pos) by a movement (mov). Both must be (x,y) tuples"""
return (pos[0]+mov[0], pos[1]+mov[1]) |
def is_pon(item):
"""
:param item: array of tile 34 indices
:return: boolean
"""
if len(item) != 3:
return False
return item[0] == item[1] == item[2] |
def enabled(start, idx, local_list, rule_list, conf_symbol, trans_symbol):
"""
Returns SMT constrains that relate a configuration and a transition applied to it
"""
result = ""
for i in range(start, idx):
for j in local_list:
rls = [r for r in rule_list if r["from"] == j]
... |
def tensor_diag(n: int, fr: int, to: int, w: float):
"""Construct a tensor product from diagonal matrices."""
def tensor_product(w1: float, w2: float, diag):
return [j for i in zip([x * w1 for x in diag],
[x * w2 for x in diag]) for j in i]
diag = [w, -w] if (0 == fr... |
def look_up_data(input_string, logical_zero, logical_one):
"""Looks up the input data to determine if the string is a logical one,
logical zero, or outside the code base.
Parameters
----------
input_string : str
data for analysis
logical_zero : list
list of strings represent... |
def squelch(prop_call, default=None, exceptions=(ValueError,)):
""" Utility function that wraps a call (likely a lambda function?) to return a default on specified exceptions """
if not exceptions:
return prop_call()
try:
return prop_call()
except exceptions:
return default |
def sum_square_difference(n: int) -> int:
"""
Calculates following formula:
(1 + 2 + ... + n)^2 - (1^2 + ... + n^2)
"""
return sum(range(1, n+1)) ** 2 - sum(x ** 2 for x in range(1, n+1)) |
def invert_rule_hierarchy(rule_hierarchy):
"""Get inverted rule hierarchy (swapped lhs and rhs)."""
new_rule_hierarchy = {
"rules": {},
"rule_homomorphisms": {}
}
for graph, rule in rule_hierarchy["rules"].items():
new_rule_hierarchy["rules"][graph] = rule.get_inverted_rule()
... |
def _attr_get_(obj, attr):
"""Returns an attribute's value, or None (no error) if undefined.
Analagous to .get() for dictionaries. Useful when checking for
value of options that may not have been defined on a given
method."""
try:
return getattr(obj, attr)
except AttributeError... |
def has_equal_block(ciphertext, block_length):
"""Checks if the given ciphertext contains two consecutive equal blocks"""
for i in range(0, len(ciphertext) - 1, block_length):
if ciphertext[i:i+block_length] == ciphertext[i+block_length:i+2*block_length]:
return True
return False |
def partial_param_bit_shift(property_key: int) -> int:
"""Get the number of bits to shift the value for a given property key."""
# We can get the binary representation of the property key, reverse it,
# and find the first 1
return bin(property_key)[::-1].index("1") |
def project_coordinates(coordinates, projection, **kwargs):
"""
Apply projection to given coordinates
Allows to apply projections to any number of coordinates, assuming
that the first ones are ``longitude`` and ``latitude``.
Examples
--------
>>> # Define a custom projection function
... |
def get_backends_url(config):
"""Return the URL for a backend."""
hub = config.get('hub', None)
group = config.get('group', None)
project = config.get('project', None)
if hub and group and project:
return '/Network/{}/Groups/{}/Projects/{}/devices/v/1'.format(hub, group,
... |
def countparens(text):
""" proper nested parens counting """
currcount = 0
for i in text:
if i == "(":
currcount += 1
elif i == ")":
currcount -= 1
if currcount < 0:
return False
return currcount == 0 |
def nCWRk(n, r):
"""Returns nCk(n+r-1, n-1) optimized for large n and small r."""
val = 1
for i in range(1, r+1):
val *= n + r - i
val //= i
return val |
def ymd_to_date(year, month, day):
""" Given year, month, day (or hour, minute, second) values, returns a
variable in YYYYMMDD (or HHMMSS) format.
Parameters
----------
year, month, day: int
Bits corresponding to year (or hour), month (or minute), and day
(or second) values
Ret... |
def cleanUnicodeFractions(s):
"""
Replace unicode fractions with ascii representation, preceded by a
space.
"1\x215e" => "1 7/8"
"""
fractions = {
u'\x215b': '1/8',
u'\x215c': '3/8',
u'\x215d': '5/8',
u'\x215e': '7/8',
u'\x2159': '1/6',
u'\x215a'... |
def domain(author):
"""Any text. Finds the first string that looks like an email
address, and extracts just the domain component. Example: ``User
<user@example.com>`` becomes ``example.com``.
"""
f = author.find(b'@')
if f == -1:
return b''
author = author[f + 1 :]
f = author.fin... |
def _process_get_set_NSCProperty(code, reply):
"""Process reply for functions zGetNSCProperty and zSETNSCProperty"""
rs = reply.rstrip()
if rs == 'BAD COMMAND':
nscPropData = -1
else:
if code in (0,1,4,5,6,11,12,14,18,19,27,28,84,86,92,117,123):
nscPropData = str(rs)
... |
def sequence_word_index(sequence, word_index_dict, pad_value=0):
"""Sequence word transfer to sequence index.
Args:
sequence: pd.Series or np.array or List of lists, sample sequence.
word_index_dict: dict, {word: index}.
pad_value: fillna value, if word not in word_index_dict, filln... |
def _BreadthFirstSearch(to_visit, children, visited_key=lambda x: x):
"""Runs breadth first search starting from the nodes in |to_visit|
Args:
to_visit: the starting nodes
children: a function which takes a node and returns the nodes adjacent to it
visited_key: a function for deduplicating node visits.... |
def linear_search(list, target):
"""
Returns the index position of the target if found, else returns None
"""
for i in range(0, len(list)):
if list[i] == target:
return i
return None |
def _FindAndRemoveArgWithValue(command_line, argname):
"""Given a command line as a list, remove and return the value of an option
that takes a value as a separate entry.
Modifies |command_line| in place.
"""
if argname not in command_line:
return ''
location = command_line.index(argname)
value = com... |
def errors(name=None, err_msg=None, err_list=None):
"""
This function will return a Dialog errors dictionary that can be returned to Slack,
and as a result the User will see error notifications on the dialog they are working
in.
The caller can use this function in one of two ways:
(1) "sing... |
def is_on(S, j):
"""
Returns 1 if and only if the `j`-th item of the set `S` is on.
Examples
========
Check if the 3-th and then 2-nd item of the set is on:
>>> S = 0b101010
>>> is_on(S, 3), is_on(S, 2)
(1, 0)
"""
return (S & (1 << j)) >> j |
def coverageTruncatedToString(coverage) :
"""Converts the coverage percentage to a formatted string.
Returns: coveragePercentageAsString, coverageTruncatedToOneDecimalPlace
Keyword arguments:
coverage - The coverage percentage.
"""
# Truncate the 2nd decimal place, rather than rounding
# to... |
def convert_ecalendar_crse(course_code):
"""McGill eCalendar uses a different course code format, so valid codes COMP-206D1-001 become comp-206d5"""
course_code = str(course_code)
course_code = course_code.lower()
code_parts = course_code.split("-")
if code_parts[0].isalpha() and code_parts[1].is... |
def findlast(text, target):
"""
looks for the last Occurrence of target
"""
last=-1
here=text.find(target)
if here>-1:
last=here
there=0
while there>-1:
there=text[last+1:].find(target)
if there>-1: last+=there+1
return last |
def is_number(string):
""" check whether a string can be converted to a number
Args:
string: value as a string, could be a number
Returns:
True/False for whether the value can be converted to a number
"""
try:
number = float(string)
except ValueError:
... |
def _add_allele(gene_string, allele = "*01"):
"""
Example
-------
>>> _add_allele('TRBV12-2')
'TRBV12-2*01'
"""
return f"{gene_string}{allele}" |
def format_pkg_list(config_dict):
"""
Takes the YAML configuration information and parses/formats the R
package list for use with an "Rscript -e **" call.
:param config_dict: The configuration dictionary created with the YAML file.
"""
config_dict = {k: v for k, v in config_dict.items() if "PKG... |
def is_elf(filename):
""" Check that a file is in the elf format
"""
with open(filename, "rb") as fp:
data = fp.read(4)
return data == "\x7fELF" |
def clean_name(name: str):
"""Clean name by stripping whitespace and newline."""
return name.splitlines()[0].strip() |
def format_pair_list(pair_list, **kwargs):
""" Given a list of 2-tuples of str, calls format with `kwargs` for each
item in the 2-tuples and return the formatted list of 2-tuples.
Parameters
----------
pair_list: list of 2-tuples of str
kwargs: keyword arguments
Arguments for the forma... |
def ValidateChecksums(reference_checksums,
new_checksums,
allow_missing_projects=False):
"""Validates that reference_checksums and new_checksums match.
Args:
reference_checksums: a dict of reference checksums, mapping from a project
name to a project checksum.
... |
def is_number(input_string):
"""
if input_string includes number only, return corresponding number,
otherwise return input_string
"""
try:
return float(input_string)
except ValueError:
pass
try:
import unicodedata
return unicodedata.numeric(input_... |
def is_instance_namedtuple(obj) -> bool:
"""
Checks if the object is an instance of 'namedtuple'.
:param obj: the object to check
:return: True if the object is an instance of 'namedtuple'
"""
return (
isinstance(obj, tuple) and hasattr(obj, "_asdict") and hasattr(obj, "_fields")
) |
def convert(lons):
""" 0~360 to -180~180
"""
if lons > 180:
lons = lons - 360
return lons |
def get_name(resource):
"""
Returns a name, or a code, or an empty string.
"""
if resource.get('name'):
return resource['name'][0].get('text', '')
if resource.get('code'):
return resource['code'][0].get('text', '')
return '' |
def fillText(text, continuationPrefix="", maxLineLength=76):
"""Add line-breaks to <text>.
Replace ' ' with '\n'+<continuationPrefix> as necessary to ensure no
line longer than <maxLineLength>. Return the result as a string, ending
with '\n'.
The text should not contain newlines, tabs, or mult... |
def format_list(data, wrap_every=3, sep=", ", newline="\n"):
"""wrap every 3 elements into a newline.
Separate every element with specified separator"""
if not data:
return ""
output = []
for idx, el in enumerate(data):
suffix = sep
if (idx + 1) % wrap_every == 0:
... |
def grow_population(initial, days_to_grow):
"""
Track the fish population growth from an initial population, growing over days_to_grow number of days.
To make this efficient two optimizations have been made:
1. Instead of tracking individual fish (which doubles every approx. 8 days which will result O... |
def keep(pair, selected):
"""
determine whether a cell pair shall be kept
ie. there is no conflicting selected candidate already
"""
# reject unselected subject
key = (pair['row_id'], pair['subj_id'])
if (key in selected) and (selected[key] != pair['subj_cand']):
return False
... |
def treatGiNumber(giNumber):
"""
Used to return null if the gi does not exists
:param giNumber: gi number
:type giNumber: string
:return: None if the gi number is non-existent
:rtype None or string
"""
if giNumber == 'NA':
return None
else:
return giNumber |
def num_batches(adhoc_modelname):
"""
Helper function to best_accuracy_trainval_loss. Takes a model name of the
form "modelnamebatch01234" and returns the number of batches used to train
it, which in this example is 5 (since [0, 1, 2, 3, 4] has five elements).
N.B. the number 10 counts 2 toward the ... |
def build_shared_pref_path(package, pref_name):
"""
Build the full path for the shared pref
:param package: The package name the shred pref belongs to.
:param pref_name: The shared preference name (xml extension can be ommited)
"""
if pref_name.endswith('.xml'):
pref_name = pref_name.rs... |
def dot(p1, p2, debug = False):
"""Dot product between two points
Args:
p1 ([float, float]): x and y coordinates
p2 ([float, float]): x and y coordinates
Returns:
float
"""
return p1[0] * p2[0] + p1[1] * p2[1] |
def uncompact(creation_sequence):
"""
Converts a compact creation sequence for a threshold
graph to a standard creation sequence (unlabeled).
If the creation_sequence is already standard, return it.
See creation_sequence.
"""
first=creation_sequence[0]
if isinstance(first,str): ... |
def RunBenchmarkTasksInSeries(tasks):
"""Runs benchmarks in series.
Arguments:
tasks: list of tuples of task: [(RunBenchmarkTask, (spec,), {}),]
Returns:
list of tuples of func results
"""
return [func(*args, **kwargs) for func, args, kwargs in tasks] |
def betabin_expval(alpha, beta, n):
"""
Expected value of beta-binomial distribution.
"""
return n * alpha / (alpha + beta) |
def divv3s(vec, scalar):
"""divide elements of 3-vector by scalar"""
return (vec[0]/scalar, vec[1]/scalar, vec[2]/scalar) |
def list_to_str(list_arg, delim=' '):
"""Convert a list of numbers into a string.
Args:
list_arg: List of numbers.
delim (optional): Delimiter between numbers.
Returns:
List converted to string.
"""
ret = ''
for i, e in enumerate(list_arg):
if i > 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.