content
stringlengths 42
6.51k
|
|---|
def bin16dec(bin: int) -> int:
"""Returns a signed integer from the first 16 bits of an integer
"""
num = bin & 0xFFFF
return num - 0x010000 if 0x8000 & num else num
|
def fetch_method(obj, method):
"""
fetch object attributes by name
Args:
obj: class object
method: name of the method
Returns:
function
"""
try:
return getattr(obj, method)
except AttributeError:
raise NotImplementedError(f"{obj.__class__} has not implemented {method}")
|
def readline(file):
"""
Return the first unread line from this file,
or the empty string if all lines are read.
"""
return file.readline()
|
def clip(lower, val, upper):
"""Clips a value. For lower bound L, upper bound U and value V it
makes sure that L <= V <= U holds.
Args:
lower: Lower boundary (including)
val: The value to clip
upper: Upper boundary (including)
Returns:
value within bounds
"""
if val < lower:
return lower
elif val > upper:
return upper
else:
return val
|
def flatten(nested_list):
"""
Flatten a list of nested lists
"""
return [item for sublist in nested_list for item in sublist]
|
def rev_strand(strand):
"""
reverse the strand
:param strand:
:return:
"""
if strand == "+":
return "-"
return "+"
|
def get_accuracy(y_bar, y_pred):
"""
Computes what percent of the total testing data the model classified correctly.
:param y_bar: List of ground truth classes for each example.
:param y_pred: List of model predicted class for each example.
:return: Returns a real number between 0 and 1 for the model accuracy.
"""
correct = 0
for i in range(len(y_bar)):
if y_bar[i] == y_pred[i]:
correct += 1
accuracy = (correct / len(y_bar)) * 100.0
return accuracy
|
def delete_from_file_name_forbidden_characters(str_filename):
"""Delete forbidden charactars in a filename from the given string
Args:
str_filename (str): Name of the file
Returns:
str: filename with removed characters which are not allowed
"""
list_chars_of_filtered_filenames = []
for str_char in str_filename:
if str_char.isalnum():
list_chars_of_filtered_filenames.append(str_char)
else:
list_chars_of_filtered_filenames.append('_')
return "".join(list_chars_of_filtered_filenames)
|
def num_steps(n, steps=0):
"""Determine number of ways a child can get to the top of the stairs."""
if steps > n:
return 0
if steps == n:
return 1
return num_steps(n, steps + 1) + num_steps(n, steps + 2) + num_steps(n, steps + 3)
|
def to_palindrome(seq):
"""
Generates two possible palindromic sequence from the input sequence
"""
init_type = type(seq)
if not (init_type is str or init_type is int):
raise TypeError("Input a string or integer only")
if init_type == int:
seq = str(seq)
forward = seq + seq[::-1]
reverse = seq[::-1] + seq
return (forward, reverse) if init_type == str \
else (int(forward), int(reverse))
|
def create_sim_table(train,
test,
distances):
"""
create a table of similarity between the train program
and test programs.
Parameters
----------
train: list
list of train programs names
test: list
list of test programs names
distances: matrix
matrix of distances where distances[i][j]
is the distance of train[i] to test[j]
Returns
-------
A dict named table where table[test[j]][train[i]]
have the value of distance between test[j] and train[i]
"""
table = {}
for j in range(len(test)):
prg_test = test[j]
table[prg_test] = {}
for i in range(len(train)):
prg_train = train[i]
table[prg_test][prg_train] = distances[i][j]
return table
|
def _from_sRGB(component):
"""
Linearize sRGB color
"""
component /= 255.0
return component / 12.92 if component <= 0.04045 else ((component+0.055)/1.055)**2.4
|
def calc_bending_force(R_ring: float, params: dict) -> float:
"""Calculate the elastic bending force of a filament in a ring.
Args:
R_ring: Radius of the ring / m
params: System parameters
"""
return params["EI"] * params["Lf"] / R_ring**3
|
def to_mixed_case(string: str):
"""
foo_bar_baz becomes fooBarBaz. Based on
pydantic's `to_camel` utility, except without
the initial capital letter.
"""
words = string.split("_")
return "".join([words[0]] + [w.capitalize() for w in words[1:]])
|
def S_get_histogram_values(_data_list, _level=0.1):
"""
Finds the groups present for given data samples
Groups will be divided based on value difference as set by level parameter
"""
ds = len(_data_list)
if ds < 1:
return []
s_data = sorted(_data_list)
bins = []
bin_cursor = 0
averages = []
counts = []
comparator = s_data[0]
bins.append([s_data[0]])
for i in range(1, ds):
if s_data[i] > (comparator + _level):
bin_cursor += 1
bins.append([s_data[i]])
comparator = s_data[i]
continue
else:
bins[bin_cursor].append(s_data[i])
for i in bins:
sz = len(i)
averages.append(sum(i)/sz)
counts.append(sz)
return list(zip(averages, counts))
|
def _parse_s3_file(original_file):
"""
Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt')
"""
bits = original_file.replace('s3://', '').split("/")
bucket = bits[0]
object_key = "/".join(bits[1:])
return bucket, object_key
|
def in_dictionary(pairs, dictionary_one_to_set):
"""Returns a list of booleans indicating if each pair of the list appears in the dictionary"""
result = []
for k, v in pairs:
result.append(1 if k in dictionary_one_to_set and v in dictionary_one_to_set[k] else 0)
return result
|
def is_blank(s):
"""
Returns True if the given string is None or blank (after stripping spaces),
False otherwise.
"""
return s is None or len(s.strip()) == 0
|
def validate_password_policy(password):
"""
Password should contain
- at least 1 uppercase character (A-Z)
- at least 1 lowercase character (a-z)
- at least 1 digit (0-9)
- at least 1 special character (punctuation)
"""
# app.logger.info("Validating password policy")
msg = "At least 1 uppercase character"
if not any(c.isupper() for c in password):
return False, msg
msg = "At least 1 lowercase character"
if not any(c.islower() for c in password):
return False, msg
msg = "At least 1 digit"
if not any(c.isdigit() for c in password):
return False, msg
msg = "At least 1 special character (punctuation)"
special_chars = "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
if not any(c in special_chars for c in password):
return False, msg
msg = "valid"
# app.logger.info("Password policy validated [{}]".format(msg))
return True, msg
|
def split_units(value):
"""Splits a string into float number and potential unit
References
Taken from https://stackoverflow.com/a/30087094
Args:
value: String with number and unit.
Returns
A tuple of a float and unit string.
Examples:
>>> split_units("2GB")
(2.0, 'GB')
>>> split_units("17 ft")
(17.0, 'ft')
>>> split_units(" 3.4e-27 frobnitzem ")
(3.4e-27, 'frobnitzem')
>>> split_units("9001")
(9001.0, '')
>>> split_units("spam sandwhiches")
(0, 'spam sandwhiches')
>>> split_units("")
(0, '')
"""
units = ""
number = 0
while value:
try:
number = float(value)
break
except ValueError:
units = value[-1:] + units
value = value[:-1]
return number, units.strip()
|
def convert_set(iterable, convert_to='list'):
"""This function casts a ``set`` variable to be a ``list`` instead so that it can be scriptable.
:param iterable: The iterable to be evaluated to see if it has a ``set`` type
:param convert_to: Defines if the iterable should be cast to a ``list`` (default) or a ``tuple``
:type convert_to: str
:returns: The converted variable as a ``list`` or ``tuple`` (or untouched if not a ``set``)
"""
if type(iterable) == set:
if convert_to == 'tuple':
iterable = tuple(iterable)
else:
iterable = list(iterable)
return iterable
|
def setter_helper(fn, value):
"""
Some property setters need to call a function on their value -- e.g. str() or float() -- before setting
the property. But, they also need to be able to accept None as a value, which throws an error.
This helper solves this problem
:param fn: function to apply to value
:param value: value to pass to property setter
:return: result of fn(value), or None
"""
return value if value is None else fn(value)
|
def find_number_to_keep(count_of_0, count_of_1, criteria) -> str:
"""
Compare numbers according to a criteria ('most' or 'least').
Criteria 'most' returns the number of which count is bigger.
Criteria 'least' returns the number of which count is lesser.
When counts are equal, criteria 'most' returns '1', and 'least' returns '0'
Args:
count_of_0 (int): count of numbers '0'
count_of_1 (int): count of numbers '1'
criteria (str): criteria for comparison
Returns:
str: resulting number (values '0' or '1')
"""
if criteria == 'most':
if count_of_0 == count_of_1:
return '1'
else:
return '0' if count_of_0 > count_of_1 else '1'
else:
if count_of_0 == count_of_1:
return '0'
else:
return '0' if count_of_0 < count_of_1 else '1'
|
def is_enumerable_str(identifier_value):
"""
Test if the quoted identifier value is a list
"""
return len(identifier_value) > 2 and identifier_value[0] in ('{', '(', '[') and identifier_value[-1] in ('}', ']', ')')
|
def chat_id(message: dict) -> int:
""" Extract chat id from message """
return message["chat"]["id"]
|
def splitdrive(path):
"""Split a pathname into drive and path specifiers.
Returns a 2-tuple "(drive,path)"; either part may be empty.
"""
# Algorithm based on CPython's ntpath.splitdrive and ntpath.isabs.
if path[1:2] == ':' and path[0].lower() in 'abcdefghijklmnopqrstuvwxyz' \
and (path[2:] == '' or path[2] in '/\\'):
return path[:2], path[2:]
return '', path
|
def remove_underline(params):
"""Remove the underline in reserved words.
The parameters def and type are python reserved words so it is necessary
to add a underline to use this words, this method remove the underline
before make a http request.
Args:
params (dict): Url query parameters.
Returns:
(dict): Validated url query parameters.
"""
modified_params = {'def_': 'def', 'type_': 'type', 'format_': 'format'}
for key, value in modified_params.items():
if key in params.keys():
param_value = params.pop(key)
params[value] = param_value
return params
|
def compare_thresh(values, op, thresh):
"""Check if value from metrics exceeds thresh."""
state = 'OK'
for value in values:
if value:
if op == 'GT' and value <= thresh:
return state
elif op == 'LT' and thresh <= value:
return state
elif op == 'LTE' and value > thresh:
return state
elif op == 'GTE' and thresh > value:
return state
state = 'ALARM'
for value in values:
if value is None:
state = 'UNDETERMINED'
return state
|
def process_page(inp):
"""
Wraps around if we split: make sure last passage isn't too short.
This is meant to be similar to the DPR preprocessing.
"""
(nwords, overlap, tokenizer), (title_idx, docid, title, url, content) = inp
if tokenizer is None:
words = content.split()
else:
words = tokenizer.tokenize(content)
words_ = (words + words) if len(words) > nwords else words
passages = [words_[offset:offset + nwords] for offset in range(0, len(words) - overlap, nwords - overlap)]
assert all(len(psg) in [len(words), nwords] for psg in passages), (list(map(len, passages)), len(words))
if tokenizer is None:
passages = [' '.join(psg) for psg in passages]
else:
passages = [' '.join(psg).replace(' ##', '') for psg in passages]
if title_idx % 100000 == 0:
print("#> ", title_idx, '\t\t\t', title)
for p in passages:
print("$$$ ", '\t\t', p)
print()
print()
print()
print()
return (docid, title, url, passages)
|
def link_to_changes_in_release(release, releases):
"""
Markdown text for a hyperlink showing all edits in a release, or empty string
:param release: A release version, as a string
:param releases: A container of releases, in descending order - newest to oldest
:return: Markdown text for a hyperlink showing the differences between the give release and the prior one,
or empty string, if the previous release is not known
"""
if release == releases[-1]:
# This is the earliest release we know about
return ''
index = releases.index(release)
previous_release = releases[index + 1]
return '\n[Changes in %s](https://github.com/catchorg/Catch2/compare/v%s...v%s)' % (release, previous_release, release)
|
def get_gse_gsm_info(line):
"""
Extract GSE and GSM info
Args:
line: the entry to process
Returns:
the GSE GSM info tuple
"""
parts = line.strip().split(",")
if parts[0] == "gse_id":
return None
return parts[0], parts[1:]
|
def rgb_clamp(colour_value):
"""
Clamp a value to integers on the RGB 0-255 range
"""
return int(min(255, max(0, colour_value)))
|
def write_tsv_file(out_filename, name_list, scalar_name, scalar_list):
"""Write a .tsv file with list of keys and values.
Args:
out_filename (string): name of the .tsv file
name_list (list of string): list of keys
scalar_name (string): 'volume', 'thickness', 'area' or
'meanCurv'. Not used for now. Might be used as part of a
pandas data frame
scalar_list (list of float): list of values corresponding to the keys
"""
import warnings
import pandas
try:
data = pandas.DataFrame({"label_name": name_list, "label_value": scalar_list})
data.to_csv(out_filename, sep="\t", index=False, encoding="utf-8")
except Exception as exception:
warnings.warn("Impossible to save {0} file".format(out_filename))
raise exception
return out_filename
|
def _max_len(choices):
"""Given a list of char field choices, return the field max length"""
lengths = [len(choice) for choice, _ in choices]
return max(lengths)
|
def remove_measure(line):
""" (str) -> str
Returns provided line with any initial digits and fractions
(and any sorrounding blanks) removed.
"""
char_track = 0
blank_char = ' '
while char_track < len(line) and (line[char_track].isdigit() or \
line[char_track] in ('/', blank_char) ) :
char_track += 1
return line[char_track:len(line)]
|
def get_payment_request(business_identifier: str = 'CP0001234', corp_type: str = 'CP',
second_filing_type: str = 'OTADD'):
"""Return a payment request object."""
return {
'businessInfo': {
'businessIdentifier': business_identifier,
'corpType': corp_type,
'businessName': 'ABC Corp',
'contactInfo': {
'city': 'Victoria',
'postalCode': 'V8P2P2',
'province': 'BC',
'addressLine1': '100 Douglas Street',
'country': 'CA'
}
},
'filingInfo': {
'filingTypes': [
{
'filingTypeCode': second_filing_type,
'filingDescription': 'TEST'
},
{
'filingTypeCode': 'OTANN'
}
]
}
}
|
def IsOutputField(help_text):
"""Determines if the given field is output only based on help text."""
return help_text and (
help_text.startswith('[Output Only]') or
help_text.endswith('@OutputOnly'))
|
def get_speed(value):
""" Return if the capturing speed is fast (no filtering) or slow (filtered) """
if (value & 64) == 64:
return 'Fast'
else :
return 'Slow'
|
def _parse_common(row):
"""Parse common elements to TF Example from CSV row for non-spans mode."""
example = {}
example['id'] = row['id']
example['text'] = row['comment_text']
example['parent_text'] = row['parent_text']
parent_id = row['parent_id'] or 0
example['parent_id'] = int(float(parent_id))
example['article_id'] = int(row['article_id'])
return example
|
def binary_mode_to_cascade_mode(binary_list, num_cascade):
"""
Parameters
----------
binary_list: list
num_cascade: int
Returns
---------
cascade_mode: int
"""
cascade_mode = 0
if binary_list == [0] * num_cascade:
cascade_mode = 0
count = 1
for ele in binary_list:
if ele == 1:
cascade_mode = count
count += 1
return cascade_mode
|
def hdf_arrays_to_dict(hdfgroup):
"""
Convert an hdf5 group contains only data sets to a dictionary of
data sets
:param hdfgroup:
Instance of :class:`h5py.Group`
:returns:
Dictionary containing each of the datasets within the group arranged
by name
"""
return {key: hdfgroup[key][:] for key in hdfgroup}
|
def generate_router_url(project_id, region, router):
"""Format the resource name as a resource URI."""
return 'projects/{}/regions/{}/routers/{}'.format(
project_id,
region,
router
)
|
def return_organisation_links(new_order):
"""
This can be updated to include the most relevant organisation links
for the required country or region.
Note the order of this list needs to vary with the F1-score so may be
best implemented as a dictionary?
"""
links = ["http://"+i+".com" for i in new_order]
return links
|
def plural(st: str) -> str:
"""Pluralise most strings.
Parameters
----------
st : str
string representing any word ending in ss or not
Returns
-------
str
plural form of string st
"""
if st[-2:] not in ['ss']:
return f'{st}s'
return f'{st}es'
|
def format_string(format_config, target_value):
"""
Formats number, supporting %-format and str.format() syntax.
:param format_config: string format syntax, for example '{:.2%}' or '%.2f'
:param target_value: number to format
:rtype: string
"""
if (format_config.startswith('{')):
return format_config.format(target_value)
else:
return format_config % (target_value)
|
def tags_str_as_set(tags_str):
"""Return comma separated tags list string as a set, stripping out
surrounding white space if necessary.
"""
return set(filter(lambda t: t != '', (t.strip() for t in tags_str.split(','))))
|
def get_handler_name(handler):
"""
Return name (including class if available) of handler
function.
Args:
handler (function): Function to be named
Returns: handler name as string
"""
name = ''
if '__self__' in dir(handler) and 'name' in dir(handler.__self__):
name += handler.__self__.name + '.'
name += handler.__name__
return name
|
def repeat(s, question):
"""
Returns the user input repeated three times and
if they include a third argument sys.argv[2]
then it will add three question marks.
"""
result = s * 3
if question:
result = result + "???"
return result
|
def parse_summary(summary):
"""Parse a string from the format 'Anzahl freie Parkplätze: 179' into both its params"""
summary = summary.split(":")
summary[0] = summary[0].strip()
if "?" in summary[0]:
summary[0] = "nodata"
try:
summary[1] = int(summary[1])
except ValueError:
summary[1] = 0
return summary
|
def spectra(spall_dict):
"""
access skyserver for details on this object
:param spall_dict:
:return:
"""
url = "http://skyserver.sdss.org/dr16/en/get/SpecById.ashx?id={}".format(
spall_dict['SPECOBJID']
)
print("\nSpectra:")
print(url)
return url
|
def sol(s, l, r):
"""
The recursive approach
"""
if r == l:
return 1
if r-l == 1 and s[l] == s[r]:
return 2
if r-l == 2 and s[l] == s[r]:
return 3
if s[l] == s[r]:
return sol(s, l+1, r-1) + 2
return max(
sol(s, l, r-1), sol(s, l+1, r)
)
|
def ensure_keys(dict_obj, *keys):
"""
Ensure ``dict_obj`` has the hierarchy ``{keys[0]: {keys[1]: {...}}}``
The innermost key will have ``{}`` has value if didn't exist already.
"""
if len(keys) == 0:
return dict_obj
else:
first, rest = keys[0], keys[1:]
if first not in dict_obj:
dict_obj[first] = {}
dict_obj[first] = ensure_keys(dict_obj[first], *rest)
return dict_obj
|
def write_unit(value):
""" Convert unit value to modbus value """
return [int(value)]
|
def count_bits(n):
"""Count number of ones in binary representation of decimal number."""
bits = 0 if n == 0 else 1
while n > 1:
bits += n % 2
n //= 2
return bits
|
def xorGate(a, b):
"""
Input:
a, b
Two 1 bit values as 1/0
Returns:
1 if a is not equal to b otherwise 0
"""
if a != b:
return 1
else:
return 0
|
def str_to_md5(tbhstring):
"""Converte uma str para md5"""
import hashlib
hashid = hashlib.md5(tbhstring.encode('utf-8')).hexdigest()
return hashid
|
def parse_var(s):
""" Parse a key, value pair, separated by '=' That's the reverse of ShellArgs.
On the command line (argparse) a declaration will typically look like:
foo=hello or foo="hello world" """
items = s.split('=')
key = items[0].strip() # we remove blanks around keys, as is logical
if len(items) > 1:
# rejoin the rest:
value = '='.join(items[1:])
return key, value
else:
return None, None
|
def render_precipitation_chance(data, query):
"""
precipitation chance (o)
"""
answer = data.get('chanceofrain', '')
if answer:
answer += '%'
return answer
|
def font_name(family, style):
"""Same as ``full_name()``, but ``family`` and ``style`` names are separated by a hyphen instead of space."""
if style == 'Regular':
font_name = family
else:
font_name = family + '-' + style
return font_name
|
def extract_version(txt):
"""This function tries to extract the version from the help text of any
program."""
words = txt.replace(",", " ").split()
version = None
for x in reversed(words):
if len(x) > 2:
if x[0].lower() == "v":
x = x[1:]
if "." in x and x[0].isdigit():
version = x
break
return version
|
def config_name_from_full_name(full_name):
"""Extract the config name from a full resource name.
>>> config_name_from_full_name('projects/my-proj/configs/my-config')
"my-config"
:type full_name: str
:param full_name:
The full resource name of a config. The full resource name looks like
``projects/project-name/configs/config-name`` and is returned as the
``name`` field of a config resource. See:
https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs
:rtype: str
:returns: The config's short name, given its full resource name.
:raises: :class:`ValueError` if ``full_name`` is not the expected format
"""
projects, _, configs, result = full_name.split('/')
if projects != 'projects' or configs != 'configs':
raise ValueError(
'Unexpected format of resource', full_name,
'Expected "projects/{proj}/configs/{cfg}"')
return result
|
def string_dlt_to_dlt(dlt_str_rep):
"""
Return dictionary/list/tuple from given string representation of dictionary/list/tuple
Parameters
----------
dlt_str_rep : str
'[]'
Examples
--------
>>> string_dlt_to_dlt("[1, 2, 3]")
[1, 2, 3]
>>> string_dlt_to_dlt("[]")
[]
>>> string_dlt_to_dlt("['1', '2', '3']")
['1', '2', '3']
>>> string_dlt_to_dlt("{'a': 1, 'b': 2}")
{'a': 1, 'b': 2}
>>> string_dlt_to_dlt("{'a': '1', 'b': '2'}")
{'a': '1', 'b': '2'}
>>> string_dlt_to_dlt("('1', '2', '3')")
('1', '2', '3')
Returns
-------
dlt : dict or list or tuple
"""
from ast import literal_eval
if isinstance(dlt_str_rep, str):
dlt = literal_eval(dlt_str_rep)
return dlt
else:
raise TypeError("Wrong datatype(s)")
|
def event_dot_nodes(doc, events, include_prop_anchors=False):
"""
Return a dot string that declares nodes for the given set of
events, along with any entities or syn_nodes reachable from
those events.
"""
# Collect node values
event_node_values = set()
entity_node_values = set()
entity_node_values1 = {}
mention_node_values = set()
valmention_node_values = set()
syn_node_values = set()
prop_node_values = set()
if events:
for event in events:
event_node_values.add(event)
if isinstance(event, EventMention):
syn_node_values.update(get_all_anchor_node_from_em(event))
if include_prop_anchors and event.anchor_prop is not None:
prop_node_values.update(get_all_anchor_prop_from_em(event))
else:
for em in event.event_mentions:
syn_node_values.update(get_all_anchor_node_from_em(em))
if include_prop_anchors and em.anchor_prop is not None:
prop_node_values.update(get_all_anchor_prop_from_em(em))
for arg in event.arguments:
if isinstance(arg, EventMentionArg):
# mention_node_values.add(arg.mention)
if arg.mention:
entity = doc.mention_to_entity.get(arg.mention)
if entity:
entity_node_values1[entity] = arg.mention
# entity_node_values.add(entity)
else:
mention_node_values.add(arg.mention)
# print "%s-----\n" % arg.mention
if arg.value_mention:
valmention_node_values.add(arg.value_mention)
# print "%s+++++\n" % arg.value_mention
else:
if arg.entity:
entity_node_values.add(arg.entity)
# entity_node_values1[arg.entity]=arg.value.mentions[0]
if arg.value_entity:
valmention_node_values.add(arg.value.value_mention)
# Display all nodes.
return ([MentionDotNode(v) for v in mention_node_values] +
[ValMentionDotNode(v) for v in valmention_node_values] +
[SynDotNode(v) for v in syn_node_values] +
[PropDotNode(v) for v in prop_node_values] +
[EntityDotNode1(k, v) for k, v in entity_node_values1.items()] +
[EntityDotNode(v) for v in entity_node_values] +
[EventDotNode(v) for v in event_node_values])
|
def easy_unpack(tuple):
"""
returns a tuple with 3 elements - first, third and second to the last
"""
tuple2=(tuple[0], tuple[2], tuple[-2])
return tuple2
|
def is_palindrome(n):
"""Returns True if integer n is a palindrome, otherwise False"""
if str(n) == str(n)[::-1]:
return True
else:
return False
|
def fibonacci(n):
"""
This function prints the Nth Fibonacci number.
>>> fibonacci(3)
1
>>> fibonacci(10)
55
The input value can only be an integer, but integers lesser than or equal to 0 are invalid, since the series is not defined in these regions.
"""
if n<=0:
return "Incorrect input."
elif n==1:
return 0
elif n==2:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
|
def _format_rest_url(host: str, append: str = "") -> str:
"""Return URL used for rest commands."""
return f"http://{host}:8001/api/v2/{append}"
|
def combine_results(lst):
"""
combines list of results
ex: [[1, ["hey", 0]], [0,[]], [1, ["you", 1]]] -> [1, [["hey", 0],["you", 1]]]
"""
a = 0; b = []
for x in lst:
a = max(a, x[0])
if x[1] != []:
b += x[1]
return a, b
|
def ip_family(address):
"""Return the ip family for the address
:param: address: ip address string or ip address object
:return: the ip family
:rtype: int
"""
if hasattr(address, 'version'):
return address.version
if '.' in address:
return 4
elif ':' in address:
return 6
else:
raise ValueError("Invalid IP: {}".format(address))
|
def farthest_parseinfo(parseinfo):
"""As we might have tried several attempts of parsing different formats
we have several error reports from the respective parsers.
The parser that made it the farthest (line, column) probably
matched the format but failed anyway.
The error report of this least unsuccessful parser is the only
one being reported.
"""
line = parseinfo.get('error_line_number', -1)
column = parseinfo.get('error_column', -1)
prev = parseinfo.get('prev_parseinfo')
if prev is None:
return line, column, parseinfo
prevline, prevcolumn, prev = farthest_parseinfo(prev)
if (prevline, prevcolumn) > (line, column):
return prevline, prevcolumn, prev
else:
return line, column, parseinfo
|
def is_query_complete(query):
"""
returns indication as to if query includes a q=, cb.q=, or cb.fq
"""
if query.startswith("cb.urlver="):
return True
if query.startswith("q=") or \
query.startswith("cb.q=") or \
query.startswith("cb.fq="):
return True
return False
|
def remove_inp_from_splitter_rpn(splitter_rpn, inputs_to_remove):
"""
Remove inputs due to combining.
Mutates a splitter.
Parameters
----------
splitter_rpn :
The splitter in reverse polish notation
inputs_to_remove :
input names that should be removed from the splitter
"""
splitter_rpn_copy = splitter_rpn.copy()
# reverting order
splitter_rpn_copy.reverse()
stack_inp = []
stack_sgn = []
from_last_sign = []
for (ii, el) in enumerate(splitter_rpn_copy):
# element is a sign
if el == "." or el == "*":
stack_sgn.append((ii, el))
from_last_sign.append(0)
# it's an input but not to remove
elif el not in inputs_to_remove:
if from_last_sign:
from_last_sign[-1] += 1
stack_inp.append((ii, el))
# it'a an input that should be removed
else:
if not from_last_sign:
pass
elif from_last_sign[-1] <= 1:
stack_sgn.pop()
from_last_sign.pop()
else:
stack_sgn.pop(-1 * from_last_sign.pop())
# creating the final splitter_rpn after combining
remaining_elements = stack_sgn + stack_inp
remaining_elements.sort(reverse=True)
splitter_rpn_combined = [el for (i, el) in remaining_elements]
return splitter_rpn_combined
|
def lcm(x, y):
"""This function takes two integers and returns the L.C.M.
Args:
x:
y:
"""
# choose the greater number
if x > y:
greater = x
else:
greater = y
while True:
if (greater % x == 0) and (greater % y == 0):
lcm = greater
break
greater += 1
return lcm
|
def split_channels(rgb):
"""
Split an RGB color into channels.
Take a color of the format #RRGGBBAA (alpha optional and will be stripped)
and convert to a tuple with format (r, g, b).
"""
return (
float(int(rgb[1:3], 16)) / 255.0,
float(int(rgb[3:5], 16)) / 255.0,
float(int(rgb[5:7], 16)) / 255.0
)
|
def contains(word, tiles):
"""
Takes two lists of a string.
First checks if each letter in the word
is in the tile set. If true then it will
check each letter in the tile, removing
it from the word and if at the end the
word is a blank list it will return true.
TBH, it's probably not perfect, but it's
passed all the tests so far...
"""
word = list(word)
if [x for x in word if x in tiles] == word:
for c in tiles:
try:
word.remove(c)
except:
pass
if word == []:
return True
return False
|
def bleach_name(name):
"""
Make a name safe for the file system.
@param name: name to make safe
@type name: L{str}
@return: A safer version of name
@rtype: L{str}
"""
assert isinstance(name, str)
name = name.replace("\x00", "_")
name = name.replace("/", "_")
name = name.replace("\\", "_")
name = name.replace("#", "_")
name = name.replace("?", "_")
name = name.replace("&", "_")
name = name.replace("=", "_")
name = name.replace(":", "_")
return name
|
def remove_dupl(a_list):
"""
Remove duplicates from a list and returns the list
:return: the list with only unique elements
"""
return list(dict.fromkeys(a_list))
|
def build_version(release_version: str) -> str:
"""Given 'X.Y.Z[-rc.N]', return 'X.Y.Z'."""
return release_version.split('-')[0]
|
def minsample(population, k, randomize=1):
"""Samples upto `k` elements from `population`, without replacement.
Equivalent to :func:`random.sample`, but works even if ``k >= len(population)``.
In the latter case, it samples all elements (in random order)."""
if randomize:
from random import sample
return sample(population, min(k, len(population)))
return population[:k]
|
def stop_worker(versionId: str) -> dict:
"""
Parameters
----------
versionId: str
"""
return {"method": "ServiceWorker.stopWorker", "params": {"versionId": versionId}}
|
def last_common_item(xs, ys):
"""Search for index of last common item in two lists."""
max_i = min(len(xs), len(ys)) - 1
for i, (x, y) in enumerate(zip(xs, ys)):
if x == y and (i == max_i or xs[i+1] != ys[i+1]):
return i
return -1
|
def lychrel(n: int):
"""
A test for lychrel numbers
candidates in base 10
capping at 10,000
"""
cap, i, numb = 10000, 0, n
while i < cap:
if numb == int(str(numb)[::-1]):
return i
else:
numb = numb+int(str(numb)[::-1])
i += 1
return True
|
def flatten_modules_to_line(modules):
"""Flatten modules dictionary into a line.
This line can then be used in fc_statements to add module info.
The flattend line looks like:
module ":" symbol [ "," symbol ]*
[ ";" module ":" symbol [ "," symbol ]* ]
Parameters
----------
modules : dictionary of dictionaries:
modules['iso_c_bindings'] = ['C_INT', ...]
"""
if modules is None:
return None
line = []
for mname, symbols in modules.items():
line.append("{}:{}".format(mname, ",".join(symbols)))
return ";".join(line)
|
def _get_object_by_type(results, type_value):
"""Get object by type.
Get the desired object from the given objects
result by the given type.
"""
return [obj for obj in results
if obj._type == type_value]
|
def get_max_day_events(events):
""" return the maximum events count in one day over all the events given """
events_count = {}
if len(events) == 0:
return 0
for event in events:
if not events_count.get(event.date_time_start.date()):
events_count[event.date_time_start.date()] = 1
else:
events_count[event.date_time_start.date()] += 1
return max(events_count.values())
|
def solve(captcha):
"""Solve captcha.
:input: captcha string
:return: sum of all paired digits that match
>>> solve('1212')
6
>>> solve('1221')
0
>>> solve('123425')
4
>>> solve('123123')
12
>>> solve('12131415')
4
"""
a = len(captcha) // 2
return sum(int(x) for x, y in
zip(captcha, captcha[a:] + captcha[:a]) if x == y)
|
def _is_text(shape):
""" Checks if this shape represents text content; a TEXT_BOX """
return shape.get('shapeType') == 'TEXT_BOX' and 'text' in shape
|
def gassian_distribution(x,scale=1,mean=10,sigma=2):
"""Returns Gaussian distribution evaluated over 'x' according to 'scale',
'mean', and 'sigma' parameters."""
from numpy import exp,pi,sqrt
return scale*(1/(sigma*sqrt(2*pi)))*exp(-(x-mean)**2/(2*sigma**2))
|
def build_query_data(result):
"""
Input: result: object of type main.result
Output: result in the form of a list of parameters for an SQL query
"""
params = []
for attribute in result:
# tags and groups are added separately
if attribute[0] != "tags" and attribute[0] != "groups":
params.append(attribute[1])
return params
|
def listr(s):
"""'x,x,x'string to list"""
return [ss for ss in s.split(',') if ss]
|
def is_not_false_str(string):
"""
Returns true if the given string contains a non-falsey value.
"""
return string is not None and string != '' and string != 'false'
|
def get_cls_import_path(cls):
"""Return the import path of a given class"""
module = cls.__module__
if module is None or module == str.__module__:
return cls.__name__
return module + '.' + cls.__name__
|
def seconds_to_ui_time(seconds):
"""Return a human-readable string representation of the length of
a time interval given in seconds.
:param seconds: the length of the time interval in seconds
:return: a human-readable string representation of the length of
the time interval
"""
if seconds >= 60 * 60 * 24:
return "%d day(s) %d:%02d:%02d" % (seconds / (60 * 60 * 24),
(seconds / (60 * 60)) % 24,
(seconds / 60) % 60,
seconds % 60)
if seconds >= 60 * 60:
return "%d:%02d:%02d" % (seconds / (60 * 60), (seconds / 60) % 60,
(seconds % 60))
return "%02d:%02d" % ((seconds / 60), seconds % 60)
|
def init(client, **kwargs):
"""
:param client:
:param kwargs:
:return:
"""
global g_client
g_client = client
return True
|
def makeSiteWhitelist(jsonName, siteList):
"""
Provided a template json file name and the site white list from
the command line options; return the correct site white list based
on some silly rules
"""
if 'LHE_PFN' in jsonName:
siteList = ["T1_US_FNAL"]
print("Overwritting SiteWhitelist to: %s" % siteList)
elif 'LHE' in jsonName or 'DQMHarvest' in jsonName:
siteList = ["T2_CH_CERN"]
print("Overwritting SiteWhitelist to: %s" % siteList)
return siteList
|
def crossProduct(list1, list2):
"""
Returns all pairs with one item from the first list and one item from
the second list. (Cartesian product of the two lists.)
The code is equivalent to the following list comprehension:
return [(a, b) for a in list1 for b in list2]
but for easier reading and analysis, we have included more explicit code.
"""
answer = []
for a in list1:
for b in list2:
answer.append ((a, b))
return answer
|
def curate_url(url):
""" Put the url into a somewhat standard manner.
Removes ".txt" extension that sometimes has, special characters and http://
Args:
url: String with the url to curate
Returns:
curated_url
"""
curated_url = url
curated_url = curated_url.replace(".txt", "")
curated_url = curated_url.replace("\r", "") # remove \r and \n
curated_url = curated_url.replace("\n", "") # remove \r and \n
curated_url = curated_url.replace("_", ".")
# remove "http://" and "/" (probably at the end of the url)
curated_url = curated_url.replace("http://", "")
curated_url = curated_url.replace("www.", "")
curated_url = curated_url.replace("/", "")
return curated_url
|
def player_has_missed_games(game_being_processed, cur_pfr_game):
"""
Function that checks if the player has missing games
:param game_being_processed: Game (by week) we are processing
:param cur_pfr_game: Game (by week) we are on for the player
:return: Bool
"""
if game_being_processed == cur_pfr_game:
return False
return True
|
def replicate_multilabel_document(document_tuple):
"""
Takes a document and a set of labels and returns multiple copies of that document - each with a single label
For example, if we pass ('foo', ['a', 'b']) to this function, then it will return
[ ('foo', 'a'), ('foo', 'b') ]
:param document_tuple: (document, array_of_labels)
:return: array of (document, label) pairs
"""
document_contents, labels = document_tuple
single_label_documents = []
for label in labels:
single_label_documents.append((document_contents, label))
return single_label_documents
|
def issues2dict(issues):
"""Convert a list of issues to a dict, keyed by issue number."""
idict = {}
for i in issues:
idict[i['number']] = i
return idict
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.