content stringlengths 42 6.51k |
|---|
def combine_values(*values):
"""Return the last value in *values* that is not ``None``.
The default combiner; good for simple values (booleans, strings, numbers).
"""
for v in reversed(values):
if v is not None:
return v
else:
return None |
def missing_digits(n):
"""Given a number a that is in sorted, increasing order,
return the number of missing digits in n. A missing digit is
a number between the first and last digit of a that is not in n.
>>> missing_digits(1248) # 3, 5, 6, 7
4
>>> missing_digits(1122) # No missing numbers
... |
def ptp_distance(x, y):
"""point to point distance"""
return 5*max(abs(x[0]-y[0]),abs(x[1]-y[1]),abs(x[2]-y[2])) |
def find_tweets_with_keywords(tweets, keywords, combination=1):
""" Tries to find tweets that have at least one of the keywords in them
:param tweets: The to be checked tweets
:param article: The article
:param combination: The minimal number of keywords that need to be in the tweet to select it
:re... |
def check(a,n_list):
"""Returns the operation performed (such as append(),remove(),insert(),print(),etc) in the list if the operations are valid, -1 otherwise"""
#split the given string a
s = a.split()
#Check the length of splited String 'a'
#if length(s) == 1,it means string should be print,so... |
def vLength(v):
""" Return Vector length """
return (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) ** 0.5 |
def hapax_legomena_ratio_extractor(word_tokens):
"""hapax_legomena_ratio
Counts word token occurs only once over total words in the text.
Words of different form are counted as different word tokens. The token.text presents only once in spaCy's doc
instance over "total_words" is counted.
Known di... |
def calc_agg_polarsim(sim, sent_stance, sent_stance_conf, cfg):
"""Calculate the polar similarity value based on a (unipolar)
similarity rating and a sentence stance rating.
:param sim: float, a (unipolar) sentence similarity rating
:param sent_stance: a stance rating label. Must be either `agree`,
... |
def pyramid(number):
"""
Function that make a coefficient's list.
number: integer
return: list.
"""
_list = []
pyramids_number = number + 1
for times in range(pyramids_number):
string = str(times)
value_list = string * times
_list.append(value_list)
inverse ... |
def get_column_width_ignore_header(runs_str, idx):
""" returns the maximum width of the given column """
return max([len(r[idx]) for r in runs_str]) |
def transform_to_seconds(duration: str) -> float:
"""Transform string (with hours, minutes, and seconds) to seconds.
Args:
duration: Examples: '1m27s', '1m27.3s', '27s', '1h27s', '1h1m27s'
Raises:
Exception: If the input is not supported.
Returns:
Duration converted in seconds... |
def decode_offer_str(offer_str):
""" create a dictionary from offer_str in outputfile """
offer_dict = {}
try:
offer_strs = offer_str.split("|")
except:
return {}
for offer_str in offer_strs:
x = offer_str.split(":")
op = int(x[0])
vals = ":".join(x[1:])
... |
def strip_sbol2_version(identity: str) -> str:
"""Ensure that an SBOL2 or SBOL3 URI is an SBOL3 URI by stripping any SBOL2 version identifier
from the end to the URI
:param identity: URI to be sanitized
:return: URI without terminal version, if any
"""
last_segment = identity.split('/')[-1]
... |
def normalize(x,min, max):
"""
Scale [min, max] to [0, 1]
Normalize x to [min, max]
"""
return (x - min) / (max - min) |
def is_sorted(lst):
"""Checks whether the input list is sorted."""
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
print(lst)
return False
return True |
def checksum_bytes(data):
"""Sum data, truncate to 8 bits"""
cs = sum(data) % 256
return cs |
def identify_unique_number(value: str) -> int:
"""
Identifies the corresponding value based on the number
This only works if the value is of length 2, 3, 4 or 7
"""
length = len(value)
if length not in (2, 3, 4, 7):
raise ValueError("Value can only be identified if it's length is 2, 3, 4... |
def compute(input_string):
"""Perform simple arithmetic based on string input.
Example: '5 + 7' -> 12
"""
values = input_string.split(' ')
num0 = int(values[0])
operator = values[1]
num1 = int(values[2])
if operator == '+':
return num0 + num1
elif operator == '-':
... |
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 ... |
def lengthOfLastWord(s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
try:
return len(s.split()[-1])
except:
return 0 |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict.
Report error on conflicting keys.
"""
result = {}
for dictionary in dict_args:
for key, value in dictionary.items():
if key in result and result[key] != value:
... |
def clean_string(string: str) -> str:
"""
input -> output
"updatedAt" -> "updated_at"
"UpdatedAt" -> "updated_at"
"base URL" -> "base_url"
"UPdatedAt" -> "u_pdated_at"
"updated_at" -> "updated_at"
" updated_at " -> "updated_at"
"updatedat" -> "updatedat"
"""
abbreviations = ... |
def indent(
text, # Text to indent
char=' ', # Character to use in indenting
indent=2 # Repeats of char
):
"""
Indent single- or multi-lined text.
"""
prefix = char * indent
return "\n".join([prefix + s for s in text.split("\n")]) |
def io_table_header(io_params, io_prefixes):
"""podmd
podmd"""
header_labs = [ ]
for collection, pars in io_params.items():
if 'non_collection' in collection:
collection = ''
else:
collection += '.'
for par in pars.keys():
header_labs.appen... |
def history_join(old_history, new_history):
"""Join two history dicts"""
if not old_history:
return new_history
if not new_history:
return old_history
history = old_history
for key in history:
history[key].extend(new_history[key])
return history |
def nsrGenera(taxonList, synonymList):
""" Extracts the unique genera from both taxonomy and synonym lists.
Combines the scientific names of obtained taxonomy and synonyms to
one list, filtering out empty lines. Selects all unique genera.
Arguments:
species: Scientific notation of all s... |
def curve_between(
coordinates, start_at, end_at, start_of_contour, end_of_contour):
"""Returns indices of a part of a contour between start and end of a curve.
The contour is the cycle between start_of_contour and end_of_contour,
and start_at and end_at are on-curve points, and the return value
... |
def insert_tag(name: str, tag: str) -> str:
"""inserts tag name right before the filename:
insert_tag('ex11','some_tag') -> 'some_tag/ex11'
insert_tag('solutions/ex11','some_tag') -> 'solutions/some_tag/ex11'
"""
name_split = name.split("/")
name_split.insert(-1, tag)
return "/".join(name_sp... |
def get_common_introduced(db_entry, arches):
"""Returns the common introduction API level or None.
If the symbol was introduced in the same API level for all architectures,
return that API level. If the symbol is not present in all architectures or
was introduced to them at different times, return None... |
def wait(time,duration,*args):
"""
Delay a command.
instead of executing it at the time specified, add a delay and then execute
"""
duration = int(duration,10)
cmd = '"'+('" "'.join(args))+'"'
return [(time+duration,cmd)] |
def ran_check(num, low, high):
"""
Write a function that checks whether a number is in a given range
(inclusive of high and low)
ran_check(5,2,7)-> 5 is in the range between 2 and 7
"""
if num in range(low, high + 1):
return '{} is in the range between {} and {}'.format(num, low, high)
... |
def filter_horizontal_edges(edges, normal):
""" Determine edges that are horizontal based on a normal value """
res = []
rnd = lambda val: round(val, 3)
for e in edges:
if normal.z:
s = set([rnd(v.co.y) for v in e.verts])
else:
s = set([rnd(v.co.z) for v in e.ver... |
def update_yaml_versions(yaml_versions, json_versions):
"""
Update the versions dictionnary to be printed in YAML with values from
the JSON versions dictionnary found in versions.json.
:param yaml_versions: versions dict to be printed in YAML format
:type yaml_versions: dict
:param json_versio... |
def getFirstMatching(values, matches):
"""
Return the first element in :py:obj:`values` that is also in
:py:obj:`matches`.
Return None if values is None, empty or no element in values is also in
matches.
:type values: collections.abc.Iterable
:param values: list of items to look through, c... |
def laxfilt(items, keymap, sep='.'):
"""
Like filt(), except that KeyErrors are not raised.
Instead, a missing key is considered to be a mismatch.
For example:
items = [
{'name': 'foo', 'server': {'id': 1234, 'hostname': 'host1'}, 'loc': 4, 'yyy': 'zzz'},
{'name': 'bar',... |
def get_user_first_name(data):
"""
Method to extract a newly added user's first name
from telegram request
"""
try:
first_name = data['message']['new_chat_member']['first_name']
return first_name
except KeyError:
exit |
def sans_ns(tag):
"""Remove the namespace prefix from a tag."""
return tag.split("}")[-1] |
def get_plist_key(plist_file, key):
"""
Returns the value of a given plist key, given the JSON encoded equivalent
of a plist file (this goes hand in hand with read_plist)
"""
try:
return plist_file[key]
except (KeyError, TypeError):
return False |
def _removeSingleMemberGroupReferences(kerning, leftGroups, rightGroups):
"""
Translate group names into glyph names in pairs
if the group only contains one glyph.
"""
new = {}
for (left, right), value in kerning.items():
left = leftGroups.get(left, left)
right = rightGroups.get(... |
def access_list_list(config_list):
"""extracts access-lists from provided configuration list ie.config_list.
returns access-lists lines in a list
"""
return [line.rstrip() for line in config_list if line.startswith("access-list ")] |
def alpha_ordering(index, collection):
"""
0 -> A, 1 -> B, ... 25 -> Z, 26 -> AA, 27 -> AB, ...
"""
s = ""
while index > 25:
d = index / 26
s += chr((d % 26) + 64)
index -= d * 26
s += chr(index + 65)
return s |
def calculate_check_digit(data):
"""Calculate MRZ check digits for data.
:data data: Data to calculate the check digit of
:returns: check digit
"""
values = {
"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5,
"6": 6, "7": 7, "8": 8, "9": 9, "<": 0, "A": 10,
"B": 11, "C": 12, "... |
def scale_frequencies(lo, hi, nyq):
"""
Scales frequencies in Hz to be between [0,1], 1 = nyquist frequency.
"""
lo = lo / nyq
hi = hi / nyq
return lo, hi |
def _fib_rec(n):
""" Calculate nth Fibonacci number using Binet's Method. Assumes
Fib(0) = Fib(1) = 1.
Args:
n integer
Returns:
tuple (Fib(n), Fib(n-1))
Preconditions:
n >= 0
"""
(f1, f2), i = (1, 0), 31
while i >= 0:
if (n >> i) > 0:
f1, f2 =... |
def join_paths(*args):
"""Join paths without duplicating separators.
This is roughly equivalent to Python's `os.path.join`.
Args:
*args (:obj:`list` of :obj:`str`): Path components to be joined.
Returns:
:obj:`str`: The concatenation of the input path components.
"""
result = ... |
def get_default_readout(n_atom_basis):
"""Default setting for readout layers. Predicts only the energy of the system.
Args:
n_atom_basis (int): number of atomic basis. Necessary to match the dimensions of
the linear layer.
Returns:
DEFAULT_READOUT (dict)
"""
DEFAULT_RE... |
def flatten_json(b, delim):
"""
A simple function for flattening JSON by concatenating keys w/ a delimiter.
"""
val = {}
for i in b.keys():
if isinstance(b[i], dict):
get = flatten_json(b[i], delim)
for j in get.keys():
val[i + delim + j] = get[j]
... |
def apple_url_fix(url):
"""
Fix Apple URL.
:param url: URL to fix
:return: fixed URL
"""
if url.startswith("webcal://"):
url = url.replace('webcal://', 'http://', 1)
return url |
def rangify(value):
"""Return a range around a given number."""
span = 5
min_val = max(value - span, 1)
max_val = max(value + span, span * 2)
return range(min_val, max_val) |
def escape(string, quote=True):
"""Returns a string where HTML metacharacters are properly escaped.
Compatibility layer to avoid incompatibilities between Python versions,
Qt versions and Qt bindings.
>>> import silx.utils.html
>>> silx.utils.html.escape("<html>")
>>> "<html>"
.. no... |
def constrain(value, lowest, highest):
"""Test whether `value` is within the range `(highest, lowest)`.
Return `value` if it is inside the range, otherwise return
`highest` if the value is *above* the range or `lowest` it the value
is *below* the range.
>>> constrain(-1, 2, 5)
2
>>> constra... |
def _is_basic_type(s):
"""
Helper function used to check if the value of the type attribute is valid
:param s: the str value in the type attribute
:type s: str
:return: `True` if the str value is valid, else return `False`
:rtype: bool
"""
s = s.strip().casefold()
if s in ["objecti... |
def mangle_string(string):
"""
Turns an arbitrary string into a decent foldername/filename
(no underscores allowed)!
"""
string = string.replace(' ', '-')
string = string.strip(",./;'[]\|_=+<>?:{}!@#$%^&*()`~")
string = string.strip('"')
return string |
def is_node_locked(node):
"""Check if node is locked. Implementation level LOL.
"""
r = False
if "isHardLocked" in dir(node):
r = node.isHardLocked()
elif "isLocked" in dir(node):
r = node.isLocked()
return r |
def whittle_dict(d, keys):
"""
Returns D2, containing just the KEYS from dictionary D,
e.g.
whittle_dict({'a': 100, 'b': 200}, ['a']) -> {'a': 100}
Will raise an exception if any of KEYS aren't keys in D.
xxx - maybe this should instead do a copy, and delete any not needed???
"""
d2 =... |
def f(integer):
"""
factorcalc.f(int > 0) -> list of int -- provides a list of all the factors of the first argument
"""
if type(integer)==int:
if integer>0:
possible_factors=[integer]
possible_factor=integer-1
for i in range(integer):
... |
def makeMushedKey(row):
""""Return a unique key based on a row, sortcat+name+edition+condition+foil+cardNumber"""
return row["SortCategory"] + "-" + row["Name"] + "-" + row["Edition"] + "-" + row["Condition"] + "-" + str(row["CardNumber"]) + "-" + str(row["IsFoil"]) |
def locateSquareHelper(x):
"""
Helps find square units, the nine 3x3 cells in a puzzle, in which a cell is in.
Input
x : row or column index of the cell in the puzzle.
Output
x : location of square unit, specifically the first cell of the unit.
"""
if x < 6:
... |
def set_gpu_entry(entry_information, want_whole_node):
"""Set gpu entry
Args:
entry_information (dict): a dictionary of entry information from white list file
Returns:
dict: a dictionary of entry information from white list file with gpu settings
"""
if "attrs" not in entry_informa... |
def bsi(items, value):
"""Returns the middle index if value matches, otherwise -1"""
lo = 0
hi = len(items) - 1
while lo <= hi:
mid = int((lo + hi) / 2)
if items[mid] == value:
return mid
elif items[mid] < value:
lo = mid + 1
else:
hi... |
def bubble(L, swap=None):
"""Bubble sort function
Parameters:
L (list): Unsorted (eventually sorted) list.
swap (boolean): Whether list's elements have been swapped before, serves as an indicator on whether we're done sorting.
Returns:
L (list): Sorted list.
"""
print(f'{L} : {swap}')
... |
def get_path_part_from_sequence_number(sequence_number, denominator):
"""
Get a path part of a sequence number styled path (e.g. 000/002/345)
Args:
sequence_number (int): sequence number (a positive integer)
denominator (int): denominator used to extract the relevant part of a path
Retur... |
def range_squared(n):
"""Computes and returns the squares of the numbers from 0 to n-1."""
squares = []
for k in range(n):
squares.append(k ** 2)
return squares |
def degrees_to_kilometers_lat(degrees: int) -> float:
"""
Convert degrees of longitude into kilometres
:param degrees:
:return:
"""
return (63567523 * degrees / 90) / 1000 |
def _cleanup_non_fields(terms):
"""Removes unwanted fields and empty terms from final json"""
to_delete = ['relationships', 'all_parents', 'development',
'has_part_inverse', 'develops_from',
'closure', 'closure_with_develops_from',
'achieves_planned_objective',... |
def get_total_tiles(min_zoom: int, max_zoom: int) -> int:
"""Returns the total number of tiles that will be generated from an image.
Args:
min_zoom (int): The minimum zoom level te image will be tiled at
max_zoom (int): The maximum zoom level te image will be tiled at
Returns:
The t... |
def solution2(nums):
"""
Efficient solution written by other guy
---
:type nums: list[int]
:rtype: list[int]
"""
output = []
for num in nums:
# Same number in the array must conduct to the same index
# And we should note that the number is always between 1 and n
... |
def _unprefix_attrs(value):
"""Internally, nested objects are stored in attrs prefixed with `_`, and wrapped in a @property.
This recursively removes the `_` prefix from all attribute names.
"""
if isinstance(value, (list, tuple)):
return [_unprefix_attrs(v) for v in value]
elif not isinstan... |
def abbrev(term_list):
"""Given a list of terms, return the corresponding list of abbreviated terms."""
abbrev_dict = {"Point": "Pt",
"ProperInterval": "PInt",
"Interval": "Int",
"Region": "Reg"}
return '|'.join([abbrev_dict[term] for term in te... |
def parse_ID_from_query_comment(comment):
"""
Parses the NCBI-specific ID from the comment reported by the Mash match. The comment will look something like:
[1870 seqs] NC_004354.4 Drosophila melanogaster chromosome X [...]
and this function will return the "NC_004354.4" part of the comment. This func... |
def isjpeg(filename):
"""
Returns true if filename has jpeg file extension
:param filename:
:return:
"""
jpeg_exts = ['jpg', 'jpeg']
if '.' not in filename:
return False
return filename.split('.')[-1].lower() in jpeg_exts |
def longest_subseq(arr):
"""
Given an array of integers, find the length of the longest sub-sequence
such that elements in the sub-sequence are consecutive integers,
the consecutive numbers can be in any order.
>>> longest_subseq([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
10
>>> longest_subseq([10... |
def update(old, new):
"""Updates the old value with the new value
Args:
old: old value to update
new: new value with updates
Returns:
updated old value
"""
old.update(new)
return old |
def convert_ip(address) :
""" Converts IP to bytes
:param str address: IP address that should be converted to bytes
:return bytes: IP converted to bytes format
"""
res = b""
for i in address.split("."):
res += bytes([int(i)])
return res |
def calculate_max_width(poly):
"""
Calculate the maximum width of a polygon and
the cooresponding y coordinate of the vertex used to calculate the maximum width
Input
poly: a set of vertices of a polygon
Ouput
width_y: the y coordinate of the vertex used to calculate the maximum widt... |
def data_calculation(sites):
"""
param sites: list of website data.
Returns the total of all site values.
"""
total = 0
for data_item in sites:
total += data_item['value']
return total |
def parse_reward_values(reward_values):
"""
Parse rewards values.
"""
values = reward_values.split(',')
reward_values = {}
for x in values:
if x == '':
continue
split = x.split('=')
assert len(split) == 2
reward_values[split[0]] = float(split[1])
r... |
def common_prefix(l):
"""
Return common prefix of the stings
>>> common_prefix(['abcd', 'abc1'])
'abc'
"""
commons = []
for i in range(min(len(s) for s in l)):
common = l[0][i]
for c in l[1:]:
if c[i] != common:
return ''.join(commons)
... |
def strip_right_multiline(txt: str):
"""Useful for prettytable output where there is a lot of right spaces,"""
return '\n'.join([x.strip() for x in txt.splitlines()]) |
def filter_dict(fl, vocab):
"""Removes entries from the :param fl: frequency list not appearing in :param vocab:."""
out = {}
for k, v in fl.items():
if k in vocab:
out[k] = v
return out |
def remove_encoding_indicator(func_string):
"""
In many functions there is a following "A" or "W" to indicate unicode or ANSI respectively that we want to remove.
Make a check that we have a lower case letter
"""
if (func_string[-1] == 'A' or func_string[-1] == 'W') and func_string[-2].islower(... |
def mock_walk(examples_folder):
"""Mock the os.walk function to return a single file."""
folder_list = []
file_list = ["metadata.yaml"]
return [("", folder_list, file_list)] |
def _is_chief(task_type, task_id):
"""Determines if the replica is the Chief."""
return task_type is None or task_type == 'chief' or (
task_type == 'worker' and task_id == 0) |
def _int_if_possible(string):
"""
PRIVATE METHOD
Tries to convert a string to an integer, falls back to the original value
"""
try:
return int(string)
except ValueError:
return string |
def divider(string):
"""Inserts a Verilog style divider into a string"""
return '\n// ' + '-' * 70 + '\n// ' + string + '\n// ' + '-' * 70 + '\n' |
def get_server_cyverse_push_config(config:dict):
"""
takes a config dictionary and returns the variables related to server deployment (push to CyVerse).
If there is any error in the configuration, returns a quadruple of -1 with a console output of the exception
"""
try:
server = config["Data... |
def linear_interpolation(x, x_0, x_1, y_0, y_1):
""" return the linearly interpolated value between two points """
return y_0+(x-x_0)*(y_1-y_0)/(x_1 - x_0) |
def find_appendix(filename):
"""if filename contains suffix '_old' or '_new', remember it to add it to sequence ID
"""
if "_new." in filename:
appendix = "_new"
elif "_old." in filename:
appendix = "_old"
else:
appendix = ""
return appendix |
def get_accuracy(class_metrics, N):
"""
Get accuracy as total # of TP / total # of samples
:param class_metrics : Map from class name to metrics (which are map from TP, TN, FP, FN to values)
:param N: total number of samples
"""
if N == 0:
return 0
TP_total = 0
for class_name in ... |
def have_common_elements(first_list, second_list):
"""
Retuns True if all the elements in the first list are also in the second.
:param list[T] first_list:
:param list[T] second_list:
:return: True if lists are the same, else False
"""
return len(set(first_list).intersection(
set(sec... |
def return_to_string(msg):
"""
Return a string of the encoded message
@type msg: [int]
@rtype: str
"""
returned_str = ""
for char in msg:
returned_str += chr(char + 65)
return returned_str |
def filter_dict(d, *keys):
"""Filter keys from a dictionary."""
f = {}
for k, v in d.items():
if k in keys:
f[k] = v
return f |
def dictflip(dictionary):
"""
Flip the names and keys in a dictionary.
This means that this:
{'key1': 'value1', 'key2': 'value2'}
will be converted into this:
{'value1': 'key1', 'value2': 'key2'}
:type dictionary: dictionary
:param dictionary: The dictionary to flip.
"""
retur... |
def add_color(value: str) -> str:
"""
Modifies the value from the parameter to a colored version of itself
Args:
value: str: the value of a particular position on the gameboard
Returns:
str: returns a string containing the value at the coord in the matching color
"""
color = ''
... |
def sphinx_doi_link(doi):
"""
Generate a string with a restructured text link to a given DOI.
Parameters
----------
doi : :class:`str`
Returns
--------
:class:`str`
String with doi link.
"""
return "`{} <https://dx.doi.org/{}>`__".format(doi, doi) |
def _set(iterable):
"""Return a set from an iterable, treating multicharacter strings as one element."""
if type(iterable) is str:
return set() if iterable == '' else {iterable}
else: return set(iterable) |
def blending(f, coal, biomass):
"""
f : float
%wt biomass in coal-biomass blend
"""
return (1.0 - f)*coal + (f)*biomass |
def RPL_WHOREPLY(sender, receipient, message):
""" Reply Code 352 """
return "<" + sender + ">: " + message |
def version_greater_or_equal_to(version, min_version):
"""Compares two version strings and returns True if version > min_version
>>> version_greater_or_equal_to('1.0', '0')
True
>>> version_greater_or_equal_to('1.0', '0.9.9.9')
True
>>> version_greater_or_equal_to('1.0', '2.0')
False
>>> version_greate... |
def str2bool(pstr):
"""Convert ESRI boolean string to Python boolean type"""
return pstr == 'true' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.