content stringlengths 42 6.51k |
|---|
def empty_operation(ops):
""" Returns True if the operation is an empty list or only contains positive integers """
return (ops == [] or all([isinstance(x, int) and (x > 0) for x in ops])) |
def patched_path(path):
"""Return 'path', doctored for RPC."""
if not path.endswith('/'):
path += '/'
if path.startswith('/RPC2/'):
# strip the first /rpc2
path = path[5:]
return path |
def get_count(value):
"""
Count bottle of beer
"""
beer = str(value) if value != 0 else "No more"
return beer + " bottles of beer" if value != 1 else beer + " bottle of beer" |
def remove_redacted(obj):
"""
Removes all string object with the value __redacted__
"""
if isinstance(obj, str):
if obj == "__redacted__":
return True, obj
else:
return False, obj
elif isinstance(obj, list):
for index, item in enumerate(obj):
... |
def match_word(word, word_):
"""
word: The word to be matched
word_: The set of alphabets
This matches the characters of the word to the set of alphabets.
"""
for word_char, alphabet in zip(word, word_):
if word_char not in alphabet:
return False
return True |
def side(a,b,c):
""" Returns a position of the point c relative to the line going through a and b
Points a, b are expected to be different
"""
d = (c[1]-a[1])*(b[0]-a[0]) - (b[1]-a[1])*(c[0]-a[0])
return 1 if d > 0 else (-1 if d < 0 else 0) |
def format_str(unformatted_str):
"""
Formats the output into a multi column list, output1 | output2 | output3
"""
output = []
for word in enumerate(unformatted_str):
if word != '':
output.append(word[1])
return output |
def evaluate_error(z1, z2):
"""
# cette methode ne marche pas car le numero de cluster pourra changer
:param z1: actual clustering
:param z2: clustering done by CEM algorithm
:return: error in percentage
"""
err = 0
n = len(z1)
for i in range(n):
if z2[i] != z1[i]:
... |
def format_metrics(metrics, split):
"""Format metric in metric dict for logging."""
return " ".join(
["{}_{}: {:.8f}".format(split, metric_name, metric_val) for metric_name, metric_val in metrics.items()]) |
def validate_path(path, configuration):
"""
Args:
path(str): incoming request path
configuration(dict): config dict
Returns:
(dict|none): returns config if path is valid, None otherwise
"""
subpaths = list(filter(''.__ne__, path.split('/')))
for index, sub_path in enume... |
def _filter_featured_downloads(lst):
"""Filter out the list keeping only Featured files."""
ret = []
for item in lst:
if 'Featured' in item['labels']:
ret.append(item)
return ret |
def getParentDirList(path):
""" Returns the directories up to a (posix) path
:param path: The path to process
:type path: ``str``
:return: The directory list
:rtype: ``list``
"""
import posixpath
path = posixpath.normpath("/%s" % path)
if path[:2] == '//':
... |
def basename(p):
"""Returns the basename (i.e., the file portion) of a path.
Note that if `p` ends with a slash, this function returns an empty string.
This matches the behavior of Python's `os.path.basename`, but differs from
the Unix `basename` command (which would return the path segment preceding
... |
def fib_recursive(n):
""" Fibonacci sequence:
f_n = f_(n-1) + f_(n-2); with f_0 = 0, f_1 = 1
Uses recusive methods to solve
"""
if n == 0:
res = 0
elif n == 1:
res = 1
else:
res = fib_recursive(n - 1) + fib_recursive(n - 2)
return res |
def convert_none_to_empty_string(value):
"""Convert the value to an empty string if it's None.
:param value: The value to convert.
:returns: An empty string if 'value' is None, otherwise 'value'.
"""
return '' if value is None else value |
def _create_subscript_in(maker, index, root):
"""
Find or create and insert object of type `maker` in `root` at `index`.
If `root` is long enough to contain this `index`, return the object at that
index. Otherwise, extend `root` with None elements to contain index
`index`, then create a new object... |
def paths_and_probs_to_dict(paths, probs, normalize=False):
"""Turn paths and path probabilities as returned from Transition Path Theory into dictionary.
Parameters
----------
paths : 1D numpy.ndarray.
Array of paths where each path is a numpy array of integer on its own.
probs : 1D numpy.... |
def choose(dict):
"""
This function is very important in the theory.
This is important because when given a distribution of options, and you're trying to guess
the correct one, your best strategy is always to pick the one with highest probability.
It's also important because when predicting a binar... |
def get_unique_char_name(toon_name, realm_name):
""" globally unique toon name in Name - Realm format"""
gu_char_name = toon_name + " - " + realm_name
return gu_char_name |
def is_reflexive(universe, relation):
"""
Function to determine if a relation of a set is reflexive
:param universe: a set
:param relation: a relation on set universe
return: True if relation is a reflexiver relation of set universe
"""
new_set = {(a, b) for a in universe for b in universe i... |
def num_digits(number):
"""
Returns number of digits in an integer.
:param number: Integer
:return: Number of digits
"""
return len(str(number)) |
def sanitize(value):
""" Sanitize program strings to make them easier to compare. """
return ''.join(value.split()) |
def __switch_dias(dia):
"""
Funcion que hace de swicth porque no se les ocurrio hacerlo a los que crearon el lenguaje
y tengo que estar haciendolo yo aunque ahora no la uso
"""
switcher = {
1: "MON",
2: "TUE",
3: "WED",
4: "THU",
5: "FRI",
6: "SAT",
... |
def flatten(lol):
"""
Flatten a list of lists
"""
return [item for sublist in lol for item in sublist] |
def shall_exclude_diagnostic_message(message):
"""Exclude certain diagnostics messages"""
exclusion_list = [
"-fno-canonical-system-headers",
"-Wunused-but-set-parameter",
"-Wno-free-nonheap-object",
"-Werror=init-list-lifetime",
"-Werror=class-conversion",
]
retu... |
def build_article_url(root_url, article_path):
"""
Build URL for blog article. Using this function will ensure the URL is constructed correctly, regardless of what
platform the article path is for.
Args
root_url: URL string to website root directory.
article_path: Path to the article on the... |
def iseven(n):
"""Return true if n is even."""
return n%2==0 |
def weights(b):
"""Return a heuristic value based on the weights of specified locations."""
value, n = 0, len(b)
weights = [
[2048, 1024, 512, 256],
[1024, 512, 256, 128],
[256, 8, 2, 1],
[4, 2, 1, 1]
]
for i in range(n):
for j in range(n):
value... |
def dh_get_matching_company_contact(first_name, last_name, email, company_contacts):
"""
Performs check identifying whether an enquirer exists in their company's contact
list in |data-hub-api|_.
:param first_name:
:type first_name: str
:param last_name:
:type last_name: str
:param ema... |
def sort_priority4(values, group):
"""
sort_priority4(python2)
:param values:
:param group:
:return:
"""
found = [False]
def helper(x):
nonlocal found
if x in group:
found[0] = True
return (0, x)
return (1, x)
values.sort(key=helper)
... |
def loadCTD(ctd):
"""
Loads standard ctd data from a dictionary of ctd values
"""
S = ctd['s']
T = ctd['t']
p = ctd['p']
lat = ctd['lat']
lon = ctd['lon']
return S, T, p, lat, lon |
def callable_get(collection, key, default=None, args=[]):
"""Get item from collection. Return collection applied to args, if it is callable"""
result = collection.get(key, default)
if callable(result):
return result(*args)
return result |
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Messag... |
def raw_resp_to_int(raw_resp):
"""
# convert response to int
('xxx 224rfff ')) # -->224
:param raw_resp: float or str collect from keyboard response
:return: int response
"""
if isinstance(raw_resp, float):
return int(raw_resp)
# apply to rows with str
if isinstance(raw_re... |
def format_remap_name(remap):
"""Format remap value for DT node name
Args:
remap: Remap definition.
Returns:
DT remap definition in lower caps
"""
if remap == 0 or remap is None:
return ""
elif "REMAP0" in remap:
return ""
elif "REMAP1" in remap:
re... |
def how_many(aDict):
"""
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
"""
return sum(len(value) for value in aDict.values()) |
def PadForGenerics(var):
"""Appends a space to |var| if it ends with a >, so that it can be compiled
within generic types.
"""
return ('%s ' % var) if var.endswith('>') else var |
def parse_state(state):
""""
prepare input for gcodeGenerator
i/p:state varible
o/p:list of tuple <formatted argument, orientation>
"""
args = []
for heightmap in state["heightmaps"]:
arg = str(heightmap["length"]) + " " +str(heightmap["width"]) + " "
if heightma... |
def _check_standardization_interval(standardize_by):
"""Check standardization interval is valid."""
valid_intervals = ['dayofyear', 'month']
is_valid = standardize_by is None or standardize_by in valid_intervals
if not is_valid:
raise ValueError(
"Unrecognized standardization inter... |
def melt_curve(start=65, end=95, inc=0.5, rate=5):
"""Generate a melt curve on the fly
No inputs neded for a standard melt curve.
Example
-------
.. code-block:: python
melt_params = melt_curve()
protocol.thermocycle(dest_plate,
thermocycle_dict,
... |
def expand_curie_to_uri(curie, context_info):
"""Expand curie to uri based on the context given
:arg str curie: curie to be expanded (e.g. bts:BiologicalEntity)
:arg dict context_info: jsonld context specifying prefix-uri relation (e.g. {"bts": "http://schema.biothings.io/"})
"""
# as suggested in ... |
def _doublequote(str):
"""
Replace double quotes if it's necessary
"""
return str.replace('"', '\\"') |
def simplify_parenthesis(textline: str) -> str:
"""Remove enclosing parenthesis if available."""
if textline.startswith("(") and textline.endswith(")"):
textline = textline[1:-1]
return textline |
def retrieval_precision(gold, predicted):
"""
Compute retrieval precision on the given gold set and predicted set.
Note that it doesn't take into account the order or repeating elements.
:param gold: the set of gold retrieved elements
:param predicted: the set of predicted elements
:return: pre... |
def get_nested_expression(adders):
"""Return a string representing the addition of all the input bitvectors.
Args:
adders: An integer, the number of nested addition operations.
Returns:
The full addition string.
"""
nested_expressions = []
for i in range(adders):
rhs = "x_0" if i == 0 else nes... |
def is_int(obj, digit=False):
"""Check if obj is int typeable.
Args:
obj (:obj:`object`): object to check
digit (:obj:`bool`, optional): default ``False`` -
* if ``True`` obj must be (str/bytes where isdigit is True) or int
* if ``False`` obj must be int
Returns:
... |
def validate_bed_format(row):
"""Error check correct BED file formatting.
Does a quick assert that row was successfully split into multiple
fields (on tab-character).
Args:
row (list): list of BED fields
Returns:
None
"""
assert len(row) >= 3, 'Bed Files must have at least 3 tab separated field... |
def arb_profit(arb_percent, stake):
"""
:param arb_percent: List. Helper function must be used with arb_percentage. This is sum of combined implied probabilities < 100% mean arb opportunity
:param stake: Float. How much you intend to throw down on the wager.
:return: Float. Riskless profit if executed a... |
def pretty_name(name):
"""Converts 'first_name' to 'First name'"""
if not name:
return u''
return name.replace('_', ' ').capitalize() |
def elem_C(w, C):
"""
Simulation Function: -C-
Inputs
----------
w = Angular frequency [1/s]
C = Capacitance [F]
"""
return 1 / (C * (w * 1j)) |
def get_edit_type(word, lemma):
""" Calculate edit types. """
if lemma == word:
return 'identity'
elif lemma == word.lower():
return 'lower'
return 'none' |
def get_order_by_querytring(ordering, current_order=None, remove=False):
"""
Using the ordering parameter (a list), returns a query string with the
orders of the columns
The parameter current_order can be passed along to handle the specific
order of a single column. So for example if you are orderi... |
def lines(string, keepends=False):
"""
Split a string into a list of strings at newline characters. Unless
*keepends* is given and true, the resulting strings do not have newlines
included.
"""
return string.splitlines(keepends) |
def compress_state(state):
"""
Compress state to combine special cards
"""
compressed_state = {
'total': state['total'],
'trumps': state['trump1'] + state['trump2'] + state['trump3'],
'dealer_card': state['dealer_card']
}
return compressed_state |
def nested_set(dic, keys, value):
"""
:param dic:
:param keys:
:param value:
:return:
"""
dictionary = dic
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
return dictionary |
def wasserstein_loss(real_logit, fake_logit):
"""
:param real_logit: logit(s) for real images (if None just return generator loss)
:param fake_logit: logit(s) for fake images
:return: loss for discriminator and generator (unless real_logit is None)
"""
loss_generator = - fake_logit
if real_l... |
def fact(n):
"""Calculate n! iteratively"""
result = 1
if n > 1:
for f in range(2 , n + 1):
result *=f
return result |
def to_bool(bool_str: str):
"""Convert str to bool."""
bool_str_lc = bool_str.lower()
if bool_str_lc in ("true", "1", "t"):
return True
if bool_str_lc in ("false", "0", "f", ""):
return False
raise ValueError(f"cannot interpret {bool_str} as a bool") |
def remove_deprecated_elements(deprecated, elements, version):
"""Remove deprecated items from a list or dictionary"""
# Attempt to parse the major, minor, and revision
(major, minor, revision) = version.split('.')
# Sanitize alphas and betas from revision number
revision = revision.split('-')[0]
... |
def round_to_num_gran(size, num=8):
"""Round size to nearest value that is multiple of `num`."""
if size % num == 0:
return size
return size + num - (size % num) |
def two_yr_suffix(year):
"""Return a suffix string of the form ``_XXYY`` based on year,
where XX = the last 2 digits of year - 1,
and YY = the last 2 digits of year
:arg year: Year from which to build the suffix;
2nd year in suffix;
e.g. 1891 produces ``_8081``
:type y... |
def user_in_role(user, roles):
"""
True if user has one of specified roles
"""
if user:
result = False
for role in roles:
result |= (role in user.roles)
return result
return False |
def convert_into_nb_of_seconds(freq: str, horizon: int) -> int:
"""Converts a forecasting horizon in number of seconds.
Parameters
----------
freq : str
Dataset frequency.
horizon : int
Forecasting horizon in dataset frequency units.
Returns
-------
int
Forecast... |
def rotatedDigits(N):
"""
:type N: int
:rtype: int 2 5 6 9
"""
count = 0
for i in range(1,N+1):
i = str(i)
if '3'in i or '4'in i or '7' in i:
continue
if '2'in i or '5'in i or '9' in i or '6' in i:
count +=1
return count |
def initialize(boardsize):
""" The new game state """
game_state = []
for i in range(0, boardsize):
game_state.append([])
for j in range(0, boardsize):
game_state[i].append('-')
return game_state |
def close_connection(connection) -> bool:
"""Function to close Database connection.
Args:
connection (mysql.connector.connection_cext):
The argument received is a MySQL connection.
Returns:
bool: The original return was False when database
connection was closed. But, I ... |
def get_table_titles(data, primary_key, primary_key_title):
"""Detect and build the table titles tuple from ORM object, currently only support SQLAlchemy.
.. versionadded:: 1.4.0
"""
if not data:
return []
titles = []
for k in data[0].__table__.columns.keys():
if not k.startswit... |
def update_portfolio(api_data, csv_target):
"""Prepare updated csv report for destination csv file"""
updates = []
for row in api_data:
symbol = row[0]
latest_price = round(float(row[1]), 3)
for item in csv_target:
if row[0] == item['symbol']:
units = int(... |
def time_string(t,precision=3):
"""Convert time given in seconds in more readable format
such as ps, ns, ms, s.
precision: number of digits"""
from numpy import isnan,isinf
if t is None: return "off"
if t == "off": return "off"
try: t=float(t)
except: return "off"
if isnan(t): return... |
def esc_control_characters(regex):
"""
Escape control characters in regular expressions.
"""
unescapes = [('\a', r'\a'), ('\b', r'\b'), ('\f', r'\f'), ('\n', r'\n'),
('\r', r'\r'), ('\t', r'\t'), ('\v', r'\v')]
for val, text in unescapes:
regex = regex.replace(val, text)
... |
def parse_list_arg(args):
"""
Parse a list of newline-delimited arguments, returning a list of strings with leading and
trailing whitespace stripped.
Parameters
----------
args : str
the arguments
Returns
-------
list[str]
the parsed arguments
"""
return [u.... |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_n... |
def _special_indexes_from_metadata(metadata, transforms, vocabulary=False):
"""Return list of SQLAlchemy index objects for the transformed metadata.
Given the stock metadata, for each transform `T` we invoke:
new_metadata = T.modify_metadata(metadata)
and at the end, we extract the indexes.
... |
def is_valid(line):
"""
Checks if the content of an edge has a valid format.
<vertex vertex weight>
:param line: A line of the input text.
:type: String
:return: A list if edge is valid, None otherwise.
"""
edge = line.rsplit()
wrong_args_number = len(edge) != 3
is_comment = lin... |
def stringToBool(s):
"""
Convert a string (True/true/1) to bool
s -- string/int value
return -- True/False
"""
return (s == "True" or s== "true" or s == "1" or s == 1) |
def email_doner(name, amount):
"""Fill in a form thank-you email for a donation."""
email_string = """Thank you {0} for your donation of {1} goofy goober dollars.""".format(name, amount)
return email_string |
def validation_metrics(ground_truth, bowtie2_prediction):
"""Calculates the recall and specificity
Find list instersection!!
parameters
----------
ground_truth
dict, contains the ground truth as obtained from the sim reads
bowtie2_prediction
dict, contains the predicted read mapp... |
def parse(argv):
"""Parse optional list of keyword arguments into a dict.
Parses a list of keyword arguments defined by a leading ``--`` and separated by ``=`` (for example, --key=value).
Args:
argv (listof str):
Keyword dict to use as an update.
Examples::
# Import the kwconfig module... |
def convert_to_bool(value):
"""Check if the value of an environment variable is truthy."""
return value.lower() in ("true", "yes", "1") |
def two_column(left, right, col1_length=65, col2_length=1):
"""Two column layout for printouts.
Example:
I did this thing done!
"""
tmp = '%-{}s%-{}s'.format(col1_length, col2_length)
# The space in front of the right column add minimal padding in case
# lefts content is very lo... |
def parse_config_dicts(INPUT_CONFIG, CROSS_VALID_CONFIG,
LABEL_VALID_CONFIG,DATA_VALID_CONFIG,
LABEL_ACTOR_CONFIG, DATA_ACTOR_CONFIG):
""" Parse configs into kwargs for librarian.create()
Args:
INPUT_CONFIG (dict):
CROSS_VALID_CONFIG (dict):
... |
def removeIntInxString(txt, sep = '.'):
""" removeIntInxString(txt, sep)
From text writen like "1. Text what u need"
transform that to "Text what u need"
Parameters
----------
txt : String
String what you want to be transformed
sep : Char
Separation between you don't need an... |
def debytes(string):
"""
Decode string if it is a bytes object.
This is necessary since Neovim, correctly, gives strings as a str, but regular
Vim leaves them encoded as bytes.
"""
try:
return string.decode()
except AttributeError:
return string |
def normalize_url(url):
""" ensure a url is "properly" constructed
Remove trailing slashes
Add http if http or https is not specified
Parameters
----------
url: string
A string to return as a url
"""
if url.endswith('/'):
url = url[:-1]
if not url.startswith('ht... |
def is_fixed_line_number(number):
"""
Fixed lines start with an area code enclosed in brackets. The area
codes vary in length but always begin with 0.
"""
if len(number) < 3:
return False
return number.find("(") != -1 and number.find(")") != -1 and number[1] == '0' |
def extract_paths(actions):
"""
<Purpose>
Given a list of actions, it extracts all the absolute and relative paths
from all the actions.
<Arguments>
actions: A list of actions from a parsed trace
<Returns>
absolute_paths: a list with all absolute paths extracted from the actions
... |
def build_minio_url(minio_host, minio_port=9000):
"""
Purpose:
Create the Minio URL from host and port
Args:
minio_host (String): Host of Minio
minio_host (Int): Port of Minio (Defaults to 9000)
Returns:
minio_url (String): URL of Minio
"""
return f"{minio_host}:... |
def get_input(desc):
"""get input values"""
value = desc.get('value', None)
return value if value is not None else desc['tensor_name'] |
def _merge_json_dicts(from_dict, to_dict):
"""Merges the json elements of from_dict into to_dict. Only works for json dicts
converted from proto messages
"""
for key, value in from_dict.items():
if isinstance(key, int) and str(key) in to_dict:
# When the key (i.e. the proto field nam... |
def dos_list_request_to_gdc(dos_list):
"""
Takes a dos ListDataObjects request and converts it into a GDC request.
:param gdc:
:return: A request against GDC as a dictionary.
"""
mreq = {}
mreq['size'] = dos_list.get('page_size', None)
mreq['from'] = dos_list.get('page_token', None)
... |
def parse_cores(core_str):
"""Parse core list passed through command line"""
cores = []
# remove spaces
core_str.replace(" ", "")
# check if not a range
if '-' not in core_str:
return list(map(int, core_str.strip().split(',')))
# parse range e.g. 2-8
core_str = core_str.strip(... |
def multi(a, b, c):
""" performs arithmetic operations this is the docstring of multi() """
return a * b - c |
def to_ver32(version):
"""
Converts version in Redfish format (e.g. v1_0_0) to a PLDM ver32
Args:
version: The Redfish version to convert
Returns:
The version in ver32 format
"""
# The last item in result will have the latest version
if version != 'v0_0_0': # This is a ve... |
def _make_reflected_gradient(X, Y, angle):
"""Generates index map for reflected gradients."""
import numpy as np
theta = np.radians(angle % 360)
Z = np.abs((np.cos(theta) * X - np.sin(theta) * Y))
return Z |
def _strip_region_tags(sample_text):
"""Remove blank lines and region tags from sample text"""
magic_lines = [
line for line in sample_text.split("\n") if len(line) > 0 and "# [" not in line
]
return "\n".join(magic_lines) |
def mapattr(value, arg):
"""
Maps an attribute from a list into a new list.
e.g. value = [{'a': 1}, {'a': 2}, {'a': 3}]
arg = 'a'
result = [1, 2, 3]
"""
if len(value) > 0:
res = [getattr(o, arg) for o in value]
return res
else:
return [] |
def pair_sum(arr, target):
"""
:param: arr - input array
:param: target - target value
Find two numbers such that their sum is equal to the target
Return the two numbers in the form of a sorted list
"""
sorted_arr = sorted(arr, reverse=True)
n = len(arr)
for larger_el in range(n - 1... |
def potential_temperature(temperature_k, pressure_hpa, pressure_reference_hpa=1000.0):
"""
Convert temperature to potential temperature based on the available pressure. Potential temperature is at a
reference pressure of 1000 mb.
Args:
temperature_k: The air temperature in units K
press... |
def euler_step(u, f, dt):
"""Returns the solution at the next time-step using Euler's method.
Parameters
----------
u : array of float
solution at the previous time-step.
f : function
function to compute the right hand-side of the system of equation.
dt : float
time-... |
def _strip_external_workspace_prefix(path):
"""Either 'external/workspace_name/' or '../workspace_name/'."""
# Label.EXTERNAL_PATH_PREFIX is due to change from 'external' to '..' in Bazel 0.4.5.
# This code is for forwards and backwards compatibility.
# Remove the 'external/' check when Bazel 0.4.4 and... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.