content stringlengths 42 6.51k |
|---|
def Rule110(universe):
"""Performs a single iteration of the Rule 110 in a borderless universe."""
new = set()
for x in universe:
if x+1 not in universe: new.add(x)
if x-1 not in universe: new.add(x); new.add(x-1)
return new |
def _prefixed_config(config, prefix):
"""Returns a dictionary containing only items from the supplied dictionary `config` which start with `prefix`, also
converting the key to lowercase and removing that prefix from it.
_prefixed_config({'ONE': 1, 'MYPREFIX_TWO': 2}, 'MYPREFIX_') == {'two': 2}
"""
... |
def build_ec2_metrics(instances):
"""Build EC2 CPU Utilization metrics"""
metrics = []
for instance in instances:
metric = ["AWS/EC2", "CPUUtilization",
"InstanceId", instance.get('InstanceId')]
metrics.append(metric)
return metrics |
def _apply_probability(kmer, label, compare_label):
"""Compute binary probability of a label for a kmer.
Parameters
----------
kmer : int
Kmer count (assumes binary presence/absence (0, 1)).
label : str
Label value for a given kmer.
compare_label : str
Label value to ass... |
def bytes2set(b, delimiter=b'\x00', encoding='utf-8'):
"""Deserialize bytes into a set of unicode strings.
>>> int2byte(b'a\x00b\x00c')
{u'a', u'b', u'c'}
"""
if not b:
return set()
list_ = b.split(delimiter)
return set(bword.decode(encoding) for bword in list_) |
def collapse_soloists(present_track_info: dict) -> dict:
"""
DAVID can provide up to 6 soloists and NEXGEN can provide up to two.
They are parsed as soloist1 .. soloist6 (or soloist2 for NG).
This squishes them down into one array element for a cleaner client
experience.
There is probably a way ... |
def bold(string):
"""Return an ANSI bold string."""
from os import name
return string if name == "nt" else "\033[1m{}\033[0;0m".format(string) |
def SetupPMLForGroup(GroupName, GroupMembersList, Enable = None, Action = None):
"""Setup PML commands for creating a group from a list of group members. The
display and open status of the group may be optionally set. The 'None' values
for Enable and Action imply usage of PyMOL defaults for the creation of ... |
def sum_of_n_odd_numbers(n):
"""
Returns sum of first n odd numbers
"""
try:
n+1
except TypeError: # invlid input hence return early
return
if n < 0: # invlid input hence return early
return
return n*n |
def tau(pv: float, compr_total: float, pi: float):
""" Time Constant
Parameters
---
pv : float
pore volume
compr_total : float
total compressibility
pi : float
productivity index
"""
return pv*compr_total/pi |
def get_number_from_string(s, number_type, default):
"""Returns a numeric value of number_type created from the given string or default if the cast is not possible."""
try:
return number_type(s.replace(",", "."))
except ValueError:
return default |
def node_pairs(graph):
"""Collect 'from-to' nodes in directed graph
Args:
graph:
An instance of dict.
Returns:
pairs:
A list of node pairs.
"""
stack = []
pairs = []
visited = set()
for vertex in graph:
stack.append(vertex)
... |
def reverse_num_situation(num_situation):
"""
Returns opposing numerical situation for specified one.
"""
if num_situation == 'PP':
return 'SH'
elif num_situation == 'SH':
return 'PP'
else:
return num_situation |
def leaves(t):
"""Returns the leaves of a tree of dotdicts as a list"""
if isinstance(t, dict):
return [l for v in t.values() for l in leaves(v)]
return [t] |
def grid_traveller(m: int, n: int) -> int:
"""
:param m: number of rows in grid
:param n: number of columns in grid
:return: number of ways to reach bottom right of the grid from a top right corner
"""
if m == 1 and n == 1:
# base case
return 1
if m == 0 or n == 0:
#... |
def fake_bin(x):
"""Convert a string of numbers to a string of binary."""
l = list(x)
new_l = []
for digit in l:
if int(digit) <5:
new_l.append("0")
else:
new_l.append("1")
return "".join(new_l) |
def change_str(name):
"""Remove spaces, commas, semicolons, periods, brackets from given string
and replace them with an underscore."""
changed = ''
for i in range(len(name)):
if name[i]=='{' or name[i]=='}' or name[i]=='.' or name[i]==':' \
or name[i]==',' or name[i]==' ':
... |
def merge_two_dicts(x, y):
"""A quick function to combine dictionaries.
Parameters
----------
x : dict
Dictionary 1.
y : dict
Dictionary 2.
Returns
-------
dict
The merged dictionary.
"""
z = x.copy() # start with keys and values of x
z.update(y) ... |
def round_if_int(val):
"""
Rounds off the decimal of a value if it is an integer float.
Parameters
----------
val : float or int
A numeric value to be rounded.
Retruns
-------
val : int
The original value rounded if applicable.
"""
if isinstance(... |
def parse_crop(cropstr):
"""
Crop is provided as string, same as imagemagick:
size_x, size_y, offset_x, offset_y, eg 10x10+30+30 would cut a 10x10 square at 30,30
Output is the indices as would be used in a numpy array. In the example,
[30,40,30,40] (ie [miny, maxy, minx, maxx])
"""
spl... |
def escaped_size(string):
"""
>>> escaped_size(r'""')
6
>>> escaped_size(r'"abc"')
9
>>> escaped_size(r'"aaa\\"aaa"')
16
>>> escaped_size(r'"\\x27"')
11
"""
return len(string) + 2 + string.count('"') + string.count('\\') |
def have_colours(stream):
"""
Detect if output console supports ANSI colors.
:param stream:
:return:
"""
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
curses.setupterm()
... |
def rename_band(bandpath):
"""
Bring bandname from CAAPR convention to Williams convention.
"""
def _any_in(candidate_parts, string):
for part in candidate_parts:
if part in string:
return True
return False
# GALEX_NUV.fits -> GALEX_NUV
bandname = ba... |
def get_iiif_image_url(iiif_manifest):
"""Given a IIIF manifest dictionary, derives the value for the info.json
file URL, which can then be stored in the roll metadata and eventually
used to display the roll image in a viewer such as OpenSeadragon."""
resource_id = iiif_manifest["sequences"][0]["canvas... |
def combine_ids(paramid_tuples):
"""
Receives a list of tuples containing ids for each parameterset.
Returns the final ids, that are obtained by joining the various param ids by '-' for each test node
:param paramid_tuples:
:return:
"""
#
return ['-'.join(pid for pid in testid) for test... |
def transceive_uid(uid, max_bits):
""" Slices the supplied uid List based on the maximum bits the UID should contain."""
return uid[:int(max_bits / 8) + (1 if (max_bits % 8) else 0)] |
def g(n):
"""assume n >= 0
1. Computes n ** 2 very inefficiently
2. When k dealing with nested loops, look at the ranges
3. Nested loops, each iterating n times
>>> g(3)
9
>>> g(5)
25
>>> g(7)
49
"""
x = 0
for i in range(n):
for j in range(n):
x += 1
return x |
def to_pos(i, j):
"""Convert a coordinate (with 0,0 at bottom left) on the board to the standard representation
>>> to_pos(0,0)
'a1'
>>> to_pos(3,3)
'd4'
"""
return 'abcdefgh'[i] + str(j + 1) |
def convert_to_base(num, base):
"""
Convert a base-10 integer to a different base.
"""
q = num//base
r = num % base
if (q == 0):
return [r]
else:
return convert_to_base(q, base) + [r] |
def int_d(v, default=None):
"""Cast to int, or on failure, return a default Value"""
try:
return int(v)
except:
return default |
def flatten(obj):
"""
Flattens an object into a list of base values.
"""
if isinstance(obj, list) or isinstance(obj, dict):
l = []
to_flatten = obj if isinstance(obj, list) else obj.values()
for sublist in map(flatten, to_flatten):
if isinstance(sublist, list):
... |
def fmt_latency(lat_min, lat_avg, lat_max):
"""Return formatted, rounded latency.
:param lat_min: Min latency
:param lat_avg: Average latency
:param lat_max: Max latency
:type lat_min: string
:type lat_avg: string
:type lat_max: string
:return: Formatted and rounded output "min/avg/max"... |
def is_point_in_poly_array(test_x, test_y, poly):
"""Implements the ray casting/crossing number algorithm. Returns TRUE if the point is within the bounds of the points that specify the polygon (poly is a list of points)."""
# Sanity checks.
if not isinstance(poly, list):
return False
num_cross... |
def rmcode(txt):
"""Remove code blocks from markdown text"""
if '```' not in txt:
return txt
i = txt.find('```')
n = txt.find('```', i + 3)
if n == -1:
return txt.replace('```', '')
txt = txt.replace(txt[i:n + 3], '')
if '```' in txt:
return rmcode(txt)
return txt... |
def hamming_similarity(s1, s2):
"""
Hamming string similarity, based on Hamming distance
https://en.wikipedia.org/wiki/Hamming_distance
:param s1:
:param s2:
:return:
"""
if len(s1) != len(s2):
return .0
return sum([ch1 == ch2 for ch1, ch2 in zip(s1, s2)]) / len(s1) |
def nsKey(comps):
"""
Returns bytes namespaced key from concatenation of ':' with qualified Base64
prefix bytes components
If any component is a str then converts to bytes
"""
comps = map(lambda p: p if not hasattr(p, "encode") else p.encode("utf-8"), comps)
return b':'.join(comps) |
def book_name_addrs(nms):
"""Returns a list of the named range addresses in a workbook.
Arguments:
nms -- Named range list
"""
return [nm.refers_to_range.get_address(include_sheetname=True) for nm in nms] |
def get_var_names(variable):
"""
get the long variable names from 'flow' or 'temp'
:param variable: [str] either 'flow' or 'temp'
:return: [str] long variable names
"""
if variable == "flow":
obs_var = "discharge_cms"
seg_var = "seg_outflow"
elif variable == "temp":
o... |
def overlap_hashes(hash_target, hash_search):
"""Return a set of hashes common between the two mappings"""
return set(hash_target).intersection(set(hash_search)) |
def unnormalize(img, norm_min, norm_max):
""" Unnormalize numpy array or torch tensor from given norm
range [norm_min, norm_max] to RGB range. """
assert norm_max > norm_min
norm_range = norm_max - norm_min
return (img - norm_min)/norm_range*255.0 |
def _parse_extra_options(opt_array):
""" Convert any options that can't be parsed by argparse into a kwargs dict; if an option is specified
multiple times, it will appear as a list in the results
:param opt_array: a list of "option=value" strings
:returns: a dict mapping from options -> values
"""
... |
def l32(pos, b, l):
""" Find out if position is over line 3
bottom
"""
x, y = pos
if (y >= 0):
return True
else:
return False |
def pascal_triangle(n):
"""gets pascal triangle for n,
-> n assumed to always be int
-> handles NO exceptions
Return: matrix of list of values representing triangle
"""
ret_mat = []
for i in range(0, n):
mat_len = len(ret_mat)
if mat_len <= 1:
ret_mat.a... |
def get_letters_set_from_algo(algo):
"""
Returns 1 if it's a chord algo, 3 if it's a melody algo. This is an arbitraty choice.
:param algo:
:return:
"""
prefix = algo.split("_")[0]
if prefix == "chords":
return 1
elif prefix == "melody":
return 3
else:
raise ... |
def _R2FromGaussian(sigmax, sigmay, pixel=0.1):
"""
"""
return (sigmax*pixel)**2 + (sigmay*pixel)**2 |
def features_to_edges(list_features, edges):
"""
Transform a list of QgsFeatures objects into a list of the corresponding
Edge objects of the layer.
:param list_features: list of the features corresponding to the desired edges
:type list_features: list of QgsFeatures objects
:param ... |
def _add_param(params, value, key):
""" If value is not None then return dict params with added (key, value) pair
:param params: dictionary of parameters
:type: dict
:param value: Value
:param key: Key
:return: if value not ``None`` then a copy of params with (key, value) added, otherwise retur... |
def removeNumbers(text):
""" Removes integers """
text = ''.join([i for i in text if not i.isdigit()])
return text |
def basic_sobject_to_dict(obj):
"""Converts suds object to dict very quickly.
Does not serialize date time or normalize key case.
:param obj: suds object
:return: dict object
"""
if not hasattr(obj, '__keylist__'):
return obj
data = {}
fields = obj.__keylist__
for field in fi... |
def _to_utf8_string(s):
"""Encodes the input csv line as a utf-8 string when applicable."""
return s if isinstance(s, bytes) else s.encode('utf-8') |
def mag2flux(mag):
"""Convert flux to arbitrary flux units"""
return 10.**(-.4*mag) |
def age_category(age, average=-1):
"""
We divided the age into 5 steps taking care of the responsibility that a person has of himself
and looking at how mush "strength" it has. This is an insteresting parameter to change while
seeing inference.
In case of nan values we put the average eta of the peo... |
def valid_date_of_birth(date_of_birth):
"""
Does the supplied date string meet our criteria for a date of birth
"""
#Do whatever you need to do...
return True |
def contains_number(s):
"""Check if string contains any number"""
return any(map(str.isdigit, s)) |
def normal_power(x, n):
"""Complexity: O(n)"""
if n == 0:
return 1
else:
return x * normal_power(x, n-1) |
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""Compare too floating point numbers."""
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression
"""
result = {}
for dictionary in dict... |
def get_photo_page(photo_info):
"""
Get the photo page URL from a photo info object
"""
ret = ''
if photo_info.get('urls') and photo_info['urls'].get('url'):
for url in photo_info['urls']['url']:
if url.get('type') == 'photopage':
ret = url.get('text')
return ... |
def obj_in_list_always(target_list, obj):
"""
>>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False
"""
for item in set(target_list):
if item is not obj:
return False
return True |
def count_interval_times(start_event, end_event, messages):
"""
Count the time in all [start_event,end_event] intervals and return the sum.
"""
interval_times = 0.0
last_start_stamp = None
last_start_time = None
# If messages is empty, return 0
if not messages:
return interval_... |
def parse_hook_module(hook_module):
""" Parse a hook_module and split it into two parts
>>> parse_hook_module('django.core.handlers.base::BaseHandler')
['django.core.handlers.base', 'BaseHandler']
>>> parse_hook_module('django.core.handlers.base')
['django.core.handlers.base', None]
"""
if ... |
def has_deprecations(cls):
"""Decorator to ensure that docstrings get updated for wrapped class"""
for obj in [cls] + list(vars(cls).values()):
if callable(obj) and hasattr(obj, '__new_docstring'):
try:
obj.__doc__ = obj.__new_docstring
except AttributeError:
... |
def getBinaryRep(n, numDigits):
"""Assumes n and numDigits are non-negative ints
Returns a numDigits str that is a binary
representation of n"""
result = ''
while n > 0:
result = str(n%2) + result
n = n//2
if len(result) > numDigits:
raise ValueError('not enough digits')
for... |
def toggle_modal(n1, n2, is_open):
"""toggle_modal()
"""
if n1 or n2:
return not is_open
return is_open |
def vecInt(vec):
"""Retruns something."""
return tuple([int(c) for c in vec]) |
def join_epiweek(year, week):
""" return an epiweek from the (year, week) pair """
return year * 100 + week |
def isFileLike(thing):
"""Returns true if thing looks like a file."""
if hasattr(thing, "read") and hasattr(thing, "seek"):
try:
thing.seek(1, 1)
thing.seek(-1, 1)
return True
except IOError:
pass
return False |
def format_data_comma(data):
""" Format the numbers in the string to include commas.
Args:
data (string or list): A text string.
Requires:
None
Returns:
(string): A text string.
"""
if not isinstance(data,list):
data=data.split... |
def card_controls(context, card_placement):
"""Display control buttons for managing one single card
"""
return {
'user': context['user'],
'card_placement': card_placement,
} |
def to_int(val):
""" Turn the passed in variable into an int; returns 0 if errors
Args:
val (str): The variable to turn into an int
Returns:
int: The int value if possible, 0 if an error occurs
"""
try:
return int(val)
except ValueError:
return 0 |
def get_reachable_resolved_callable_ids(callables, entrypoints):
"""
Returns a :class:`frozenset` of callables ids that are resolved and
reachable from *entrypoints*.
"""
return frozenset().union(*(callables[e].get_called_callables(callables)
for e in entrypoints)) |
def cpf_checksum(cpf):
"""
CPF Checksum algorithm.
"""
if cpf in map(lambda x: str(x) * 11, range(0, 10)):
return False
def dv(partial):
s = sum(b * int(v)
for b, v in zip(range(len(partial) + 1, 1, -1), partial))
return s % 11
dv1 = 11 - dv(cpf[:9])
... |
def reduced_chi_squared(chi_squared, N, P):
"""
:param chi_squared: Chi squared value
:param N: (int) number of observations
:param P: (int) number of important parameters
:return: Reduced Chi squared
"""
return chi_squared / (N - P) |
def calculate_bodyfat_per_week(data) -> float:
"""Reads a list that stores a week's worth of data to calculate and return average body fat per week"""
total = 0
day = len(data)
for index, body_fat in enumerate(data):
total += body_fat[3]
return total / day |
def Uunbalance_calc(ua,ub,uc):
"""Calculate voltage/current unbalance."""
uavg = (ua + ub + uc)/3
return (max(ua,ub,uc) - min(ua,ub,uc))/uavg |
def combine_names(names, ids=None):
"""Combine the selected names into one new name.
Parameters
----------
names : list of str
String names
ids : numpy.ndarray, optional
Selected index
Returns
-------
str
"""
if ids is None:
return '+'.join(sorted(names)... |
def bits2val(bits):
"""For a given enumeratable bits, compute the corresponding decimal integer."""
# We assume bits are given in high to low order. For example,
# the bits [1, 1, 0] will produce the value 6.
return sum(v * (1 << (len(bits)-i-1)) for i, v in enumerate(bits)) |
def generate_base_map(read_data_list):
"""
generate data base map
"""
tx_len = len(read_data_list[0])
rx_len = len(read_data_list[0][0])
sum_list = [([0.0] * rx_len) for i in range(tx_len)]
for i in range(len(read_data_list)):
for j in range(len(read_data_list[i])):
for... |
def is_uppercase(value):
"""
Is the value all uppercase? Returns True also if there are no alphabetic characters.
"""
return value == value.upper() |
def zone_compare(value, zones):
"""
Determines whether value is in a known zone
"""
for zone in zones:
if value.endswith("." + zone) or value == zone:
return zone
return None |
def complete_proverb(pvb):
"""
Checks if the proverb is complete.
Assumes the proverb is converted to have underscores replacing
unknown letters.
Assumes everything is uppercase.
:param pvb: a proverb
:type pvb: str
:return: True | False
:rtype: bool
"""
if "_" n... |
def _lstrip(source: str, prefix: str) -> str:
""" Strip prefix from source iff the latter starts with the former. """
if source.startswith(prefix):
return source[len(prefix) :]
return source |
def check_no_match(expected_id: str, par_id: str) -> bool:
"""Checks if paragraph ID matches the expected doc ID"""
if par_id.split('.pdf')[0].upper().strip().lstrip() == expected_id.upper().strip().lstrip():
return False
else:
return True |
def parse_firewall(firewall):
"""
Parse firewall into firewall dict
"""
firewall_dict = {}
for connect, v in firewall.items():
firewall_dict[eval(connect)] = v
return firewall_dict |
def list_if_in(input_list, string_in):
"""Return a list without input items not containing an input string.
Parameters
----------
input_list : list[str]
A list of strings.
string_in : str
A string to check items in the list.
Returns
-------
list
A copy of input ... |
def set_mathjax_style(style_css, mathfontsize):
"""Write mathjax settings, set math fontsize
"""
jax_style = """<script>
MathJax.Hub.Config({
"HTML-CSS": {
/*preferredFont: "TeX",*/
/*availableFonts: ["TeX", "STIX"],*/
styles: {
scale: %d,
... |
def GetPressure(u, rho, gamma):
"""
RETURNS: pressure in simulation units
INPUT: u : thermal energy
rho : density
gamma : adiabatic index
"""
return (gamma-1.)*rho*u |
def convert_string_to_list(input_string):
"""Convert a given string into an array compatible with data model tsvs for array attributes."""
# remove single & double quotes, remove spaces, remove [ ], separate remaining string on commas (resulting in a list)
output_list = str(input_string).replace("'", '').r... |
def get_number_same_as_index(lst: list) -> int:
"""
Parameters
-----------
lst: the given sorted list
Returns
---------
Notes
------
binary search
"""
left, right = 0, len(lst) - 1
while left <= right:
mid = (left + right) // 2
if lst[mid] == mid:
... |
def has_field_name(s):
"""
fieldName -> hasFieldName
"""
return 'has' + s[:1].upper() + s[1:] |
def scale(coord_paths, scale_factor):
"""
Take an array of paths, and scale them all away from (0,0) cartesian using a
scalar factor, return the resultinv paths.
"""
new_paths = []
for path in coord_paths:
new_path = []
for point in path:
new_path.append( (point[0]*sc... |
def camelcase(name):
"""Converts a string to CamelCase.
Args:
name (str): String to convert.
Returns:
str: `name` in CamelCase.
"""
return ''.join(x.capitalize() for x in name.split('_')) |
def prng(ofs,siz=0,cnt=0):
"""
create a range of memory map addresses separated by siz bytes
"""
if siz !=0 and cnt!=0:
# an array of cnt elements separated by siz bytes
return range(ofs,cnt*siz+ofs,siz)
else:
# a range with a single address
return range(ofs,ofs+1) |
def ensure_extension(path, ext):
""" Make sure path ends with the correct extension """
if path.endswith(ext): return path
else: return path + ext |
def ClusterSpecString(num_workers,
num_param_servers,
port):
"""Generates general cluster spec."""
spec = 'worker|'
for worker in range(num_workers):
spec += 'tf-worker%d:%d' % (worker, port)
if worker != num_workers-1:
spec += ';'
spec += ',ps|'
for ... |
def shorten(text):
"""Collapse whitespace in a string."""
return ' '.join(text.split()) |
def __deep_warn_equal(path, d1, d2, d1name, d2name):
"""Print warning if two structures are not equal (deeply)."""
if type(d1) == dict:
iterator = d1
else:
if len(d1) != len(d2):
return ["Warning: <{}> has length {} in {} but {} in {}".format(
path, len(d1), d1nam... |
def next_temperature(prev_temp, prev_next_temp, prev_to_prev_temp, lamb):
"""
Calculator of the next temperature
to be computed with the explicit
method
"""
return prev_temp + lamb * (prev_next_temp - 2*prev_temp + prev_to_prev_temp) |
def find_plus(word):
"""
returns 1 if the word containe '+'
Input=word Output=flag
"""
if '+' in word:
return 1
return 0 |
def to_char(value: int) -> str:
"""
Convert an integer to a single character, where 0 equals A.
Note: This method will return an uppercase character.
:param value: an integer
:return: a character representation
"""
return chr(ord("A") + value) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.