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 d... |
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 g... |
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 t... |
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'... |
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... |
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 '... |
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
re... |
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 n... |
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 ()
... |
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 ... |
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 ... |
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 =... |
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 ke... |
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()
)
#... |
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(... |
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 ... |
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 ind... |
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.low... |
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:
... |
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
... |
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":
... |
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 sugges... |
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_tex... |
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 ... |
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:
co... |
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 pro... |
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':
... |
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.
... |
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(ls... |
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:
... |
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(v... |
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(s... |
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-th... |
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']
... |
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-M... |
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]
"""
r... |
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)
Tr... |
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... |
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],
... |
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 fir... |
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 i... |
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)
""... |
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] + bb... |
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... |
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:
... |
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.
Retur... |
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... |
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 ind... |
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(... |
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:
p... |
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.