content stringlengths 42 6.51k |
|---|
def fake_download(server):
"""Mock out download from server, such that connect works offline"""
return "Test Stub", [] |
def read_markdown(raw_md):
""" Reads the raw MarkDown and return the table and callback strings """
read_table = False
read_callback = False
data = []
data_callback = []
for line in raw_md.split(b'\n'):
line = line.decode('UTF-8')
if line == '| Option | Data-Attr | Defaults | Typ... |
def is_valid(point_x, point_y, grid, width, height):
"""see if a point is valid"""
if not grid[int(point_y)][int(point_x)]:
return False
if point_y < 0 or point_x < 0:
return False
if point_y > height or point_x > width:
return False
return True |
def undo_move(board, col, piece):
"""removes the topmost piece from that column(undoing move)"""
for row in range(6):
if board[row][col] == piece:
board[row][col] = " "
break
return board |
def _urljoin(*args):
"""
Joins given arguments into a url. Both trailing and leading slashes are
stripped before joining.
"""
return "/".join(map(lambda x: str(x).strip("/"), args)) + "/" |
def cm2inch(*values):
"""Convert from centimeter to inch
Parameters
----------
*values
Returns
-------
tuple
Examples
--------
>>> cm2inch(2.54, 5.08)
(1.0, 2.0)
"""
return tuple(v / 2.54 for v in values) |
def _evaluate_features(features_name: list, features_index: list, config_features_available: bool):
"""
This ensures that (1) if feature names are provided in the config file, one and only one of the
arguments, `features_name` or `features_index`, might be given, and (2) if feature names are
NOT provide... |
def assure_list(s):
"""Given not a list, would place it into a list. If None - empty list is returned
Parameters
----------
s: list or anything
"""
if isinstance(s, list):
return s
elif s is None:
return []
else:
return [s] |
def emoji_remove_underscope(text: str) -> str:
"""cleans text from underscops in emoji expressions and <> in annotations"""
tokens = []
for token in text.split():
if len(token) > 3 and '_' in token:
token = token.replace('_', ' ')
if token[0] == '<' and token[-1] == '>':
... |
def capitalize_or_join_words(sentence):
"""
If the given sentence starts with *, capitalizes the first and last letters of each word in the sentence,
and returns the sentence without *.
Else, joins all the words in the given sentence, separating them with a comma, and returns the result.
For exampl... |
def valid_statement(source):
""" Is source a valid statement?
>>> valid_statement('x = 1')
True
>>> valid_statement('x = print foo')
False
"""
try:
compile(source, '', 'single')
return True
except SyntaxError:
return False |
def applyRule(x):
"""
x: an int
output: an int after applying the rule
"""
if x % 2 is 0: # x is even
return int(x/2)
return int(3*x+1) |
def user_pub(users):
"""User jbenito (restricted/restricted)."""
return users["pub"] |
def wraparound_calc(length, gran, minLen):
"""
HELPER FUNCTION
Computes the number of times to repeat a waveform based on
generator granularity requirements.
Args:
length (int): Length of waveform
gran (int): Granularity of waveform, determined by signal generator class
minLe... |
def calculate_from_string(math_string):
"""Solve equation from string, using "calculate_mathematical_expression" function"""
divided_str = math_string.split(" ")
num1 = float(divided_str[0])
num2 = float(divided_str[2])
sgn = divided_str[1]
if sgn == "+":
return num1 + num2
elif sgn ... |
def _is_hex(content):
"""
Make sure this is actually a valid hex string.
:param content:
:return:
"""
hex_digits = '0123456789ABCDEFabcdef'
for char in content:
if char not in hex_digits:
return False
return True |
def decode_bytes(data):
"""
Helper function to decode bytes into string, I think it ends up being called per character
"""
lines = ""
try:
lines = data.decode("ascii")
except UnicodeDecodeError as e:
try:
lines = data.decode("utf-8")
# last option: try to deco... |
def get_valid_post_response(data):
"""
Returns success message correct processing of post/get request
:param str data: message
:return: response
:rtype: object
"""
response = {"status": 201, "message": "Created", "data": data}
return response |
def my_lcs(string, sub):
"""
Calculates longest common subsequence for a pair of tokenized strings
:param string : list of str : tokens from a string split using whitespace
:param sub : list of str : shorter string, also split using whitespace
:returns: length (list of int): length of the longest co... |
def makescalar(origlist):
"""Recursive function to make all elements of nested lists into floats.
To accommodate array inputs, all the functions here first broadcast to
numpy arrays, generating nested lists of arrays. When the inputs are
floats, these 0-d arrays should be cast back into floats. This fu... |
def removeMacColons(macAddress):
""" Removes colon character from Mac Address """
return macAddress.replace(':', '') |
def parse_apg_url(apg_url):
"""Return the method, url and browser from an apg_url."""
method = apg_url.split("/apg/")[1].split("/?url=")[0]
url = apg_url.split("/?url=")[1].split("&browser")[0]
try:
browser = apg_url.split("&browser=")[1].split("&")[0]
except IndexError:
browser = No... |
def insert_ordered(value, array):
"""
This will insert the value into the array, keeping it sorted, and returning the
index where it was inserted
"""
index = 0
# search for the last array item that value is larger than
for n in range(0,len(array)):
if value >= array[n]: i... |
def rivers_with_station(stations):
"""Given list of stations (MonitoringStation object), return the
names of the rivers that are being monitored"""
# Collect all the names of the rivers in a set to avoid duplicate entries
rivers = {station.river for station in stations}
# Return a list for conveni... |
def translate_rich_to_termcolor(*colors) -> tuple:
"""
Translate between rich and more_termcolor terminology.
This is probably prone to breaking.
"""
_colors = []
for c in colors:
_c_list = []
### handle 'bright'
c = c.replace('bright_', 'bright ')
### handle 'on... |
def sort_data_by_cloud(data):
"""
sort_data_by_cloud
data: list of dictionaries
one dictionary per PanDA schedresource (computingsite)
keys:
cloud
computingsite
and a bunch of ot... |
def _format_input_label(input_label):
""" Formats the input label into a valid configuration. """
return {
'name': input_label['name'],
'color': (input_label['color'][1:] if input_label['color'].startswith('#') else input_label['color']),
'description': input_label['description'] if 'des... |
def rhonfw(re,alpha):
"""
NAME: rhonfw
PURPOSE: Calculate the ratio of the NFW and soliton sections.
USAGE: x = rhonfw(re,alpha)
ARGUMENTS: alpha is a positive parameter,
re is the transition radius.
RETURNS: The value of the ratio of the sections.
WRITTEN: Antonio Herr... |
def get_ip_prefix_from_adapters(local_ip, adapters):
"""Find the network prefix for an adapter."""
for adapter in adapters:
for ip_cfg in adapter.ips:
if local_ip == ip_cfg.ip:
return ip_cfg.network_prefix |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
if type(input_list)!=list:
return "Inappropriate input type"
next0,next2 = 0, len(input_list)-1 # helper indice... |
def get_numeric_log_level(log_level):
"""Return a number that will calculate to the verbosity level"""
if log_level.lower() == "debug":
return 4
elif log_level.lower() == "info":
return 3
elif log_level.lower() == "warning":
return 2
elif log_level.lower() == "error":
... |
def get_data_view_status(data_view_id):
"""
URL for retrieving the statuses of all services
associated with a data view.
:param data_view_id: The ID of the desired data views
:type data_view_id: str
"""
return "data_views/{}/status".format(data_view_id) |
def my_location(state):
"""
Get the location of the current player.
:param state: The current game state.
:returns: tuple (x, y)
"""
return state['gladiators'][state['current_player']]['pos'] |
def bbox_hflip(bbox, rows, cols):
"""Flip a bounding box horizontally around the y-axis."""
x_min, y_min, x_max, y_max = bbox
return [1 - x_max, y_min, 1 - x_min, y_max] |
def predict_score(predicts, actuals):
"""
Find the number of correct cell predictions.
:param predicts: a list of predictions.
:param actuals: a list of actual cells.
:return: # correct predictions, # cells
"""
len_preds = len(predicts)
len_actuals = len(actuals)
shorter_len = min(le... |
def mean(container):
"""Averages all elements in container
Args:
container: a container of sum()able elements
Returns:
The mean value of all elements
"""
return sum(container)/len(container) |
def fibonacci(number):
""" Returns True if number is fibonacci """
if number == 1:
return True
f1 = 1
f2 = 2
while f2 < number:
f3 = f1 + f2
f1 = f2
f2 = f3
return f2 == number |
def spCheck(diffs, sp_buf):
"""Quick function to check if events land within the spatial window."""
checks = [e for e in diffs if abs(e) < sp_buf]
if any(checks):
check = True
else:
check = False
return check |
def indent(level) :
"""Return indentation string for specified level"""
x = ""
for i in range(0, level) : x += " " # FIXME : make this stuff faster
return x |
def _remove_device_types(name, device_types):
"""Strip device types from a string.
August stores the name as Master Bed Lock
or Master Bed Door. We can come up with a
reasonable suggestion by removing the supported
device types from the string.
"""
lower_name = name.lower()
for device_t... |
def validate_gateway_response_type(response_type):
""" Validate response type
:param response_type: The GatewayResponse response type
:return: The provided value if valid
"""
valid_response_types = [
"ACCESS_DENIED",
"API_CONFIGURATION_ERROR",
"AUTHORIZER_FAILURE",
"A... |
def get_comp_pairs(mut_ids):
"""Get pairs of compensated IDs."""
ans = []
if len(mut_ids) == 2:
pair = (mut_ids[0], mut_ids[1])
ans.append(pair)
else:
pair_1 = (mut_ids[0], mut_ids[1])
pair_2 = (mut_ids[1], mut_ids[2])
ans.append(pair_1)
ans.append(pair_2)... |
def f90str(s):
"""Convert string repr of Fortran string to Python string."""
assert type(s) == str
f90quotes = ["'", '"']
if s[0] in f90quotes and s[-1] in f90quotes:
return s[1:-1]
raise ValueError |
def segregate(str):
"""3.1 Basic code point segregation"""
base = bytearray()
extended = set()
for c in str:
if ord(c) < 128:
base.append(ord(c))
else:
extended.add(c)
extended = sorted(extended)
return bytes(base), extended |
def find( s, target, i=0 ):
"""Version fo find which returns len( s ) if target is not found"""
result = s.find( target, i )
if result == -1: result = len( s )
return result |
def swap(s):
"""Swaps ``s`` according to GSM 23.040"""
what = s[:]
for n in range(1, len(what), 2):
what[n - 1], what[n] = what[n], what[n - 1]
return what |
def not_roca(version):
"""ROCA affected"""
return not ((4, 2, 0) <= version < (4, 3, 5)) |
def getBetween(myString, startChunk, endChunk):
"""
returns a string between two given chunks.
@param myString
@param startChunk: substring that bounds the result string from left
@param startChunk: substring that bounds the result string from right
>>> getBetween('teststring', 'st','in')
'... |
def parabolic(a, x):
"""
Parabolic fit function.
:param a: Coefficients array of length 3
:param x: free parameter
:return: float
"""
return a[0] + a[1] * x + a[2] * x ** 2 |
def D_c_to_D_a(D_c, redshift):
"""calculate the angular diameter distance (D_a) from comoving distance (D_c) and redshift (
redshift)"""
return D_c/(1 + redshift) |
def padNumber(number, pad):
"""pads a number with zeros
"""
return ("%0" + str(pad) + "d") % number |
def read_dficts_coords_to_details(dficts, dficts_details, calib=False):
"""
Parsable details:
1. read test coords to get test details:
1.1 measurement volume: z min, z max
1.2 # of particles: p_num
:param dficts:
:param dficts_details:
:return:
"""
for name,... |
def hmean(a, b):
"""Return the harmonic mean of two numbers."""
return float(2*a*b) / (a + b)
# return harmonic_mean([a, b]) |
def _get_output_filename(dataset_dir, split_name):
"""Creates the output filename.
Args:
dataset_dir: The directory where the temporary files are stored.
split_name: The name of the train/test split.
Returns:
An absolute file path.
"""
return '%s/mnist_artificial_%s.tfrecord' % (dataset_dir, spl... |
def limit_length(s, length):
""" Add ellipses to overly long strings """
if s is None:
return None
ELLIPSES = '...'
if len(s) > length:
return s[:length - len(ELLIPSES)] + ELLIPSES
return s |
def num_from_str(string, base=0):
"""
Accept a string.
Return as an integer if possible,
else as a float,
else raise.
"""
try:
return int(string, base=base)
except ValueError:
return float(string) |
def find_index(segmentation, stroke_id):
"""
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 0)
0
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 1)
0
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 5)
2
>>> find_index([[0, 1, 2], [3, 4], [5, 6, 7]], 6)
2
"""
for i, symbol in en... |
def argmin_list(seq, func):
""" Return a list of elements of seq[i] with the lowest
func(seq[i]) scores.
>>> argmin_list(['one', 'to', 'three', 'or'], len)
['to', 'or']
"""
best_score, best = func(seq[0]), []
for x in seq:
x_score = func(x)
if x_score < best_scor... |
def build_repository(pharses):
"""
Build the bible repository as a dict from identifier to context
Jhn 3:10 --> text in John chapter 3 pharse 10
"""
repository = {}
for pharse in pharses:
book, _, other = pharse.partition(' ')
locator, _, context = other.partition(' ')
re... |
def datetime64_(name="date", format="%Y-%m-%d"):
"""Return a date category with format"""
return "datetime64(" + name + "," + format + ")" |
def nested_map(x, f):
"""Map the function f to the nested structure x (dicts, tuples, lists)."""
if isinstance(x, list):
return [nested_map(y, f) for y in x]
if isinstance(x, tuple):
return tuple([nested_map(y, f) for y in x])
if isinstance(x, dict):
return {k: nested_map(x[k], f) for k in x}
retu... |
def deserialize_utf8(value, partition_key):
"""A deserializer accepting bytes arguments and returning utf-8 strings
Can be used as `pykafka.simpleconsumer.SimpleConsumer(deserializer=deserialize_utf8)`,
or similarly in other consumer classes
"""
# allow UnicodeError to be raised here if the decodin... |
def common_neighbors(set_one: list, set_two: list) -> int:
"""
Calculate Common neighbors score for input lists
:param set_one: A list of graph nodes -> part one
:param set_two: A list of graph nodes -> part two
:return: Common neighbours score
"""
return len(set(set_one) & set(set_two)) |
def isSuffixOf(xs, ys):
"""
isSuffixOf :: Eq a => [a] -> [a] -> Bool
The isSuffixOf function takes two lists and returns True iff the first list
is a suffix of the second. The second list must be finite.
"""
return xs == ys[-len(xs):] |
def step(nodes, outputs, edges):
"""Return updated state in the form of a collection
of nodes, a collection of outputs, and a collection
of edges, given a collection of nodes, a collection
of outputs, and a collection of edges.
A node only propagates values if it has two values.
Parameters
... |
def dict_repr(obj):
"""
Creates an unambiguous and consistent representation of a dictionary.
Args:
obj: The dictionary to produce the representation of
Returns:
The string representation
"""
result = '{'
for key in sorted(obj):
elem = obj[key]
if isinstance... |
def add(curvelist):
"""
Add one or more curves.
>>> curves = pydvif.read('testData.txt')
>>> c = pydvif.add(curves)
:param curvelist: The list of curves
:type curvelist: list
:returns: curve -- the curve containing the sum of the curves in curvelist
"""
numcurves = len(curvelist)... |
def build_ex(config, functions):
"""Additional BIOS build function
:param config: The environment variables to be used in the build process
:type config: Dictionary
:param functions: A dictionary of function pointers
:type functions: Dictionary
:returns: config dictionary
:rtype: Dictionary... |
def convert_str_to_int(str_list, keys): # converts labels from string to intege
""""converts string to integer per appliance dictionary"""
list_int = []
for i in str_list:
list_int.append(keys[i])
return list_int |
def get_sample(partition, index):
"""retrieve the sample name
"""
# para partition: which partition, train/dev/test
# para index: the index of sample
if index < 0:
print("\nINCORRECT INDEX INPUT")
return
sample_name = ''
if partition == 'train':
if index > 104:
... |
def comb(n, k, combs={}):
"""Combination nCk with memo."""
if k > n - k:
k = n - k
if k == 0:
return 1
if k == 1:
return n
if (n, k) in combs:
return combs[n, k]
num = den = 1
for i in range(k):
num *= n - i
den *= i + 1
res = num // den
... |
def pending_order(order_list, period):
"""Return the order that arrives in actual period"""
indices = [i for i, order in enumerate(order_list) if order.sent]
sum = 0
for i in indices:
if period - (i + order_list[i].lead_time + 1) == 0:
sum += order_list[i].quantity
return sum |
def _prefix(str):
"""Prefixes a string with an underscore.
Args:
str (str): The string to prefix.
Returns:
str: The prefixed string.
"""
return str if str.startswith("_") else "_%s" % str |
def word_for_char(X, character):
"""
Diagnostic function, collect the words where a character appears
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:param character:
:return:
>>> word_for_char( [['the', 'quick', 'brown'],['how', 'now', 'cow']], '... |
def distinct(collection: list) -> int:
"""
Checks for the distinct values in a collection and returns the count
Performs operation in nO(nlogn) time
:param collection: Collection of values
:returns number of distinct values in the collection
"""
length = len(collection)
if length == 0:
... |
def lib_utils_oo_list_to_dict(lst, separator='='):
""" This converts a list of ["k=v"] to a dictionary {k: v}.
"""
kvs = [i.split(separator) for i in lst]
return {k: v for k, v in kvs} |
def _get_port_to_string(iface):
"""Simple helper which allows to get string representation for interface.
Args:
iface(list): Which IXIA interface to use for packet sending (list in format [chassis_id, card_id, port_id])
Returns:
str: string in format "chassis_id/card_id/port_id"
"""
... |
def is_number(text):
"""
Checking if the text is a number
:param text: text we want to examine
:type text: str
:return: whether this is a number or not
:rtype: bool
"""
try:
float(text.strip())
except ValueError:
return False
return True |
def netstring_from_buffer(buff):
"""
Reads a netstring from a buffer, returning a pair containing the
content of the netstring, and all unread data in the buffer.
Note that this assumes that the buffer starts with a netstring - if it
does not, then this function returns ``(b'', buff)``.
>>... |
def _get_source_url(pypi_name, filename):
"""get the source url"""
# example: https://files.pythonhosted.org/packages/source/u/ujson/ujson-1.2.3.tar.gz
return 'https://files.pythonhosted.org/packages/source/{}/{}/{}'.format(
pypi_name[0], pypi_name, filename) |
def long_substr(data):
""" http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python """
substr = ''
if len(data) > 1 and len(data[0]) > 0:
for i in range(len(data[0])):
for j in range(len(data[0]) - i + 1):
if j > len(substr) a... |
def _extract_match_id(match_json):
"""
Extract the match_id from json response.
{
"matches": [
{
"id": "0000...",
"match_id": 1313,
"similarity": "001000"
}
]
}
"""
matches = match_json.get('matches', [])
... |
def sorted_names(queue):
"""Sort the names in the queue in alphabetical order and return the result.
:param queue: list - names in the queue.
:return: list - copy of the queue in alphabetical order.
"""
new_queue = queue[:]
new_queue.sort()
return new_queue |
def title(text, level=0):
"""Given a title, format it as a title/subtitle/etc."""
return '\n' + text + '\n' + '=-~_#%^' [level] * len(text) + '\n\n' |
def price_change_color_red_green(val: str) -> str:
"""Add color tags to the price change cell
Parameters
----------
val : str
Price change cell
Returns
-------
str
Price change cell with color tags
"""
val_float = float(val.split(" ")[0])
if val_float > 0:
... |
def _no_spaces(string, replace_with='_'):
"""
Remove whitespace from a string, replacing chunks of whitespace with a
particular character combination (replace_with, default is underscore)
"""
return replace_with.join(string.split()) |
def duplicate_check(file):
"""Checks the potfiles for duplicate lines/hashes"""
seen = set()
duplicates = 0
try:
with open(file, "r") as source:
line = source.readline()
while line is not '':
if line in seen:
duplicates += 1
... |
def _fmt_unique_name(appname, app_uniqueid):
"""Format app data into a unique app name.
"""
return '{app}-{id:>013s}'.format(
app=appname.replace('#', '-'),
id=app_uniqueid,
) |
def translate_list_02(char_list):
"""Working on a list.
CPU-acceleration with Numba."""
num_list = []
for word in char_list:
if word == 'A':
num = 1
elif word == 'B':
num = 2
elif word == 'C':
num = 3
elif word == 'D':
num... |
def tag_handler(tag, separator, post_html):
"""
This function switches from a specific {tag} to a specific
markdown {separator}
Example 1: <em>text</em> => *text*
Example 2: <strong>text</strong> => **text**
"""
old_tag = tag
close_tag = "</{0}>".format(tag)
tag = "<{0}".format(tag)... |
def calc_tcp(gamma, td_tcd, eud):
"""Tumor Control Probability / Normal Tissue Complication Probability
1.0 / (1.0 + (``td_tcd`` / ``eud``) ^ (4.0 * ``gamma``))
Parameters
----------
gamma : float
Gamma_50
td_tcd : float
Either TD_50 or TCD_50
eud : float
equivalen... |
def identical_aa(x,y):
"""
Compare two amino acids
:param x:
:param y:
:return:
"""
if x == y:
return True
if x == 'X' or y == 'X':
return True
return False |
def run_program(codes, noun = None, verb = None):
"""
>>> run_program([1, 0, 0, 0, 99])
[2, 0, 0, 0, 99]
>>> run_program([2, 3, 0, 3, 99])
[2, 3, 0, 6, 99]
>>> run_program([2, 4, 4, 5, 99, 0])
[2, 4, 4, 5, 99, 9801]
>>> run_program([1, 1, 1, 4, 99, 5, 6, 0, 99])
[30, 1, 1, 4, 2, 5, 6... |
def mergeuniques(xs, ys):
""" merge lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
xs.sort() # sort clause unneeded if lists already sorted (as in instructions), but added for generalising
ys.sort()
while True:
if xi >= len(xs): # If xs list is finish... |
def matrix_matrix_product(A, B):
"""Compute the matrix-matrix product AB as a list of lists."""
m, n, p = len(A), len(B), len(B[0])
return [[sum([A[i][k] * B[k][j] for k in range(n)])
for j in range(p) ]
for i in range(m) ] |
def project_use_silo(project_doc):
"""Check if templates of project document contain `{silo}`.
Args:
project_doc (dict): Project document queried from database.
Returns:
bool: True if any project's template contain "{silo}".
"""
templates = project_doc["config"].get("template") or ... |
def normalize_float(f):
"""Round float errors"""
if abs(f - round(f)) < .0000000000001:
return round(f)
return f |
def day_num(x):
"""function returning the next compass point in the clockwise direction"""
res = {"Sunday":0, "Monday":1, "Tuesday":2, "Wednesday":3, "Thursday":4,
"Friday":5, "Saturday":6}
ans = res.get(x, None)
return ans |
def teams(organization, no_teams, teams_and_members):
"""A fixture that returns a list of teams, which are all returned by the
github.Organization.Organization.get_teams function."""
team_names = teams_and_members.keys()
for name in team_names:
organization.create_team(name, permission="push")
... |
def build_api_url(latitude: str, longitude: str) -> str:
"""
Build a URL to send to the API
:param latitude: A string representing the latitude
:param longitude: A string representing the longitude
:return: A formatted URL string
"""
url = "https://api.open-meteo.com/v1/forecast?"
url +=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.