content stringlengths 42 6.51k |
|---|
def tess(mjd, hist=[], **kwargs):
"""cadence requirements for tess
Request: 2 observations?
mjd: float or int should be ok
hist: list, list of previous MJDs
"""
if len(hist) == 0:
return True
if len(hist) > 1:
return False
return mjd - hist[0] > 1 |
def get_command_from_argument(argv):
""" extract command from the command line arguments """
for arg in argv[1:]:
if not arg.startswith('-'):
return arg
return None |
def qualified_name(cls):
"""Full name of a class, including the module. Like qualified_class_name, but when you already have a class """
module = cls.__module__
if module is None or module == str.__class__.__module__:
return cls.__name__
return module + '.' + cls.__name__ |
def int2Poly(bInt):
"""Convert a "big" integer into a "high-degree" polynomial"""
exp = 0
poly = []
while bInt:
if bInt & 1:
poly.append(exp)
exp += 1
bInt >>= 1
return poly[::-1] |
def kappa_analysis_cicchetti(kappa):
"""
Analysis kappa number with Cicchetti benchmark.
:param kappa: kappa number
:type kappa : float
:return: strength of agreement as str
"""
try:
if kappa < 0.4:
return "Poor"
if kappa >= 0.4 and kappa < 0.59:
retu... |
def getitem(data, item):
"""Implementation of `getitem`."""
return data.__getitem__(item) |
def _structure_parent_category(_payload, _parent_id):
"""This function structures the parent category field for a group hub if applicable.
.. versionadded:: 2.6.0
:param _payload: The payload to which the parent category field should be added
:type _payload: dict
:param _parent_id: The parent cate... |
def exactly_one(*args):
"""Asserts one of the arguments is not None
Returns:
result(bool): True if exactly one of the arguments is not None
"""
return sum([1 for a in args if a is not None]) == 1 |
def _join_host_port(host, port):
"""Adapted golang's net.JoinHostPort"""
template = "%s:%s"
host_requires_bracketing = ':' in host or '%' in host
if host_requires_bracketing:
template = "[%s]:%s"
return template % (host, port) |
def collatz(number):
"""If number is even (number // 2) else (3 * number + 1)
Args:
number (int): number to collatz
Returns:
int: collatz number
"""
if (number % 2) == 0:
print(number // 2)
return number // 2
print(3 * number + 1)
return 3 * number + 1 |
def joinLinks(links, sep=', ', last=None, sort=False):
"""Return a string joining *links* as reStructuredText."""
links = list(links)
if sort:
links.sort()
if last is None:
last = ''
else:
last = last + '`' + links.pop() + '`_'
return '`' + ('`_' + sep + '`').join(links)... |
def countN(x: int, y: int, fld: list) -> int:
""" Count all alive neighbours """
mw, mh = len(fld), len(fld[0])
""" check 3 row elements above, check 2 sides, check 3 row elements below """
return fld[(x-1) % mw][(y-1)% mh] + fld[x][(y-1)% mh] + fld[(x+1) % mw][(y-1)% mh] +\
fld[(x-1) % mw][y] ... |
def Bresenham3D(x1, y1, z1, x2, y2, z2):
"""Takes two coordinates and gives the set of coordinates that connects them with a straight line
Adapted from https://www.geeksforgeeks.org/bresenhams-algorithm-for-3-d-line-drawing/
Arguments:
x1 {int} -- first x coodinate
y1 {int} -- firs... |
def serialize_composite_output(analysis, type):
"""."""
return {
'id': None,
'type': type,
'attributes': {
'thumb_url': analysis.get('thumb_url', None),
'tile_url': analysis.get('tile_url', None),
'dem': analysis.get('dem', None),
'zonal_st... |
def trycast(value):
"""
Try to cast a string attribute from an XML tag to an integer, then to a
float. If both fails, return the original string.
"""
for cast in (int, float):
try:
return cast(value)
except ValueError:
continue
return value |
def basic_name_formatter(name):
"""Basic formmater turning '_' in ' ' and capitalising.
"""
return name.replace('_', ' ').capitalize() |
def genIDStr(bmcList):
"""Turn a list of EthernetInterfaces into a list of xnames."""
bmcStr = ""
for bmc in bmcList:
if len(bmcStr) > 0:
bmcStr += "," + bmc['ComponentID']
else:
bmcStr += " " + bmc['ComponentID']
return bmcStr |
def compute_brightness(brightness):
"""Return the hex code for the specified brightness"""
value = hex(int(brightness))[2:]
value = value.zfill(4)
value = value[2:] + value[:2] # how to swap endianness
return "57" + value |
def lr_poly(base_lr, epoch, max_epoch, power):
""" Poly_LR scheduler
"""
return base_lr * ((1 - float(epoch) / max_epoch) ** power) |
def instantiate(generator_or_value):
"""
Dynamic typing hack to try to call generators if provided,
otherwise return the value directly if not callable. This will
break badly if used for values that can be callable.
"""
if callable(generator_or_value):
return generator_or_value()
el... |
def fix_logger_name(logger, method_name, event_dict):
"""
Captured stdlib logging messages have logger=feedhq.logging and
logger_name=original_logger_name. Overwrite logger with correct name.
"""
if 'logger_name' in event_dict:
event_dict['logger'] = event_dict.pop('logger_name')
return ... |
def create_job_path(folders, project, branch=None):
""" Create the Jenkins path based on the folders, project, and branch
provided """
job_paths = []
for folder in folders:
job_paths.append("job/{FOLDER}/".format(FOLDER=folder))
job_path = job_paths.append("job/{PROJ}".format(PROJ=project))
... |
def create_edge(_source, _target, _label='', _edge_type=''):
"""Creates an edge whose id is "source_target".
Parameters:
_source (str): source node @id
_target (str): target node @id
_label (str): label shown in graph
_edge_type (str): type of edge, influences shape on graph
"""
re... |
def is_free_square(state, x, y):
"""
:return: True if the given x, y coordinates are free spots, given the provided state
"""
return (x, y) not in state[0] and (x, y) not in state[1] |
def parse_pid(pid):
""" Parse the mesos pid string,
:param pid: pid of the form "id@ip:port"
:type pid: str
:returns: (id, ip, port)
:rtype: (str, str, str)
"""
id_, second = pid.split('@')
ip, port = second.split(':')
return id_, ip, port |
def is_palindrome(number):
"""Returns TRUE if number is a palindrome"""
nString = str(number)
if nString==nString[::-1]:
return True |
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
"""
Calculate the maximum metric value when we have multiple ground truths.
i.e., for each question, we have multiple answers.
:param metric_fn: the function to calculate metric
:param prediction: our model predicted answer str... |
def calculate_z_serial_purepython(maxiter, zs, cs):
"""Calculate output list using Julia update rule"""
output = [0] * len(zs)
for i in range(len(zs)):
n = 0
z = zs[i]
c = cs[i]
while n < maxiter and abs(z) < 2:
z = z * z + c
n += 1
output[i] =... |
def format_tweet_msg(title, url, description):
"""Format a tweet combining the title, description and URL.
It ensures the total size does not exceed the tweet max characters limit.
And it also replaces common words in the description to use hashtags.
"""
# First let's introduce hashtags to the desc... |
def is_tag(t):
"""Is `t` a tag?
"""
return t.strip().startswith('{%') |
def remove_smallwords(tokens, smallwords_threshold: int) -> list:
"""
Function that removes words which length is below a threshold
["hello", "my", "name", "is", "John", "Doe"] --> ["hello","name","John","Doe"]
Parameters
----------
text : list
list of strings
smallwords_threshold: ... |
def integer_diff(arr, n):
"""Return number of times integer difference, n, occurs within array.
input = two parameters, a list of integers
an integer, n, which equals difference
output = integer, number of times, n achieved in list
ex: int_diff([1, 1, 5, 6, 9, 16, 27], 4) # ... |
def stringify(sub):
"""Returns python string versions ('' and "") of original substring"""
check_str_s = "'" + sub + "'"
check_str_d = '"' + sub + '"'
return check_str_s, check_str_d |
def replace(text, searchValue, replaceValue):
"""
Return a string where all search value are replaced by the replace value.
"""
return text.replace(searchValue, replaceValue) |
def gif2star(gif_coord, gif_dimensions, mrc_dimensions):
""" Remap a coordinate in gif-space into star-space (e.g. rescale the image back to full size and invert the y-axis)
gif_coord = tuple, (x, y)
gif_dimensions = tuple, (x, y)
mrc_dimensions = tuple, (x, y)
"""
## fin... |
def compute_ecross(sch1, sch2, cos2phi, sin2phi):
"""Compute cross ellipticity."""
return - (sch2 * cos2phi - sch1 * sin2phi) |
def addWordNgrams(hash_list, n, bucket):
"""add word grams"""
ngram_hash_list = []
len_hash_list = len(hash_list)
for index, hash_val in enumerate(hash_list):
bound = min(len_hash_list, index + n)
for i in range(index + 1, bound):
hash_val = hash_val * 116049371 + hash_list[... |
def sum_of_squares(N):
"""Return the sum of squares of natural numbers."""
return (N * (N + 1) * (2 * N + 1)) // 6 |
def abspath(cwd, payload):
""" Get the absolute path """
# Just a few special cases "..", "." and ""
# If payload start's with /, set cwd to /
# and consider the remainder a relative path
if payload.startswith('/'):
cwd = "/"
for token in payload.split("/"):
if token == '..':
if cwd != '/':
cwd = '/'.j... |
def is_private(string):
"""Return ``True`` if string is a private attribute name."""
return string.startswith('_') |
def format_opt_parameters(dict_, pos):
"""Format the values depending on whether they are fixed or estimated."""
# Initialize baseline line
val = dict_["coeffs"][pos]
is_fixed = dict_["fixed"][pos]
bounds = dict_["bounds"][pos]
line = ["coeff", val, " ", " "]
if is_fixed:
line[-2] =... |
def add_additional_data_to_papers(papers, extra_data, extra_data_use_keys):
"""Enhance paper metadata using extra data
:param papers: list of paper metadata
:type papers: list
:param extra_data: extra data as a dictionary with keys as DOIs
:type extra_data: dict
:param extra_data_use_keys: list... |
def valid_word(draw, word):
""" Verify if a word is valid, according to the draw
"""
draw_list = list(draw)
for letter in word:
if letter not in draw_list:
return False
else:
draw_list.remove(letter)
return True |
def triangle_area(p1, p2, p3):
"""
Calculate the triangle area given from 3 points
:param p1:
:param p2:
:param p3:
:return:
"""
x1, y1 = p1[0], p1[1]
x2, y2 = p2[0], p2[1]
x3, y3 = p3[0], p3[1]
return abs((x1 * (y2 - y3) + x2 * (y3 - y1)
+ x3 * (y1 - y2)) / 2... |
def numSpecialEquivGroups(A):
"""
:type A: List[str]
:rtype: int
"""
def count(A):
ans = [0] * 52
for i, letter in enumerate(A):
ans[ord(letter) - ord('a') + 26 * (i%2)] += 1
return tuple(ans)
return len({count(word) for word in A}) |
def findKeyD(phi,e):
"""
Finds the private key d using the extended Euclidean algorithm
"""
x = 0
old_x = 1
y = 1
old_y = 0
r = e
old_r = phi
while not r == 0:
q = old_r // r
old_r, r = r, old_r - q*r
old_x, x = x, old_x - q*x
... |
def create_mock_file_content(session_id, file_name):
""" creates mock file content """
return """; file {} from session {}
(domain (...)
)
""".format(session_id, file_name) |
def is_prime(n: int) -> bool:
"""Decide the whether the given integer is prime number or not
>>> is_prime(1)
False
>>> is_prime(2)
True
>>> is_prime(119)
False
>>> is_prime(977)
True
>>> is_prime(-37)
Traceback (most recent call last):
...
ValueError: n must be >... |
def round_robin(varlist, pserver_endpoints):
"""
distribute variables to several endpoints.
"""
assert (len(varlist) > len(pserver_endpoints))
eplist = []
pserver_idx = 0
for var in varlist:
server_for_param = pserver_endpoints[pserver_idx]
eplist.append(server_for_param)
... |
def removeStopWords(listWords,stopwords):
"""
Filters out stopwords in a list of words
"""
return list(filter(lambda x : len(x)>0 and x not in stopwords, listWords)) |
def get_alpha(value: float):
"""Bound alpha to range [0.01,1]."""
return min(1, max(value, 0.01)) |
def get_attribute(data, attribute, default_value):
"""get json attriubte from data."""
return data.get(attribute) or default_value |
def clean_place(place, places):
"""
Perform place name cleanup and optional substitution for bulk edits
"""
result = place
result = result.replace(' ', ' ')
for match in places:
result = result.replace(match, places[match])
return result |
def addEdgeMI(em_dict, edge, value):
"""
Add motif information to edge dictionary.
Input:
em_dict: (dictionary) the dictionary of edge motif degree
edge: (int) the id of edge
value: (int) the change value of edge
Output:
em_dict: (dictionary) changed ... |
def row_full(row, puzzle):
"""
Takes a row number, and a sudoku puzzle as parameter
Returns True if there is no empty space on the row
ReturnsFalse if otherwise
"""
for col in range(0, 9):
if puzzle[row][col] == -1:
return False
return True |
def facti(n: int) -> int:
"""Imperative Factorial
>>> fact(0)
1
>>> fact(1)
1
>>> fact(7)
5040
"""
if n == 0:
return 1
f = 1
for i in range(2, n):
f = f*i
return f |
def add_tag(tag: str, s: str) -> str:
""" Adds a tag on either side of a string. """
return "<{}>{}</{}>".format(tag, s, tag) |
def exclude_customview_hook(endpoints):
"""This excludes API endpoints of custom-view's ones. Because it's not always
necessary to generage custom-view's OpenAPI schema.
"""
result = []
for (path, path_regex, method, callback) in endpoints:
if "/custom/" not in path:
result.appen... |
def unpack(inp, tar):
"""
Unpack the data so that it can be processed by pytorch_lightning
distributed learning
"""
return (*[v for v in inp.values()], tar, list(inp.keys())) |
def get_blanks(nrows, ncols, plot_set):
"""Return a list of plot locations that should remain blank."""
assert type(plot_set) == set
nplots = nrows * ncols
plot_numbers = range(1, nplots + 1)
return list(set(plot_numbers) - plot_set) |
def find_rank(wr):
"""
Return the list of ranks for the solution kappa.
Parameter:
wr -- list of Decimal
Return:
rank -- list of integer
"""
# List of ranks
rank = []
# If the list is not empty, retrieve the rank in [0,1]
if wr:
# Count number of rank increment ('wr4' or 'wr5' or 'wr6')
# and rank ... |
def convert_bb_spec(xmin, ymin, xmax, ymax):
"""
Convert a bounding box representation
"""
x = xmin
y = ymin
width = xmax - xmin
height = ymax - ymin
return x, y, width, height |
def append_if(array, item):
"""Append an ``item`` to an ``array`` if its not already in it.
:param array: ``list`` List object to append to
:param item: ``object`` Object to append to the list
:returns array: returns the amended list.
"""
if item not in array:
array.append(item)
... |
def or_of_bits(*bits):
"""OR the given bits.
Args:
*bits (int): Bits for OR. More than one argument required.
Return:
or_bit (int): OR of the given bits.
Example:
>>> or_of_bits(1, 4, 16)
21 # 0b10101, 0x15
>>> or_of_bits(0b00010, 0b10000)
18 # 0b10010,... |
def extract_class_name(line: str) -> str:
"""
Extracts class name from class definition in the form of "class {CLASS_NAME}({Type}):"
"""
start_token = "class "
end_token = "("
start, end = line.find(start_token) + len(start_token), line.find(end_token)
return line[start:end] |
def three_sum_fast(arr):
"""O(n^2)"""
result = []
arr.sort()
for i in range(len(arr) - 2):
if i > 0 and arr[i] == arr[i - 1]:
continue
start = i + 1
end = len(arr) - 1
while start < end:
if arr[i] + arr[start] + arr[end] == 0:
res... |
def filenameToModuleName(filename):
"""Converts a game data path to a module name."""
if filename.startswith('Scripts/'):
filename = filename[8:]
if filename.endswith('.py'):
filename = filename[:-3]
filename = filename.replace('/', '.')
return filename |
def _should_skip(d: str) -> bool:
"""Skip directories that should not contain py sources."""
if d.startswith("python/.eggs/"):
return True
if d.startswith("python/."):
return True
if d.startswith("python/build"):
return True
if d.startswith("python/ray/cpp"):
return T... |
def normalize_image(image):
"""
Image values normalized between -1 and +1.
"""
a = -1.0
b = 1.0
px_min = 0
px_max = 255
normalized_image = a + ( ( (image - px_min)*(b - a) )/( px_max - px_min ) )
return normalized_image |
def interpolate(color_a, color_b, factor):
"""
Interpolate between two colors be the given factor
:param color_a: List or tuple of three value, red, green and blue
:param color_b: List or tuple of three value, red, green and blue
:param factor: Factor for interpolating between the two colors
:re... |
def findMinDepthRefine(Sdict, R, w, foundIdList):
"""Find the min cost subset. the subset that covers the most seqiences is the best.
This has a new list attached to it which is the list of IDs already found
Args:
Sdict: dict between motif Ids and sequences the motif occurs in
R: the list of sequences not covere... |
def word_tally(word_list):
"""
Compiles a dictionary of words. Keys are the word, values are the number of occurrences
of this word in the page.
:param word_list: list
List of words
:return: dictionary
Dict of words: total
"""
word_dict = {}
for word in word_list:
... |
def three_digit(number):
""" Add 0s to inputs that their length is less than 3.
:param number:
The number to convert
:type number:
int
:returns:
String
:example:
>>> three_digit(1)
'001'
"""
number = str(number)
if len(number) == 1:
retu... |
def merge_sort_p(inp):
"""docstring"""
if len(inp) <= 1:
return inp
mid = len(inp) // 2
rlen = len(inp) - mid
lft = merge_sort_p(inp[:mid])
rgt = merge_sort_p(inp[mid:])
i = j = 0
out = []
while i < mid or j < rlen:
if j >= rlen or (i < mid and lft[i] <= rgt[j]):
... |
def ConvertToFloat(line, colnam_list):
"""
Convert some columns (in colnam_list) to float, and round by 3 decimal.
:param line: a dictionary from DictReader.
:param colnam_list: float columns
:return: a new dictionary
"""
for name in colnam_list:
line[name] = round(float(line[name])... |
def iroot(k, n):
""" http://stackoverflow.com/questions/15978781/how-to-find-integer-nth-roots"""
u, s = n, n+1
while u < s:
s = u
t = (k-1) * s + n // pow(s, k-1)
u = t // k
return s |
def get_all_case_combinations(np):
"""
Returns all case combinations for the noun-phrase (regular, upper, lower, title)
Args:
np (str): a noun-phrase
Returns:
list(str): List of all case combinations
"""
candidates = [np, np.upper(), np.lower(), np.title()]
return candidates |
def listify(*args):
"""
A function that creates a tuple
of all the arguments passed, for
inputs to InputMultiPath Spec
Parameters
----------
*args: a list of arguments
Returns
-------
[(*args)] :
a single-element list of a ... |
def get_result_for_multijob_test(states):
"""Return worst final result for a test that has several PanDA jobs"""
result = None
state_dict = {
'active': 0,
'failed': 1,
'finished': 2,
'succeeded': 3,
}
result_index = min([state_dict[s] for s in list(set(states)) if s ... |
def chain_id(id_set):
""" Function to create unique IDs """
alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'BB',
'CC', 'DD', 'EE', 'FF', 'GG', 'HH', 'II', 'JJ', 'KK', 'LL', 'MM', 'NN',
'OO', 'PP', 'QQ', '... |
def _build_predict_tx_message(msg, msg_uuid, row, model_name, model_gcp_project,
model_region, model_date, model_api_endpoint):
"""Creates a JSON object for predict transaction cloud function.
Args:
msg: A JSON object representing the original message received by this cloud
... |
def _match_enums(enum_hypothesis_list, enum_reference_list):
"""
matches exact words in hypothesis and reference and returns
a word mapping between enum_hypothesis_list and enum_reference_list
based on the enumerated word id.
:param enum_hypothesis_list: enumerated hypothesis list
:type enum_hy... |
def is_in_cell(point:list, corners:list) -> bool:
"""
Checks if a point is within a cell.
:param point: Tuple of lat/Y,lon/X-coordinates
:param corners: List of corner coordinates
:returns: Boolean whether point is within cell
:Example:
"""
y1, y2, x1, x2 = corners[2][0], corn... |
def is_number(x):
"""Tests whether a variable (e.g. '12') contains a number."""
try:
float(x)
return True
except (ValueError, TypeError):
return False |
def _response(nones):
"""Create list of dicts.
Args:
nones: Dict of values keyed by timestamp
Returns:
result: List of key-value pair dicts
"""
# Return a list of dicts
result = []
for timestamp, value in sorted(nones.items()):
result.append({'timestamp': timestamp... |
def num_row_elements(row):
"""Get number of elements in CSV row."""
try:
rowset = set(row)
rowset.discard("")
return len(rowset)
except TypeError:
return 0 |
def dict_to_string(data):
"""Takes a dictionary and converts it to a string to send
over serial connection with Micro:Bit
Args:
data: Dict
Returns:
str: JSON string of the data.
"""
return (str(data).replace("'", '"')
.replace(": False", ": false")
... |
def is_network_rate_error(exc):
"""
:param exc: Exception
Exception thrown when requesting network resource
:return: bool
True iff exception tells you abused APIs
"""
keys = ["429", "Connection refused"]
for key in keys:
if key in str(exc):
return True
re... |
def parse_hl_lines(expr):
"""Support our syntax for emphasizing certain lines of code.
expr should be like '1 2' to emphasize lines 1 and 2 of a code block.
Returns a list of ints, the line numbers to emphasize.
"""
if not expr:
return []
try:
return list(map(int, expr.split())... |
def ListFromConcat(*items):
"""Generate list by concatenating inputs"""
itemsout = []
for item in items:
if item is None:
continue
if type(item) is not type([]):
itemsout.append(item)
else:
itemsout.extend(item)
return itemsout |
def check_comp(component, allowed):
"""Check if a component is valid."""
if not isinstance(component, str):
raise TypeError("Component must be a string")
component = component.upper().strip()
if component not in allowed:
raise ValueError(
"Component %s not a valid type. " % ... |
def kwargs_to_string(kwargs):
"""
Given a set of kwargs, turns them into a string which can then be passed to a command.
:param kwargs: kwargs from a function call.
:return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.
"""
outstr = ''
for ... |
def formatVisParams(visParams):
""" format visualization params to match getMapId requirement """
copy = {key: val for key, val in visParams.items()}
def list2str(params):
n = len(params)
if n == 3:
newbands = '{},{},{}'.format(params[0], params[1], params[2])
else:
... |
def round_filters(filters, width_coefficient, depth_divisor, min_depth):
"""Calculate and round number of filters based on width multiplier.
Use width_coefficient, depth_divisor and min_depth.
Args:
filters (int): Filters number to be calculated.
Params from arch_params:
width_coe... |
def get_divisors(n, includeN=True):
"""
>>> get_divisors(28)
[1, 2, 4, 7, 14, 28]
>>> get_divisors(28, includeN=False)
[1, 2, 4, 7, 14]
Derived from https://qiita.com/LorseKudos/items/9eb560494862c8b4eb56
"""
lower_divisors, upper_divisors = [], []
i = 1
while i * i <= n:
... |
def lcs(path):
"""
Given an edit script path returns the longest common subseqence.
"""
result = []
for i in range(1, len(path)):
x, y = path[i]
px, py = path[i - 1]
dx, dy = x - px, y - py
if dx == 1 and dy == 1:
result.append((px, py))
return result |
def HEXtoVOLTS(ADChexStr):
"""ADC: 1000.0 volts full scale (D1B6).
(for scaling ADC input)
HEXtoVOLTS('D1B6') => 1000
HEXtoVOLTS('BCD4') => 900 """
return int(int(ADChexStr,16) / 53.686 + 0.5) |
def indexcount(index, tp):
"""Number of dimensions with a specific index type
Args:
index(index): object used in indexing or slicing
Returns:
num: length of the list indexing
"""
if isinstance(index, tuple):
return sum([indexcount(i, tp) for i in index])
elif isinstance(... |
def slash_join(*args):
"""
Joins together strings and guarantees there is only one '/' in between the each string joined.
Double slashes ('//') are assumed to be intentional and are not deduplicated.
"""
def rmslash(path):
path = path[1:] if len(path) > 0 and path[0] == "/" else path
... |
def add_init_or_construct(template, variable_slot, new_data, scope, add_location=-1):
"""Add init or construct statement."""
if isinstance(new_data, list):
template[variable_slot][scope].extend(new_data)
return template
if add_location < 0:
template[variable_slot][scope].append(new_d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.