content
stringlengths 42
6.51k
|
---|
def get_catalog_record_embargo_available(cr):
"""Get access rights embargo available date as string for a catalog record.
Args:
cr (dict): A catalog record
Returns:
str: The embargo available for a dataset. Id not found then ''.
"""
return cr.get('research_dataset', {}).get('access_rights', {}).get('available', '')
|
def subset_to_seq(subset_sol):
"""Convert subset solution (e.g.: [[0,1],[0,0,1]]) into sequence solution (e.g.: ['r2','c3'])"""
m = len(subset_sol[0])
n = len(subset_sol[1])
seq_sol = list()
for i in range(m):
if subset_sol[0][i]:
seq_sol.append(f"r{i+1}")
for j in range(n):
if subset_sol[1][j]:
seq_sol.append(f"c{j+1}")
return seq_sol
|
def _is_quantity(obj):
"""Test for _units and _magnitude attrs.
This is done in place of isinstance(Quantity, arg), which would cause a circular import.
Parameters
----------
obj : Object
Returns
-------
bool
"""
return hasattr(obj, "_units") and hasattr(obj, "_magnitude")
|
def _dims_to_strings(dims):
"""
Convert dims that may or may not be strings to strings.
"""
return [str(dim) for dim in dims]
|
def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12):
"""
Returns True if a==b to the given relative and absolute errors, otherwise
False.
"""
# if the numbers are close enough (absolutely), then they are equal
if abs(a-b) < max_absolute_error:
return True
# if not, they can still be equal if their relative error is small
if abs(b) > abs(a):
relative_error = abs(a-b)/abs(b)
else:
relative_error = abs(a-b)/abs(a)
#print abs(a-b), relative_error
return relative_error <= max_relative_error
|
def reference_sibling(py_type: str) -> str:
"""
Returns a reference to a python type within the same package as the current package.
"""
return f'"{py_type}"'
|
def cTypeReplacements(tex):
"""
Replace the Latex command "\CONST{<argument>}" with just
argument.
"""
while (tex.find("\\CTYPE") != -1):
index = tex.find("\\CTYPE")
startBrace = tex.find("{", index)
endBrace = tex.find("}", startBrace)
tex = tex[:index] + tex[startBrace+1:endBrace] + tex[endBrace+1:]
return tex
|
def _center_coordinates(frag, center_atoms=0):
""" normalize centroids of multiple lists of [x,y,z] to the origin, (0,0,0) """
cx,cy,cz = 0.0,0.0,0.0
# collect the sum
for i in range(len(frag)):
cx, cy, cz = cx+frag[i][0], cy+frag[i][1], cz+frag[i][2]
points = len(frag)
x,y,z = cx/points,cy/points,cz/points
if center_atoms:
# decrement by the average
for i in range(len(frag)):
frag[i][0], frag[i][1], frag[i][2] = frag[i][0]-x, frag[i][1]-y, frag[i][2]-z
return -x, -y, -z
|
def get_dict_value(dictionary, key):
""" return the value of a dictionary key
"""
try:
return dictionary[key]
except (KeyError, IndexError):
return ''
|
def glissando_rate(times, start_freq, freq_rate):
"""returns frequency array to represent glissando from start at a given rate"""
return (start_freq + (times*freq_rate))
|
def integerize_arg(value):
"""Convert value received as a URL arg to integer.
Args:
value: Value to convert
Returns:
result: Value converted to iteger
"""
# Try edge case
if value is True:
return None
if value is False:
return None
# Try conversion
try:
result = int(value)
except:
result = None
# Return
return result
|
def find_totals_dimensions(dimensions, share_dimensions):
"""
WRITEME
:param dimensions:
:param share_dimensions:
:return:
"""
return [dimension
for dimension in dimensions
if dimension.is_rollup or dimension in share_dimensions]
|
def _amount(amount, asset='SBD'):
"""Return a steem-style amount string given a (numeric, asset-str)."""
assert asset == 'SBD', 'unhandled asset %s' % asset
return "%.3f SBD" % amount
|
def standard_field(input_name):
"""Returns a standard form of data field name"""
return input_name.lower()
|
def possible_bipartition(dislikes):
""" Will return True or False if the given graph
can be bipartitioned without neighboring nodes put
into the same partition.
Time Complexity: O(N+E)
Space Complexity: O(N)
"""
if not dislikes:
return True
if len(dislikes[0]) > 0:
to_visit = [0]
else:
to_visit = [1]
group_a = set()
group_b = set()
visited = []
while to_visit:
current = to_visit.pop(0)
visited.append(current)
a = True
b = True
for dislike in dislikes[current]:
if dislike in group_a:
a = False
if dislike in group_b :
b = False
if dislike not in visited and dislike not in to_visit:
to_visit.append(dislike)
if a == True:
group_a.add(current)
elif b == True:
group_b.add(current)
else:
return False
return True
|
def unparse_color(r, g, b, a, type):
"""
Take the r, g, b, a color values and give back
a type css color string. This is the inverse function of parse_color
"""
if type == '#rgb':
# Don't lose precision on rgb shortcut
if r % 17 == 0 and g % 17 == 0 and b % 17 == 0:
return '#%x%x%x' % (r / 17, g / 17, b / 17)
type = '#rrggbb'
if type == '#rgba':
if r % 17 == 0 and g % 17 == 0 and b % 17 == 0:
return '#%x%x%x%x' % (r / 17, g / 17, b / 17, a * 15)
type = '#rrggbbaa'
if type == '#rrggbb':
return '#%02x%02x%02x' % (r, g, b)
if type == '#rrggbbaa':
return '#%02x%02x%02x%02x' % (r, g, b, a * 255)
if type == 'rgb':
return 'rgb(%d, %d, %d)' % (r, g, b)
if type == 'rgba':
return 'rgba(%d, %d, %d, %g)' % (r, g, b, a)
|
def ps_new_query(tags=[], options = "all"):
"""
Query from PostgreSQL
Args:
tags: list of tags
options: 'all' means the posting must contains all the tags while 'any' means
that the posting needs to contain at least one of the tags
Returns:
job postings containing the tags, either containing all of the tags or
at least one of the tags
"""
if options == 'all':
sql_query = "SELECT * FROM jobs WHERE tags @> array{} LIMIT 25".format(tags)
else:
sql_query = "SELECT * FROM jobs WHERE tags && array{} LIMIT 25".format(tags)
return sql_query
|
def keys_to_str(to_convert):
"""
Replaces all non str keys by converting them.
Useful because python yaml takes numerical keys as integers
"""
if not isinstance(to_convert, dict):
return to_convert
return {str(k): keys_to_str(v) for k, v in to_convert.items()}
|
def azure_file_storage_account_settings(sdv, sdvkey):
# type: (dict, str) -> str
"""Get azure file storage account link
:param dict sdv: shared_data_volume configuration object
:param str sdvkey: key to sdv
:rtype: str
:return: storage account link
"""
return sdv[sdvkey]['storage_account_settings']
|
def _heaviside(x1: float, x2: float) -> float:
"""A custom Heaviside function for Numba support.
Parameters
----------
x1 : float
The value at which to calculate the function.
x2 : float
The value of the function at 0. Typically, this is 0.5 although 0 or 1 are also used.
Returns
-------
val : float
The value of the Heaviside function at the given point.
"""
if x1 > 0:
return 1.0
elif x1 == 0:
return x2
else:
return 0.0
|
def render_emoji(emoji):
"""Given norm_emoji, output text style emoji."""
if emoji[0] == ":":
return "<%s>" % emoji
return emoji
|
def dispatch(result):
"""DB query result parser"""
return [row for row in result]
|
def getGroupings(dimnames, groupings):
"""
see Schema.getGroupings above
"""
assert isinstance(groupings, dict), "groupings must be a dictionary"
assert isinstance(dimnames, list), "dimnames must be a list"
index_groupings = {}
for dim, groups in groupings.items():
index_groupings[dimnames.index(dim)] = groups
return index_groupings
|
def is_property(class_to_check, name):
"""Determine if the specified name is a property on a class"""
if hasattr(class_to_check, name) and isinstance(getattr(class_to_check, name), property):
return True
return False
|
def true_g(x):
"""
Compute the expected values of a point.
Parameters
----------
x : tuple of int
A feasible point
Returns
-------
tuple of float
The objective values
"""
chi2mean = 1
chi2mean2 = 3
obj1 = (x[0]**2)/100 - 4*x[0]/10 + (x[1]**2)/100 - 2*x[1]/10 + 15
obj2 = (x[0]**2)/100 + (x[1]**2)/100 - 4*x[1]/10 + 12
return obj1, obj2
|
def matchesType(value, expected):
"""
Returns boolean for whether the given value matches the given type.
Supports all basic JSON supported value types:
primitive, integer/int, float, number/num, string/str, boolean/bool, dict/map, array/list, ...
"""
result = type(value)
expected = expected.lower()
if result is int:
return expected in ("integer", "number", "int", "num", "primitive")
elif result is float:
return expected in ("float", "number", "num", "primitive")
elif result is str:
return expected in ("string", "str", "primitive")
elif result is bool:
return expected in ("boolean", "bool", "primitive")
elif result is dict:
return expected in ("dict", "map")
elif result is list:
return expected in ("array", "list")
return False
|
def _str_real(x):
"""Get a simplified string representation of a real number x."""
out = str(x)
return "({})".format(out) if '/' in out else out
|
def deduplicate(iterable):
""" Removes duplicates in the passed iterable. """
return type(iterable)(
[i for i in sorted(set(iterable), key=lambda x: iterable.index(x))])
|
def compare_settings(local_config_vars, remote_config_vars):
"""Compare local and remote settings and return the diff.
This function takes two dictionaries, and compares the two. Any given
setting will have one of the following statuses:
'=' In both, and same value for both (no action required)
'!' In both, but with different values (an 'update' to a known setting)
'+' [In local, but not in remote (a 'new' setting to be applied)
'?' In remote, but not in local (reference only - these are generally
Heroku add-on specfic settings that do not need to be captured
locally; they are managed through the Heroku CLI / website.)
NB This function will convert all local settings values to strings
before comparing - as the environment settings on Heroku are string.
This means that, e.g. if a bool setting is 'true' on Heroku and True
locally, they will **not** match.
Returns a list of 4-tuples that contains:
(setting name, local value, remote value, status)
The status value is one of '=', '!', '+', '?', as described above.
"""
diff = []
for k, v in local_config_vars.items():
if k in remote_config_vars:
if str(remote_config_vars[k]) == str(v):
diff.append((k, v, remote_config_vars[k], '='))
else:
diff.append((k, v, remote_config_vars[k], '!'))
else:
diff.append((k, v, None, '+'))
# that's the local settings done - now for the remote settings.
for k, v in remote_config_vars.items():
if k not in local_config_vars:
diff.append((k, None, v, '?'))
return sorted(diff)
|
def f(x):
"""
Quadratic function.
It's easy to see the minimum value of the function
is 5 when is x=0.
"""
return x**2 + 5
|
def fromSQLName(text):
"""
"""
return text.replace('_', ' ').title()
|
def _read_bdf_global(instream):
"""Read global section of BDF file."""
# read global section
bdf_props = {}
x_props = {}
comments = []
parsing_x = False
nchars = -1
for line in instream:
line = line.strip('\r\n')
if not line:
continue
elif line.startswith('COMMENT'):
comments.append(line[8:])
elif line.startswith('STARTPROPERTIES'):
parsing_x = True
elif line.startswith('ENDPROPERTIES'):
parsing_x = False
else:
keyword, values = line.split(' ', 1)
values = values.strip()
if keyword == 'CHARS':
# value equals number of chars
# this signals the end of the global section
nchars = int(values)
comments = '\n'.join(comments)
return nchars, comments, bdf_props, x_props
elif parsing_x:
x_props[keyword] = values
else:
# record all keywords in the same metadata table
bdf_props[keyword] = values
raise ValueError('No character information found in BDF file.')
|
def jaccard_distance(text1, text2):
""" Measure the jaccard distance of two different text.
ARGS:
text1,2: list of tokens
RETURN:
score(float): distance between two text
"""
intersection = set(text1).intersection(set(text2))
union = set(text1).union(set(text2))
return 1 - len(intersection) / len(union)
|
def permutate(seq):
"""permutate a sequence and return a list of the permutations"""
if not seq:
return [seq] # is an empty sequence
else:
temp = []
for k in range(len(seq)):
part = seq[:k] + seq[k+1:]
#print k, part # test
for m in permutate(part):
temp.append(seq[k:k+1] + m)
#print m, seq[k:k+1], temp # test
return temp
|
def s3_backup_mode_extended_s3_validator(x):
"""
Property: ExtendedS3DestinationConfiguration.S3BackupMode
"""
valid_types = ["Disabled", "Enabled"]
if x not in valid_types:
raise ValueError("S3BackupMode must be one of: %s" % ", ".join(valid_types))
return x
|
def sideeffect_python_found(*args, **kwargs): # pylint: disable=unused-argument
"""Custom side effect for patching subprocess.check_output."""
if 'sourceanalyzer' in args[0]:
return "Nothing to see here"
return ""
|
def replace_underscore_with_space(original_string):
"""
Another really simple method to remove underscores and replace with spaces for titles of plots.
Args:
original_string: String with underscores
Returns:
replaced_string: String with underscores replaced
"""
return original_string.replace('_', ' ')
|
def part2(course):
"""Find the end position of the submarine"""
aim, depth, horizontal = 0, 0, 0
for value in course:
command, unit = value.split(" ")
if command == "forward":
horizontal += int(unit)
depth += aim * int(unit)
elif command == "up":
aim -= int(unit)
else:
aim += int(unit)
return horizontal * depth
|
def twgoExpirationFacts(msg):
"""Used by :func:`twgoExpirationTime` to find latest stop time,
and if all records have one.
Finds the latest stop time in a message and also if all
records have a stop time (if all records don't have a stop
time, knowing the latest is moot).
Args:
msg (dict): Message to be evaluated.
Returns:
tuple: Tuple:
1. (str) Latest stop time in the message. Will return
``None`` if there are no stop times in the message.
2. (bool) ``True`` if all records have a stop time.
Else ``False``.
"""
latestStopTime = None
allRecordsHaveStopTime = True
if 'geometry' not in msg:
return (latestStopTime, False)
geoDicts = msg['geometry']
for x in geoDicts:
if 'stop_time' in x:
if latestStopTime == None:
latestStopTime = x['stop_time']
elif x['stop_time'] > latestStopTime:
# Bonus: ISO datetime sorts correctly as strings!
latestStopTime = x['stop_time']
else:
allRecordsHaveStopTime = False
return (latestStopTime, allRecordsHaveStopTime)
|
def is_float(value, return_value=False):
""" Return value as float, if possible """
try:
value = float(value)
except ValueError:
if not return_value:
return False
if return_value:
return value
return True
|
def gcd(a, b):
"""
given a and b, return the greatest common divisor
>>> gcd(75, 21)
3
>>> gcd(52, 81)
1
>>> gcd(27, 18)
9
>>> gcd(300, 42)
6
>>> gcd(254, 60)
2
"""
while b != 0:
(a, b) = (b, a % b)
return a
|
def _validate_output_feature_name_from_test_stats(
output_feature_name,
test_stats_per_model
):
"""Validate prediction output_feature_name from model test stats and return it as list.
:param output_feature_name: output_feature_name containing ground truth
:param test_stats_per_model: list of per model test stats
:return output_feature_names: list of output_feature_name(s) containing ground truth
"""
output_feature_names_set = set()
for ls in test_stats_per_model:
for key in ls:
output_feature_names_set.add(key)
try:
if output_feature_name in output_feature_names_set:
return [output_feature_name]
else:
return output_feature_names_set
# raised if output_feature_name is emtpy iterable (e.g. [] in set())
except TypeError:
return output_feature_names_set
|
def _check_value(remote_value, local_value):
"""
Validates if both parameters are equal.
:param remote_value:
:param local_value:
:return: True if both parameters hold the same value, False otherwise
:rtype: bool
"""
if isinstance(remote_value, bool) or isinstance(local_value, bool):
remote_value = False if remote_value is None else remote_value
local_value = False if local_value is None else local_value
if remote_value is not None and local_value is not None:
return True if remote_value == local_value else False
elif remote_value is None and local_value is None:
return True
else:
return False
|
def sec_played(time):
"""Converts mm:ss time format to total seconds"""
minutes_and_sec = time.split(':')
return int(minutes_and_sec[0]) * 60 + int(minutes_and_sec[1])
|
def is_file_like(v):
"""
Return True if this object is file-like or is a tuple in a format
that the requests library would accept for uploading.
"""
# see http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests
return hasattr(v, 'read') or (
isinstance(v, tuple) and len(v) >= 2 and hasattr(v[1], 'read'))
|
def mapparms(old, new) :
"""
Linear map parameters between domains.
Return the parameters of the linear map ``offset + scale*x`` that maps
`old` to `new` such that ``old[i] -> new[i]``, ``i = 0, 1``.
Parameters
----------
old, new : array_like
Domains. Each domain must (successfully) convert to a 1-d array
containing precisely two values.
Returns
-------
offset, scale : scalars
The map ``L(x) = offset + scale*x`` maps the first domain to the
second.
See Also
--------
getdomain, mapdomain
Notes
-----
Also works for complex numbers, and thus can be used to calculate the
parameters required to map any line in the complex plane to any other
line therein.
Examples
--------
>>> from numpy import polynomial as P
>>> P.mapparms((-1,1),(-1,1))
(0.0, 1.0)
>>> P.mapparms((1,-1),(-1,1))
(0.0, -1.0)
>>> i = complex(0,1)
>>> P.mapparms((-i,-1),(1,i))
((1+1j), (1+0j))
"""
oldlen = old[1] - old[0]
newlen = new[1] - new[0]
off = (old[1]*new[0] - old[0]*new[1])/oldlen
scl = newlen/oldlen
return off, scl
|
def update_lease(leases, entry):
"""
Update a dictionary of DHCP leases with a new entry.
The dictionary should be indexed by MAC address. The new entry will be
added to the dictionary unless it would replace an entry for the same MAC
address from a more recent lease file.
"""
mac_addr = entry['mac_addr']
if mac_addr in leases:
existing = leases[mac_addr]
if existing['as_of'] >= entry['as_of']:
return existing
leases[mac_addr] = entry
return entry
|
def variant_size(variant):
""" Can only call this function on a vcf variant dict """
return abs(len(variant['ALT']) - len(variant['REF']))
|
def get_clevr_pblock_op(block):
"""
Return the operation of a CLEVR program block.
"""
if 'type' in block:
return block['type']
assert 'function' in block
return block['function']
|
def convert_numeric_list(str_list):
"""
try to convert list of string to list of integer(preferred) or float
:param str_list: list of string
:return: list of integer or float or string
"""
assert isinstance(str_list, list)
if not str_list:
return str_list
try:
return list(map(int, str_list))
except ValueError:
try:
return list(map(float, str_list))
except ValueError:
return str_list
|
def validate_instance(in_instance):
"""
Check that the user provided a valid instance
"""
if not in_instance:
return "dev"
else:
i = in_instance.lower()
if i in ["prod", "test", "dev"]:
return i
else:
raise IOError("Invalid instance. Must be dev, test, or prod.")
|
def list_to_string(list, separator=", "):
"""Returns a new string created by converting each items in `list` to a
new string, where each word is separated by `separator`.
:param list: list of iterable items to covert to a string.
:param separator: character to use as a separator between the list items.
"""
return separator.join(map(str, list))
|
def action_tuple_to_str(action):
"""
Converts the provided action tuple to a string.
:param action: the action
:return: a string representation of the action tuple
"""
if action is None:
return None
return str(action[0]) + str(action[1]) + action[2]
|
def deleteSpecChars(text, specialChars):
"""
This function removes special characters from a string and returns a new string
INPUT:
text: string
specialChars: List of characters to be removed
OUTPUT:
newTextList: type <list> Each element in list is a string
"""
for char in specialChars:
text = text.replace(char, '')
return text
|
def isVariableCandidate(atomsList):
"""
Check is atoms list from an atom term is variable or not.
It checks if the atoms are in decrease order.
Parameters
----------
atomsList : list
Bonded term list of atoms
Returns
-------
variable : bool
True if are a variable candidate
"""
for ele in atomsList[1:]:
if atomsList[0]<ele:
return False
return True
|
def is_positive_number(*arr):
"""Check if the numbers are positive number.
:param arr: number array
:return: True if are positive number, or False if not
"""
for n in arr:
if n <= 0:
return False
return True
|
def quick_sort(integers):
"""Perform a quick sort on a list of integers, selecting a pivot
point, partition all elements into a first and second part while
looping so all elements < pivot are in first part, any elements
> then pivot are in seconds part, recursively sort both half's
and combine.
"""
integers_clone = list(integers)
def helper(arr, first, last):
"""Quick sort helper method for finding pivot/split points in list."""
if first < last:
split = partition(arr, first, last)
helper(arr, first, split - 1)
helper(arr, split + 1, last)
def partition(arr, first, last):
"""Generate a partition point for the given array."""
pivot_value = arr[first]
left = first + 1
right = last
done = False
while not done:
while left <= right and arr[left] <= pivot_value:
left += 1
while arr[right] >= pivot_value and right >= left:
right -= 1
if right < left:
done = True
else:
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
temp = arr[first]
arr[first] = arr[right]
arr[right] = temp
return right
helper(integers_clone, 0, len(integers_clone) - 1)
return integers_clone
|
def decode_database_key(s):
"""Extract Guage_id, Reading_type, Datestr form provided keystring.
"""
lst = s.split("-")
gid = lst[0]
rdng = lst[1]
dstr = lst[2]
return (gid, rdng, dstr)
|
def splitext( filename ):
""" Return the filename and extension according to the first dot in the filename.
This helps date stamping .tar.bz2 or .ext.gz files properly.
"""
index = filename.find('.')
if index == 0:
index = 1+filename[1:].find('.')
if index == -1:
return filename, ''
return filename[:index], filename[index:]
return os.path.splitext(filename)
|
def is_instance(list_or_dict):
"""Converts dictionary to list"""
if isinstance(list_or_dict, list):
make_list = list_or_dict
else:
make_list = [list_or_dict]
return make_list
|
def _get_opt_attr(obj, attr_path):
"""Returns the value at attr_path on the given object if it is set."""
attr_path = attr_path.split('.')
for a in attr_path:
if not obj or not hasattr(obj, a):
return None
obj = getattr(obj, a)
return obj
|
def flatten_list(l):
"""Flatten list of lists"""
return [item for sublist in l for item in sublist]
|
def _bool_to_bool(data):
"""
Converts *Javascript* originated *true* and *false* strings
to `True` or `False`. Non-matching data will be passed untouched.
Parameters
----------
data : unicode
Data to convert.
Returns
-------
True or False or unicode
Converted data.
"""
if data == 'true' or data is True:
return True
elif data == 'false' or data is False:
return False
else:
return data
|
def parse_url(url):
"""
Parse a 'swift://CONTAINER/OBJECT' style URL
:param url:
:return: dictionary with "container" and "obj" keys
"""
url = url.replace("swift://", "")
if url.find("/") == -1:
raise ValueError("Swift url must be 'swift://container/object'")
pieces = url.split("/")
containername = pieces[0]
objname = "/".join(pieces[1:])
return {
"container": containername,
"obj": objname,
}
|
def contains(sequence, value):
"""A recursive version of the 'in' operator.
"""
for i in sequence:
if i == value or (hasattr(i, '__iter__') and contains(i, value)):
return True
return False
|
def jump(current_command):
"""Return Jump Mnemonic of current C-Command"""
#jump exists after ; if ; in string. Always the last part of the command
if ";" in current_command:
command_list = current_command.split(";")
return command_list[-1]
else:
return ""
|
def binary_sum(S, start, stop):
"""Return the sum of the numbers in implicit slice S[start:stop]."""
if start >= stop: # zero elements in slice
return 0
elif start == stop-1: # one element in slice
return S[start]
else: # two or more elements in slice
mid = (start + stop) // 2
return binary_sum(S, start, mid) + binary_sum(S, mid, stop)
|
def mean(array):
"""
Calculates the mean of an array/vector
"""
import numpy as np
array=np.array(array)
result= np.mean(array)
return result
|
def isiterable(obj):
"""Return True iff an object is iterable."""
try:
iter(obj)
except Exception:
return False
else:
return True
|
def get_git_sha_from_dockerurl(docker_url: str, long: bool = False) -> str:
""" We encode the sha of the code that built a docker image *in* the docker
url. This function takes that url as input and outputs the sha.
"""
parts = docker_url.split("/")
parts = parts[-1].split("-")
sha = parts[-1]
return sha if long else sha[:8]
|
def get_image(images, image_name):
"""Get the image config for the given image_name, or None."""
for image in images:
if image["name"] == image_name:
return image
return None
|
def fix_tract(t):
"""Clean up census tract names.
:param t: Series of string tract names
:returns: Series of cleaned tract names
"""
if type(t) == str:
return t
return str(t).rstrip("0").rstrip(".")
|
def icontains(header_value: str, rule_value: str) -> bool:
"""
Case insensitive implementation of str-in-str lookup.
Parameters
----------
header_value : str
String to look within.
rule_value : str
String to look for.
Returns
-------
bool
Whether *rule* exists in *value*
"""
return rule_value.lower() in header_value.lower()
|
def same_fringe(tree1, tree2):
""" Detect is the given two trees have the same fringe. A fringe is a list
of leaves sorted from left to right.
"""
def is_leaf(node):
return len(node['children']) == 0
def in_order_traversal(node):
if node == None:
return []
if is_leaf(node):
return [node['key']]
leaves = []
for child in node['children']:
leaves.extend(in_order_traversal(child))
return leaves
leaves1 = in_order_traversal(tree1)
leaves2 = in_order_traversal(tree2)
return leaves1 == leaves2
|
def CheckUpperLimitWithNormalization(value, upperLimit, normalization=1, slack=1.e-3):
"""Upper limit check with slack.
Check if value is no more than upperLimit with slack.
Args:
value (float): Number to be checked.
upperLimit (float): Upper limit.
normalization (float): normalization value
slack (float); Slack for check.
Returns:
bool: True if value is no more than upperLimit with slack
"""
if(value - upperLimit <= normalization*slack):
return True
else:
return False
|
def is_id_in_annotation(xml_id, annotation_id):
"""is_id_in_annotation
:param xml_id: list of id occured in xml files
:param annotation_id: list of id which used for annotation
"""
not_in_anno = [x for x in xml_id if x not in annotation_id]
not_in_xml = [x for x in annotation_id if x not in xml_id]
return not_in_anno, not_in_xml
|
def ru(v, n = 100.0):
"""Round up, to the nearest even 100"""
import math
n = float(n)
return math.ceil(v/n) * int(n)
|
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
for i in board:
if i[0] != None:
if i[0] == i[1] == i[2]:
return i[0]
for i in range(3):
if board[0][i] != None:
if board[0][i] == board[1][i] == board[2][i]:
return board[0][i]
if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[0][0] != None:
return board[0][0]
if board[0][2] == board[1][1] and board[2][0] == board[1][1]and board[0][2] != None:
return board[0][2]
return None
|
def DER_SNR(flux):
# =====================================================================================
"""
DESCRIPTION This function computes the signal to noise ratio DER_SNR following the
definition set forth by the Spectral Container Working Group of ST-ECF,
MAST and CADC.
signal = median(flux)
noise = 1.482602 / sqrt(6) median(abs(2 flux_i - flux_i-2 - flux_i+2))
snr = signal / noise
values with padded zeros are skipped
USAGE snr = DER_SNR(flux)
PARAMETERS none
INPUT flux (the computation is unit independent)
OUTPUT the estimated signal-to-noise ratio [dimensionless]
USES numpy
NOTES The DER_SNR algorithm is an unbiased estimator describing the spectrum
as a whole as long as
* the noise is uncorrelated in wavelength bins spaced two pixels apart
* the noise is Normal distributed
* for large wavelength regions, the signal over the scale of 5 or
more pixels can be approximated by a straight line
For most spectra, these conditions are met.
REFERENCES * ST-ECF Newsletter, Issue #42:
www.spacetelescope.org/about/further_information/newsletters/html/newsletter_42.html
* Software:
www.stecf.org/software/ASTROsoft/DER_SNR/
AUTHOR Felix Stoehr, ST-ECF
24.05.2007, fst, initial import
01.01.2007, fst, added more help text
28.04.2010, fst, return value is a float now instead of a numpy.float64
"""
from numpy import array, where, median, abs
flux = array(flux)
# Values that are exactly zero (padded) are skipped
flux = array(flux[where(flux != 0.0)])
n = len(flux)
# For spectra shorter than this, no value can be returned
if (n>4):
signal = median(flux)
noise = 0.6052697 * median(abs(2.0 * flux[2:n-2] - flux[0:n-4] - flux[4:n]))
return float(signal / noise)
else:
return 0.0
|
def is_palindrome1(str):
"""
Create slice with negative step and confirm equality with str.
"""
return str[::-1] == str
|
def strip_newlines(s):
"""
Strip new lines and replace with spaces
"""
return s.replace('\n', ' ').replace('\r', '')
|
def der_allele(var):
"""
Returns the derived allele of this SNP variant.
Args:
var: A variant string representing a SNP
Returns:
The derived base as uppercase
"""
var = var.rstrip(')!')
return var[-1].upper()
|
def __parseConnectionString(connectionString):
"""
Parses the queue connection string. Returns a dict of parameters found.
"""
return dict(item.split('=') for item in connectionString.split(';'))
|
def tally_letters(string):
"""Given a string of lowercase letters, returns a dictionary mapping each
letter to the number of times it occurs in the string."""
count_char = {}
for char in string:
count = 0
if char not in count_char:
for c in string:
if char == c:
count += 1
count_char[char] = count
return count_char
|
def text(el, strip=True):
"""
Return the text of a ``BeautifulSoup`` element
"""
if not el:
return ""
text = el.text
if strip:
text = text.strip()
return text
|
def mhdistsq(a, b):
""" The function computes the 'Squared Manhattan Distance' in two dimensions """
return ((a[0] - b[0])**2 + (a[1] - b[1])**2)
|
def find_tweets_with_keywords_idf(tweets, keywords, idf, idf_treshold=5):
""" Tries to find tweets that have at least one of the keywords in them
:param tweets: The to be checked tweets
:param article: The article
:param idf_treshold: The minimal som of mathing idf values that need to be in the tweet to select it
:return: A list of the [idf_sum, tweet] that are related to the article
"""
article_tweets_idfs = []
for tweet in tweets:
idf_sum = 0
p = False
for keyword in keywords:
tweet_keywords = tweet.get_keywords()
if keyword in tweet_keywords:
if keyword not in idf:
print("Could not find idf value of %s" % idf)
idf_sum += 3
else:
idf_sum += idf[keyword]
if idf_sum >= idf_treshold:
p = True
if p:
article_tweets_idfs.append((idf_sum, tweet, ))
return article_tweets_idfs
|
def plot_kwargs(kwargs):
"""
Specializes proc_kwargs for plots.
"""
plt_args = {'alpha': None,
'color': None,
'linestyle': None,
'linewidth': None,
'marker': None,
'markersize': None,
'label': None
}
for k, v in plt_args.items():
try:
plt_args[k] = kwargs[k]
except KeyError:
continue
return plt_args
|
def invalid_shape(current_shape):
"""
:param tuple current_shape: The current shape of the data after a convolution is applied.
:return: True if the shape is invalid, that is, a negative or 0 components exists. Else, it
returns False.
:rtype: bool
"""
# check all components
for component in current_shape:
if component <= 0:
return True
# return False if they are ok
return False
|
def are_equal(drive_list, partition_infos):
"""Checks whether partitions in a drive fit to the expected partition infos.
"""
if len(drive_list) == len(partition_infos):
for drive_info, partition_info in zip(drive_list, partition_infos):
if drive_info[0] != partition_info[0]:
return False
return True
return False
|
def count_syllables(lang, word):
"""
Detect syllables in words
Thanks to http://codegolf.stackexchange.com/questions/47322/how-to-count-the-syllables-in-a-word
"""
if lang == 'en':
cnt = len(''.join(" x"[c in"aeiouy"]for c in(word[:-1]if'e' == word[-1]else word)).split())
else:
cnt = len(''.join(" x"[c in"aeiou"]for c in(word[:-1]if'e' == word[-1]else word)).split())
return cnt
|
def _check_key(node_index, key):
"""Checks that node ordinal key is equal to provided integer key and raise ValueError if not.
"""
if node_index != key:
raise ValueError(
"Nodes of the networkx.OrderedMultiDiGraph must have sequential integer keys consistent with the order"
"of the nodes (e.g. `list(graph_nx.nodes)[i] == i`), found node with index {} and key {}"
.format(node_index, key))
return True
|
def func_mass_foundation_onshore(height: float, diameter: float) -> float:
"""
Returns mass of onshore turbine foundations
:param height: tower height (m)
:param diameter: rotor diameter (m)
:return:
"""
return 1696e3 * height / 80 * diameter ** 2 / (100 ** 2)
|
def skalarprodukt (vec1, vec2):
"""bildet das Skalarprodukt aus zwei Vektoren
Vektor (Eingabe + Ausgabe): Liste der Form [x1, x2, x3]"""
result = vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2]
return result
|
def load_dict_from_file(path):
"""Loads key=value pairs from |path| and returns a dict."""
d = {}
with open(path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if '=' in line:
name, value = line.split('=', 1)
d[name] = value
return d
|
def unique_courses(slots_table):
"""Obtain list of unique courses from slot listing.
Arguments:
slots_table (list of dict) : TA slot records
Returns:
(list of str) : sorted list of course numbers
"""
# obtain list of unique course numbers
course_set = set()
for slot in slots_table:
course_set.add(slot["course"])
course_list = list(course_set)
course_list.sort()
return course_list
|
def array_split(ary,n):
"""
>>> data = [1,2,3,4,5]
>>> array_split(data,3)
[[1, 2], [3, 4], [5]]
>>> grps = array_split(range(0,1121),8)
>>> total_len = 0
>>> for grp in grps: total_len += len(grp)
>>> assert(total_len == len(range(0,1121)))
"""
step = int(round(len(ary)/float(n)))
if step == 0:
step = 1
ret = []
idx = 0
for ii in range(0,n):
if ii == n-1:
app = ary[idx:]
else:
app = ary[idx:idx+step]
if len(app) > 0:
ret.append(app)
idx = idx + step
return(ret)
|
def parser_valid_description(myadjs, mynouns, objadjs, objnouns) :
"""Checks whether (myadjs, mynouns) is a valid description for
(objadjs,objnouns)."""
if not myadjs and not mynouns :
return False
for madj in myadjs :
if madj not in objadjs :
return False
for mnoun in mynouns :
if mnoun not in objnouns :
return False
return True
|
def funkcija(f, domena, kodomena):
"""Je li f:domena->kodomena?"""
return f.keys() == domena and set(f.values()) <= kodomena
|
def get_available_setup_commands():
"""
Returns the list of commands :epkg:`pyquickhelper` implements
or allows.
"""
commands = ['bdist_egg', 'bdist_msi', 'bdist_wheel', 'bdist_wininst', 'build27',
'build_ext', 'build_script', 'build_sphinx', 'clean_pyd', 'clean_space',
'copy27', 'copy_dist', 'copy_sphinx', 'history', 'lab', 'local_pypi',
'notebook', 'publish', 'publish_doc', 'register', 'run27', 'run_pylint',
'sdist', 'setup_hook', 'setupdep', 'test_local_pypi',
'unittests', 'unittests_GUI', 'unittests_LONG', 'unittests_SKIP',
'upload_docs', 'write_version', 'local_jenkins']
return commands
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.