content stringlengths 42 6.51k |
|---|
def dasherize(word):
"""Replace underscores with dashes in the string.
Example::
>>> dasherize("puni_puni")
"puni-puni"
"""
return word.replace("_", "-") |
def force_ord(char):
"""
In python 3, casting bytes to a list returns a list of ints rather than
a list of bytes, as python 2 does (with str)
"""
return char if isinstance(char, int) else ord(char) |
def parse_claim(line):
"""Parse line to tuple with edge coordinates and size of rectangle."""
_, claim = line.split(' @ ')
edge_part, rectangle_part = claim.split(': ')
edge = [int(num) - 1 for num in edge_part.split(',')]
rectangle = [int(num) for num in rectangle_part.split('x')]
return edge, ... |
def rint(f: float) -> int:
"""
Rounds to an int.
rint(-0.5) = 0
rint(0.5) = 0
rint(0.6) = 1
:param f: number
:return: int
"""
return int(round(f, 0)) |
def _fake_send_to_daemon(message):
"""
This function emulate the send_to_daemon method of commandparser
:return: the message received from client_daemon
"""
if 'register' in message:
# User creation validated
if 'Str0ng_Password' in message['register'][1]:
return {'conten... |
def int2nice(num):
"""
:return: nicer version of number ready for use in sentences
:rtype: str
"""
nice = {
0: 'no',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
... |
def select_top_boundary(boundaries_list, scores_list, score_thr):
"""Select poly boundaries with scores >= score_thr.
Args:
boundaries_list (list[list[list[float]]]): List of boundaries.
The 1st, 2rd, and 3rd indices are for image, text and
vertice, respectively.
scores_... |
def _get_headers(params):
"""
Return HTTP headers required.
"""
return {"Authorization": "OAuth {oauth}".format(oauth=params["api_key"])} |
def set_target_frame(target_frame, prefix='', rconn=None):
"""Sets the target_frame of the item currently being tracked
Return True on success, False on failure"""
if rconn is None:
return False
try:
result = rconn.set(prefix+'target_frame', target_frame.lower())
except Exception:... |
def string_to_max_list(s):
"""Given an input string, convert it to a descendant list of numbers
from the length of the string down to 0"""
out_list = list(range(len(s) - 1, -1, -1))
return out_list |
def parse_ucx(name):
"""
Helper function that takes an object name and returns a 2-tuple consisting of
the original object name (without 'UCX_' prefix) and UCX index suffix as an int.
https://docs.unrealengine.com/latest/INT/Engine/Content/FBX/StaticMeshes/index.html#collision
Will return (... |
def guess(key, values):
"""
Returns guess values for the parameters of this function class based on the input. Used for fitting using this class.
"""
return [min(values),
0.4, -68, 10,
0.4, -40, 10,
0.4, -10, 10,
0.4, 20, 10,
0.4, 50, 10,
... |
def absolute_value(x):
"""Return the absolute value of X.
>>> absolute_value(-3)
3
>>> absolute_value(0)
0
>>> absolute_value(3)
3
"""
if x < 0:
return -x
elif x == 0:
return 0
else:
return x |
def levenshtein_distance(str1, str2):
"""
dynamic levenshtein distance.
:str1: str1
:str2: str2
return the minimal edition between two strings.
"""
d=dict()
for i in range(len(str1)+1):
d[i]=dict()
d[i][0]=i
for i in range(len(str2)+1):
d[0][i] = i
for i i... |
def get_forward_closure(node, connections):
"""
For a given node return two sets of nodes such that:
- the given node is in the source_set
- the sink_set contains all the connection targets for nodes of the
source_set
- the source_set contains all the connection starts for nodes from t... |
def is_empty_dataframe(dataframe):
"""
Checks if the provided dataframe is empty
Args:
dataframe (pandas.Dataframe: Dataframe
Returns:
Bool: False if the dataframe is not empty
"""
return dataframe is not None and dataframe.empty |
def _FirewallTargetTagsToCell(firewall):
"""Comma-joins the target tags of the given firewall rule."""
return ','.join(firewall.get('targetTags', [])) |
def get_html_lines(html_files):
"""
Parameters
----------
html_files: list of files
list of html files created by get_html_files()
Return
------------
list of strs
all lines from html_files in one list
"""
html_lines = []
for file in html_files:
lin... |
def show_bag_contents(bag): #function 1
"""Show the contents of your bag."""
#global bag
print("")
if "rock" in bag:
bag["rock"] +=1
print("Your bag contains: " + str(bag["rock"]) + " rocks")
else:
bag["rock"] =1
print("Your bag contains: " + str(bag["rock"]) + " rock")
return bag |
def action_count(raw_val):
"""Count the items in raw_val, or set it to None if it isn't a list."""
if isinstance(raw_val, list):
return len(raw_val)
else:
return None |
def agg_event_role_tpfpfn_stats(pred_records, gold_records, role_num):
"""
Aggregate TP,FP,FN statistics for a single event prediction of one instance.
A pred_records should be formated as
[(Record Index)
((Role Index)
argument 1, ...
), ...
], where argument 1 should sup... |
def repeat(func, num: int = 1, *args, **kwargs):
"""
Repeats execution of the function consecutively,
as many times as specified and returns the result
of the last run.
:param func: the decorated function
:param num: the number of times to run the function
:param args: the positional args o... |
def combineWith_(string):
"""
combine all strings given with _
"""
if len(string) == 0:
return ''
s = string[0]
for item in string[1:-1]:
if item == '':
continue
s = s + '_' + item
if not s == '' and not string[-1] == '':
... |
def unpack_singleton(x):
"""
>>> unpack_singleton([[[[1]]]])
1
>>> unpack_singleton(np.array(np.datetime64('2000-01-01')))
array('2000-01-01', dtype='datetime64[D]')
"""
while isinstance(x, (list, tuple)):
try:
x = x[0]
except (IndexError, TypeError, KeyError):
... |
def lst2gha(lst, site_long=116.670456):
"""
Convert LST in decimal degree to GHA in decimal hours.
Longitude of the observer can be specify with site_long = +/- decimal
degree, where + is east and - is west of the prime meridian. Else assume
MWA 128T location, site_long = 116.670456.
"""
g... |
def findsections(blocks):
"""Finds sections.
The blocks must have a 'type' field, i.e., they should have been
run through findliteralblocks first.
"""
for block in blocks:
# Searching for a block that looks like this:
#
# +------------------------------+
# | Section ... |
def fn1(n):
"""Terms for the zeta function."""
return 1./n/n |
def is_canonical_chromosome(chr):
"""Check if chr is 1-22, X or Y (M not included)
Args:
chr (str): chromosome name
Returns:
is_canonical (bool): True if chr is 1-22, X or Y
"""
is_canonical = False
if chr.startswith("chr"):
chr = chr.replace("chr", "")
if chr == "... |
def _file_size_to_str(file_size: int) -> str:
"""File size int to str"""
if file_size >= 1e9:
return f"{round(file_size / 1e9, 1)}gb"
if file_size >= 1e6:
return f"{round(file_size / 1e6, 1)}mb"
if file_size >= 1e3:
return f"{round(file_size / 1e3, 1)}kb"
return f"{file_si... |
def fact(n):
"""return the factorial of the given number."""
r=1
while n>0:
r=r*n
n=n-1
return r |
def quote(s):
"""
Converts a variable into a quoted string
"""
if (s[0] == s[-1]) and s.startswith(("'", '"')):
return str(s)
return '"' + str(s) + '"' |
def get_elements_list(schema, path, paths):
"""returns all 'child' elements in schema joined with parent path"""
for schema_el in schema:
gen_p = '.'.join(path + [schema_el])
if type(schema[schema_el]) is dict:
get_elements_list(schema[schema_el], path + [schema_el], paths)
e... |
def set_bit(v, index, x):
"""Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value."""
mask = 1 << index # Compute mask, an integer with just bit 'index' set.
v &= ~mask # Clear the bit indicated by the mask (if x is False)
if x:
v |= mask # If x was True, set... |
def is_prime(n):
"""Returns True is n is prime, False if not"""
for i in range(2,n-1):
if n%i == 0:
return False
return True |
def _get_const_args(const_args, n_const):
"""
check and return const_args from the passed value to DirectionalSimulator
"""
if const_args is None:
const_args = [[]] * n_const
try:
const_args = list(const_args)
except TypeError:
const_args = [[const_args]] * n_const
i... |
def _nop_df(data, **kwargs):
"""Test function for test_pd_run."""
for key, val in kwargs.items():
data[key] = val
return data |
def create_collection_filename(user: str, ext: str = "csv") -> str:
"""Return a filename for a collection."""
return f"export_collection_{user}.{ext}" |
def slugify(text):
"""replaces white-space separation with hyphens"""
return "-".join(text.split()) |
def find_city_and_province_from_location(loc: str):
"""
returns just the first line
:param loc:
:return:
"""
parts = loc.split('\n')
return parts[0].strip() |
def parse_frame_message(msg:str):
"""
Parses a CAN message sent from the PCAN module over the serial bus
Example: 't1234DEADBEEF' - standard (11-bit) identifier message frame
'R123456784' - extended (29-bit) identifier request frame
Returns a tuple with type, ID, size, and message
Ex... |
def callable(thing):
"""This function was replaced in python3 with the below"""
return hasattr(thing, '__call__') |
def getOptional(data, key, default=None, cls=None):
"""
Get the value mapped to the requested key. If it's not present, return the default value.
"""
if key in data:
value = data[key]
if cls and value.__class__ != cls:
raise Exception("Protocol field has wrong data type: '%s... |
def ArchForAsmFilename(filename):
"""Returns the architectures that a given asm file should be compiled for
based on substrings in the filename."""
if 'x86_64' in filename or 'avx2' in filename:
return ['x86_64']
elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
return ['x86']... |
def _split(text):
"""Split a line of text into two similarly sized pieces.
>>> _split("Hello, world!")
('Hello,', 'world!')
>>> _split("This is a phrase that can be split.")
('This is a phrase', 'that can be split.')
>>> _split("This_is_a_phrase_that_can_not_be_split.")
('This_is_a_phrase... |
def get_rank(ranks, tid):
""" Find tid in a jagged array of ranks in a given week. Return None if unranked """
for irank,ts in enumerate(ranks):
if tid in ts:
return irank+1
return None |
def D(x, y):
""" Converts D/data codes to bytes.
Does not result in 8b10b data; requires explicit encoding.
See the USB3 / PCIe specifications for more information.
"""
return (y << 5) | x |
def bmi_recommendation(bmi):
"""Given a BMI, return a pair
(bool - True if BMI is healthy) and (str - recommendation)
"""
if bmi < 18.5:
return (False, 'You are underweight. You should see a doctor.')
elif bmi < 25:
return (True, 'You are within the ideal weight range.')
return (... |
def get_ordinal_indicator(number):
"""
Returns the ordinal indicator for an integer.
Args:
number (int): An integer for which the ordinal indicator will be determined.
Returns:
str: The integer's ordinal indicator.
"""
ordinal_dict = {1: 'st', 2: 'nd', 3: 'rd'}
if number > ... |
def exnToString(exn):
"""Turns a simple exception instance into a string (better than str(e))"""
strE = str(exn)
if strE:
return '{0!s}: {1!s}'.format(exn.__class__.__name__, strE)
return exn.__class__.__name__ |
def gcd(x, y):
"""Euclidian algorithm to find Greatest Common Devisor of two numbers"""
while y:
x, y = y, x % y
return x |
def find_capital_character(string, offset):
"""
Find capital character in a string after offset.
"""
for index in range(offset, len(string)):
if string[index].isupper():
return index
return None |
def not_any(tuple1, tuple2):
"""Checks that no element of tuple2 is in tuple1"""
if tuple2 is None:
return True
if tuple1 is None:
return False
for e in tuple2:
if e in tuple1:
return False
return True |
def _ancestors_contains_blacklisted_tag(xpath_string, blacklisted_tags):
"""
returns
-------
True, if the xpath_string (i.e. the ancestors) contains any blacklisted_tag
"""
xpath = xpath_string.split("/")
for tag in blacklisted_tags:
if tag in xpath:
return True
retur... |
def uniq_srt(it):
"""Returns the input sequence unified and sorted (according to the values)
>>> uniq_srt([3, 3, 5, 3, 4, 2, 4])
[2, 3, 4, 5]
>>> uniq_srt('abrakadabra')
['a', 'b', 'd', 'k', 'r']
"""
return sorted(set(it)) # your solution |
def sizeof_fmt(num, suffix='B'):
"""
given a file size in bytes, output a human-readable form.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1000.0:
return "{:.3f} {}{}".format(num, unit, suffix)
num /= 1000.0
return "{:.1f} {} {}".format(num, 'Y'... |
def normalize_boolean(value: bool) -> str:
"""
5.1.1.4 - c.2:
Boolean values shall be rendered using either t for true or f for false.
"""
if value:
return "t"
else:
return "f" |
def split_model(mod):
""" Take a model given by a set of operations and split it into a set of models
and operators
model = 3*pf1-pf2 ->
model = (models, coefs, operators)
model = ((pf1, pf2), (3, 1), (multiple, subtract))
"""
# Dictionary to map symbols to strings ... |
def eval_char(c):
"""Returns the character code of the string s, which may contain
escapes."""
if len(c) == 1:
return ord(c)
elif c[-1] == "'":
return ord("'")
elif c[0] == "\\" and c[1] not in "abtrnvfxuU01234567\\":
c = c[1:] # unnecessary backslash?
elif c == "\\u":
... |
def _check_expired(notafter_epoch):
"""
Can be used to check for expired certs
Returns True if expired, False otherwise
"""
import time
epoch_time = int(time.time())
cert_epoch = int(notafter_epoch)
return cert_epoch < epoch_time |
def parse_string(value):
"""
parses string for python keywords or numeric value
Parameters
----------
value : str or float
the value to be parsed (true, false, none, null, na, or float)
Returns
-------
boolean, None, float, original value
"""
if value is None:
r... |
def order(*args):
"""
Will collect field type to order by.
"""
# Need to unpack the tuple!
t = list(args)
j = ",".join(t)
return j.split(",") |
def int_base_0(x: str) -> int:
"""@brief Converts a string to an int with support for base prefixes."""
return int(x, base=0) |
def remove_unknowns(vocab, sentence):
"""
assuming sentence is a list
"""
for i in range(len(sentence)):
if not sentence[i] in vocab:
sentence[i] = "<unk>"
return sentence |
def letters_numbers_equals_eff(A):
"""
Here, I'm trying to outputs the sub-array that its numbers and letters equals:
[1, 1, 2, 's', 7, 's', 'b', 5, 'q'] -> 1,8 (4 int and 4 str)
:param A:
:return:
"""
def _count(A):
cnt_int = 0
map_int = set()
cnt_str = 0
ma... |
def set_force_update_on_page_load(forceUpdateOnPageLoad: bool) -> dict:
"""
Parameters
----------
forceUpdateOnPageLoad: bool
"""
return {
"method": "ServiceWorker.setForceUpdateOnPageLoad",
"params": {"forceUpdateOnPageLoad": forceUpdateOnPageLoad},
} |
def GetFunctionImageNames( baseName, funcNameList ):
"""Generate a list of FITS filenames as would be created by makeimage in "--output-functions"
mode.
"""
nImages = len(funcNameList)
imageNameList = [ "%s%d_%s.fits" % (baseName, i + 1, funcNameList[i]) for i in range(nImages) ]
return imageNameList |
def get_product_id(text):
"""Returns product ID for a given link."""
product_id = text.split('?')[0]
product_id = product_id.replace('.', '/').split('/')
if len(product_id) == 1:
product_id = product_id[0]
else:
product_id = product_id[-2]
try:
return int(product_id)
... |
def env_injector_xyz(env):
"""Returns the coordinates of the sample injector. XXX units unknown?"""
if env is not None:
return tuple([
env.epicsStore().value("CXI:USR:MZM:0%i:ENCPOSITIONGET" %(i+1))
for i in range(3)]) |
def all_equal(sequence):
""" Returns true, if all elements of sequence are equal"""
return all(x == sequence[0] for x in sequence) |
def adj_check(tag):
"""
:param tag: a string representing a POS-TAG
:return: boolean if the given tag belongs to the adjective class
"""
return tag in ['JJ', 'JJR', 'JJS'] |
def is_valid_argument_model(argument):
"""
Validates CLI model specified argument level.
With this validation, every argument is mandated to have name and help at the minimum.
Any other custom validation to the arguments can go here.
Parameters
----------
argument(dict): A dictonary obje... |
def _get_device_identifier(identifier_byte):
"""
Convert the identifier byte to a device identifier (model type).
Values are based on the information from page 24 of the datasheet.
"""
if identifier_byte in (0x00, 0xFF):
identifier_string = "Engineering sample"
elif identifier_byte == 0x... |
def is_correlated(corr_matrix, feature_pairs, rho_threshold=0.8):
"""
Returns dict where the key are the feature pairs and the items
are booleans of whether the pair is linearly correlated above the
given threshold.
"""
results = {}
for pair in feature_pairs:
f1, f2 = pair.split("__"... |
def get_ax_location(legend_style):
""" Get the legend location from the verticalAlign key or return default """
align = legend_style.get('align', None)
vertical_align = legend_style.get('verticalAlign', None)
if not align or not vertical_align:
return 'best'
vertical_align = vertical_align... |
def flat_dict(item, parent=None):
"""Returns a flat version of the nested dict item"""
if not parent:
parent = dict()
for k, val in item.items():
if isinstance(val, dict):
parent = flat_dict(val, parent)
else:
parent[k] = val
return parent |
def pydyn_ver(*args):
"""
Returns PYPOWER-Dynamics version info for current installation.
"""
ver = {'Name': 'PYPOWER-Dynamics',
'Version': '1.1',
'Release': '',
'Date': '31-May-2015'}
return ver |
def second_half(value):
"""
Only returns second half of list
"""
return value[int(len(value)/2):] |
def get_phrases_and_tags(entities):
"""
Args:
entities (Iterable[Entity]):
Returns:
Set[Tuple[Tuple[str],str]]:
"""
return {(entity.words, entity.tag) for entity in entities} |
def repeat(phrase, num):
"""Return phrase, repeated num times.
>>> repeat('*', 3)
'***'
>>> repeat('abc', 2)
'abcabc'
>>> repeat('abc', 0)
''
Ignore illegal values of num and return None:
>>> repeat('abc', -1) is None
True
>>> repeat('abc',... |
def pad_binary_string(binary_string, required_length):
"""
Pads a binary string with additional zeros.
Example: pad_binary_string('101',5) -> '00101'
:param binary_string: a binary representation as a string
:param required_length: the number of digits required in the output binary string
:retu... |
def compute_version(text):
"""Compute a version number from a version string"""
version_parts = text.split(".")
version = 0
try:
if len(version_parts) >= 1:
version = int(version_parts[0]) * 100 * 100
if len(version_parts) >= 2:
version += int(version_parts[1]) *... |
def collatz_sequence(seed):
"""Given seed generates Collatz sequence"""
sequence = [seed]
counter = seed
# pylint: disable=misplaced-comparison-constant
while 1 != counter:
# pylint: disable=misplaced-comparison-constant
counter = (int(counter/2) if 0 == counter%2 else 3*counter+1)
... |
def drop_trailing_zeros(number):
""" drop trailing zeros from decimal """
if number == 0:
return 0
else:
return number.rstrip('0').rstrip('.') if '.' in number else number |
def is_even(k: int) -> bool:
"""Returns True if k is even, and False otherwise."""
# Reduces any number to its rightmost bit. If it is odd, that will
# complement then 1 and return 1 as a result of the bitwise AND. If
# it is even, it will return 0.
return k & 1 == 0 |
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
True
... |
def sort_keys(json_data):
"""This function alphabetizes/sorts the dictionary keys.
.. versionadded:: 1.0.0
:param json_data: The unsorted JSON data from the imported file
:type json_data: dict
:returns: A list of tuples containing the keys and values with the keys having been alphabetized/sorted
... |
def parse_threshold_list(parselist, current):
"""Parse where the value lands on the require threshold"""
for index in range(len(parselist)):
if current <= parselist[index]:
return parselist[index]
return 100 |
def sanitize_input(data):
"""
Currently just a whitespace remover. More thought will have to be given with how
to handle sanitzation and encoding in a way that most text files can be successfully
parsed
"""
replace = {
ord('\f') : ' ',
ord('\t') : ' ',
ord('\n') ... |
def nba_league(x):
"""Takes in initials of league and returns numeric API Code
Input Values: "NBA", "WNBA", or "NBADL"
Used in: _Draft.Anthro(), _Draft.Agility(), _Draft.NonStationaryShooting(),
_Draft.SpotUpShooting(), _Draft.Combine()
"""
leagues = {"NBA": "00", "WNBA": "10", "NBADL": "20"... |
def playlist_password(playlist_name, limit):
"""
# Takes in a string representing playlist name
# and an integer character limit. Generates and
# returns a string by defined rules that has a
# length less than or equal to the character limit.
>>> playlist_password("World's Best Lasagne",... |
def get_mvarg(size_pos, position="full"):
"""Take xrandrs size&pos and prepare it for wmctrl (MVARG) format
MVARG: <G>,<X>,<Y>,<W>,<H>
* <G> - gravity, 0 is default
"""
allowed = ["left", "right", "top", "bottom", "full"]
if position not in allowed:
raise ValueError(f"Position has... |
def valid_index(
idx,
size,
circular=False):
"""
Return a valid index for an object of given size.
Args:
idx (int): The input index.
size (int): The size of the object to index.
circular (bool): Use circular normalization.
If True, just use a modu... |
def gcd(x, y):
"""The greatest common devisor using euclid's algorithm."""
while x % y != 0:
x %= y
(x, y) = (y, x)
return y |
def get_L_BB_s_d(L_HP_d, L_dashdash_d, L_dashdash_s_d):
"""
Args:
L_HP_d: param L_dashdash_d:
L_dashdash_s_d:
L_dashdash_d:
Returns:
"""
return L_dashdash_s_d - L_HP_d * (L_dashdash_s_d / L_dashdash_d) |
def create_instance(objcls, settings, crawler, *args, **kwargs):
"""Construct a class instance using its ``from_crawler`` or
``from_settings`` constructors, if available.
At least one of ``settings`` and ``crawler`` needs to be different from
``None``. If ``settings `` is ``None``, ``crawler.settings``... |
def _one_forward_closed(x, y, c, l):
"""convert coordinates to zero-based, both strand, open/closed coordinates.
Parameters are from, to, is_positive_strand, length of contig.
"""
x -= 1
if not c:
x, y = l - y, l - x
return x, y |
def get_tweets(api, t_user):
"""Get tweets from api.
Parameters
----------
api : tweepy.API
twitter api object
t_user : str
The username of twitter you want to get.
Returns
-------
list
A list of tweets.
"""
# test authentication
try:
api.... |
def _quote(s):
"""Quotes the given string for use in a shell command.
This function double-quotes the given string (in case it contains spaces or
other special characters) and escapes any special characters (dollar signs,
double-quotes, and backslashes) that may be present.
Args:
s: The stri... |
def simplify(ints: list) -> list:
"""
In order to speed up the process we should simplify
the input list by reducing duplicate values, see sample below:
[1,4,5,1,1,1,1,1,4,7,8] >>> [1,4,5,1,4,7,8]
:param ints: a list of integers
:return: simplified list of integers
"""
result = list()
temp = -1
for i in in... |
def in_rectangle(rect, point):
"""
to check if a point is contained in the rectangle or not
Args:
rect: rectangle
point: points to be checked
Returns: a boolean value, true or false. If inside the rectangle it returns True
"""
if point[0] < rect[0]:
return False
el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.