content
stringlengths 42
6.51k
|
---|
def format_check_update_request(request):
"""
parses the update request
return dictionary
Parameters:
------------
request: station_name0:column0:value0, [station_name1:]column1:value1, [...] or list
station_nameN: first entry must have the station_name,
if it does not then propagate first station_name but
can't restart 3 then 2
columnN: name of geo_location column
valueN: corresponding new value
"""
if request is None:
return None
data = {}
if type(request) == str:
tmp = request.split(',')
data_to_proc = []
for d in tmp:
data_to_proc.append(d.split(':'))
else:
data_to_proc = request
if len(data_to_proc[0]) == 3:
station_name0 = data_to_proc[0][0]
for d in data_to_proc:
if len(d) == 3:
pass
elif len(d) == 2:
d.insert(0, station_name0)
else:
print('Invalid format for update request.')
continue
if d[0] in data.keys():
data[d[0]].append(d)
else:
data[d[0]] = [d]
else:
print('Invalid parse request - need 3 parameters for at least first one.')
data = None
return data
|
def num_padding_bytes(length):
"""Return the number of padding bytes needed for the given length."""
return ((length + 7) & ~7) - length
|
def get_root_table_from_path(path):
"""extract root table name from path"""
spath = path.split('.')
if len(spath) == 0:
return path
else:
return spath[0]
|
def check_answer(guess, answer, turns):
"""
Check the user's guess against actual answer. If not right then minus 1 lives.
"""
if guess > answer:
print("Too High")
return turns - 1
elif guess < answer:
print("Too Low")
return turns - 1
else:
print(f" You got it! The answer was {answer} ")
|
def convert_frame(exon_frame):
"""converts genePred-style exonFrame to GFF-style phase"""
mapping = {0: 0, 1: 2, 2: 1, -1: '.'}
return mapping[exon_frame]
|
def _collect_package_prefixes(package_dir, packages):
"""
Collect the list of prefixes for all packages
The list is used to match paths in the install manifest to packages
specified in the setup.py script.
The list is sorted in decreasing order of prefix length so that paths are
matched with their immediate parent package, instead of any of that
package's ancestors.
For example, consider the project structure below. Assume that the
setup call was made with a package list featuring "top" and "top.bar", but
not "top.not_a_subpackage".
::
top/ -> top/
__init__.py -> top/__init__.py (parent: top)
foo.py -> top/foo.py (parent: top)
bar/ -> top/bar/ (parent: top)
__init__.py -> top/bar/__init__.py (parent: top.bar)
not_a_subpackage/ -> top/not_a_subpackage/ (parent: top)
data_0.txt -> top/not_a_subpackage/data_0.txt (parent: top)
data_1.txt -> top/not_a_subpackage/data_1.txt (parent: top)
The paths in the generated install manifest are matched to packages
according to the parents indicated on the right. Only packages that are
specified in the setup() call are considered. Because of the sort order,
the data files on the bottom would have been mapped to
"top.not_a_subpackage" instead of "top", proper -- had such a package been
specified.
"""
return list(
sorted(
((package_dir[package].replace(".", "/"), package) for package in packages),
key=lambda tup: len(tup[0]),
reverse=True,
)
)
|
def array_search(l, val):
"""
Returns the index of `val` in `l`.
"""
try:
return l.index(val)
except ValueError:
return False
|
def encodeentity(s):
""" Default encoder for HTML entities: replaces &, <, > and " characters only. """
return s.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')
|
def set_node_schedulability(facts):
""" Set schedulable facts if not already present in facts dict
Args:
facts (dict): existing facts
Returns:
dict: the facts dict updated with the generated schedulable
facts if they were not already present
"""
if 'node' in facts:
if 'schedulable' not in facts['node']:
if 'master' in facts:
facts['node']['schedulable'] = False
else:
facts['node']['schedulable'] = True
return facts
|
def preparse(tokens):
"""
Break up a tokenized source into lists; this allows input like
pl> (a, b) (c, d)
to work as expected.
"""
count_open = 0
lists = []
current_list = []
if len(tokens) == 0:
raise SyntaxError("Unexpected EOF while preparsing.")
for token in tokens:
if token == '(':
count_open += 1
current_list.append('(')
elif token == '\'(':
count_open += 1
current_list.append('\'(')
elif token.startswith("'"):
current_list.append('"{}"'.format(token[1:]))
continue
elif token == ')':
if count_open == 0:
# Too many closing parens
raise SyntaxError(" Unexpected ) while preparsing!")
count_open -= 1
current_list.append(')')
if count_open == 0:
# This list is done; split it off and start a new one
lists.append(current_list)
current_list = []
else:
# Any other token
current_list.append(token)
continue
# Once the loop is done, there can't be any remaining open
# parentheses, or the source is unbalanced
if count_open != 0:
raise SyntaxError("Missing a closing parenthesis while" +
"preparsing ({}).".format(count_open))
return lists
|
def cilogon_id_map_to_ssh_keys(m):
""" convert id map (as returned by get_cilogon_ldap_id_map) to a dict with
structure: {CILogonID: [sshPublicKey, ...], ...} for each id that has
ssh public keys defined """
return {
k: v['data']['sshPublicKey']
for k, v in m.items()
if 'sshPublicKey' in v['data']
}
|
def _shift_twelve(number):
"""Shifts the number by 12, if it is less than 0.
Parameters
----------
number : int
Returns
-------
int
"""
return number + 12 if number < 0 else number
|
def listNet(netList):
"""Returns a string containing all the nets available n the following format.'---Name net: ~s. Net: ~s' """
result = ""
for net in netList:
result = result + "---Name of the net: " + net["name"] + ". Net: " + net["netString"] + "\n"
return result
|
def lunique(original_list):
""" list unique """
result = []
for o in original_list:
if o not in result:
result.append(o)
return result
# je fais ca plutot que de list(set(...)) pour garder l'ordre
|
def digitSum(number):
"""
The function will get the sum of the number.
"""
sumNum = 0
while number:
sumNum += number % 10 # Get last digit of the number.
number //= 10 # Remove the last digit of the number.
return sumNum
|
def viewDimensionsFromN(n=1):
"""
Compute the number of horizontal and vertical views needed to reach at least n views.
Returns a pair of numbers.
"""
h = 0
w = 0
while True:
if h * w >=n:
break
h += 1
if h * w >= n:
break
w += 1
return (h, w)
|
def get_insert_order(deps, insert_order=None):
"""
We're in for some trouble if there are circular deps.
"""
insert_order = []
dep_list = [(t, p) for t, p in deps.items()]
for tablename, parents in dep_list:
# If all parents are already ordered, add this to the ordered list.
if not [p for p in parents if p not in insert_order]:
insert_order.append(tablename)
else:
# Otherwise, add tuple to end of list, so we check it again.
dep_list.append((tablename, parents))
return insert_order
|
def convert_to_args(conf, prefix=None):
"""
Convert hierarchical configuration dictionary to argparse arguments.
'environment' at root level is a special case: if it is a hash,
it is converted into an array of VAR=VALUE pairs.
"""
args = []
conf = conf or {}
prefix = prefix or ()
if not prefix and 'environment' in conf:
environment = conf['environment']
if isinstance(environment, dict):
conf['environment'] = [
'{0}={1}'.format(k, v)
for k, v in environment.items()
]
for key, value in conf.items():
arg_prefix = prefix + (key,)
if isinstance(value, dict):
args.extend(convert_to_args(value, arg_prefix))
else:
if not isinstance(value, (list, tuple)):
value = (value,)
if len(value) > 0:
args.append('--' + '.'.join(arg_prefix))
for val in value:
args.append(str(val))
return args
|
def is_above_line(point_a, point_b, test_point):
"""
A method to check whether a point is above the line between two given points
or not.
Args:
point_a (numpy array): a point on the line.
point_b (numpy array): another point on the line.
test_point (numpy array): the point that needs to be tested.
Returns:
state (bool): whether the proposition is True or False.
"""
d_1 = (point_b[0] - point_a[0])
d_2 = (test_point[1] - point_a[1])
d_3 = (point_b[1] - point_a[1])
d_4 = (test_point[0] - point_a[0])
pos = (d_1 * d_2) - (d_3 * d_4)
if pos >= 0: # this means anything on the line is being considered as above
# the line, this is useful in generating simple polygon.
return True
else:
return False
|
def translate(text, conversion_dict, before=lambda _: _):
""" Translate words from a text using a conversion dictionary
@brief text The text to be translated
@brief conversion_dict The conversion dictionary
@brief before A function to transform the input
"""
# if empty:
if not text: return text
# preliminary transformation:
before = before or str.lower
t = before(text)
for key, value in conversion_dict.items():
t = t.replace(key, value)
return t
|
def cam_id_to_name(cam_id):
"""Convert the camera ID to camera name"""
if cam_id == 0:
return "clairton1"
elif cam_id == 1:
return "braddock1"
elif cam_id == 2:
return "westmifflin1"
else:
return None
|
def maxi(a,b):
""" Maximal value
>>> maxi(3,4)
4
"""
if a > b:
return a
return b
|
def convert_input_to_css_name(input: str) -> str:
"""Convert the spoken input of a color name to the CSS official name."""
return input.lower().replace(" ", "")
|
def find_reasonable_year_ticks(start_time, end_time):
"""
Function to find reasonable spacing between years for x-ticks.
Args:
start_time: Float for left x-limit in years
end_time: Float for right x-limit in years
Returns:
times: The times for the x ticks
"""
duration = end_time - start_time
if duration > 1e3:
spacing = 1e2
elif duration > 75.:
spacing = 25.
elif duration > 25.:
spacing = 10.
elif duration > 15.:
spacing = 5.
elif duration > 5.:
spacing = 2.
else:
spacing = 1.
times = []
working_time = start_time
while working_time < end_time:
times.append(working_time)
working_time += spacing
return times
|
def url_exists(repoA, repoB):
"""
Returns True if given repourl repoA exists in repoB
"""
if type(repoB) in (list, tuple):
return repoA.rstrip('/') in [existing_url.rstrip('/') for existing_url in repoB]
else:
return repoA.rstrip('/') == repoB.rstrip('/')
|
def is_time_between(begin_time, end_time, check_time):
"""
https://stackoverflow.com/a/10048290/6928824
"""
if begin_time < end_time:
return check_time >= begin_time and check_time <= end_time
# crosses midnight
else:
return check_time >= begin_time or check_time <= end_time
|
def sjis_to_hex_string(jp, control_codes={}):
"""Returns a hex string of the Shift JIS bytes of a given japanese string."""
jp_bytestring = ""
try:
sjis = jp.encode('shift-jis')
except AttributeError:
# Trying to encode numbers throws an attribute error; they aren't important, so just keep the number
sjis = str(jp)
jp_bytestring = sjis
for cc in control_codes:
cc_hex = sjis_to_hex_string(cc)
if cc_hex in jp_bytestring:
jp_bytestring = jp_bytestring.replace(cc_hex, control_codes[cc])
return jp_bytestring
|
def fitbox(fig, text, x0, x1, y0, y1, **kwargs):
"""Fit text into a NDC box.
Args:
textsize (int, optional): First attempt this textsize to see if it fits.
"""
if text is None:
return None
figbox = fig.get_window_extent().transformed(
fig.dpi_scale_trans.inverted()
)
# need some slop for decimal comparison below
px0 = x0 * fig.dpi * figbox.width - 0.15
px1 = x1 * fig.dpi * figbox.width + 0.15
py0 = y0 * fig.dpi * figbox.height - 0.15
py1 = y1 * fig.dpi * figbox.height + 0.15
xanchor = x0
if kwargs.get("ha", "") == "center":
xanchor = x0 + (x1 - x0) / 2.0
yanchor = y0
if kwargs.get("va", "") == "center":
yanchor = y0 + (y1 - y0) / 2.0
txt = fig.text(
xanchor,
yanchor,
text,
fontsize=kwargs.get("textsize", 50),
ha=kwargs.get("ha", "left"),
va=kwargs.get("va", "bottom"),
color=kwargs.get("color", "k"),
)
def _fits(txt):
"""Test for fitting."""
tb = txt.get_window_extent(fig.canvas.get_renderer())
return tb.x0 >= px0 and tb.x1 < px1 and tb.y0 >= py0 and tb.y1 <= py1
if not _fits(txt):
for size in range(50, 1, -2):
txt.set_fontsize(size)
if _fits(txt):
break
return txt
|
def percentage(value, total_sum):
"""calculate a percentage"""
if total_sum == 0:
return 0
else:
return round(100 * float(value) / float(total_sum))
|
def is_multiple_objs(objs, types=None):
"""Check if 'objs' is single or plural objects and if 'types' then
check it according types, return boolean value.
Examples:
if 'objs':
[obj1, obj2, ...]; (obj1, obj2); (obj1 and obj2) then True
[obj]; (obj); obj then False
"""
is_multiple = False
if isinstance(objs, (list, tuple)) and len(objs) >= 2:
is_multiple = (all(isinstance(item, types) for item in objs)
if types else True)
return is_multiple
|
def band_age(age):
"""
Banding method that maps a Boston Marathon runner's (integer) age to a labeled age band and level.
**Note**: The age brackets on the BAA website are as follows:
* 14-19*, 20-24, 25-29, 30-34, 35-39, 40-44, 45-49, 50-54, 55-59, 60-64, 65-70, 70-74, 75-79, and 80
This places 70 into two brackets. We have assumed this is a typo and use the bands '65-69' and '70-74'.
We have also ignored the minimum age in case it has not been the same in every year
:param int age: Age of Boston Marathon runner
:return: (banded_level, age_banding) where: banded_level is banded level of age for Boston Marathon runner and
age_banding is banding of age for Boston Marathon runner in 5 year increments
:rtype: (int, str)
"""
if age <= 19:
bid = 1
bstr = '<= 19'
elif age <= 24:
bid = 2
bstr = '20-24'
elif age <= 29:
bid = 3
bstr = '25-29'
elif age <= 34:
bid = 4
bstr = '30-34'
elif age <= 39:
bid = 5
bstr = '35-39'
elif age <= 44:
bid = 6
bstr = '40-44'
elif age <= 49:
bid = 7
bstr = '45-49'
elif age <= 54:
bid = 8
bstr = '50-54'
elif age <= 59:
bid = 9
bstr = '55-59'
elif age <= 64:
bid = 10
bstr = '60-64'
elif age <= 69:
bid = 11
bstr = '65-69'
elif age <= 74:
bid = 12
bstr = '70-74'
elif age <= 79:
bid = 13
bstr = '75-79'
else:
bid = 14
bstr = '80+'
return bid, bstr
|
def merge(left, right):
"""
Merge subroutine: Merges two sorted halves into a new array.
Merging is done using separate indices for the left and right half and copying over elements of either into the new
array.
- The current left is copied if it is smaller than the current right element and the index is moved.
- Vice versa the current right element is copied if it is smaller than the current left element
Above steps are repeated until all the elements from both halves have been copied to the new array
:param left: left half
:param right: right half
:return: both sides merged with element in ascecnding order
"""
n = len(left) + len(right)
c = [None] * n
i, j = 0, 0
for k in range(n):
if j >= len(right) or i < len(left) and left[i] < right[j]:
c[k] = left[i]
i += 1
elif j < len(right):
c[k] = right[j]
j += 1
return c
|
def invert0(x):
"""
Invert 0 -> 1 if OK = 0, FALSE > 1
"""
return 0 if x > 0 else 1
|
def is_palindrome(s):
""" (str) -> boolean
Returns true if the argument is a palindrome else false
>>> is_palindrome("noon")
True
>>> is_palindrome("later")
False
>>> is_palindrome("radar")
True
"""
# converts (s) to lower case and assigns it to the variable word
word = s.lower()
return word == word[::-1]
|
def span2str(span):
"""
:param span: span array representing [start, end]
:return: string version of span array
"""
return '{}_{}'.format(str(span[0]), str(span[1]))
|
def filter_tweets_on_polarity(tweets, keep_positive=True):
"""Filter the tweets by polarity score, receives keep_positive bool which
determines what to keep. Returns a list of filtered tweets."""
sorted_tweets = []
for tweet in tweets:
if keep_positive and tweet.polarity > 0:
sorted_tweets.append(tweet)
elif not keep_positive and tweet.polarity < 0:
sorted_tweets.append(tweet)
return sorted_tweets
|
def calc_mid_bar(value1, value2, *args):
"""Calculate percentage of value out of the maximum
of several values, for making a bar chart. Return
the midpoint between the height of the first and second
parameter."""
top = max(args + (value1, value2))
percent = (value1 + value2) / 2 / top * 100
return percent
|
def position(instructions):
"""Find out current position."""
hpos, depth, aim = 0, 0, 0
for line in instructions:
command, value = line.split()
value = int(value)
if command == "forward":
hpos += value
depth += aim * value
elif command == "down":
aim += value
elif command == "up":
aim -= value
return hpos * aim, hpos * depth
|
def suggest(x, limit=17):
"""
:params x: -> float
the length of a or b or c of the crystal.
:params limit: -> float
the minimum limit for product of x and k.
So k is the minimum positive integer that
satisfy: x * k >= limit
Note:
Rule for k grid suggestion:
for x = a|b|c, k is the minimum positive integer that
satisfy: x * k >= limit.
"""
k = 1
while k * x < limit:
k += 1
return k
|
def _ip_bridge_cmd(action, params, device):
"""Build commands to add/del IPs to bridges/devices."""
cmd = ['ip', 'addr', action]
cmd.extend(params)
cmd.extend(['dev', device])
return cmd
|
def human_bytes(n):
"""
Return the number of bytes n in more human readable form.
"""
if n < 1024:
return '%d B' % n
k = n/1024
if k < 1024:
return '%d KB' % round(k)
m = k/1024
if m < 1024:
return '%.1f MB' % m
g = m/1024
return '%.2f GB' % g
|
def get_samples(profileDict):
"""
Returns the samples only for the metrics (i.e. does not return any
information from the activity timeline)
"""
return profileDict["samples"]["metrics"]
|
def find_new_array_name(arrays, name: str):
""" Tries to find a new name by adding an underscore and a number. """
index = 0
while "dace_" + name + ('_%d' % index) in arrays:
index += 1
return "dace_" + name + ('_%d' % index)
|
def num_prompts(data):
""" Find the number of unique prompts in data. """
pmts = set()
for row in data:
pmts.add(row[2] + row[3] + row[4])
return len(pmts)
|
def scrub_text(text):
"""Cleans up text.
Escapes newlines and tabs.
Parameters
----------
text : str
Text to clean up.
"""
scrubbed_text = text.rstrip()
scrubbed_text = scrubbed_text.replace("\\x", "\\\\x")
scrubbed_text = scrubbed_text.replace("\0", "\\0")
scrubbed_text = scrubbed_text.replace("\n", "\\n")
scrubbed_text = scrubbed_text.replace("\t", " "*4)
return scrubbed_text
|
def get_events(headers, data):
""" Build a list of dictionaries that have the detail and what that detail "contains".
Args:
headers (list): Headers for these type of events (Provides the order and expected output)
data (dict): Event data to lookup
Returns:
list: list of dictionary objects that maps the data to what is contained.
"""
# Map header names to what is contained in each.
contains_map = {
'source_addr': ['ip'],
'destination_ip': ['ip'],
'username': ['user name'],
'process_table_id': ['threatresponse process table id'],
'process_name': ['file path', 'file name'],
'process_id': ['pid'],
'process_command_line': ['file name'],
'file': ['file path'],
'domain': ['domain'],
'ImageLoaded': ['file path', 'file name'],
'Hashes': ['md5']
}
events = []
for event in data:
event_details = []
for head in headers:
data = event.get(head, None)
event_details.append({
'data': data,
'contains': contains_map.get(head, None) if data else None
})
events.append(event_details)
return events
|
def is_in_pianos(na, list_of_piano):
"""E.g., na="MAPS_MUS-alb_esp2_SptkBGCl.wav", list_of_piano=['SptkBGCl', ...]
then return True.
"""
for piano in list_of_piano:
if piano in na:
return True
return False
|
def service_direction(
direction_int # type: int
):
"""Parse InMon-defined service direction"""
if direction_int == 1:
return "Client"
elif direction_int == 2:
return "Server"
else:
return "Unknown"
|
def aic(lnL, nfp, sample_size=None):
"""returns Aikake Information Criterion
Parameters
----------
lnL
the maximum log
nfp
the number of free parameters in the model
sample_size
if provided, the second order AIC is returned
"""
if sample_size is None:
correction = 1
else:
assert sample_size > 0, "Invalid sample_size %s" % sample_size
correction = sample_size / (sample_size - nfp - 1)
return -2 * lnL + 2 * nfp * correction
|
def trim_str(string, max_len, concat_char):
"""Truncates the given string for display."""
if len(string) > max_len:
return string[:max_len - len(concat_char)] + concat_char
return string
|
def _prepend_comments_to_lines(content: str, num_symbols: int = 2) -> str:
"""Generate new string with one or more hashtags prepended to each line."""
prepend_str = f"{'#' * num_symbols} "
return "\n".join(f"{prepend_str}{line}" for line in content.splitlines())
|
def jira_global_tag_v2(task):
"""
For a global tag update request, get the dictionary of the jira issue that will be created
or a string with an issue key if a comment should be added to an existing issue.
The dictionary can be empty. Then the default is to create an unassigned Task issue in the BII project.
For creating a sub-issue the parent key has to be set and the issuetype id has to be 5.
The summary can be customized with a format string. Possible format keys are
* tag: the upload GT name
* user: the user name of the person who requests the GT update
* reason: the reason for the update given by he user
* release: the required release as specified by the user
* request: the type of request: Addition, Update, or Change
* task: the task = parameter of this function
* time: the time stamp of the request
A tuple can be used to customize the description. The first element is then the dictionary
or string of the jira issue and the second element a format string for the description.
The same fields as for the summary can be used for the description.
The following examples show
A) how to create a new jira issue in the BII project assigned to to user janedoe:
return {"assignee": {"name": "janedoe"}}
B) how to create a sub-issue (type id 5) of BII-12345 in the BII project
assigned to user janedoe and a summary text containing the user name and time of the request::
return {
"project": {"key": "BII"},
"parent": {"key": "BII-12345"},
"issuetype": {"id": "5"},
"assignee": {"name": "janedoe"},
"summary": "Example global tag request by {user} at {time}"
}
C) how to add a comment to BII-12345::
return "BII-12345"
D) how to add a comment to BII-12345 with adjusted description containing only the global tag name
and the reason for a request::
return ("BII-12345", "Example comment for the global tag {tag} because of: {reason}")
Parameters:
task (str): An identifier of the task. Supported values are 'master', 'validation', 'online', 'prompt', data', 'mc', 'analysis'
Returns:
The dictionary for the creation of a jira issue or a string for adding a comment to an
existing issue or a tuple for an adjusted description or None if no jira issue should be created.
"""
if task == 'master':
return {"assignee": {"name": "depietro"}}
elif task == 'validation':
return {"assignee": {"name": "jikumar"}}
elif task == 'online':
return {"assignee": {"name": "seokhee"}}
elif task == 'prompt':
return {"assignee": {"name": "lzani"}}
elif task == 'data':
return {"assignee": {"name": "lzani"}}
elif task == 'mc':
return {"assignee": {"name": "amartini"}}
elif task == 'analysis':
return {"assignee": {"name": "fmeier"}}
|
def to_datetime_weekday(weekday: str):
"""Return the number corresponding to weekday string in datetime format"""
res = -1
if weekday.lower() == 'mon':
res = 0
if weekday.lower() == 'tue':
res = 1
if weekday.lower() == 'wed':
res = 2
if weekday.lower() == 'thu':
res = 3
if weekday.lower() == 'fri':
res = 4
if weekday.lower() == 'sat':
res = 5
if weekday.lower() == 'sun':
res = 6
return res
|
def get_seq_start(pose):
"""
Function that extracts the first (x,y)
point from a list of 6D poses.
Parameters
----------
pose : nd.array
List of 6D poses.
Returns
-------
x_start : float
Start x point.
y_start : float
Start y point
"""
x_start = pose[0][3]
y_start = pose[0][5]
return x_start, y_start
|
def notCommonSecondList(lst1, lst2):
"""Return elements not in common in second lists"""
if lst1 == None or type(lst1) != list:
raise ValueError("lst1 must be a list.")
if lst2 == None or type(lst2) != list:
raise ValueError("lst2 must be a list.")
return list(set(lst2).difference(lst1))
|
def binary_search(arr, key, low, high):
"""
arr: array that contains keys
key: a key to be searched in array arr
low: low indice of array arr
high: high indice of array arr
"""
middle = (low+high) // 2
if low > high:
return -1 #key is not found
if arr[middle] == key:
return middle
if arr[middle] < key:
return binary_search(arr, key, low, middle-1)
else:
return binary_search(arr, key, middle+1, high)
|
def generate_link(**kwargs):
"""Generate a tag with the content, a <p> and inside a <a>
Returns:
kwargs: content for <blockquote>, href and text to <a>
"""
return f'<blockquote>{kwargs["content"]} <a href="{kwargs["href"]}" target="_blank">{kwargs["link_text"]}</a></blockquote>'.strip()
|
def linear_search(values, target):
"""
Return the index of the target item in the values array.
If the item appears more than once in the array,
this method doesn't necessarily return the first instance.
Return -1 if the item isn't in the array.
"""
steps = 0
for i in range(len(values)):
steps += 1
# See if this is the item.
if values[i] == target:
return i, steps
# Stop if we've passed where the target would be.
if values[i] > target:
break
# The item isn't in the array.
return -1, steps
|
def fix_forts(report_city):
""" Changes Ft. -> Fort.
"""
city_components = report_city.split(" ")
if city_components[0].strip().lower() == "ft.":
city_components[0] = "Fort"
return " ".join(city_components)
|
def greeting_dynamic(name):
"""Dynamically typed function."""
return "Hello " + name
|
def sequence_mass(sequence):
"""Return a mass for this sequence - initially will be 128.0 * len"""
# if input is simply a sequence length, return the appropriate
# multiple
if isinstance(sequence, type(42)):
return 128.0 * sequence
# otherwise it must be a string
return 128.0 * len(sequence)
|
def fnAngleDiff(ang1,ang2,wrappedangle):
"""
in [deg] not [rad]
if wrappedangle = 360 [deg], then keep the result in the range [0,360).
180 [deg], [0,180)
http://gamedev.stackexchange.com/questions/4467/comparing-angles-and-working-out-the-difference
13 Nov 2016. used when finding the error in estimated keplerians.
Edited: 14 Nov 2016: the angle to wrap about.
"""
diffangle = (wrappedangle/2.) - abs(abs(ang1 - ang2) - (wrappedangle/2.));
return diffangle
|
def is_anagram(a: str, b: str) -> bool:
"""
>>> is_anagram("xyxyc", "xyc")
False
>>> is_anagram("abba", "ab")
False
>>> is_anagram("abba", "bbaa")
True
"""
return bool(len(a) == len(b) and set(a) == set(b))
|
def get_Sigma_params(param_dict):
"""
Extract and return parameters from dictionary for all
forms other than the powerlaw form
"""
rScale = param_dict['rScale']
rc = param_dict['rc']
sScale = param_dict['sScale']
df = param_dict['df']
B = param_dict['B']
C = param_dict['C']
return rScale, rc, sScale, df, B, C
|
def prepare_experiment(study_name: str, season: str, timestamp: str) -> dict:
"""Returns a dictionary with the correct experiment configuration
Args:
studyName(string): the name of the study
season(string): the season of the study
timestamp(string): ISO 8601 timestamp formatted as YYYY-MM-DDThh:mm:ssTZD
Return:
A dictionary containing the experiment values
Notes:
No checks are made on the values passed in to ensure they conform
"""
return {
"studyName": study_name,
"season": season,
"observationTimeStamp": timestamp
}
|
def get_center(bounds):
"""
Calculate center point from bounds in longitude, latitude format.
Parameters
----------
bounds : list-like of (west, south, east, north) in geographic coordinates
geographic bounds of the map
Returns
-------
list: [longitude, latitude]
"""
return [
((bounds[2] - bounds[0]) / 2.0) + bounds[0],
((bounds[3] - bounds[1]) / 2.0) + bounds[1],
]
|
def convert_farenheit_to_kelvin(temp):
"""Convert the temperature from Farenheit to Kelvin scale.
:param float temp: The temperature in degrees Farenheit.
:returns: The temperature in degrees Kelvin.
:rtype: float
"""
return ((temp + 459.67) * 5) / 9
|
def minify(value):
"""
remove unneeded whitespaces
perhaps add fancypancy html/js minifier
"""
value = ' '.join(value.split())
return value
|
def format_size(size):
""" Format into byes, KB, MB & GB """
power = 2**10
i = 0
power_labels = {0: 'bytes', 1: 'KB', 2: 'MB', 3: 'GB'}
while size > power:
size /= power
i += 1
return f"{round(size, 2)} {power_labels[i]}"
|
def isUndefined(value):
"""
Indicates if the given parameter is undefined (None) or not.
:param value: any kind of value.
:type value: any
:return: True if the value is None.
:rtype: bool
Examples:
>>> print isUndefined(3)
False
>>> print isUndefined(None)
True
"""
try:
return value is None
except:
return True
|
def get_file_section_name(section_key, section_label=None):
"""Build a section name as in the config file, given section key and label."""
return section_key + (" {0}".format(section_label) if section_label else "")
|
def sum_2_level_dict(two_level_dict):
"""Sum all entries in a two level dict
Parameters
----------
two_level_dict : dict
Nested dict
Returns
-------
tot_sum : float
Number of all entries in nested dict
"""
'''tot_sum = 0
for i in two_level_dict:
for j in two_level_dict[i]:
tot_sum += two_level_dict[i][j]
'''
tot_sum = 0
for _, j in two_level_dict.items():
tot_sum += sum(j.values())
return tot_sum
|
def _create_point_feature(record, sr, x_col="x", y_col="y", geom_key=None, exclude=[]):
"""
Create an esri point feature object from a record
"""
feature = {}
if geom_key is not None:
feature["SHAPE"] = {
"x": record[geom_key][x_col],
"y": record[geom_key][y_col],
"spatialReference": sr,
}
feature["attributes"] = {
k: v
for k, v in record.items()
if k not in feature["SHAPE"].keys()
and k not in exclude
}
else:
feature["SHAPE"] = {
"x": record[x_col],
"y": record[y_col],
"spatialReference": sr,
}
feature["attributes"] = {
k: v
for k, v in record.items()
if k not in feature["SHAPE"].keys() and k not in exclude
}
return feature
|
def is_palindrome_v3(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon')
True
>>> is_palindrome_v1('racecar')
True
>>> is_palindrome_v1('dented')
False
"""
i = 0
# Last string index.
j = len(s) - 1
# Run loop until first and last character do not equal anymore
# and until all characters have been compared.
while s[i] == s[j] and i < j:
i = i + 1
j = j - 1
return j <= i
|
def add_ignore_empty(x, y):
"""Add two Tensors which may be None or ().
If x or y is None, they are assumed to be zero and the other tensor is
returned.
Args:
x (Tensor|None|()):
y (Tensor(|None|())):
Returns:
x + y
"""
def _ignore(t):
return t is None or (isinstance(t, tuple) and len(t) == 0)
if _ignore(y):
return x
elif _ignore(x):
return y
else:
return x + y
|
def IsInModulo(timestep, frequencyArray):
"""
Return True if the given timestep is in one of the provided frequency.
This can be interpreted as follow::
isFM = IsInModulo(timestep, [2,3,7])
is similar to::
isFM = (timestep % 2 == 0) or (timestep % 3 == 0) or (timestep % 7 == 0)
"""
for frequency in frequencyArray:
if frequency > 0 and (timestep % frequency == 0):
return True
return False
|
def compute_iou(bboxA, bboxB):
"""compute iou of two bounding boxes
Args:
bboxA(list): coordinates of box A (i,j,w,h)
bboxB(list): coordinates of box B (i,j,w,h)
Return:
float: iou score
"""
ix = max(bboxA[0], bboxB[0])
iy = max(bboxA[1], bboxB[1])
mx = min(bboxA[0] + bboxA[2], bboxB[0] + bboxB[2])
my = min(bboxA[1] + bboxA[3], bboxB[1] + bboxB[3])
area_inter = max(mx - ix, 0) * max(my - iy, 0)
area_A = bboxA[2] * bboxA[3]
area_B = bboxB[2] * bboxB[3]
iou = float(area_inter) / float(area_A + area_B - area_inter)
return iou
|
def _s2_st_to_uv(component: float) -> float:
"""
Convert S2 ST to UV.
This is done using the quadratic projection that is used by default for S2. The C++ and Java S2
libraries use a different definition of the ST cell-space, but the end result in IJ is the same.
The below uses the C++ ST definition.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L312-L315
"""
if component >= 0.5:
return (1.0 / 3.0) * (4.0 * component ** 2 - 1.0)
return (1.0 / 3.0) * (1.0 - 4.0 * (1.0 - component) ** 2)
|
def json_substitute(json, value, replacement):
"""
Substitute any pair whose value is 'value' with the replacement
JSON 'replacement'. Based on pscheduler.json_decomment().
"""
if type(json) is dict:
result = {}
for item in json.keys():
if json[item] == value:
result[item] = replacement
else:
result[item] = json_substitute(json[item], value, replacement)
return result
elif type(json) is list:
result = []
for item in json:
result.append(json_substitute(item, value, replacement))
return result
else:
return json
|
def fastexp(a: float, n: int) -> float:
"""Recursive exponentiation by squaring
>>> fastexp( 3, 11 )
177147
"""
if n == 0:
return 1
elif n % 2 == 1:
return a*fastexp(a, n-1)
else:
t = fastexp(a, n//2)
return t*t
|
def continuous_fraction_coefs (a, b):
"""
Continuous fraction coefficients of a/b
"""
ret = []
while a != 0:
ret.append( int(b//a) )
a, b = b%a, a
return ret
|
def _get_bit(x: int, i: int) -> bool:
"""Returns true iff the i'th bit of x is set to 1."""
return (x >> i) & 1 != 0
|
def has_shebang_or_is_elf(full_path):
"""Returns if the file starts with #!/ or is an ELF binary.
full_path is the absolute path to the file.
"""
with open(full_path, 'rb') as f:
data = f.read(4)
return (data[:3] == '#!/' or data == '#! /', data == '\x7fELF')
|
def sanitized(s):
"""Sanitize HTML/XML text.
:param str s: source text
:rtype: str
:return: sanitized text in which &/</> is replaced with entity refs
"""
return s.replace("&", "&").replace("<", "<").replace(">", ">")
|
def is_number(s):
"""Determines if a string looks like a number or not."""
try:
float(s)
return True
except ValueError:
return False
|
def between(arg, interval):
"""
Computes whether a given number is between a given interval or not.
Parameters
----------
arg: scalar
Number to be evaluated.
interval: tuple
Interval in which perform the evaluation.
Returns
-------
result: bool
If arg is between interval, result=True, and result=False in other
case.
"""
if arg>=interval[0] and arg<=interval[1]:
result=True
else:
result=False
return(result)
|
def get_list_intersection(list_a, list_b):
"""
Get the intersection between list_a and list_b
:param list_a:
:param list_b:
:return:(list) list_intersection
"""
assert isinstance(list_a, list)
assert isinstance(list_b, list)
return list((set(list_a).union(set(list_b))) ^ (set(list_a) ^ set(list_b)))
|
def denormalize(grid):
"""Denormalize input grid from range [0, 1] to [-1, 1]
Args:
grid (Tensor): The grid to be denormalize, range [0, 1].
Returns:
Tensor: Denormalized grid, range [-1, 1].
"""
return grid * 2.0 - 1.0
|
def not_infinite(instructions):
""" check if loop is infinite """
index = 0
visited = set()
while (index not in visited) and (index < len(instructions)):
visited.add(index)
opr, val = instructions[index].split()
index = index + int(val) if opr == "jmp" else index + 1
if index == len(instructions):
return True
return False
|
def isLeapYear(year):
""" is_leap_year == PEP8, forced mixedCase by CodeWars """
return year % 4 == 0 and not year % 100 == 0 or year % 400 == 0
|
def filter_namelist(names, filter_prefixes=None, ignore_prefixes=None,
ignore_suffixes=None):
"""Filters the names list for entries that match the filter_prefixes,
and do not match the ignore_prefixes or ignore_suffixes.
"""
ret = set(names)
if filter_prefixes:
ret = set(e for e in ret
if e.startswith(tuple(filter_prefixes)))
if ignore_prefixes:
ret = set(e for e in ret
if not e.startswith(tuple(ignore_prefixes)))
if ignore_suffixes:
ret = set(e for e in ret
if not e.endswith(tuple(ignore_suffixes)))
return ret
|
def partition(a, sz):
"""splits iterables a in equal parts of size sz"""
return [a[i:i+sz] for i in range(0, len(a), sz)]
|
def read(fname):
"""Return contents of fname"""
txt = None
with open(fname) as ftoken:
txt = ftoken.read()
return txt
|
def find_host_for_osd(osd, osd_status):
""" find host for a given osd """
for obj in osd_status['nodes']:
if obj['type'] == 'host':
if osd in obj['children']:
return obj['name']
return 'unknown'
|
def combine_list(list1, list2):
""" combine two lists without creating duplicate entries) """
return list1 + list(set(list2) - set(list1))
|
def poly_to_str(terms):
"""Returns algebraic expression of the sum of all the list of PolyTerm's."""
poly_str = ''
for term in terms:
if term.coeff == 0:
continue
if term.coeff < 0:
if poly_str == '':
poly_str += '-'
else:
poly_str += ' - '
elif poly_str != '':
poly_str += ' + '
if abs(term.coeff) != 1:
poly_str += str(abs(term.coeff))
if term.power == 0:
continue
if term.power == 1:
poly_str += term.variable
else:
poly_str += term.variable + '^' + str(term.power)
return poly_str
|
def average(numbers):
"""
:param list[float] numbers: a list of numbers
:returns: the average of the given number sequence. an empty list returns 0.
:rtype: float
"""
return float(sum(numbers)) / max(len(numbers), 1)
|
def make_list(string):
"""Make a list of floats out of a string after removing unwanted chars."""
l1 = string.strip('[] \n')
l2 = l1.split(',')
return [float(c.strip()) for c in l2]
|
def date_specificity(date_string):
"""Detect date specificity of Zotero date string.
Returns 'ymd', 'ym', or 'y' string.
"""
length = len(date_string)
if length == 10:
return 'ymd'
elif length == 7:
return 'ym'
elif length == 4:
return 'y'
return None
|
def LinearlyInterpolate(lower, upper, ratio):
"""
Linearly interpolate between the given values by the given ratio
"""
return (upper - lower) * ratio + lower
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.