content stringlengths 42 6.51k |
|---|
def word_pig_latin_translation(word):
"""This function does the translation for word"""
VOVELS =['a','e','i','o','u']
#case: words containing punctuations
if not word.isalpha():
return word
#case: Capitalized words
if word[0].isupper():
return word_pig_latin_translation(word.l... |
def get_document(document_name):
"""
This function responds to a request for /api/document-base
with the patient's records
:return: pdf document
"""
# Create the list of people from our data
with open(document_name, "r") as f:
return f.read() |
def pageCount(n, p):
#
# Write your code here.
#
"""
###########Pseudocode###########
-> n = number of pages
-> p = target page
-> if p is close to first page:
-> return int(p/2)
-> if p is close to the last page:
-> return int... |
def in_region(pos, b, e):
""" Returns pos \in [b,e] """
return b <= pos and pos <= e |
def maximum(a, b):
"""
:param a: int, any number
:param b: int, any number
:return: the bigger one
"""
if a >= b:
return a
else:
return b |
def distance(a,b):
"""
Calculates the Levenshtein distance between a and b.
References
==========
http://en.wikisource.org/wiki/Levenshtein_distance#Python
"""
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
a,b = b,a
n,m = m,n
... |
def filter_json(json, *keys):
"""Returns the given JSON but with only the given keys."""
return {key: json[key] for key in keys if key in json} |
def remove_repeated_element(repeated_list):
"""
Remove duplicate elements
:param repeated_list: input list
:return: List without duplicate elements
"""
repeated_list.sort()
new_list = [repeated_list[k] for k in range(len(repeated_list)) if
k == 0 or repeated_list[k] != repea... |
def E_float2(y, _):
"""Numerically stable implementation of Muller's recurrence."""
return 8 - 15/y |
def length(value):
""" Gets the length of the value provided to it.
Returns:
If the value is a collection, it calls len() on it.
If it is an int, it simply returns the value passed in"""
try:
if isinstance(value, int):
return value
else:
result = len(... |
def json_or_default(js, key, defval=None):
"""
Loads key from the JS if exists, otherwise returns defval
:param js: dictionary
:param key: key
:param defval: default value
:return:
"""
if key not in js:
return defval
return js[key] |
def to_camelCase(in_str):
"""
Converts a string to camelCase.
:param in_str: The input string.
:type in_str: str
:return: The input string converted to camelCase.
:rtype: str
"""
if in_str.find(' ') > -1:
words = in_str.split(' ')
elif in_str.find('_') > -1:
... |
def remove_dul(entitylst):
"""
Remove duplicate entities in one sequence.
"""
entitylst = [tuple(entity) for entity in entitylst]
entitylst = set(entitylst)
entitylst = [list(entity) for entity in entitylst]
return entitylst |
def _is_end_of_rti(line):
"""Check if line in an rti is at the end of the section."""
return (
line
and "@" not in line
and not line == "\n"
and not line.strip().startswith("#")
) |
def check_command_help_len(argv_):
"""return bool"""
return len(argv_) == 2 |
def summ(listy):
"""
Input: A list of numbers.
Output: The sum of all the numbers in the list, iterative.
"""
total = 0
for i in listy:
total += i
return total |
def merge_with_thres_LL(other_LL, thres_LL, pairs):
"""Merge the dictionaries containing the threshold-LL and other thresholds.
Other_LL will be modified in place.
"""
for u_id, l_id in pairs:
for key in thres_LL[u_id][l_id]:
other_LL[u_id][l_id][key] = thres_LL[u_id][l_id][key]
... |
def list_union(a, b):
""" return the union of two lists """
return list(set(a) | set(b)) |
def extract_columns(spec, data):
"""Transforms some data into a format suitable for print_columns_...
The data is a list of anything, to which the spec functions will be applied.
The spec is a list of tuples representing the column names
and how to the column from a row of data. E.g.
[ ('Master', lambda m... |
def measure_counts_deterministic(shots, hex_counts=True):
"""Measure test circuits reference counts."""
targets = []
if hex_counts:
# Measure |00> state
targets.append({'0x0': shots})
# Measure |01> state
targets.append({'0x1': shots})
# Measure |10> state
ta... |
def word_list_to_string(word_list, delimeter=" "):
"""Creates a single string from a list of strings
This function can be used to combine words in a list into one long sentence
string.
Args:
word_list (list/tuple): A list (or other container) of strings.
delimeter (str, Optional): A st... |
def polygon_clip(subjectPolygon, clipPolygon):
""" Clip a polygon with another polygon.
Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python
Args:
subjectPolygon: a list of (x,y) 2d points, any polygon.
clipPolygon: a list of (x,y) 2d points, has to be *convex*
Note:
**points have to b... |
def Euler(diffeq, y0, t, h): # uses docstring """..."""
""" Euler's method for n ODEs:
Given y0 at t, returns y1 at t+h """
dydt = diffeq(y0, t) # get {dy/dt} at t
return y0 + h*dydt # Euler method on a vector @\lbl{line:vecop}@ |
def json_dumpb(obj: object) -> bytes:
"""Compact formating obj as JSON to UTF-8 encoded bytes."""
import json
return json.dumps(obj, separators=(',', ':'), ensure_ascii=False).encode('utf-8') |
def create(place_found):
""" function to create response dictionary """
# add basic attributes to response
response = {
'name': place_found['name'],
'address': place_found['vicinity']
}
# if these attributes are in place_found, add those to response
if 'price_level'... |
def compute_agreement_score(num_matches, num1, num2):
"""
Computes agreement score.
Parameters
----------
num_matches: int
Number of matches
num1: int
Number of events in spike train 1
num2: int
Number of events in spike train 2
Returns
-------
score: fl... |
def median(inlistin):
"""median: Finds the median of the provided array.
Args:
inlistin (array): An array of numbers to find the median of
Returns:
Float: the median of the numbers given
"""
inlistin = sorted(inlistin)
inlisto = 0
length = len(inlistin)
for x in range(int(length / 2) - 1):
del inlistin[0]... |
def calculate_amount(principal, rate, term, frequency):
""" Calculate the principal plus interest given the
principal, rate, term and frequency
"""
return round(principal * ((1 + ((rate / 100 / frequency))) ** (frequency * term)), 2) |
def format_stringv3(value):
"""Return a vCard v3 string. Embedded commas and semi-colons are backslash quoted"""
return value.replace("\\", "").replace(",", r"\,").replace(";", r"\;") |
def is_nullable(schema_item: dict) -> bool:
"""
Checks if the item is nullable.
OpenAPI does not have a null type, like a JSON schema,
but in OpenAPI 3.0 they added `nullable: true` to specify that the value may be null.
Note that null is different from an empty string "".
This feature... |
def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float:
"""
Convert a given value from Celsius to Kelvin and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin
"""
return round(celsius + 273... |
def is_float(s):
"""Determine whether str can be cast to float."""
try:
float(s)
return True
except ValueError:
return False |
def none_to_string(string: None) -> str:
"""Convert None types to an empty string.
:param string: the string to convert.
:return: string; the converted string.
:rtype: str
"""
_return = string
if string is None or string == "None":
_return = ""
return _return |
def has_inline_pass(line: str) -> bool:
"""True if line ends with a pass command."""
return line.endswith("phmdoctest:pass") |
def _kface_cell_value(arr, loc):
""" Returns K face value for cell-centered data. """
i, j, k = loc
# FIXME: built-in ghosts
return 0.5 * (arr(i+1, j+1, k+1) + arr(i+1, j+1, k)) |
def parse_hcount(hcount_str):
"""
Parses a SMILES hydrogen count specifications.
Parameters
----------
hcount_str : str
The hydrogen count specification to parse.
Returns
-------
int
The number of hydrogens specified.
"""
if not hcount_str:
return 0
if... |
def get_tablename_query(column_id, boundary_id, timespan):
"""
given a column_id, boundary-id (us.census.tiger.block_group), and
timespan, give back the current table hash from the data observatory
"""
return """
SELECT numer_tablename, numer_geomref_colname, numer_tid,
... |
def build_agg_feature_name(feature_prefix: str, agg_func: str, agg_window: str) -> str:
"""
Creates the feature name for the aggregation feature based on the prefix, aggregation function and window
:param feature_prefix: The prefix
:param agg_func: The aggregation function (SUM, MIN, COUNT etc)
:pa... |
def unescape_html_entities(text: str) -> str:
"""
Replaces escaped html entities (e.g. ``&``) with their ASCII representations (e.g. ``&``).
:param text:
"""
out = text.replace("&", '&')
out = out.replace("<", '<')
out = out.replace(">", '>')
out = out.replace(""", '"')
return out |
def get_insert_many_query(table_name):
"""Build a SQL query to insert a RDF triple into a SQlite dataset"""
return f"INSERT INTO {table_name} (subject,predicate,object) VALUES ? ON CONFLICT (subject,predicate,object) DO NOTHING" |
def get_deltas(number, lst):
"""Returns a list of the change from a number each value of a list is"""
return [abs(i - number) for i in lst] |
def _sp_sleep_for(t: int) -> str:
"""Return the subprocess cmd for sleeping for `t` seconds."""
return 'python -c "import time; time.sleep({})"'.format(t) |
def getBits (num, gen):
""" Get "num" bits from gen. """
out = 0
for i in range (num):
out <<= 1
val = gen.next ()
if val != []:
out += val & 0x01
else:
return []
return out |
def cal_kt(raw_trajs_frequent_pattern, sd_trajs_frequent_pattern):
"""
calculate KT
Args:
raw_trajs_frequent_pattern: frequent patterns of the original trajectory
sd_trajs_frequent_pattern : frequent patterns that generate trajectories
Returns:
KT
"""
con... |
def is_type(typecheck, data):
"""
Generic type checker
typically used to check that a string can be cast to int or float
"""
try:
typecheck(data)
except ValueError:
return False
else:
return True |
def mbuild(width, height):
"""Build a NxN matrix filled with 0."""
result = list()
for i in range(height):
result.append(list())
for j in range(width):
result[i].append(0.0)
return result |
def measurement_id(measurement_uuid: str, agent_uuid: str) -> str:
"""
Measurement IDs used by Iris
>>> measurement_id("57a54767-8404-4070-8372-ac59337b6432", "e6f321bc-03f1-4abe-ab35-385fff1a923d")
'57a54767-8404-4070-8372-ac59337b6432__e6f321bc-03f1-4abe-ab35-385fff1a923d'
Measurement IDs used by... |
def remove_child_items(item_list):
"""
For a list of filesystem items, remove those items that are duplicates or children of other items
Eg, for remove_child_items['/path/to/some/item/child', '/path/to/another/item', '/path/to/some/item']
returns ['/path/to/another/item', '/path/to/some/item']
I... |
def get_pack_format_and_mask_for_num_bytes(num_bytes,
signed=False,
little_endian=True):
"""Return the struct pack format and bit mask for the integer values of size
|num_bytes|."""
if num_bytes == 1:
pack_fmt = 'B'
mask... |
def is_subpath(spath, lpath):
"""
check the short path is a subpath of long path
:param spath str: short path
:param lpath str: long path
"""
if lpath.startswith(spath):
slen, llen = len(spath), len(lpath)
return True if slen == llen else lpath[slen] == '/'
return False |
def convert_str(input_str):
"""Try to convert string to either int or float, returning the original string if this fails."""
try:
ret = int(input_str)
except ValueError:
# try float.
try:
ret = float(input_str)
except ValueError:
ret = input_str
re... |
def page_double_hyphen(record):
"""
Separate pages by a double hyphen (--).
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "pages" in record:
if "-" in record["pages"]:
p = [i.strip().strip('-') for i in record["pages"].split... |
def software_and_version(path):
""" return 'corda-os', '4.4' """
dirs = str(path).split("/")
# locate 'docs'
while dirs[0] != "docs":
dirs.pop(0)
return dirs[1], dirs[2] |
def hide_passwords(key, value):
"""
Return asterisks when the given key is a password that should be hidden.
:param key: key name
:param value: value
:return: hidden value
"""
hidden_keys = ['key', 'pass', 'secret', 'code', 'token']
hidden_value = '*****'
return hidden_value if any(... |
def _calculate_ticks(group_len: int, width: float):
"""Given some group size, and width calculate
where ticks would occur.
Meant for bar graphs
"""
if group_len % 2 == 0:
start = ((int(group_len / 2) - 1) * width * -1) - (width / 2.0)
else:
start = int((group_len / 2)) * width *... |
def column_marker(column):
"""
Unique markers modulo 7
"""
if (column)//7 == 0:
marker = 'x'
elif (column)//7 == 1:
marker = '+'
else:
marker = 'd'
return marker |
def euler_step(theta,dtheta,ddtheta,dt):
"""
Euler Step
Parameters
----------
theta (tf.Tensor):
Joint angles
(N,nq)
dtheta (tf.Tensor):
Joint velocities
(N,nq)
ddtheta (tf.Tensor):
Joint accelerations
(N,nq)
dt (float):
Delta t
... |
def parse_env(entries):
"""entries look like X=abc"""
res = {}
for e in entries:
if "=" in e:
e = e.split("=", 2)
res[e[0]] = e[1]
return res |
def aggvar_hurst_measure(measure):
"""Hurst computation parameter from aggvar slope fit.
Parameters
----------
measure: float
the slope of the fit using aggvar method.
Returns
-------
H: float
the Hurst parameter.
"""
H = float((measure+2.)/2.)
return H |
def build_predicate_direction(predicate: str, reverse: bool) -> str:
"""Given a tuple of predicate string and direction, build a string with arrows"""
if reverse:
return f"<-{predicate}-"
else:
return f"-{predicate}->" |
def generate_options_for_monitoring_tool(server=None, **kwargs):
"""
Define a list of tuples that will be returned to generate the field options
for the monitoring_tool Action Input.
In this example Mode is dependent on Monitoring_Tool. Dependencies between
parameters can be defined within the depe... |
def align_left(msg, length):
""" Align the message to left. """
return f'{msg:<{length}}' |
def _GetSchemeFromUrlString(url_str):
"""Returns scheme component of a URL string."""
end_scheme_idx = url_str.find('://')
if end_scheme_idx == -1:
# File is the default scheme.
return 'file'
else:
return url_str[0:end_scheme_idx].lower() |
def get_modulus_residue(value, modulus):
"""
Computes the canonical residue of value mod modulus.
Parameters:
value (int): The value to compute the residue of
modulus (int): The modulus used to calculate the residue
Returns:
An integer "r" between 0 and modulus - 1, where value... |
def scale_coords(coords):
"""Returns coordinate list scaled to matplotlib coordintates.
- coords: list of lists, of x,y coordinates:
[[x1,y1],[x2,y2],[x3,y3],...]
"""
new_coords = []
#get min and max x coordinates
max_x = max([c[0] for c in coords])
min_x = min([c[0] for... |
def downsample_array(array):
"""down sample given array"""
skip = 5
result = array[::skip]
result.append(array[-1])
return result |
def get_position_from_periods(iteration, cumulative_period):
"""Get the position from a period list.
It will return the index of the right-closest number in the period list.
For example, the cumulative_period = [100, 200, 300, 400],
if iteration == 50, return 0;
if iteration == 210, return 2;
i... |
def splitList(content, cut):
"""splits an array in two.
arguments :
`content` : (ndarray/list)
the array to split in two.
`cut` : (float) in [0:1]
the ratio by which we will split the array.
"""
c = int(len(content) * cut)
return (content[:c], content[c:]) |
def cast_to_int(value: str) -> int:
"""
Casts to int. Casts the empty string to 0.
"""
if value == '':
return 0
return int(value) |
def flatten_list(li):
"""Flatten shallow nested list"""
return [element for sub_list in li for element in sub_list] |
def generate_nginx_config(app_name=None, urls=None, state_dir='/var/tmp',
app_port=8000, **kwargs):
"""
Generates an nginx config
:param app_name: Name of application
:param urls: List of public urls as strings
:param state_dir: Application state dir (default: /var/tmp)
:param app_port: App... |
def _target_selectors(targets):
"""
Return the target selectors from the given target list.
Transforms the target lists that the client sends in annotation create and
update requests into our internal target_selectors format.
"""
# Any targets other than the first in the list are discarded.
... |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible
looking to the right, False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the in... |
def reverse2(snippet):
"""Reverse second sequence.
Change a + b to b - a and a - b or b - a to a + b.
"""
text = snippet
if '0123456789/' in text:
text = text.replace('0123456789/', '9876543210/')
else:
text = text.replace('9876543210/', '0123456789/')
return text |
def findLongestSubstring(a):
""" Finds and returns the longest consecutive subsequence of integers in the provided list. """
lsidx = leidx = csidx = ceidx = 0
# Loop through all the elements in the list with their indices
for i, n in enumerate(a):
# Check if the current number is higher than th... |
def subfile_split(value):
"""Split a subfile into the name and payload.
:param value: The value in the SUBFILE tag.
:return: (name, data).
"""
name = value.split(b'\x00', 1)[0].decode('utf-8')
data = value[128:]
return name, data |
def valid(guess):
"""
This is a predicate function to check whether a user input is a letter and with only one letter.
:param guess:
:return: bool
"""
if guess.isalpha() and len(guess) == 1:
return True
return False |
def paths_from_issues(issues):
"""Extract paths from list of BindConfigIssuesModel."""
return [issue.path for issue in issues] |
def verify_expire_version(versioning):
"""
:type: versioning: str
:param versioning: Type of expiration versioning.
Can be only current or previous. Required.
:return: fixed versioning format
:raises: ValueError: Invalid start or limit
"""
VERSION_CONVERT = {"current": "curver_aft... |
def getObjectLabel(objectData, objectName):
"""
Returns the object label specified in object_data.yaml
:param objectName:
:return:
"""
if objectName not in objectData:
raise ValueError('there is no data for ' + objectName)
return objectData[objectName]['label'] |
def deduplicate(elements):
"""Remove duplicate entries in a list of dataset annotations.
Parameters
----------
elements: list(vizier.datastore.annotation.base.DatasetAnnotation)
List of dataset annotations
Returns
-------
list(vizier.datastore.annotation.base.DatasetAnnotation)
... |
def calc_longitude_shift(screen_width: int, percent_hidden: float) -> float:
"""Return the amount to shift longitude per column of screenshots."""
return 0.00000268 * screen_width * (1 - percent_hidden) * 2
# return 0.0000268 * screen_width * (1 - percent_hidden) |
def translate_ascii(number):
"""
Helper function to figure out alphabet of a particular number
* ASCII for lower case 'a' = 97
* chr(num) returns ASCII character for a number
"""
return chr(number + 96) |
def capillary(srz, ss, crmax, rzsc):
"""capillary rise"""
if rzsc - srz > crmax:
srz += crmax
ss -= crmax
else:
srz += rzsc - srz
ss -= rzsc - srz
return srz, ss |
def remove_first_line(text):
"""Remove the first line from a text block.
source: string of newline-separated lines
returns: string of newline-separated lines
"""
_, _, rest = text.partition('\n')
return rest |
def new_in_list(my_list, idx, element):
"""Replace an element in a copied list at a specific position."""
if idx < 0 or idx > (len(my_list) - 1):
return (my_list)
copy = [x for x in my_list]
copy[idx] = element
return (copy) |
def flatten_json(y):
"""
This supplemental method flattens a JSON by renaming subfields using dots as delimiters between levels
Args:
y - the JSON to flatten
Returns:
A flattened JSON string
"""
out = {}
def flatten(x, name=''):
# If the Nested key-value
#... |
def get_wind_direction_string(wind_direction_in_deg):
"""Get the string interpretation of wind direction in degrees"""
if wind_direction_in_deg is not None:
if wind_direction_in_deg <=23:
return "N"
elif wind_direction_in_deg > 338:
return "N"
elif (23 < wind_dir... |
def convert_latitude(lat_NS):
""" Function to convert deg m N/S latitude to DD.dddd (decimal degrees)
Arguments:
lat_NS : tuple representing latitude
in format of MicroGPS gps.latitude
Returns:
float representing latitidue in DD.dddd
"""
return (... |
def find_in_list(content, token_line, last_number):
"""
Finds an item in a list and returns its index.
"""
token_line = token_line.strip()
found = None
try:
found = content.index(token_line, last_number+1)
except ValueError:
pass
return found |
def _context_string(context):
"""Produce a string to represent the code block context"""
msg = 'Code block context:\n '
lines = ['Selective arithmetic coding bypass: {0}',
'Reset context probabilities on coding pass boundaries: {1}',
'Termination on each coding pass: ... |
def load_string_list(file_path, is_utf8=False):
"""
Load string list from mitok file
"""
try:
with open(file_path, encoding='latin-1') as f:
if f is None:
return None
l = []
for item in f:
item = item.strip()
if ... |
def is_quantity(d):
""" Checks if a dict can be converted to a quantity with units """
if(isinstance(d,dict) and len(d.keys())==2 and "value" in d and "units" in d):
return True
else:
return False |
def distance_euclidienne_carree(p1, p2):
"""
Calcule la distance euclidienne entre deux points.
"""
x = p1[0] - p2[0]
y = p1[1] - p2[1]
return x * x + y * y |
def flushsearch(hand):
"""
Returns true if a flush exists in the hand.
"""
return len(list(dict.fromkeys(x[1] for x in hand))) == 1 |
def parse_challenge(challenge):
"""
"""
items = {}
for key, value in [item.split(b'=', 1) for item in challenge.split(b',')]:
items[key] = value
return items |
def num_items_in_each_chunk(num_items, num_chunks):
"""
Put num_items items to num_chunks drawers as even as possible.
Return a list of integers, where ret[i] is the number of items put to drawer i.
"""
if num_chunks == 0:
return [0]
num_items_per_chunk = num_items // num_chunks
ret ... |
def _default_with_off_flag(current, default, off_flag):
"""Helper method for merging command line args and noxfile config.
Returns False if off_flag is set, otherwise, returns the default value if
set, otherwise, returns the current value.
"""
return (default or current) and not off_flag |
def sort(lst):
"""Standard merge sort.
Args:
lst: List to sort
Returns:
Sorted copy of the list
"""
if len(lst) <= 1:
return lst
mid = len(lst) // 2
low = sort(lst[:mid])
high = sort(lst[mid:])
res = []
i = j = 0
while i < len(low) and j < len(high... |
def containsAll(str, set):
"""Check whether sequence str contains ALL of the items in set."""
for c in set:
if c not in str: return 0
return 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.