content stringlengths 42 6.51k |
|---|
def bacon_strategy(score, opponent_score):
"""This strategy rolls 0 dice if that gives at least BACON_MARGIN points,
and rolls BASELINE_NUM_ROLLS otherwise.
>>> bacon_strategy(0, 0)
5
>>> bacon_strategy(70, 50)
5
>>> bacon_strategy(50, 70)
0
"""
"*** YOUR CODE HERE ***"
retu... |
def arg_type(arg):
"""Returns the type of argument, either "url" or "path".
Args:
arg (str): Either a URL to a GitHub repository or the system path to a project.
Returns:
The type of argument, either "url" or "path".
"""
return "url" if "github.com" in arg else "path" |
def solve_figure_horizontal_dimensions(ncols, subplot_width_in_inches, left_margin_in_inches, right_margin_in_inches, wspace):
"""
Determine horizontal figure dimensions from fixed subplot dimensions for
matplotlib.pyplot.subplots and matplotlib.pyplot.subplots_adjust.
Returns: fig_width_in_inches, lef... |
def convert_distance_to_probability(distances, a, b):
"""
convert (euclidean) distance in low-d into probability,
as a function of a, b params.
Parameters
----------
distances : float
euclidean sitances
a : int
the a/alpha UMAP parameter
b : int
the b/beta ... |
def device_quadruple(devstr):
"""
Validates Device-Parameter and returns a quadruple of a device
"""
import argparse
try:
elements = devstr.replace("(", "").replace(")", "").split(",")
cluster = int(0)
if elements.__len__() < 3 or elements.__len__() > 4:
raise arg... |
def mro_hasattr(cls: type, attr: str) -> bool:
"""Check if an attribute exists in a type's class hierarchy
Args:
cls (type): The type
attr (str): The attribute
Returns:
bool: True if has the attribute.
Raises:
TypeError: Not called on a type
"""
if not isinsta... |
def hamming_distance(s1: str, s2: str):
""" The Hamming distance between equal-length strings """
if len(s1) != len(s2):
return float('inf')
return sum(el1 != el2 for el1, el2 in zip(s1, s2)) |
def get_events_indices(eventcode, eventtypes):
"""
:param eventcode: list of event codes from operant conditioning file
:param eventtypes: list of event types to index
:return: list of indices of target events
"""
return [i for i, event in enumerate(eventcode) if event in eventtypes] |
def strip_moment(observable_key: str):
"""Convert a observable name to a base observable and a statistical moment"""
if observable_key.endswith("_std"):
moment = "std"
key = observable_key.rstrip("std").rstrip("_")
elif observable_key.endswith("_skew"):
moment = "skew"
key =... |
def color_complement(color):
"""
Calculate complement color.
:param color: given color (hex format)
:type color: str
:return: complement color (hex format) as str
"""
color = color[1:]
color = int(color, 16)
comp_color = 0xFFFFFF ^ color
comp_color = "#%06x" % comp_color
ret... |
def try_parse_int(possible_int):
"""Try to parse an int."""
try:
return int(possible_int)
except (TypeError, ValueError):
return 0 |
def _get(self, key, default=None):
"""
Return the value for key if key is in present, else default.
"""
try:
return self[key]
except KeyError:
return default |
def get_new_pair_info(illumina_name):
"""
take a filename from CASAVA 1.8 output and figure out whether it's the
first or second read (or single-end read) and return a tuple
(pair_index, second_file_name, new_output_name).
"""
end = illumina_name.find('.fastq')
if end == -1:
return N... |
def sumar( a, b):
"""sumar dos numeros a y b"""
z = a + b
return z |
def set_range(val, start, end):
"""States the range of movement."""
# determine the input vale is in the supplied range
return (val >= start and val <= end) |
def flatten_list(root):
"""Flatten the given list.
All the non-list elements would be aggregated to the root-level,
with the same order as they appear in the original list.
Parameters
----------
root : collections.Iterable[any]
The list to be flatten.
Returns
-------
list[... |
def fibonacci(n):
"""Calculates the nth fibonacci number
Args:
n (int): the fibonacci number to get (e.g. 3 means third)
Returns:
int: nth fibonacci number
"""
first = (0, 1)
if n in first:
return n
previous, current = first
for index in range(2, n + 1):
previ... |
def float_list_string(vals, nchar=7, ndec=3, nspaces=2, mesg='', left=0):
"""return a string to display the floats:
vals : the list of float values
nchar : [7] number of characters to display per float
ndec : [3] number of decimal places to print to
nspaces : [2] number of spa... |
def dtype_to_field_type(ty):
"""Simple converter that translates Pandas column types to data types for
Draco.
"""
if ty in ["float64", "int64"]:
return "number"
elif ty in ["bool"]:
return "boolean"
elif ty in ["object"]:
return "string"
elif ty in ["datetime64[ns]"]:... |
def int_to_digits(n,B=10,bigendian=False):
"""
Convert the integer n to its digits in base B
"""
n = abs(n)
D = []
while n != 0:
n,r = divmod(n,B)
D.append(r)
if bigendian:
return tuple(D)
else:
return tuple([i for i in reversed(D)]) |
def calc_period(start, end) -> int:
"""
Given two tuples for start and end hour, determine the number of hours
in the interval (inclusive of starting and ending hour).
:param start: A list of date (as integer) and hour (as integer in HHMM format with 00 for minutes)
:param end: (same)
:return: N... |
def _range_overlap(a_min, a_max, b_min, b_max):
"""Neither range is completely greater than the other
"""
return (a_min <= b_max) and (b_min <= a_max) |
def get_frequencies(file_size_hash):
"""Collect data on equi-size file groups.
This is not for user operation of this program. This is an optional
data collection for the programmer.
Results:
For each group of files that are of the same size in bytes:
Groups of less than 46 files each acc... |
def average(l):
"""The average value of a list"""
if len(l) == 0:
return 0
return sum(l)/len(l) |
def flate_pump_feed(F_mass, rho_F):
"""
Calculates the flow rate pump for Feed.
Parameters
----------
F_mass : float
The flow rate of Feed, [kg / s]
rho_F : float
The density of feed, [kg / m**3]
Returns
-------
flate_pump_feed : float
The flow rate pump for F... |
def expand_ref(json_obj, definition):
"""expand the $ref in json schema"""
if isinstance(json_obj, dict):
for key in list(json_obj.keys()):
if key == "$ref":
if json_obj[key].startswith("#/definitions/"):
concept = json_obj[key].split('/')[-1]
... |
def normalize_module_name(name):
"""
Convert module name reported by pytest to Python conventions.
This function strips the .py suffix and replaces '/' by '.', so that
'ham/spam.py' becomes 'ham.spam'.
"""
if name.endswith('.py'):
name = name[:-3]
return name.replace('/', '.') |
def is_close(val1, val2, tol=1e-6):
"""Shorthand for `abs(val2 - val1) < tol`."""
return abs(val2 - val1) < tol |
def prime_sieve(n):
"""
Return a list of all primes smaller than or equal to n.
This algorithm uses a straightforward implementation of the
Sieve of Eratosthenes. For more information, see
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Algorithmic details
-------------------
... |
def get_errno(exc):
""" Get the error code out of socket.error objects.
socket.error in <2.5 does not have errno attribute
socket.error in 3.x does not allow indexing access
e.args[0] works for all.
There are cases when args[0] is not errno.
i.e. http://bugs.python.org/issue6471
Maybe there ... |
def verify_boolean(flag, title):
"""
:type: str
:param flag: Boolean parameter to check
:type: str
:param title: Name of boolean parameter to print
:rtype: str
:return: Fix flag format
:raises: ValueError: invalid form
"""
if flag is None:
return None
flag = str(fl... |
def levenshtein(s1, s2):
"""Calculate the Levenshtein distance between two strings
Args:
s1 (str): first string
s2 (str): second string
Returns:
int: distance between s1 and s2
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len... |
def schedule_rule_pre_hook(rule: dict) -> dict:
"""Copy value for the value key over from alternative names."""
rule = rule.copy()
for key in ("v", "temp"):
if key in rule:
rule.setdefault("value", rule[key])
del rule[key]
return rule |
def containing(a: str, b: str) -> int:
"""Returns how many chars a contains of b."""
return sum([1 for c in b if c in a]) |
def _number(string):
"""Extracts an int from a string. Returns a 0 if None or an empty string was passed."""
if not string:
return 0
elif string == "":
return 0
else:
return int(string) |
def unravel(data, key):
"""Transforms {key:{another_key: values, another_key2: value2}} into
{key_another_key:value, key_another_key2:value}"""
for d in data:
values = d.pop(key)
for k, v in values.items():
d[key+'_'+k] = v
return data |
def const_bool(value):
"""Create an expression representing the given boolean value.
If value is not a boolean, it is converted to a boolean. So, for
instance, const_bool(1) is equivalent to const_bool(True).
"""
return ['constant', 'bool', ['{0}'.format(1 if value else 0)]] |
def turned_off_response(message):
"""Return a device turned off response."""
return {'requestId': message.get('requestId'), 'payload': {'errorCode': 'deviceTurnedOff'}} |
def order_pair(words: tuple) -> tuple:
"""
Ensure consistency ordering of pairs.
"""
# Sort alphabetically first to ensure consistency when pair is same length.
return tuple(sorted(sorted(words), key=len, reverse=True)) |
def find_first(arr, val):
""" Index of the first occurence of val in arr.
"""
i = 0
while i < len(arr):
if val == arr[i]:
return i
i += 1
raise Exception('val not found in arr') |
def _build_selpand(item, attributes):
"""
This method builds an expand or select term for an STA Query
:param item: string either expand or select
:param attributes: a list of strings that has to be expanded / selected
:return: the resulting select or expand-term
"""
selector = item + "="
... |
def _call(calls):
"""Make final call"""
final_call = ''
if calls['is_hiv'] == 'No':
final_call = 'NonHIV'
return final_call
if calls['deletion'] == 'Yes':
final_call = 'Large Deletion'
if calls['inversion'] == 'Yes':
final_call += ' with Internal Inversion'
... |
def produce_ids_h(entry):
"""generate code for a ID info entry (row of csv file)"""
component_id = entry["ID"]
component_name = entry["Component"]
return f"#define {component_name} {component_id}\n" |
def percent2float(x):
"""
Convert percent to float
"""
return float(x.strip('%'))/100 |
def compare_match(server_names, certificate_sans):
"""
Compares if the certificate would secure this domain
:param server_names: list of ServerName values
:param certificate_sans: list of SAN's that would be secured by the certificate
:return:
"""
matches = []
for server_name in server_n... |
def sanitize_choices(choices, choices_all):
"""Clean up a stringlist configuration attribute: keep only choices
elements present in choices_all, remove duplicate elements, expand '*'
wildcard while keeping original stringlist order.
"""
seen = set()
others = [x for x in choices_all if x not in c... |
def safe_version(*args, **kwargs) -> str:
"""
Package resources is a very slow load
"""
import pkg_resources
return pkg_resources.safe_version(*args, **kwargs) |
def get_policies_for_resource(cluster, indices, policies):
"""
Find policies that apply to a given resource.
cluster / boolean /
does the policy apply to the root resources
or calls that read about or affect the cluster
indices / list /
a simple list of index name that the polic... |
def get_offending_line(error_line: int, code: str) -> str:
"""Extracts the offending line"""
error_line -= 1
code_lines = code.splitlines()
offending_line = None
try:
offending_line = code_lines[error_line]
except IndexError:
offending_line = code_lines[-1]
return offendin... |
def day_num(num):
""" Get day from int """
if num == "Sunday":
return 0
elif num == "Monday":
return 1
elif num == "Tuesday":
return 2
elif num == "Wednesday":
return 3
elif num == "Thursday":
return 4
elif num == "Friday":
return 5
elif nu... |
def parse_prefill(arguments):
"""Parses ``-p/--prefill`` command line arguments.
:param list[string] arguments: all arguments given to -p/--prefill
:returns: dict with all command line answers
:rtype: dict
"""
retval = {}
for arg in arguments:
key, value = arg.split("=")
if ... |
def _find_human_readable_labels(synsets, synset_to_human):
"""Build a list of human-readable labels.
Args:
synsets: list of strings; each string is a unique WordNet ID.
synset_to_human: dict of synset to human labels, e.g.,
'n02119022' --> 'red fox, Vulpes vulpes'
Returns:
List o... |
def is_self_mapping_dict(dictionary) -> bool:
"""
Is the mathematical definition of a self mapping dictionary
"""
for key, values in dictionary.items():
for i in values:
if not i in dictionary:
return False
return True |
def test_db(tasks):
"""
Returns test DB components as tuples.
The test DB contains: 3 teams, 3 users per team, 2 tasks per user, 1 manager per team.
"""
teams = tasks[0]
employees = tasks[1]
managers = tasks[2]
task = tasks[3]
return teams, employees, managers, task |
def get_neighbours(x, y, thresh_shape):
"""Get direct neighbours for an x, y location in a square
Args:
x (int): x coord
y (int): y coord
thresh_shape ((int, int)): tuple containing square shape
Returns:
List: list of tuples with x,y coords
"""
x_lim, y_lim = thresh... |
def _get_day_of_year(arg):
"""
Get the day position in the year starting from 1
Parameters
----------
arg : tuple
Returns
-------
int with the correct day of the year starting from 1
"""
ml = [31,28,31,30,31,30,31,31,30,31,30,31]
if arg[0]%4==0:
... |
def triangle_shape(height):
"""return a triangle of x
Args:
height (int): number of stages
Returns:
str: triangle
"""
s = "x"
esp = " "
if height == 0:
return ""
return "\n".join(
[
(height - 1 - i) * esp + (2 * i + 1) * s + (height - 1 - i) ... |
def report(batch_size, epochs, lr, resize, model_name, back_bone, remark, scales):
"""
create the reporter dict, record important information in the experiment
"""
specs = {}
specs['model_name'] = model_name
specs['batch_size'] = batch_size
specs['training_epochs'] = epochs
specs... |
def but_her_emails(string=None,filename=None):
"""Extract email addresses from a string
or file."""
import re
if string is None:
with open("emails.txt",'r') as myfile:
string=myfile.read().replace('\n', '')
match = re.findall(r'[\w\.-]+@[\w\.-]+', string)
return match |
def nameToLabel(mname):
"""
Convert a string like a variable name into a slightly more human-friendly
string with spaces and capitalized letters.
@type mname: C{str}
@param mname: The name to convert to a label. This must be a string
which could be used as a Python identifier. Strings which d... |
def dist(a, b):
"""
>>> dist((1,1), (2,2))
2
>>> dist((1,1), (2,1))
1
>>> dist((1,1), (1,1))
0
>>> dist((3,5), (-1,-10))
19
"""
return abs(a[0] - b[0]) + abs(a[1] - b[1]) |
def get_job_id_from_url(url_path):
"""Given a smrtlink job url (e.g., https://smrtlink-alpha.nanofluidics.com:8243/sl/#/analysis/job/13695), return job id 13695"""
return url_path.split('/')[-1] |
def errorResult(errorCode, messsage=None):
"""Generate error result"""
messages = {
'INVALIDATE_CONTROL_ORDER': 'invalidate control order',
'SERVICE_ERROR': 'service error',
'DEVICE_NOT_SUPPORT_FUNCTION': 'device not support',
'INVALIDATE_PARAMS': 'invalidate params',
... |
def get_count_value(obj):
"""
Returns count of child objects from LLDB value.
:param lldb.SBValue obj: LLDB value object.
:return: Count of child objects from LLDB value.
:rtype: int | None
"""
# Passed None value.
if obj is None:
return None
# Return 0 if object has no val... |
def _get_int_from_big_endian_bytearray(array, offset):
""" Get an int from a byte array, using big-endian representation,\
starting at the given offset
:param array: The byte array to get the int from
:type array: bytearray
:param offset: The offset at which to start looking
:type offset: i... |
def lemmatize_sentence(sentence: dict, terms: dict):
"""
Lemmatize naf sentence
Args:
sentence: dict of sentence (naf)
terms: list of terms dict (naf)
Returns:
lemmatized sentences as string
"""
return [terms[term["id"]]["lemma"] for term in sentence["terms"]] |
def cost_function(observed_values, average_simulated_values):
"""cost function"""
score = 0
for obs, sim in zip(observed_values, average_simulated_values):
score += ((obs - sim) / obs)**2
return score |
def sorted_fields(fields):
""" recursively sort field lists to ease comparison """
recursed = [dict(field, fields=sorted_fields(field['fields'])) for field in fields]
return sorted(recursed, key=lambda field: field['id']) |
def PackStatKey(client_id, scope):
"""Helper to create a hashable dictionary key that can be json serialized.
Args:
client_id: String, possibly with spaces, of the domain issued a token.
scope: String with no spaces reflecting the scope of access granted.
Returns:
Single string key.
"""
return '... |
def sin_bias_from_e(e_field: float, thickness_sin: float) -> float:
"""
Estimates the bias in SiNx based on the value of the electric field and the thickness of the layer.
Parameters
----------
e_field: float
The electric field in the SiNx layer (V/cm)
thickness_sin: float
The t... |
def merge_caption(marker_dict):
"""Treat first value as a caption to the rest."""
values = list(marker_dict.values())
if not values:
return ''
elif len(values) == 1:
return values[0]
else:
return '{}: {}'.format(values[0], ' '.join(values[1:])) |
def fibonacci(num):
""" Calculate fibonacci number (iterative function)"""
nb1, nb2 = 0, 1
for nbr in range(2 ,num+1):
nb1, nb2 = nb2, nb1 + nb2
return nb2 |
def o_minimum(listy):
"""
Input: A list of numbers.
Output: The lowest number in the list, using min function.
"""
if listy != []:
return (min(listy)) |
def _get_session_auth_info(_helper_cfg):
"""This function parses session authentication information if found in the helper file.
.. versionchanged:: 2.2.0
Removed one of the preceding underscores in the function name
"""
_session_auth = {}
_session_info = ['username', 'password']
for _ke... |
def simpleqp_unquote(qs):
"""Simple unquote from quoted-printable style."""
esc = '='
hex = '0123456789ABCDEF'
out = []
i = iter(qs)
while True:
try:
c = next(i)
except StopIteration:
break
if c == esc:
try:
hh = next(i)... |
def make_list(value):
"""Return a list of items from a comma-separated string.
Surrounding whitespace will be stripped from the list items. If the
provided string is empty, an empty list will be returned. This function
will also accept the value None and return an empty list.
"""
if value is No... |
def disf_tags_from_easy_read(text):
"""List of disfluency tags from the inline easy read marked up utterances
"""
tags = []
for w in text.split():
tags.append(w[:w.rfind(">") + 1])
return [tag.replace("_", " ") for tag in tags] |
def uniquify(seq):
"""
Fast implimentation of a function to strip out non-unique entries in a Python list, but preserving list order.
Usage:
>>> print(uniquify( [1,4,2,4,7,2,1,1,1,'s','a',0.1] ) )
[1, 4, 2, 7, 's', 'a', 0.10000000000000001]
"""
seen = set()
seen_add = seen.ad... |
def annual_edition_for(title, notice):
"""Annual editions are published for different titles at different
points throughout the year. Find the 'next' annual edition"""
if title <= 16:
month = '01'
elif title <= 27:
month = '04'
elif title <= 41:
month = '07'
else:
... |
def strip_ml_tags(in_text):
"""Description: Removes all HTML/XML-like tags from the input text.
Inputs: s --> string of text
Outputs: text string without the tags
# doctest unit testing framework
>>> test_text = "Keep this Text <remove><me /> KEEP </remove> 123"
>>> strip_ml_tags(test_text)
'Keep this Text K... |
def reflect(cp, anchor):
"""
Reflect the point `cp` through the anchor.
"""
vec = (cp[0] - anchor[0], cp[1] - anchor[1])
neg = (-vec[0], -vec[1])
return (anchor[0] + neg[0], anchor[1] + neg[1]) |
def solution(X, A):
"""Find the earliest time that a frog can jump to position X.
In order to reach X, a leaf must be present at every position from 1 to X.
Args:
X (int): The position that the frog must reach.
A (list): A list of integers from 1 to X, where A[k] represents a leaf
... |
def camelize(key):
"""Convert a python_style_variable_name to lowerCamelCase.
Examples
--------
>>> camelize('variable_name')
'variableName'
>>> camelize('variableName')
'variableName'
"""
return ''.join(x.capitalize() if i > 0 else x
for i, x in enumerate(key.spli... |
def product(factors : list, default):
"""
factors is just a list of everything you are multiplying together
works like built-in sum function
takes a default by which to multiply everything
"""
p = default
for x in factors:
p *= x
return p |
def yandex_operation_is_success(data: dict) -> bool:
"""
:returns:
Yandex response contains status which
indicates that operation is successfully ended.
"""
return (
("status" in data) and
(data["status"] == "success")
) |
def uri_base(uri):
"""
Get the base URI from the supplied URI by removing any parameters and/or fragments.
"""
base_uri = uri.split("#", 1)[0]
base_uri = base_uri.split("?", 1)[0]
return base_uri |
def get_keyword_query(keyword):
"""
Generate the corresponding SQL Statement and SQL parameters for query the watchlist DB
:param keyword:
:return: the statement and statement parameters
"""
sql_parameters = [{'name': 'input_keyword', 'value': {'stringValue': "{0}".format(keyword)}}]
stateme... |
def get_attr_flows(results, key='variable_costs'):
"""
Return all flows of an EnergySystem for a given attribute,
which is not zero.
Parameters
----------
results : dict
Results dicionary of the oemof.solph optimisation including the
Parameters with key 'param'.
key : str
... |
def evacuate(parties):
"""Evacuates a senator."""
biggest_party = max(parties, key=parties.get)
parties[biggest_party] -= 1
return biggest_party |
def value_or_default(value, default):
"""
Returns the supplied value of it is non None, otherwise the supplied default.
"""
return value if value is not None else default |
def format_multuple_modules(modules):
"""
Forms the numbered output of modules from the list
:param list modules: list of modules paths
:return str:
"""
return '\n'.join(['{}. {}'.format(index, name) for index, name in enumerate(modules, 1)]) |
def natural_sort(l):
"""
Returns alphanumerically sorted input
#natural sort from the interwebs (http://stackoverflow.com/questions/11150239/python-natural-sorting)
"""
import re
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for ... |
def binary_to_hex(binary_string: str) -> str:
"""Convert binary string to hexadecimal string
Resulting hex will be uppercase
Args:
binary_string (str): Binary string
Returns:
str: Hexadecimal string
"""
return f"{int(binary_string, 2):x}".upper() |
def contains_stack_cookie_keywords(s):
""" check if string contains stack cookie keywords
Examples:
xor ecx, ebp ; StackCookie
mov eax, ___security_cookie
"""
if not s:
return False
s = s.strip().lower()
if "cookie" not in s:
return False
... |
def insertion_sort(arr):
"""
Insertion sort iteratively takes the next element in arr
and moves backward, placing it in the correct position
"""
for i in range(1, len(arr)):
curr = arr[i]
j = i-1
while j >= 0 and curr < arr[j] :
arr[j + 1] = arr[j]
... |
def index_to_row(index):
"""
Returns the row name of given 0-based index.
Parameters
----------
index : int
0-based row index.
Returns
-------
unicode
Row name.
Examples
--------
# Doctests skip for Python 2.x compatibility.
>>> index_to_row(0) # docte... |
def get_added_after(
fetch_full_feed, initial_interval, last_fetch_time=None, filter_args=None
):
"""
Creates the added_after param, or extracts it from the filter_args
:param fetch_full_feed: when set to true, will limit added_after
:param initial_interval: initial_interval if no
:param last_fe... |
def get_better_targ(targ_x, targ_y, base_dir):
"""
:param targ_x: the (base) target x-coordinate
:param targ_y: the (base) target y-coordinate
:param base_dir: the direction from the previous step (NESW)
:rtype: tuple
:return: (better x target, better y target)
"""
if base_dir == 180:
... |
def _merge_nics(management_network_id, *nics_sources):
"""Merge nics_sources into a single nics list, insert mgmt network if
needed.
nics_sources are lists of networks received from several sources
(server properties, relationships to networks, relationships to ports).
Merge them into a single list,... |
def truncate(data: str, length: int, append: str = "") -> str:
"""
Truncates a string to the given length\n
`data` The string to truncate\n
`length` The length to truncate to\n
`append` Text to append to the end of truncated string. Default: ''
"""
return (data[:length] + append) if len(data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.