content stringlengths 42 6.51k |
|---|
def uncapitalize(text: str) -> str:
"""Returns the given text uncapitalized"""
# return early if empty string or none
if not text: return ''
# return lower if one character
elif len(text) == 1:
return text[0].lower()
# return as-is if first word is uppercase
elif text.split(' ')[0].i... |
def get_number_features(dict_features):
"""Count the total number of features based on input parameters of each feature
Parameters
----------
dict_features : dict
Dictionary with features settings
Returns
-------
int
Feature vector size
"""
number_features = 0
f... |
def cell_size_to_meters(cell_size_param_value):
"""Convert the cell size tool parameter string value to a numerical value in units of meters.
Args:
cell_size_param_value (str): cell size tool parameter string value
Raises:
ValueError: If the units are invalid.
Returns:
... |
def fibo_rec(num):
"""Recursive Fibo."""
return num if num <= 1 else fibo_rec(num - 1) + fibo_rec(num - 2) |
def _get_runtime(heap=None):
""" Generates the runtime section of a Myria deployment file """
runtime = '[runtime]\n'
if heap:
runtime += 'jvm.heap.size.max.gb = %s\n' % heap
else:
runtime += '# No runtime options specified\n'
return runtime + '\n' |
def replace_all(string, terms):
"""
Removes any occurances of words specified in the terms list from the chosen string
Parameters
----------
string: str
string to remove terms from
terms: list
list of terms to be removed from string
Returns
-------
str
strin... |
def sign(x):
"""
The sign function
:rtype: integer
:return: the sign of x
:type x: double or integer
:param x: any arbitrary real number
"""
if (x<0): return -1
elif (x>0): return 1
else: return 0 |
def reformat_host_name(input_hostname):
"""
convert input_hostname to dns-safe hostname with prpper info
- upper case the input
- strip domain stuff from the end
- prepend <CLUSTER_TAG>-ZDEL-
:param str input_hostname: ex. some_host_name.domain.com
:rtype: str # reformatted hostnameex.... |
def validate_geojson(filename : str) -> bool:
"""Function to validate if the input is a geojson file.
Parameters
----------
filename : str
The path to a geojson file.
Returns
-------
bool
A True/False validation of the extension.
"""
return filename.endswith('.geojson') |
def supprimeExtension(str):
"""
Fonction qui supprime l'extension de notre str
param : str : string -> chaine de caractere qu'on souhaite supprimer l'extension.
return string : chaine de caractere sans extenstion
"""
#appliquer cette fonction avant supprimePonctuation
return "".join... |
def rangeFrameLabler(tickLocs, tickLabels, cadence):
"""
Takes lists of tick positions and labels and drops the marginal text label where the gap between ticks is less than half the cadence value
:param list tickLocs: List of current tick locations on the axis
:param list tickLabels: List of tick label... |
def get_extended_error(response_body):
"""Get extended error
:params response_body: Response from HTTP
:type response_body: class 'redfish.rest.v1.RestResponse'
"""
try:
expected_dict = response_body.dict
message_dict = expected_dict["error"]["@Message.ExtendedInfo"][0]
i... |
def _add_one_state_rnn(x, h):
""" RNN that increases the state by one each timestep. """
h += 1
print("x", x)
print("h", h)
return x, h |
def clear_bit(S, j):
"""
Returns a new set from set `S` with the `j`-th item turned off.
Examples
========
Clear/turn off item in position 1 of the set:
>>> S = 0b101010
>>> bin(clear_bit(S, 1))
'0b101000'
"""
return S & ~(1 << j) |
def mysql_to_dict(mysql_fetchall, columns):
"""Function used to return a dict with columns as its keys and the values as its values"""
mysql_fetchall = list(zip(*mysql_fetchall))
return {columns[i]: mysql_fetchall[i] for i in range(len(columns))} |
def _split_comma_separated(string):
"""Return a set of strings."""
return set(text.strip() for text in string.split(',') if text.strip()) |
def create_table_sql(table_name: str, column_titles: list) -> str:
"""Return string that can be used to create SQL data table
The column_titles should include the DATATYPE as part of the same string
"""
command = 'CREATE TABLE ' + table_name + ' ('
print(column_titles)
for i in column_titles[:-... |
def nm_to_uh(s):
"""Get the userhost part of a nickmask.
(The source of an Event is a nickmask.)
"""
return s.split("!")[1] |
def query(qstring):
"""
Parse query parameters and return dictionary.
"""
# try parsing query string else fail
try:
# check for empty string of query items
if not qstring:
# return empty dict
return {}
# create default parameter dict
pdict =... |
def rmod(denom, result, num_range):
"""
Calculates the inverse of a mod operation.
The *denom* parameter specifies the denominator of the original mod (%)
operation. In this implementation, *denom* must be greater than 0. The
*result* parameter specifies the result of the mod operation. For obvious... |
def _cell_above_exists(column_index: int, rows: list) -> bool:
"""
Return True if the cell above the current cell exists.
Keyword arguments:
column_index -- the index of the column
rows -- the rows to check
"""
return column_index < len(rows[len(rows) - 1]) |
def _parse_restriction_split(source_object, restriction_split, search_low_dbnum,
search_high_dbnum):
"""
Parses a split restriction string and sets some needed variables.
Returns a tuple in the form of: (low dbnum, high dbnum)
"""
r... |
def camel_case_to_lower_with_underscores(camelcased: str) -> str:
"""Convert CamelCased names to lower_case_with_underscores."""
chunk_positions = []
prev_split_pos = 0
for pos, (prev_is_upper, char_is_upper, next_is_upper) in enumerate(
zip(
(x.isupper() for x in camelcased[:-2]),
... |
def dictadd(dict_a, dict_b):
"""
Returns a dictionary consisting of the keys in `a` and `b`.
If they share a key, the value from b is used.
"""
result = {}
result.update(dict_a)
result.update(dict_b)
return result |
def is_video(filename):
"""
Checks if the filename is video or not
arguments:
filename: str, filename
returns:
bool, True or False
"""
video_formats = ["mp4", "avi"]
for video_format in video_formats:
return filename.endswith(video_format)
return False |
def convert_to_celsius(fahrenheit: float) -> float:
"""Return the number of Celsius degrees equivalent to fahrenheit
degrees.
>>> convert_to_celsius(75)
23.88888888888889
"""
return (fahrenheit - 32.0) * 5.0 / 9.0 |
def _read_params(dct, symb1, symb2):
""" Calculate pot
"""
params = dct.get((symb1, symb2), None)
if params is None:
params = dct.get((symb2, symb1), None)
return params |
def grammatical_join(words):
"""Join a list of words, using an oxford comma if appropriate."""
if '__getitem__' not in words:
words = list(words)
if len(words) == 2:
return ' and '.join(words)
else:
words = words[:-2] + [', and '.join(words[-2:])]
return ', '.join(words) |
def nrz_decision(x,t):
"""produces nrz symbol from analog voltage
Parameters
----------
x : float
the analog voltage
t: float
voltage threshold between 0 and 1 symbol
Returns
-------
int
the nrz symbol that represents x
"""
if x<t:
r... |
def fill_knapsack(raw_items, weight_limit):
"""You are given weights and values of items, put these items in a knapsack
of capacity weight_limit to get the maximum total value in the knapsack."""
table = [ [0]*(weight_limit+1) for _ in range(len(raw_items)) ]
# initialise first row
value_item = ... |
def _get_ips(ips_as_string):
"""Returns viable v4 and v6 IPs from a space separated string."""
ips = ips_as_string.split(" ")[1:] # skip the header
ips_v4, ips_v6 = [], []
# There is no guarantee if all the IPs are valid and sorted by type.
for ip in ips:
if not ip:
continue
... |
def find_peak(list_of_integers):
""" Python function to find peak number"""
le = len(list_of_integers)
if le == 0:
return
m = le // 2
pivot = list_of_integers[m]
left = list_of_integers[m - 1]
if (m == le - 1 or pivot >= list_of_integers[m + 1]) and\
(m == 0 or pivot >= ... |
def to_choices_list(data) -> list:
"""Return a sorted list of key/value tuples that identifies each BIF."""
sorted_list = []
other_bifs = []
for d in data:
# Keep the SSF BIFs at the top
if 'ssf' in d['name'].lower():
sorted_list.append((d['name'], d['name']))
else:
... |
def m3kgtoft3lb(m3kg):
"""
Convertie les m3/kg en ft3/lb
note: 1m3/kg = 16.0185ft3/lb
:param m3kg: density [m]
:return ft3lb: density [ft]
"""
ft3lb = m3kg * 16.0185
return ft3lb |
def isnumber(*args):
"""Checks if value is an integer, long integer or float.
NOTE: Treats booleans as numbers, where True=1 and False=0.
"""
return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args)) |
def find_combos_brute_force(adapters, position):
"""Part 2 - recursion, too slow"""
if position == len(adapters) - 1:
return 1
else:
answer = 0
for new_position in range(position + 1, len(adapters)):
if adapters[new_position] - adapters[position] <= 3:
an... |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid. Please change it to one
suitable for your service.
"""
return username == 'uploads' and password == 'secretpassword' |
def get(value, arg, default=None):
""" Call the dictionary get function """
return value.get(arg, default) |
def vce(vc=0,ve=0):
"""
Parameters
----------
vc : TYPE, optional
DESCRIPTION. The default is 0.
ve : TYPE, optional
DESCRIPTION. The default is 0.
Returns
-------
None.
"""
voltage = vc - ve
return voltage |
def get_sum(list):
"""Calc the sum of values from a list of numbers
Args:
list: The list from where the calc will be done
Returns:
Return the sum of values from a list of numbers
"""
sum = 0
for value in list:
sum += value
return sum |
def filter_layer_collections_by_object(layer_collections, obj):
"""Returns a subset of collections that contain the given object."""
return [lc for lc in layer_collections if obj in lc.collection.objects.values()] |
def find_name(slaves, name):
"""Function: find_name
Description: Locates and returns a slave's instance from an array of slave
instances.
Arguments:
(input) slaves -> List of slave instances.
(input) name -> Name of server being searched for.
(output) Slave instance or N... |
def abs(n):
"""
this is abs function
example:
>>> abs(1)
1
>>> abs(-1)
1
>>> abs(0)
0
"""
return n if n>=0 else (-n) |
def get_mac_addr(bytes):
"""
Properly format a mac address.
Expected final format: AA:BB:CC:DD:EE:FF
"""
bytes_str = map('{:02x}'.format, bytes)
mac_addr = ':'.join(bytes_str).upper()
return mac_addr |
def _to_wring(d):
"""Dump to LTL formula in Wring syntax
Assume that d is a dictionary describing a GR(1) formula in the
manner of tulip.spec.form.GRSpec; e.g., it should have a key named
'env_init'. Compare with _to_gr1c().
"""
assumption = ''
if d['env_init']:
assumption += ' * '.... |
def right_remove(text, to_remove):
""" Removes a part of a string, if it ends with it.
str.rstrip is similar, but can remove too much.
For example, '4.mp4'.rstrip('.mp4') will remove the leading four!
This function does not do that.
"""
if text.endswith(to_remove):
return te... |
def extract_str(input_: str) -> str:
"""Extracts strings from the received input.
Args:
input_: Takes a string as argument.
Returns:
str:
A string after removing special characters.
"""
return "".join([i for i in input_ if not i.isdigit() and i not in [",", ".", "?", "-", "... |
def get_match_ref_color(is_match):
"""
Get color for base matching to reference
:param is_match: If true, base matches to reference
:return:
"""
if 45.0 <= is_match <= 55.0:
return 1
elif 250.0 <= is_match <= 255.0:
return 0 |
def remove_dups(lst):
"""
Inputs:
lst - A list object
Outputs:
Returns a new list with the same elements in lst,
in the same order, but without duplicates. Only
the first element of each replicated element will
appear in the output.
"""
result = []
dups = set()
... |
def unary(op, v):
"""
interpretor for executing unary operator expressions
"""
if op == "+":
return v
if op == "-":
return -v
if op.lower() == "not":
return not(v) |
def _unpersist_broadcasted_np_array(broadcast):
"""
Unpersist a single pyspark.Broadcast variable or a list of them.
:param broadcast: A single pyspark.Broadcast or list of them.
"""
if isinstance(broadcast, list):
[b.unpersist() for b in broadcast]
else:
broadcast.unpersist()
... |
def fsextract(string,method):
"""
Extracts the indices or filenames from a comma-separated string
Input Parameters
----------------
string : str
a comma separated string of either file names or file index numbers.
method : {'index','filename'}
'index' if the values passed are ... |
def powerlaw(x, amplitude=1, exponent=1.0):
"""Return the powerlaw function.
x -> amplitude * x**exponent
"""
return amplitude * x**exponent |
def float_to_dollars(value:float) -> str:
"""
Take in a float (32.00)
"""
return f"${value:,.2f}" |
def _GenerateDepencencies(variable_names):
"""
Determines what input columns are needed based on the parameters and which parameters
are coming from columns vs raw values.
"""
code = [
"\n\nprotected override Func<int, bool> GetDependenciesCore(Func<int, bool> activeOutput)",
... |
def get_fact_value(item, attribute_name, json_property):
"""
returns the value of a fact (attribute) from an item
iterates over the "facts" list - looking for a matching attributeId
to the parameter attribute_name
returns the "value" json_property or ""
"""
# get the value of a specific fac... |
def fibonacci(n):
"""Recursive function to print nth Fibonacci number"""
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2)) |
def _create_ip_to_node_map(meta_map):
"""
Create IP to NodeId mapping from meta_map
"""
ip_to_node = {}
if not meta_map or not isinstance(meta_map, dict):
return ip_to_node
for node in meta_map:
if not meta_map[node] or not 'ip' in meta_map[node]:
continue
... |
def _fixed_masks_arg(mask):
"""
Prepare the ``fixed_image_masks`` argument of SyN.
Example
-------
>>> _fixed_masks_arg("atlas_mask.nii.gz")
['NULL', 'atlas_mask.nii.gz']
"""
return ["NULL", mask] |
def flatten(l):
""" convert list of list to list"""
return [item for sublist in l for item in sublist] |
def text_length_validator(value, values):
""" Provides a validator function that a valid string for the display
commands of the Keithley. Raises a TypeError if value is not a string.
If the string is too long, it is truncated to the correct length.
:param value: A value to test
:param values: The a... |
def list_of_vars(arg_plot):
"""Construct list of variables per plot.
Args:
arg_plot (str): string with variable names separated with
``-`` (figures), ``.`` (subplots) and ``,`` (same subplot).
Returns:
three nested lists of str
- variables on the same subplot;
-... |
def _is_textfile_bad_(filename):
""" """
try:
_ = open(filename).read().splitlines()
return False
except:
return True |
def make_obsname(name, unique_names={},
maxlen=13 # allows for number_yyyymm
):
"""Make an observation name of maxlen characters or
less, that is not in unique_names."""
for i in range(len(name) - maxlen + 1):
end = -i if i > 0 else None
slc = slice(-(maxle... |
def remove_vector_fields(attributes, data):
"""
Flatten data values to remove vector fields.
Transforms "x: {name: val, rep: vector(val)}" to "x: val"
"""
for attrib in attributes:
if attrib['similarity'] == 'Semantic USE':
print('data: ')
print(data)
value = data.get(attrib['name'])
if value is n... |
def is_valid_reference(ref):
""" Checks if reference is correct """
references = 'first', 'average', 'experimental'
return ref in references |
def levenshtein_distance(original_str, edited_str) -> int:
"""
original_str: The string before edit operations are performed.
edited_str: The string after edit operations are performed
returns the minimum number of edits required.
O(N * M) time
O(N * M) space
"""
# initialize 2D array... |
def utm_getZone(longitude):
"""Calculate UTM Zone from Longitude.
Arguments
---------
longitude: float
longitude coordinate (Degrees.decimal degrees)
Returns
-------
out: int
UTM Zone number.
"""
return (int(1+(longitude+180.0)/6.0)) |
def _MakeSampleSeconds(sample_times):
"""Helper to convert an array of time values to a tr157 string."""
deltas = [str(int(round(end - start))) for start, end in sample_times]
return ','.join(deltas) |
def make_mangrove_child(n):
"""
Generates a cersion of the MANGROVE_CHILD* macro, with * = n.
:param n: The nesting level of the MANGROVE_CHILD macro, i.e. how many 'fieldN'
arguments it should accept.
"""
if n < 2:
raise ValueError("Argument n must be at least 2. Received n=%... |
def intToVec(n):
"""Convert a 2-byte integer into a 4-element vector"""
return [n >> 12, (n >> 4) & 0xf, (n >> 8) & 0xf, n & 0xf] |
def non_zero_balance(balance):
"""
Return the balance with zero-value coins removed
"""
non_zero_balance = {}
for coin, amount in balance.items():
if amount > 0:
non_zero_balance[coin] = amount
return non_zero_balance |
def api_methods():
"""
API symbols that should be available to users upon module import.
"""
return {
'point', 'scalar',
'scl', 'rnd', 'inv', 'smu',
'pnt', 'bas', 'mul', 'add', 'sub'
} |
def solution(S):
"""Find the position on a string S formed by a set of two characters
such that, the number of of one characters on the left is equal
to the number of the same characters on the right.
(())))(
abbaaab => 4 (abba, aab)
"""
o = 0
for i, s in enumerate(S, 1):
o += s... |
def cellsInLayer(ii):
"""
Return number of cells in layer ii
"""
return (2*ii+1) |
def norm_b(_, pivot_stats, s):
"""Pivoted byte normalization."""
return 1.0 - s + s * pivot_stats["b"] / pivot_stats["avgb"] |
def is_png(data):
"""True if data is the first 8 bytes of a PNG file."""
return data[:8] == '\x89PNG\x0d\x0a\x1a\x0a' |
def reverse(l):
"""
REVERSE list
outputs a list whose members are the members of the input list, in
reverse order.
"""
l = l[:]
l.reverse()
return l |
def w_is_typed(tokens):
""" Check whether a sequence of commands includes a type specifier. """
return (
'type' in tokens or
'answerblock' in tokens or
'drawbox' in tokens or
'answerfigure' in tokens
) |
def mod_sqrt_fact_eratosthenes_sieve(n):
"""
Something like a sieve of Eratosthenes for factorization - 1
Complexity: O(sqrt(N))
We can find all the factors of a number using a simple
alternation to the Eratosthenes sieve. Factors are the
numbers you multiply to get another number. Those number... |
def twoNumberSum(array, targetSum):
"""
The problem comes down to this : targetsum = x+y
So, since I know the tragetsum, I am trying ot find out the value of x
which can be formed into a equation 'x = targetsum-y'
What really happens lets explain with an example
array = [3,7,1,... |
def _ensure_has_len(seq):
"""If seq is an iterator, put its values into a list."""
try:
len(seq)
except TypeError:
return list(seq)
else:
return seq |
def wrap(headr, data):
"""
Input:
headr -- text of html field
data -- text to be wrapped.
Returns a corresponding portion of an html file.
"""
return '<%s>%s</%s>' % (headr, data, headr) |
def remove_duplicates(mylist):
"""
Removes duplicate values from a list
"""
return list(set(mylist)) |
def DecodeMyPyString(s):
# type: (str) -> str
"""Workaround for MyPy's weird escaping.
Used below and in cppgen_pass.py.
"""
byte_string = bytes(s, 'utf-8')
# In Python 3
# >>> b'\\t'.decode('unicode_escape')
# '\t'
raw_string = byte_string.decode('unicode_escape')
return raw_... |
def team_sign(team : int) -> int:
"""Gives the sign for a calculation based on team.
Arguments:
team {int} -- 0 if Blue, 1 if Orange.
Returns:
int -- 1 if Blue, -1 if Orange
"""
return -2 * team + 1 |
def incl_user_data_buf(buf, dstfile, owner='root:root', permissions='0644'):
"""Return dict formatted for conversion to YAML. Use 'buf' as file
contents
"""
return {
'path': dstfile,
'content': buf,
'owner': owner,
'permissions': permissions,
} |
def split(args):
""" This exists only for the mem request """
return {
'join' : {'__mem_gb': 10}
} |
def lucas(n):
""" accepts lucas number, returns nth number """
""" Using the lucas number sequence"""
if n==1:
return 2
elif n==2:
return 1
else:
return lucas(n-1)+lucas(n-2) |
def _variable_map_by_name(variables):
"""
Returns Dict,representing referenced variable fields mapped by name.
Keyword Parameters:
variables -- list of 'variable_python_type' Warehouse support DTOs
>>> from pprint import pprint
>>> var1 = { 'column':'frob_hz', 'title':'Frobniz Resonance (Hz)'... |
def apply_threshold(en, de, sentlength):
"""
:param en: English language sentences
:param de: German language sentences
:param sentlength: cutoff length of a sentences
:return: trimmed sentences
"""
en_sents= []
de_sents = []
for i in range(len(en)):
en_len = len(en[i])
... |
def go(i, partials):
"""Compute one element value from the FFT.
It is kind of uglified for performance."""
step = 2 * i
end = len(partials) - 1
mode = 1
lo = -1 + i
hi = lo + i
res = 0
# We loop until hi is too big and then do a separate check for lo
# so that we can avoid ha... |
def rgb(r=0, g=0, b=0, mode='RGB'):
"""
Convert **r**, **g**, **b** values to a `string`.
:param r: red part
:param g: green part
:param b: blue part
:param string mode: ``'RGB | %'``
:rtype: string
========= =============================================================
mode ... |
def combine(value, new=None):
""" Jinja2 filter which merges dictionaries.
"""
new = new or {}
value = dict(value)
value.update(new)
return value |
def find_lcs_length_optimized(first_sentence_tokens: tuple, second_sentence_tokens: tuple,
plagiarism_threshold: float) -> int:
"""
Finds a length of the longest common subsequence using an optimized algorithm
When a length is less than the threshold, it becomes 0
:param fi... |
def Justify(string: str, maxWidth: int) -> str:
"""Returns justified string.
Keyword args:
string -- string largo para que se note
maxWidth -- ancho del texto final
Use:
print(Justify(string, maxWidth))
"""
words = string.split()
res, cur, num_of_letters = [], [], 0
for w in wo... |
def no_none(s):
""" Template helper: prevent None from appearing in output.
@param s: the input value
@returns: a string version of the value, or "" if None
"""
return str(s) if s is not None else '' |
def current_filename_with_extensions(filename, extensions):
"""
A private helper method. Returns the filename and its extensions.
:param filename: a string, the file's name
:param extensions: a list, the extensions
:return: a string, a filename with extensions
"""
filename_with_extensions = ... |
def get_iteration(nb, batch_size):
"""
Given total sample size and batch size, return
number of batch.
"""
basic = nb//batch_size
total = basic + (0 if nb%batch_size==0 else 1)
return total |
def bytearray_to_int(bytes, bytesize):
"""Utility function to convert a bytearray into an integer.
It interprets the bytearray in the little endian format. For a big endian
bytearray, just do ba.reverse() on the object before passing it in.
"""
import struct
if bytesize == 1:
return by... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.