content stringlengths 42 6.51k |
|---|
def parse_location(string):
"""Return tuple (long, latitude) from string with coordinates."""
if string and string.strip():
return map(float, string.split(",", 1)) |
def simplify_matrix(matrix):
"""
If A owes B and B owes A back, then only a single transaction can settle both up.
:param matrix: payment matrix
:return: simplified payment matrix
"""
i_j_pairs = [[i, j] for i in range(4) for j in range(4) if i < j]
for i_j_pair in i_j_pairs:
i = i_j... |
def getCharOverlapCount(from1, to1, from2, to2):
"""Calculates the number of overlapping characters of the two given areas."""
#order such that from1 is always prior from2
if from1 > from2:
tmp = from1
from1 = from2
from2 = tmp
tmp = to1
to1 = to2
t... |
def get_entry(dct, names):
"""get the entry of a folded dct by the names of the entries"""
if len(names) == 0:
return dct
return get_entry(dct[names[0]], names[1:]) |
def link(url):
"""Return 'url' explicitly remarked up as a link.
>>> link("http://server.test/")
'[[http://server.test/]]'
:url: the string to be remarked up
:returns: 'url' encased in appropriate remarkup
"""
return "[[{url}]]".format(url=url) |
def parse_string_to_list(line):
"""Parse a line in the csv format into a list of strings"""
if line is None:
return []
line = line.replace('\n', ' ')
line = line.replace('\r', ' ')
return [field.strip() for field in line.split(',') if field.strip()] |
def check_same(li):
"""Check if all elements in the list are the same and not equal ' '.
Returns False of the value in the list."""
same = all([i == li[0] for i in li])
if same and li[0] != ' ':
return li[0]
return False |
def sign(x):
"""
Returns the sign of x
:param x:
:return:
"""
if x > 0:
return +1
elif x < 0:
return -1
elif x == 0:
return 0 |
def spy_game(nums):
"""
Write a function that takes in a list of integers and returns True if it contains 007 in order
:param nums: array
:return: bool
"""
code = [0, 0, 7, "x"]
for num in nums:
if num == code[0]:
code.pop(0) # code.remove(num) also works
return len... |
def list_contains(sublist, list_):
"""Tests whether sublist is contained in full list_."""
for i in range(len(list_)-len(sublist)+1):
if sublist == list_[i:i+len(sublist)]:
return True
return False |
def parseopts(opts):
"""
parses the command-line flags and options passed to the script
"""
params = {}
for opt, arg in opts:
if opt in ["-K"]:
params['K'] = int(arg)
elif opt in ["--input"]:
params['inputfile'] = arg
elif opt in ["--output"]:
... |
def _dotall(pattern):
"""Make the '.' special character match any character inside the pattern, including a newline.
This is implemented with the inline flag `(?s:...)` and is equivalent to using `re.DOTALL` when
it is the only pattern used. It is necessary since `mistune>=2.0.0`, where the pattern is pass... |
def seq_search(arr,ele):
"""
General Sequential Search. Works on Unordered lists.
"""
# Start at position 0
pos = 0
# Target becomes true if ele is in the list
found = False
# go until end of list
while pos < len(arr) and not found:
# If match
... |
def count_tup(tupl, value, start=None, end=None):
"""
Counts the number of times ``value`` occurs in ``tupl[start:end]``.
Optional arguments start and end are interpreted as in slice notation.
:param tupl: The tuple to search
:type tupl: ``tuple``
:param value: The value to count... |
def get_active_users(network_sp_users, active_users_perc, area_km2):
"""
Estimate the number of active users.
"""
active_users = round(
network_sp_users *
# (smartphone_users_perc/100) *
(active_users_perc/100) /
area_km2
)
return active_users |
def getOrthographyReferenced(crappyReferenceString, row, orthographies):
"""Return the id of the orthography model referenced in ``crappyReferenceString``.
``crappyReferenceString`` is something like "Orthography 1" or "Object Language Orthography 3"
and ``row`` is a row in the applicationsettings table. `... |
def calculate_chow_liu_log_likelihood(datum, conditioners, log_marginals, log_conditionals):
"""
@return: The likelihood of the datum given the Chow-Liu tree. I.e. using the conditional
likelihoods.
"""
result = 0.0
for f, v in enumerate(datum):
if None != v:
conditioner = co... |
def check_iterable_item_type(iter_obj):
""" Check if all items within an iterable are the same type.
Args:
iter_obj: iterable object
Returns:
iter_type: type of item contained within the iterable. If
the iterable has many types, a boolean False is returned instead.
... |
def view(path, *, sep='->'):
""" Forms string representation of path. """
if path is None:
return 'None'
return sep.join([str(point) for point in path]) |
def amount_primes(num: int) -> int:
"""
Calculates the amount of perfect numbers between 1 and 'num'.
With this approach, we obtain:
- Temporal Complexity => O(n)
- Spacial Complexity => O(n)
"""
# Generate detected primes. 0 and 1 are not primes
primes = [True for... |
def to_float(value):
"""
Convert given value to float if possible.
:param value: input value
:type value: mixed
:return: float value
:rtype: float
"""
try:
return float(value)
except ValueError:
assert False, 'value %s cannot be converted to float' % str(value) |
def get_sql_name(text):
"""
Create valid SQL identifier as part of a feature storage table name
"""
# Normalize identifier
text = "".join(c.lower() if c.isalnum() else " " for c in text)
text = "_".join(text.split())
return text |
def jaccard(s, t):
"""
Calculate the Jaccard Index of two sets.
J(S, T) = |S ^ T| / |S v T|
Parameters
----------
s, t : iterable
Returns
-------
float
"""
s_, t_ = set(s), set(t)
return len(s_ & t_) / len(s_ | t_) |
def mean_average(list_of_numbers):
"""Return the mean average of a list of numbers."""
return sum(list_of_numbers) / len(list_of_numbers) |
def has_sum_pair(input_list: list, sum: int) -> list:
"""Given list and desired integer sum, determines if a pair sums to that value."""
complement_set = set()
for number in input_list:
if (sum - number) in complement_set:
return [True, [number, sum - number]]
complement_se... |
def freq_dist(corpus):
"""Counts number of tokens in a corpus"""
output = {}
for text in corpus:
for word in text:
output[word] = output.get(word, 0) + 1
return output |
def get_sizes(doc: dict) -> list:
"""
Helper function to get unique sizes within a PDF
:param doc: The list of blocks within a PDF
:type: list
:rtype: list
:return: a list of unique font sizes
"""
# ensuring object is not None/empty
if not doc:
return []
unique_fonts = ... |
def format_time(seconds, with_hours=True):
"""Transforms seconds in a hh:mm:ss string.
If `with_hours` if false, the format is mm:ss.
"""
minus = seconds < 0
if minus:
seconds *= -1
m, s = divmod(seconds, 60)
if with_hours:
h, m = divmod(m, 60)
r = '%02d:%02d:%02... |
def format_country(ctry):
""" formats a country.
If is None returns None to chain with join_commas """
if ctry is not None:
return u" ({0})".format(ctry)
else:
return u'' |
def decode_byte_vector_to_string(byte_vector: bytes, ncolumns: int) -> str:
"""From byte vector to string"""
return byte_vector[:ncolumns].decode("ASCII").strip() |
def get(parameters, key, default=None, cast=str):
"""
Get the given query string parameter.
"""
try:
return cast(parameters[key][0]) if key in parameters else default
except TypeError:
return default |
def build_endpoint_rule_name(endpoint, method):
"""Build policy rule name for endpoint."""
return ('%(endpoint)s:%(method)s' %
{'endpoint': endpoint, 'method': method.lower()}) |
def duration(spec):
"""
>>> duration('1')
1.0
>>> duration('1s')
1.0
>>> duration('1 s')
1.0
>>> duration('1h')
3600.0
>>> duration('1d')
86400.0
>>> duration('1m')
60.0
"""
if spec.endswith('s'):
return float(spec[:-1])
elif spec.endswith('m'):
... |
def resource_descriptor(session, Type='String', RepCap='', AttrID=1050304, buffsize=2048, action=['Get', '']):
"""[Resource Descriptor <string>]
The resource descriptor specifies the connection to a physical device. It is either specified in the Configuration Store or passed in the ResourceName parameter of the... |
def find_complement(dna):
"""
:param dna: str, DNA consequence provided by user to be compared
:return: str, complement DNA consequence for given DNA consequence
"""
complement = ''
for i in range(len(dna)):
ch = dna[i]
if ch == 'A':
complement += 'T'
elif ch... |
def stationarity(sequence):
"""
Compute the stationarity of a sequence.
A stationary transition is one whose source and destination symbols
are the same. The stationarity measures the percentage of transitions
to the same location.
Parameters
----------
sequence : list
A list o... |
def error_loanword(value):
"""Checks whether the item is an unidentified loanword"""
return '<' in value |
def _parse_float(s):
"""Parse a floating point with implicit dot and exponential notation.
>>> _parse_float(' 12345-3')
0.00012345
"""
return float(s[0] + "." + s[1:6] + "e" + s[6:8]) |
def open_bed_file(bed_file_name):
"""Open BED file of sequence overlaps"""
with open(bed_file_name) as f:
cores = [i.split() for i in f.readlines() if "CORE" in i]
return cores |
def mul(c1, val):
"""Multiplies an encrypted counter by a public value"""
a1, b1 = c1
return (val*a1, val*b1) |
def multiline_code(string: str, language=None) -> str:
"""
Add multiline code md style.
:param language: Language of the code (default NONE)
:param string: The string to process.
:type string:str
:return: Formatted String.
:rtype: str
"""
return f"```{language if language else ''}\n... |
def squish_corpus(corpus, replace):
"""Squishes a corpus of data using a replacement dict
corpus: text data to squish
replace: the replacement dict
returns: the squished corpus (list of strings)
"""
squished = []
for line in corpus:
squished.append(' '.join([replace[token] for toke... |
def extended_euclid(a, b):
"""
For given a, b returns a tuple containing integers x, y and d such that
a*x + b*y = d. Here d = gcd(a, b).
Usage
=====
extended_euclid(a, b) -> returns x, y and gcd(a, b).
Details
=======
``a`` Any instance of Integer
``b`` Any insta... |
def _aws_profile(awsrc = {}):
"""Downloads the archive from AWS S3 using the AWS CLI.
Args:
awsrc: Configuration options for the AWS CLI tool
"""
extra_flags = ["--profile", awsrc["profile"]] if "profile" in awsrc else []
extra_environment = {"AWS_CONFIG_FILE": awsrc["profile_location"]} if "... |
def createProperMovieDictionary(raw_dict):
"""
Takes the dictionary provided by the request (full of strings)
and formats it where some variables need to have other types (e.g int, float)
also escapes all the single quotes characters in strings
:param raw_dict: the raw dictionary with the movie inf... |
def format_val(val: float) -> str:
"""Format float and return as str. Rules are round to two decimal places,
then remove any trailing 0s and decimal point if necessary.
Args:
val (float): Number to format.
Returns:
str: Number rounded to two decimal places with trailing '0' and '.'
... |
def copy_keys_except(dic, *keys):
"""Return a copy of the dict without the specified items.
"""
ret = dic.copy()
for key in keys:
try:
del ret[key]
except KeyError:
pass
return ret |
def collect_alphabets(cooccs):
"""
Return the `x` and `y` alphabets from a list of co-occurrences.
:param list cooccs: The list of co-occurrence tuples.
:return tuple alphabets: A tuple of two elements, the sorted list of
symbols in series `x` and the sorted list of symbols in series `y`.
... |
def deparen(s):
"""
Remove all interior parantheses from sequence.
"""
return s.replace("(", "").replace(")", "") |
def shear_bending_stress(V, Q, I, b):
""" Shear stresses due to bending
:param float V: Shear max_force in y direction
:param float Q: first moment of in cross section in y direction
:param float I: Area moment of inertia around the y axis
:param float b: thickness
:returns: Shear stress resul... |
def common_items(seq1, seq2):
""" Find common items between two sequences - version #1 """
common = []
for item in seq1:
if item in seq2:
common.append(item)
return common |
def calc_pages(total_count: int, this_count: int):
"""
preforms ciel operation to find the total number of pages
"""
return -(-total_count // this_count) |
def fullyConnectedTopology(elementList):
"""Creates a the adjacency list for a fully conected topology out of a linear
list of all elements in the network.
:param list[string] elementList: A list of all elements in the network.
"""
adjacencyList = {}
for pe in elementList:
adjacentTo = ... |
def calc_baryonic_mass_eos_insensitive(mass_g, radius_14):
"""
:param mass_g: gravitational mass in solar mass
:param radius_14: radius of 1.4 M_sun neutron star in meters
:return: baryonic mass
"""
mb = mass_g + radius_14**(-1.) * mass_g**2
return mb |
def get_type_list(feature_number):
"""
:param feature_number: an int indicates the number of features
:return: a list of features n
"""
if feature_number == 1:
type_list = ["close"]
elif feature_number == 2:
type_list = ["close", "volume"]
raise NotImplementedError("the f... |
def is_only_non_letters(word):
""" Returns True if the word only contains non-letter characters """
for letter in word:
if letter.isalpha():
return False
return True |
def get_lengths(pairs):
"""Get sum of lengths for each comment pair."""
return [len(c1) + len(c2) for c1, c2 in pairs] |
def transform_0_1( transform_in ):
"""
actually transforms the truthyness of anything
# for is_covid probably
"""
if transform_in:
return( "Yes")
else:
return( "No") |
def get_distance_far_box_edge(box, im_w):
"""
Simple method to get the distance (In Pixels!) to the far box edge of a
given box for a given image width.
"""
(left, right, top, bot) = box
center_image = im_w / 2
return max(abs(left - center_image), abs(right - center_image)) |
def dict_equal_primitive(this, that):
"""Compare two dictionaries but consider only primitive values"""
if not this.keys() == that.keys():
return False
equal_fields = []
for k, v in this.items():
if isinstance(v, (int, float, bool, str)):
equal_fields.append(v == that[k])
... |
def get_class_to_idx(item, class_mapping):
"""Method to return id for corresponding item."""
for k in class_mapping:
if k in item:
return class_mapping[k] |
def inverse(pattern):
""" gets the inverse pattern of a pattern """
new_pattern = ''
for item in pattern:
if item == '0':
new_pattern += '1'
elif item == '1':
new_pattern += '0'
else:
new_pattern += item
return new_pattern |
def _path_to_labber_section(path: str, delim: str) -> str:
"""Path to Labber format. Delete slashes from start and end.
Returns:
Formatted path in Labber format with given delimited."""
return path.strip("/").replace("/", delim) |
def serialize_entidad_federativa(entidad_federativa):
"""
$ref: '#/components/schemas/entidadFederativa'
CatPaises
"""
if entidad_federativa:
return {
"clave": entidad_federativa.codigo,
"valor": entidad_federativa.entidad_federativa
}
return {"clave":14,... |
def parse_tags(source):
"""
extract any substring enclosed in parenthesis
source should be a string
normally would use something like json for this
but I would like to make it easy to specify these tags and their groups
manually (via text box or command line argument)
http://stackoverf... |
def gcd(a, b):
"""Return the Greatest Common Divisor of a and b using
Euclid's Algorithm."""
while a != 0:
a, b = b % a, a
return b |
def cast_to_number_or_bool(inputstr):
"""Cast a string to int, float or bool. Return original string if it can't be
converted.
Scientific expression is converted into float.
"""
if inputstr.strip().lower() == "true":
return True
elif inputstr.strip().lower() == "false":
return F... |
def is_sum_of(target, numbers):
"""Find if target number can be summed from two numbers."""
for index, number in enumerate(numbers):
new_target = target - number
if new_target in set(numbers[0:index] + numbers[index:]):
return True
return False |
def dotget(root, path: str, default=None) -> object:
""" Access an item in the root field via a dot path.
Arguments:
- root: Object to access via dot path.
- path: Every dot path should be relative to the state property.
- default: Default value if path doesn't exist.
Returns: Value. If path do... |
def bitarray2int(bitarray):
""" Changes array's base from binary (base 2) to int (base 10).
Parameters:
bitarray: Binary Array.
>> Examples: bitarray2int([1, 1, 0]) returns 6
bitarray2int([0, 0, 1, 1,0]) returns 6
bitarray2int([1, 1, 1, 1, 1, 1, 1, 1]) r... |
def format_track(__, data):
"""Returns a formatted HTML line describing the track."""
return (
"<li><a href='{artist_tag}/{album_tag}.html'>{artist} - {album}</a>"
" - {track}</li>\n"
).format(**data) |
def write_new_frag_file(molecule_name,fragment_splitted , out_file):
""" writing a new fragment file
input:
output: a file
"""
alleles_segments = fragment_splitted[0]
quality = fragment_splitted[1]
if len(quality)>1: # it can be improved by adding the single allele to previous segment
... |
def string_to_isotope(string: str):
"""
Attempts to interpret an undefined key as an isotope/element combination (e.g. "13C" becomes 'C', 13). Raises a
ValueError if the string cannot be interpreted as such.
:param string: string to interpret
:return: element, isotope
:rtype: (str, int)
"""... |
def compute_interval_score(u, l, alpha, x):
"""
Function that computes the interval score
"""
return (u-l) + 2/alpha * (l-x) * (x < l) + 2/alpha * (x-u)*(x > u) |
def response_type_cmp(allowed, offered):
"""
:param allowed: A list of space separated lists of return types
:param offered: A space separated list of return types
:return:
"""
if ' ' in offered:
ort = set(offered.split(' '))
else:
try:
ort = {offered}
e... |
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
result = []
# Implement th... |
def append_method(form, method):
""" Return a new form with ``method`` added to methods_stack """
stack = form[4]
return form[:4] + (stack+(method,),) |
def as_variable(identifier: str) -> str:
"""
Translate the identifier of a mapry composite to a variable name in Python.
:param identifier: mapry identifier of a composite
:return: translated to a Python variable name
>>> as_variable('Some_URL_class')
'some_url_class'
"""
return ident... |
def _dict_iteritems(dictionary):
"""Get an iterator or view on the items of the specified dictionary.
This method is Python 2 and Python 3 compatible.
"""
try:
return dictionary.iteritems()
except AttributeError:
return dictionary.items() |
def is_float(variable):
"""Checks if a variable is a floating point value"""
return type(variable) == float |
def getPackageDetails(installedPackages, foundPackages):
"""
Gets the name, version, and repoName for the packages
"""
packageDetails = []
for package in foundPackages:
pkgDetail = {}
for installedPackage in installedPackages:
if package == installedPackage[0]:
pkgDetail['name'] = instal... |
def nums_to_numbits(nums):
"""Convert `nums` into a numbits.
Arguments:
nums: a reusable iterable of integers, the line numbers to store.
Returns:
A binary blob.
"""
try:
nbytes = max(nums) // 8 + 1
except ValueError:
# nums was empty.
return b''
bb ... |
def module_name_split(name):
"""
Split the module name into package name and module name.
"""
if "." in name:
package_name, module = name.rsplit(".", 1)
else:
package_name, module = "", name
return package_name, module |
def new_fps(original_fps: int, n_frames_original: int, n_frames_new: int) -> int:
""" Heuristically adjusts fps of delagged video to the new number of frames
by reducing the original fps and thus leveling the increased speed of the
filtered video being a side-effect of the frame discarding
... |
def validate_inputs(value, _):
"""Validate the entire input namespace."""
if 'scale_factors' not in value and ('scale_count' not in value
and 'scale_count' not in value):
return 'neither `scale_factors` nor the pair of `scale_count` and `scale_increment` were def... |
def get_stored_content_length(headers):
"""Return the content length (in bytes) of the object as stored in GCS.
x-goog-stored-content-length should always be present except when called via
the local dev_appserver. Therefore if it is not present we default to the
standard content-length header.
Args:
hea... |
def unique(alist):
"""
Returns a list containing only unique elements from the input list (but preserves
order, unlike sets).
"""
result = []
for item in alist:
if item not in result:
result.append(item)
return result |
def commas_no(qset):
"""Formats a queryset as a list seperated by commas and "og" at the end."""
string_list = list(map(str, qset))
if len(string_list) < 2:
return "".join(string_list)
return f"{', '.join(string_list[:-1])} og {string_list[-1]}" |
def interval_to_milliseconds(interval):
"""Convert a Binance interval string to milliseconds
:param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
None if unit not one of m, h, d or w
None if string not in corr... |
def bubble_sort(list1):
"""
It is similar is bubble sort but recursive.
:param list1: mutable ordered sequence of elements
:return: the same list in ascending order
>>> bubble_sort([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort([])
[]
>>> bubble_sort([-2, -45, -5])
... |
def get_valid_values(value, min_value, max_value):
"""Assumes value a string, min_value and max_value integers.
If value is in the range returns True.
Otherwise returns False."""
valid_values = [i for i in range(min_value, max_value + 1)]
try:
value = int(value)
except ValueError:
... |
def heading_count(phrase,char='~'):
"""Returns the number of negating prefixes in <phrase> and the <phrase> shorn of prefixes."""
count = 0
for x in phrase:
if x != char:
break
count+=1
return count,phrase[count:] |
def parser_network_name_Descriptor(data,i,length,end):
"""\
parser_network_name_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
Parses a descriptor containing the name of the 'network' of which the
multiplex is a part. In the United Kingdom for the Freeview Terrestrial
Servic... |
def hex2rgb(string):
"""hex2rgb(string)
return the integer value of a string, base 16
"""
return int(string, 16) |
def _make_tuple_of_string(x):
"""Converts `x` into a list of `str` if possible.
Args:
x: a `str`, a list of `str`, a tuple of `str`, or `None`.
Returns:
`x` if it is a tuple of str, `tuple(x)` if it is a list of str,
`(x)` if `x` is a `str`, `()` if x is `None`.
Raises:
TypeError: `x` is not ... |
def dependents(tokens, head_index):
"""Returns an ordered list of the token indices of the dependents for
the given head."""
# Create head->dependency index.
head_to_deps = {}
for i, token in enumerate(tokens):
head = token['dependencyEdge']['headTokenIndex']
if i != head:
... |
def hue_to_ASTM_hue(hue, code):
"""
Converts from the *Munsell* *Colorlab* specification hue to *ASTM* hue
number in domain [0, 100].
Parameters
----------
hue : numeric
*Munsell* *Colorlab* specification hue.
code : numeric
*Munsell* *Colorlab* specification code.
Retu... |
def combine(list1, list2):
"""
Write a function that combines two lists by alternatingly taking elements.
For example: given the two lists [a, b, c] and [1, 2, 3], the function
should return [a, 1, b, 2, c, 3].
"""
output = []
for i in range(max(len(list1), len(list2))):
output.appen... |
def csv_file_name(rows=10**5, columns=10, seed=0):
"""Return file name for given parameters."""
return f"data_{rows}_{columns}_{seed}.csv" |
def bfs(Adj,source): #uses Adjacency rep of a graph
"""assumes Adj as a nested List or dictionary and the indexes(keys) are
label of vertex and the sublist in each index contains the lables of
other vertexes which are connected to the indexed node"""
parent = {source: None} #parent of ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.