content stringlengths 42 6.51k |
|---|
def K(A,L=None):
"""
Function we are trying to maximize: sum_{i<j} A[L[i]][L[j]]
A is m x m matrix,
L is a subset of range(m) (or defaults to range(m) if no L given)
"""
if L==None:
L = range(len(A))
return sum([A[L[i]][L[j]] for j in range(len(L)) for i in range(j)]) |
def _get_names(config):
"""
Find names of csv files (file=) or dataframes (df=) called in config
"""
tsnames = []
tsvars = []
for k, v in config.items():
if "=" in str(v):
tsnames.append((v.split("=")[0], v.split("=")[1].rsplit(":", 1)[0]))
if ".costs." in k:
... |
def partition(m):
"""Returns the number of different ways one hundred can be written as a sum
of at least two positive integers.
>>> partition(100)
190569291
>>> partition(50)
204225
>>> partition(30)
5603
>>> partition(10)
41
>>> partition(5)
6
>>> partition(3)
... |
def is_subpath(x, y):
""" Returns True if x is a subpath of y, otherwise return False.
Example:
is_subpath('/a/', '/b/') = False
is_subpath('/a/', '/a/') = True
is_subpath('/a/abc', '/a/') = True
is_subpath('/a/', '/a/abc') = False
"""
if y.endswith('/'):
return x.startswith(y) ... |
def celstofar(celsius):
""" This function convert celsius to fahrenheit, with celsius as the parameter.."""
fahrenheit = (9 * celsius) / 5 + 32
return fahrenheit |
def check_solution(population, password):
"""
Check if the population found a solution to the problem
"""
return any(ind == password for ind in population) |
def to_list(val):
"""
Method for casting an object into
a list if it isn't already a list
"""
return val if type(val) is list else [val] |
def lz77_decompress(data):
"""Decompresses rwdata used to initialize variables.
The table at address 0x0801807c has format:
0-3 Relative offset to this elements location to the initialization function.
Example:
0x0801807c + (0xFFFE9617 - 0x100000000) == 0x8001693
... |
def unique(seq):
"""
unique a list by preserve the order
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] |
def calc_pad_same(in_siz, out_siz, stride, ksize):
"""Calculate same padding width.
Args:
ksize: kernel size [I, J].
Returns:
pad_: Actual padding width.
"""
return (out_siz - 1) * stride + ksize - in_siz |
def canonproto(text):
"""canonicalize a protocol name"""
if (text == 'tcp') or (text == 'udp'):
return text
else:
return None |
def cubeUsingMap(myList: list) -> list:
"""
Simple map function for cube of numbers in the list using map and lambda.
"""
odd = list(map(lambda x: x**3, myList))
return odd |
def SelectDefaultBrowser(possible_browsers):
"""Return the newest possible browser."""
if not possible_browsers:
return None
return max(possible_browsers, key=lambda b: b.last_modification_time) |
def lerp(a: float, b: float, t: float) -> float:
"""
returns a linear interpolation between a and b at t
:param a: the first value
:param b: the second value
:param t: the interpolation value
Example:
>>> lerp(0, 1, 0.5)
>>> 0.5
"""
return a + t * (b - a) |
def _unembed(tree_list):
"""Unembeds (or deletes) extra spaces at the end of the strings."""
unembedded = []
for line in tree_list:
unembedded.append(line.rstrip())
return unembedded |
def splitext(fname):
"""Splits filename and extension (.gz safe)
>>> splitext('some/file.nii.gz')
('file', '.nii.gz')
>>> splitext('some/other/file.nii')
('file', '.nii')
>>> splitext('otherext.tar.gz')
('otherext', '.tar.gz')
>>> splitext('text.txt')
('text', '.txt')
"""
f... |
def specframe2sample(frame, hop_size=3072, win_len=4096):
"""
Takes frame index (int) and returns the corresponding central time (sec)
"""
return frame * hop_size + win_len / 2 |
def common_chars(box1, box2):
"""Return all common characters between box1 and box2 in order
>>> common_chars('abcdef', 'abddeg')
'abde'
"""
return ''.join(i if i == j else '' for i, j in zip(box1, box2)) |
def create_vector(p1, p2):
"""Contruct a vector going from p1 to p2.
p1, p2 - python list wth coordinates [x,y,z].
Return a list [x,y,z] for the coordinates of vector
"""
return list(map((lambda x,y: x-y), p2, p1)) |
def recursiveAbecedarian(word):
"""
Returns True if letters within word are arranged alphabetically.
This function does this recursively.
"""
#alternate implementation, not mine
if len(word) <=1:
return True
if word[0] > word[1]:
return False
recursiveAbec... |
def convert_to_roman_numeral(number_to_convert):
"""
Converts Hindi/Arabic (decimal) integers to Roman Numerals.
Args:
param1: Hindi/Arabic (decimal) integer.
Returns:
Roman Numeral, or an empty string for zero.
"""
arabic_numbers = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9,... |
def capitalize_title(title: str) -> str:
"""Capitalize a string.
:param title: str - title string that needs title casing
:return: str - title string in title case (first letters capitalized)
"""
return title.title() |
def any(name, alternates):
"""Return a named group pattern matching list of alternates."""
return "(?P<%s>" % name + "|".join(alternates) + ")" |
def get_zero_point(header):
"""
This function ...
:param header:
:return:
"""
# Loop over all keys in the header
for key in header:
if "MAGZP" in key: return header[key]
# If no keyword is found that states the zero-point, return None
return None |
def update_controls(map_type):
"""Update slider after radio selection.
Update slider after radio selection. If 'flow' selected, show
slider. If 'speed' or 'road' selected, hide slider.
Parameters
----------
map_type : str
Currently selected map type from radio.
Returns
-------... |
def pig_latin(s):
"""Function creates words with arbitrary rules."""
vowels = ['a', 'e', 'i', 'o', 'u']
lowstring = s.lower()
if lowstring.isalpha():
if lowstring[0] in vowels:
return(lowstring + 'way')
elif lowstring[0] not in vowels:
vowel_index = 0
... |
def _hd(data):
"""Helper function for printing the raw data"""
return " ".join("%02X" % e for e in data) |
def valid_callsign(callsign):
"""
Validates an over-the-air callsign. APRS-IS is more forgiving.
Verifies that a valid callsign is valid:
>>> valid_callsign('W2GMD-1')
True
>>>
Verifies that an invalid callsign is invalid:
>>> valid_callsign('BURRITOS-99')
False
>>>
:param... |
def getattr_recursive(item, attr_key, *args):
"""
Allows dot member notation in attribute name when getting an item's attribute.
NOTE: also searches dictionaries
"""
using_default = len(args) >= 1
default = args[0] if using_default else None
for attr_key in attr_key.split('.'):
try... |
def base_unique_id(latitude, longitude):
"""Return unique id for entries in configuration."""
return f"{latitude}_{longitude}" |
def compute_percentage(shifts, sales):
"""
:param shifts:
:type shifts: dict
:param sales:
:type sales: dict
:return: A dictionary with time as key (string) with format %H:%M and
percentage of sales per labour cost as value (float),
If the sales are null, then return -cost instead of per... |
def total_words(book):
"""Count total words in book histogram
"""
return sum(book.values()) |
def _adding_dists(_distanceorweighs, dists_oi, to_dists_oi):
"""Adding predistances to new distances."""
# print _distanceorweighs, dists_oi, to_dists_oi
# assert(_distanceorweighs in [True, False])
# assert(len(dists_oi) == len(to_dists_oi))
# assert(all([type(e) in numbertypes for e in to_dists_oi]))
... |
def fresnel_number(a, L, lambda_):
"""Compute the Fresnel number.
Notes
-----
if the fresnel number is << 1, paraxial assumptions hold for propagation
Parameters
----------
a : float
characteristic size ("radius") of an aperture
L : float
distance of observation
lam... |
def _emptyMember(tag=None, text=None, attrib=None, children=None,
namespace=None):
"""Return an empty stock Element representation"""
if tag is None:
tag = ''
if namespace is None:
namespace = ''
if text is None:
text = ''
if attrib is None:
attrib = ... |
def is_prime_v1(n):
"""Return 'True' if 'n' is a prime number. False otherwise."""
if n == 1:
return False # 1 is not prime
for d in range(2, n):
if n%d == 0:
return False
return True |
def writeToFile(fileName: str, content: str):
"""Writes content to the given file."""
with open(fileName, "w") as f:
f.write(content)
return None |
def get_formatted_progress(progress):
"""Return workflow progress in format of finished/total jobs."""
total_jobs = progress.get("total", {}).get("total") or "-"
finished_jobs = progress.get("finished", {}).get("total") or "-"
return "{0}/{1}".format(finished_jobs, total_jobs) |
def _get_qt_qmake_config(qmake_config, qt_version):
""" Return a dict of qmake configuration values for a specific Qt version.
"""
qt_qmake_config = {}
for name, value in qmake_config.items():
name_parts = name.split(':')
if len(name_parts) == 2 and name_parts[0] == qt_version:
... |
def get_which_data_rows(model, which_data_rows):
"""
Helper to get the data rows to plot.
"""
if which_data_rows == 'all' or which_data_rows is None:
return slice(None)
return which_data_rows |
def seatsInTheater(nCols, nRows, col, row):
"""
Given the total number of rows and columns
in the theater (nRows and nCols, respectively),
and the row and column you're sitting in, return
the number of people who sit strictly behind
you and in your column or to the left, assuming
all se... |
def indexToGridCell(flat_map_index, map_width):
"""
Converts a linear index of a flat map to grid cell coordinate values
flat_map_index: a linear index value, specifying a cell/pixel in an 1-D array
map_width: the map's width
returns: list with [x,y] grid cell coordinates
"""
grid_cell_map_... |
def list_reply(objects):
"""Construct message used by CtrlServer when replying to list requests.
By 'list', we mean 'give me all the callable methods on your systems'.
:param objects: Dict of subsystem object names to their callable methods.
:type objects: dict
:returns: Constructed list_reply dic... |
def GetRangePct(MinValue, MaxValue, Value):
"""Calculates the percentage along a line from **MinValue** to
**MaxValue** that value is.
:param MinValue: Minimum Value
:param MaxValue: Maximum Value
:param Value: Input value
:returns: The percentage (from 0.0 to 1.0) betwen the two values where
... |
def create_creative_set_config(creative_ids, sizes, prefix):
"""
Returns an array of creative set config object.
Args:
creative ids (int array): the IDs of the creatives
sizes(String array): sizes for creative
prefix (string): creative name prefix
Returns:
an array: an ... |
def is_uuid_field(field_name):
"""
:param field_name:
:return: True if field_name looks like a uuid name
"""
if field_name is not None and field_name in ["uuid", "UUID"] or field_name.endswith("uuid"):
return True
return False |
def mutual_information_calc(response_entropy, conditional_entropy):
"""
Calculate mutual information.
:param response_entropy: response entropy
:type response_entropy : float
:param conditional_entropy: conditional entropy
:type conditional_entropy : float
:return: mutual information as f... |
def parse_coordinates(*args):
""" parse 2D/3D coordinates x,y(,z) in a variety of fashions, and return a 3-element tuple """
n = len(args)
if n == 0:
return (0.0,0.0,0.0)
if n == 1:
try: # try if a Point object is supplied
return args[0].coordinates()
except:
if type(args[0]) in... |
def pe2(limit=4000000):
"""
Sum of the even-valued Fibonacci sequence
>>> pe2()
4613732
"""
a, b, s = 1, 2, 2
while b <= limit:
a, b = b, a + b
if not b & 1:
s += b
return s |
def _get_list(list_=None):
"""get list from yaml file element"""
if not isinstance(list_, list):
if list_ is None:
_ = []
else:
_ = [list_]
else:
_ = list_
return _ |
def odd_occurence_hashmap(arr):
"""
Implement the solution by using a hashmap.
We iterate through the list once, and store every value that we encounter,
then iterate through our hashmap/dictionary structure once.
Space complexity: $O(n)$; Time complexity: $O(n)$.
Parameters
... |
def get_default_name(obj, scope):
"""Return a unique name for the given object in the given scope."""
classname = obj.__class__.__name__.lower()
if scope is None:
sdict = {}
else:
sdict = scope.__dict__
ver = 1
while '%s%d' % (classname, ver) in sdict:
ver += 1
retur... |
def factorial(number: int) -> int:
"""
>>> factorial(5)
120
>>> factorial(0)
1
>>> import random
>>> import math
>>> numbers = list(range(0, 50))
>>> for num in numbers:
... assert factorial(num) == math.factorial(num)
>>> factorial(-1)
Traceback (most recent call las... |
def normalize_url(prefix: str, path: str) -> str:
"""Function to normalize URLs before reaching into S3"""
if prefix:
return f"{prefix.rstrip('/')}/{path.lstrip('/')}"
return path |
def get_api_id(stack_outputs, api_logical_id):
"""Obtains the API ID from given stack outputs.
:type stack_outputs: dict
:param stack_outputs: CloudFormation stack outputs.
:type api_logical_id: str
:param api_logical_id: logical ID of the API resource.
:rtype: str
:return: API ID.
"... |
def vedHexChecksum(byteData):
"""
Generate VE Direct HEX Checksum
- sum of byteData + CS = 0x55
"""
CS = 0x55
for b in byteData:
CS -= b
CS = CS & 0xFF
return CS |
def numobs_needed(numobs_target, numobs_done):
"""
Determines the number of observations still needed for an object.
"""
numobs = numobs_target - numobs_done
return max(0,numobs) |
def MyRound(speed, base=5):
"""
This module rounds off the harmonized speed to nearest '5's.
"""
return int(base * round(float(speed)/base)) |
def generate_citation(metadata_dict):
"""
Generate a citation from the other metadata.
"""
format_args = dict(metadata_dict)
format_args["year"] = format_args.pop("updated_datetime").split("-")[0]
format_string = "{creator}, {year}: {title}. {publisher}, {object_id}"
return format_string.for... |
def degree_of_item(train):
"""Calculates degree of items from user-item pairs."""
item_to_deg = {}
for pair in train:
_, item = pair
if item in item_to_deg:
item_to_deg[item] += 1
else:
item_to_deg[item] = 1
return item_to_deg |
def service_level(orders_received, orders_delivered):
"""Return the inventory management service level metric, based on the percentage of received orders delivered.
Args:
orders_received (int): Orders received within the period.
orders_delivered (int): Orders successfully delivered within the p... |
def generate_cat_str(cats):
"""generates a string of %s 's that is as long as the number of elements in cats"""
q_cat_str = "(" + ("".join("%s, " for _ in range(len(cats))))[0:-2] + ")"
return q_cat_str |
def should_distort_images(flip_left_right, random_crop, random_scale,
random_brightness):
"""Whether any distortions are enabled, from the input flags.
Args:
flip_left_right: Boolean whether to randomly mirror images horizontally.
random_crop: Integer percentage setting th... |
def isUnsavedPath(path):
"""Return true if the given path is a special <Unsaved>\sub\path file."""
tag = "<Unsaved>"
length = len(tag)
if path.startswith(tag) and (len(path) == length or path[length] in "\\/"):
return True
else:
return False |
def check_image_counter(name):
"""
Note: This method is only ever entered if there actually is a name as well
as there will never be a .fits at the end.
Pre: Takes in an image name as a string and sees if the standard iterator
is on the end of the image name.
Post: Returns a boolean of whether t... |
def greet_user(user_name):
"""Creates a greeting for a user base off of the user name"""
if len(user_name) % 2 == 0:
greeting = "Nice to see you!"
else:
greeting = "Thanks for visiting!"
return greeting |
def find_start(array, window, minimum):
"""Simple debounce function going left to right.
Args:
array (list-like): The data to parse, can technically be any iterable
window (int): How many consecutive values to be a real trigger
minimum (float): The minimum value to count towards the win... |
def _compute_treatment_effect_raw(
sum_treated, n_treated, sum_untreated, n_untreated
):
"""Compute the average treatment effect.
Computes the average treatment effect (ATE) using the sum of outcomes of
treated and untreated observations (*sum_treated* and *sum_untreated*) and
the number of treated... |
def models_as_dict(model_iter, names):
"""(for annealing) given a list of list of targets and kernels -- flatten for save_models and load_models, above"""
assert isinstance(model_iter, (tuple, list)) or all(
map(lambda ms: isinstance(ms, (tuple, list)), model_iter.values())
), "takes a list or dict ... |
def is_factor(obj):
""" Is obj a Factor?
"""
return hasattr(obj, "_factor_flag") |
def pretty_date(time=None): # noqa
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
:param time:
"""
from datetime import datetime
now = datetime.now()
if type(time) is int:
diff ... |
def Canto(d,r,l,t):
""" Determina el canto donde d en mt y l y t en mm"""
return d + (0.5*l + t + r)/1000 |
def get_essential( m ):
""" Get the "essential" leds, along with the associated tri.
Format: 'ess[led] = tri'
An essential LED is an LED that lights a triangle surface, where that LED is the only LED to light that triangle surface.
i.e. without that LED, the given triangle will never be lit... |
def get_str_from_list(message_list: list, cc: str = "and", punct: bool = True) -> str:
"""Returns list as a formatted string for speech.
message list: [list] of the components to be joined.
cc: [str] coordinating conjunction to place at end of list.
punct: bool - indicates if should include punctua... |
def check_reserved(string):
"""
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
"$" | ","
Hence for certain inputs, e.g. service name, configuration key etc whic... |
def outer_edge_check(p,start,end):
""" This function checks if a specific coordinate is at the edge of the grid."""
return (p-end)==0 or (p-start)==0 |
def create_clusters(cluster_sizes):
"""Given list of cluster sizes (list of ints), produces a list of clusters, where
the cluster at index i has size of the ith size in the list. Clusters are sets
of integers, with these integers representing nodes
Returns clusters (List of sets of integers)
... |
def _fix_sequence(seq):
"""Returns string where terminal gaps are replaced with terminal CCA.
Some of the sequence in the Genomic tRNA Database have gaps where the
acceptor stem (terminal CCA) should be. This function checks the
number of terminal gaps and replaces with appropriate par... |
def date_string(dates):
"""Returns a date string from an array of dates."""
date_strings = []
for date in dates:
try:
expression = date["expression"]
except KeyError:
if date.get("end"):
expression = "{0}-{1}".format(date["begin"], date["end"])
... |
def isfloat(value: str) -> bool:
"""
Check if the given string is a float.
:param value: String to check
:return: True if float
"""
try:
float(value)
return True
except ValueError:
return False |
def int_to_string( x ):
"""Convert integer x into a string of bytes, as per X9.62."""
assert x >= 0
if x == 0: return chr(0)
result = ""
while x > 0:
q, r = divmod( x, 256 )
result = chr( r ) + result
x = q
return result |
def fixup_datetime_string_format(datetime_string: str) -> str:
"""
Take datetime as formatted in iso6801, and replace the timezone with "Z"
This function is necessary because the Thanos api doesn't accept timezones in the format airflow provides them in.
"""
return datetime_string[:-6] + "Z" |
def get_date_format(date_filter):
"""
Utility for returning the date format for a given date filter
@param date filter : the given date filter
@return the date format for a given filter
"""
vals = {"day": "%Y-%m-%d", "hour": "%Y-%m-%d : %H"}
return vals[date_filter] |
def extract_from_uri(uri):
""" split a ur into a bucket_id and object_id
Args:
url (str): uri reference to a file in GCS
Returns:
bucket_id, object_id
"""
uri_s = uri[5:]
parts = uri_s.split('/',1)
return parts[0], parts[1] |
def get_divisive_norm(ind, divisive_norm_list):
"""
Returns an element from a list of divisive norms if the list is not None.
:param ind: index of the elements
:param divisive_norm_list: list of DivisiveNorm
:return: DivisiveNorm or None (if divisive_norm_list == None)
"""
i... |
def get_launch_config_name(cluster):
"""Get the name for a cluster's launch configuration.
Args:
cluster
The name of a cluster.
Returns:
The launch configuration's name.
"""
return str(cluster) + "--ecs-cluster-launch-configuration" |
def get_num_classes(DATASET: str) -> int:
"""Get the number of classes to be classified by dataset."""
if DATASET == 'MELD':
NUM_CLASSES = 7
elif DATASET == 'IEMOCAP':
NUM_CLASSES = 6
else:
raise ValueError
return NUM_CLASSES |
def egcd(a, b):
""" Extended Euclidian algorithm
:param a: int
:param b: int
:return:
"""
if not b:
return 1, 0, a
q, r = a // b, a % b
s, t, g = egcd(b, r)
return t, s - q * t, g |
def insertion_sort(arr: list):
"""
Insertion sorting a list. Big-O: n^2 (average/worst) time; 1 on space.
"""
for ndx in range(1, len(arr)):
pos = ndx
val = arr[ndx]
while pos > 0 and arr[pos-1] > val:
arr[pos] = arr[pos-1]
pos = pos-1
arr[pos] = v... |
def get_matches(match_dict):
"""Create a set of match name and value tuples"""
return {(entry['OXMTlv']['field'], entry['OXMTlv']['value']) for entry in match_dict} |
def entry_string(key, value, entry_char=">", attribution_char="=",
end_char="\n"):
"""Converts a keyword and a value to an accepted input string for
'read_config_file.
Inputs
----------
key : str
Keyword (name of the option/parameter). If not string, a
conversion is... |
def cyclic_sort_vertices_2d(Vlist):
"""
Return the vertices/rays in cyclic order if possible.
NOTES:
This works if and only if each vertex/ray is adjacent to exactly
two others. For example, any 2-dimensional polyhedron satisfies
this.
See
:meth:`~sage.geometry.polyhedron.base.Polyhed... |
def interplote_avrg_result_dict_start(result_dict: dict) -> dict:
"""make sure every display local density starts from (100,...)"""
for key, value in result_dict.items():
if value[0][0] != 100:
value.insert(0, (100, 0))
return result_dict |
def _get_file_rel_path(file_path):
"""Get the lab/Subjects/subject/... part of a file path."""
file_path = str(file_path).replace('\\', '/')
# Find the relative part of the file path.
i = file_path.index('/Subjects')
if '/' not in file_path[:i]:
return file_path
i = file_path[:i].rindex(... |
def obj_to_path(obj):
"""Quasi-inverse of obj_to_path: Get a root_obj and attr_path from an object.
Obviously, would only be able to work with some types (only by-ref types?).
>>> class A:
... def foo(self, x): ...
... foo.x = 3
... class B:
... def bar(self, x): ...
... |
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found.
Running time: 0(t * p) for t characters in the text and p characters in the
pattern. For every character in the text we always loop through the whole pattern.
... |
def figure_alti(qcval):
"""hack"""
if qcval > 100000.:
return None
return float(qcval / 100.0) |
def _sqlname(name):
"""parse database name and table name from given name string
name: a string of the form 'databaseurl?table=tablename'
"""
key = '?table='
if name is None: db, table = None, None # name=None
elif name.startswith((key,'table=')): # name='table=memo'
db, table = None, n... |
def transform_noise_level(value, model):
""" Validate a noise level
Args:
value (:obj:`float`): value
model (:obj:`ListVector`): model
Returns:
:obj:`float`: value
Raises:
:obj:`ValueError`: if the value is not a non-negative float
"""
if value < 0:
msg... |
def score_string(alt, term_dict, value_dict, operation_dict,
score_dict, record_aggregate=max):
"""Calculates the performance score for each element.
Args:
alt (string) : Usually vcf key
term_dict (dict) : Dictionnary of alt config term
value_dict ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.