Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def topng(self, path, prefix='image', overwrite=False):
from thunder.images.writers import topng
# TODO add back colormap and vmin/vmax
topng(self, path, prefix=prefix, overwrite=overwrite) | [
"\n Write 2d images as PNG files.\n\n Files will be written into a newly-created directory.\n Three-dimensional data will be treated as RGB channels.\n\n Parameters\n ----------\n path : string\n Path to output directory, must be one level below an existing direc... |
Please provide a description of the function:def map_as_series(self, func, value_size=None, dtype=None, chunk_size='auto'):
blocks = self.toblocks(chunk_size=chunk_size)
if value_size is not None:
dims = list(blocks.blockshape)
dims[0] = value_size
else:
... | [
"\n Efficiently apply a function to images as series data.\n\n For images data that represent image sequences, this method\n applies a function to each pixel's series, and then returns to\n the images format, using an efficient intermediate block\n representation.\n\n Param... |
Please provide a description of the function:def count(self):
if self.mode == 'spark':
return self.tordd().count()
if self.mode == 'local':
return prod(self.values.values.shape) | [
"\n Explicit count of the number of items.\n\n For lazy or distributed data, will force a computation.\n "
] |
Please provide a description of the function:def collect_blocks(self):
if self.mode == 'spark':
return self.values.tordd().sortByKey().values().collect()
if self.mode == 'local':
return self.values.values.flatten().tolist() | [
"\n Collect the blocks in a list\n "
] |
Please provide a description of the function:def map(self, func, value_shape=None, dtype=None):
mapped = self.values.map(func, value_shape=value_shape, dtype=dtype)
return self._constructor(mapped).__finalize__(self, noprop=('dtype',)) | [
"\n Apply an array -> array function to each block\n "
] |
Please provide a description of the function:def first(self):
if self.mode == 'spark':
return self.values.tordd().values().first()
if self.mode == 'local':
return self.values.first | [
"\n Return the first element.\n "
] |
Please provide a description of the function:def toimages(self):
from thunder.images.images import Images
if self.mode == 'spark':
values = self.values.values_to_keys((0,)).unchunk()
if self.mode == 'local':
values = self.values.unchunk()
return Images... | [
"\n Convert blocks to images.\n "
] |
Please provide a description of the function:def toseries(self):
from thunder.series.series import Series
if self.mode == 'spark':
values = self.values.values_to_keys(tuple(range(1, len(self.shape)))).unchunk()
if self.mode == 'local':
values = self.values.unch... | [
"\n Converts blocks to series.\n "
] |
Please provide a description of the function:def toarray(self):
if self.mode == 'spark':
return self.values.unchunk().toarray()
if self.mode == 'local':
return self.values.unchunk() | [
"\n Convert blocks to local ndarray\n "
] |
Please provide a description of the function:def flatten(self):
size = prod(self.shape[:-1])
return self.reshape(size, self.shape[-1]) | [
"\n Reshape all dimensions but the last into a single dimension\n "
] |
Please provide a description of the function:def first(self):
if self.mode == 'local':
return self.values[tuple(zeros(len(self.baseaxes))) + (slice(None, None),)]
if self.mode == 'spark':
return self.values.first().toarray() | [
"\n Return the first element.\n "
] |
Please provide a description of the function:def tolocal(self):
from thunder.series.readers import fromarray
if self.mode == 'local':
logging.getLogger('thunder').warn('images already in local mode')
pass
return fromarray(self.toarray(), index=self.index, label... | [
"\n Convert to local mode.\n "
] |
Please provide a description of the function:def tospark(self, engine=None):
from thunder.series.readers import fromarray
if self.mode == 'spark':
logging.getLogger('thunder').warn('images already in local mode')
pass
if engine is None:
raise ValueE... | [
"\n Convert to spark mode.\n "
] |
Please provide a description of the function:def sample(self, n=100, seed=None):
if n < 1:
raise ValueError("Number of samples must be larger than 0, got '%g'" % n)
if seed is None:
seed = random.randint(0, 2 ** 32)
if self.mode == 'spark':
result =... | [
"\n Extract random sample of records.\n\n Parameters\n ----------\n n : int, optional, default = 100\n The number of data points to sample.\n\n seed : int, optional, default = None\n Random seed.\n "
] |
Please provide a description of the function:def map(self, func, index=None, value_shape=None, dtype=None, with_keys=False):
# if new index is given, can infer missing value_shape
if value_shape is None and index is not None:
value_shape = len(index)
if isinstance(value_sha... | [
"\n Map an array -> array function over each record.\n\n Parameters\n ----------\n func : function\n A function of a single record.\n\n index : array-like, optional, default = None\n If known, the index to be used following function evaluation.\n\n val... |
Please provide a description of the function:def mean(self):
return self._constructor(self.values.mean(axis=self.baseaxes, keepdims=True)) | [
"\n Compute the mean across records\n "
] |
Please provide a description of the function:def sum(self):
return self._constructor(self.values.sum(axis=self.baseaxes, keepdims=True)) | [
"\n Compute the sum across records.\n "
] |
Please provide a description of the function:def max(self):
return self._constructor(self.values.max(axis=self.baseaxes, keepdims=True)) | [
"\n Compute the max across records.\n "
] |
Please provide a description of the function:def min(self):
return self._constructor(self.values.min(axis=self.baseaxes, keepdims=True)) | [
"\n Compute the min across records.\n "
] |
Please provide a description of the function:def reshape(self, *shape):
if prod(self.shape) != prod(shape):
raise ValueError("Reshaping must leave the number of elements unchanged")
if self.shape[-1] != shape[-1]:
raise ValueError("Reshaping cannot change the size of th... | [
"\n Reshape the Series object\n\n Cannot change the last dimension.\n\n Parameters\n ----------\n shape: one or more ints\n New shape\n "
] |
Please provide a description of the function:def between(self, left, right):
crit = lambda x: left <= x < right
return self.select(crit) | [
"\n Select subset of values within the given index range.\n\n Inclusive on the left; exclusive on the right.\n\n Parameters\n ----------\n left : int\n Left-most index in the desired range.\n\n right: int\n Right-most index in the desired range.\n ... |
Please provide a description of the function:def select(self, crit):
import types
# handle lists, strings, and ints
if not isinstance(crit, types.FunctionType):
# set("foo") -> {"f", "o"}; wrap in list to prevent:
if isinstance(crit, string_types):
... | [
"\n Select subset of values that match a given index criterion.\n\n Parameters\n ----------\n crit : function, list, str, int\n Criterion function to map to indices, specific index value,\n or list of indices.\n "
] |
Please provide a description of the function:def center(self, axis=1):
if axis == 1:
return self.map(lambda x: x - mean(x))
elif axis == 0:
meanval = self.mean().toarray()
return self.map(lambda x: x - meanval)
else:
raise Exception('Axis ... | [
"\n Subtract the mean either within or across records.\n\n Parameters\n ----------\n axis : int, optional, default = 1\n Which axis to center along, within (1) or across (0) records.\n "
] |
Please provide a description of the function:def standardize(self, axis=1):
if axis == 1:
return self.map(lambda x: x / std(x))
elif axis == 0:
stdval = self.std().toarray()
return self.map(lambda x: x / stdval)
else:
raise Exception('Axis... | [
"\n Divide by standard deviation either within or across records.\n\n Parameters\n ----------\n axis : int, optional, default = 0\n Which axis to standardize along, within (1) or across (0) records\n "
] |
Please provide a description of the function:def zscore(self, axis=1):
if axis == 1:
return self.map(lambda x: (x - mean(x)) / std(x))
elif axis == 0:
meanval = self.mean().toarray()
stdval = self.std().toarray()
return self.map(lambda x: (x - mea... | [
"\n Subtract the mean and divide by standard deviation within or across records.\n\n Parameters\n ----------\n axis : int, optional, default = 0\n Which axis to zscore along, within (1) or across (0) records\n "
] |
Please provide a description of the function:def squelch(self, threshold):
func = lambda x: zeros(x.shape) if max(x) < threshold else x
return self.map(func) | [
"\n Set all records that do not exceed the given threhsold to 0.\n\n Parameters\n ----------\n threshold : scalar\n Level below which to set records to zero\n "
] |
Please provide a description of the function:def correlate(self, signal):
s = asarray(signal)
if s.ndim == 1:
if size(s) != self.shape[-1]:
raise ValueError("Length of signal '%g' does not match record length '%g'"
% (size(s), self.s... | [
"\n Correlate records against one or many one-dimensional arrays.\n\n Parameters\n ----------\n signal : array-like\n One or more signals to correlate against.\n "
] |
Please provide a description of the function:def _check_panel(self, length):
n = len(self.index)
if divmod(n, length)[1] != 0:
raise ValueError("Panel length '%g' must evenly divide length of series '%g'"
% (length, n))
if n == length:
... | [
"\n Check that given fixed panel length evenly divides index.\n\n Parameters\n ----------\n length : int\n Fixed length with which to subdivide index\n "
] |
Please provide a description of the function:def mean_by_panel(self, length):
self._check_panel(length)
func = lambda v: v.reshape(-1, length).mean(axis=0)
newindex = arange(length)
return self.map(func, index=newindex) | [
"\n Compute the mean across fixed sized panels of each record.\n\n Splits each record into panels of size `length`,\n and then computes the mean across panels.\n Panel length must subdivide record exactly.\n\n Parameters\n ----------\n length : int\n Fixed... |
Please provide a description of the function:def _makemasks(self, index=None, level=0):
if index is None:
index = self.index
try:
dims = len(array(index).shape)
if dims == 1:
index = array(index, ndmin=2).T
except:
raise T... | [
"\n Internal function for generating masks for selecting values based on multi-index values.\n\n As all other multi-index functions will call this function, basic type-checking is also\n performed at this stage.\n "
] |
Please provide a description of the function:def _map_by_index(self, function, level=0):
if type(level) is int:
level = [level]
masks, ind = self._makemasks(index=self.index, level=level)
nMasks = len(masks)
newindex = array(ind)
if len(newindex[0]) == 1:
... | [
"\n An internal function for maping a function to groups of values based on a multi-index\n\n Elements of each record are grouped according to unique value combinations of the multi-\n index across the given levels of the multi-index. Then the given function is applied\n to to each of th... |
Please provide a description of the function:def select_by_index(self, val, level=0, squeeze=False, filter=False, return_mask=False):
try:
level[0]
except:
level = [level]
try:
val[0]
except:
val = [val]
remove = []
... | [
"\n Select or filter elements of the Series by index values (across levels, if multi-index).\n\n The index is a property of a Series object that assigns a value to each position within\n the arrays stored in the records of the Series. This function returns a new Series where,\n within ea... |
Please provide a description of the function:def aggregate_by_index(self, function, level=0):
result = self._map_by_index(function, level=level)
return result.map(lambda v: array(v), index=result.index) | [
"\n Aggregrate data in each record, grouping by index values.\n\n For each unique value of the index, applies a function to the group\n indexed by that value. Returns a Series indexed by those unique values.\n For the result to be a valid Series object, the aggregating function should\n ... |
Please provide a description of the function:def stat_by_index(self, stat, level=0):
from numpy import sum, min, max
STATS = {
'sum': sum,
'mean': mean,
'median': median,
'stdev': std,
'max': max,
'min': min,
'... | [
"\n Compute the desired statistic for each uniue index values (across levels, if multi-index)\n\n Parameters\n ----------\n stat : string\n Statistic to be computed: sum, mean, median, stdev, max, min, count\n\n level : list of ints, optional, default=0\n Spe... |
Please provide a description of the function:def gramian(self):
if self.mode == 'spark':
rdd = self.values.tordd()
from pyspark.accumulators import AccumulatorParam
class MatrixAccumulator(AccumulatorParam):
def zero(self, value):
... | [
"\n Compute gramian of a distributed matrix.\n\n The gramian is defined as the product of the matrix\n with its transpose, i.e. A^T * A.\n "
] |
Please provide a description of the function:def times(self, other):
if isinstance(other, ScalarType):
other = asarray(other)
index = self.index
else:
if isinstance(other, list):
other = asarray(other)
if isinstance(other, ndarray)... | [
"\n Multiply a matrix by another one.\n\n Other matrix must be a numpy array, a scalar,\n or another matrix in local mode.\n\n Parameters\n ----------\n other : Matrix, scalar, or numpy array\n A matrix to multiply with\n "
] |
Please provide a description of the function:def _makewindows(self, indices, window):
div = divmod(window, 2)
before = div[0]
after = div[0] + div[1]
index = asarray(self.index)
indices = asarray(indices)
if where(index == max(indices))[0][0] + after > len(index)... | [
"\n Make masks used by windowing functions\n\n Given a list of indices specifying window centers,\n and a window size, construct a list of index arrays,\n one per window, that index into the target array\n\n Parameters\n ----------\n indices : array-like\n ... |
Please provide a description of the function:def mean_by_window(self, indices, window):
masks = self._makewindows(indices, window)
newindex = arange(0, len(masks[0]))
return self.map(lambda x: mean([x[m] for m in masks], axis=0), index=newindex) | [
"\n Average series across multiple windows specified by their centers.\n\n Parameters\n ----------\n indices : array-like\n List of times specifying window centers\n\n window : int\n Window size\n "
] |
Please provide a description of the function:def subsample(self, sample_factor=2):
if sample_factor < 0:
raise Exception('Factor for subsampling must be postive, got %g' % sample_factor)
s = slice(0, len(self.index), sample_factor)
newindex = self.index[s]
return sel... | [
"\n Subsample series by an integer factor.\n\n Parameters\n ----------\n sample_factor : positive integer, optional, default=2\n Factor for downsampling.\n "
] |
Please provide a description of the function:def downsample(self, sample_factor=2):
if sample_factor < 0:
raise Exception('Factor for subsampling must be postive, got %g' % sample_factor)
newlength = floor(len(self.index) / sample_factor)
func = lambda v: v[0:int(newlength *... | [
"\n Downsample series by an integer factor by averaging.\n\n Parameters\n ----------\n sample_factor : positive integer, optional, default=2\n Factor for downsampling.\n "
] |
Please provide a description of the function:def fourier(self, freq=None):
def get(y, freq):
y = y - mean(y)
nframes = len(y)
ft = fft.fft(y)
ft = ft[0:int(fix(nframes/2))]
ampFt = 2*abs(ft)/nframes
amp = ampFt[freq]
am... | [
"\n Compute statistics of a Fourier decomposition on series data.\n\n Parameters\n ----------\n freq : int\n Digital frequency at which to compute coherence and phase\n "
] |
Please provide a description of the function:def convolve(self, signal, mode='full'):
from numpy import convolve
s = asarray(signal)
n = size(self.index)
m = size(s)
# use expected lengths to make a new index
if mode == 'same':
newmax = max(n, m)
... | [
"\n Convolve series data against another signal.\n\n Parameters\n ----------\n signal : array\n Signal to convolve with (must be 1D)\n\n mode : str, optional, default='full'\n Mode of convolution, options are 'full', 'same', and 'valid'\n "
] |
Please provide a description of the function:def crosscorr(self, signal, lag=0):
from scipy.linalg import norm
s = asarray(signal)
s = s - mean(s)
s = s / norm(s)
if size(s) != size(self.index):
raise Exception('Size of signal to cross correlate with, %g, '... | [
"\n Cross correlate series data against another signal.\n\n Parameters\n ----------\n signal : array\n Signal to correlate against (must be 1D).\n\n lag : int\n Range of lags to consider, will cover (-lag, +lag).\n "
] |
Please provide a description of the function:def detrend(self, method='linear', order=5):
check_options(method, ['linear', 'nonlinear'])
if method == 'linear':
order = 1
def func(y):
x = arange(len(y))
p = polyfit(x, y, order)
p[-1] = 0
... | [
"\n Detrend series data with linear or nonlinear detrending.\n\n Preserve intercept so that subsequent operations can adjust the baseline.\n\n Parameters\n ----------\n method : str, optional, default = 'linear'\n Detrending method\n\n order : int, optional, defa... |
Please provide a description of the function:def normalize(self, method='percentile', window=None, perc=20, offset=0.1):
check_options(method, ['mean', 'percentile', 'window', 'window-exact'])
from warnings import warn
if not (method == 'window' or method == 'window-exact') and window... | [
"\n Normalize by subtracting and dividing by a baseline.\n\n Baseline can be derived from a global mean or percentile,\n or a smoothed percentile estimated within a rolling window.\n Windowed baselines may only be well-defined for\n temporal series data.\n\n Parameters\n ... |
Please provide a description of the function:def toimages(self, chunk_size='auto'):
from thunder.images.images import Images
if chunk_size is 'auto':
chunk_size = str(max([int(1e5/prod(self.baseshape)), 1]))
n = len(self.shape) - 1
if self.mode == 'spark':
... | [
"\n Converts to images data.\n\n This method is equivalent to series.toblocks(size).toimages().\n\n Parameters\n ----------\n chunk_size : str or tuple, size of series chunk used during conversion, default = 'auto'\n String interpreted as memory size (in kilobytes, e.g.... |
Please provide a description of the function:def tobinary(self, path, prefix='series', overwrite=False, credentials=None):
from thunder.series.writers import tobinary
tobinary(self, path, prefix=prefix, overwrite=overwrite, credentials=credentials) | [
"\n Write data to binary files.\n\n Parameters\n ----------\n path : string path or URI to directory to be created\n Output files will be written underneath path.\n Directory will be created as a result of this call.\n\n prefix : str, optional, default = 'ser... |
Please provide a description of the function:def addextension(path, ext=None):
if ext:
if '*' in path:
return path
elif os.path.splitext(path)[1]:
return path
else:
if not ext.startswith('.'):
ext = '.'+ext
if not path.ends... | [
"\n Helper function for handling of paths given separately passed file extensions.\n "
] |
Please provide a description of the function:def select(files, start, stop):
if start or stop:
if start is None:
start = 0
if stop is None:
stop = len(files)
files = files[start:stop]
return files | [
"\n Helper function for handling start and stop indices\n "
] |
Please provide a description of the function:def readlocal(path, offset=None, size=-1):
try:
with open(path, 'rb') as f:
if offset:
f.seek(offset)
buf = f.read(size)
except IOError as e:
if e.errno == errno.ENOENT:
raise FileNotFoundError(... | [
"\n Wrapper around open(path, 'rb') that returns the contents of the file as a string.\n\n Will rethrow FileNotFoundError if it receives an IOError.\n "
] |
Please provide a description of the function:def listrecursive(path, ext=None):
filenames = set()
for root, dirs, files in os.walk(path):
if ext:
if ext == 'tif' or ext == 'tiff':
tmp = fnmatch.filter(files, '*.' + 'tiff')
files = tmp + fnmatch.filter(fil... | [
"\n List files recurisvely\n "
] |
Please provide a description of the function:def listflat(path, ext=None):
if os.path.isdir(path):
if ext:
if ext == 'tif' or ext == 'tiff':
files = glob.glob(os.path.join(path, '*.tif'))
files = files + glob.glob(os.path.join(path, '*.tiff'))
els... | [
"\n List files without recursion\n "
] |
Please provide a description of the function:def normalize_scheme(path, ext):
path = addextension(path, ext)
parsed = urlparse(path)
if parsed.scheme:
# this appears to already be a fully-qualified URI
return path
else:
# this looks like a local path spec
import os
... | [
"\n Normalize scheme for paths related to hdfs\n "
] |
Please provide a description of the function:def get_by_scheme(path, lookup, default):
parsed = urlparse(path)
class_name = lookup.get(parsed.scheme, default)
if class_name is None:
raise NotImplementedError("No implementation for scheme " + parsed.scheme)
return class_name | [
"\n Helper function used by get*ForPath().\n "
] |
Please provide a description of the function:def list(path, ext=None, start=None, stop=None, recursive=False):
files = listflat(path, ext) if not recursive else listrecursive(path, ext)
if len(files) < 1:
raise FileNotFoundError('Cannot find files of type "%s" in %s'
... | [
"\n Get sorted list of file paths matching path and extension\n "
] |
Please provide a description of the function:def read(self, path, ext=None, start=None, stop=None, recursive=False, npartitions=None):
path = uri_to_path(path)
files = self.list(path, ext=ext, start=start, stop=stop, recursive=recursive)
nfiles = len(files)
self.nfiles = nfiles... | [
"\n Sets up Spark RDD across files specified by dataPath on local filesystem.\n\n Returns RDD of <integer file index, string buffer> k/v pairs.\n "
] |
Please provide a description of the function:def list(path, filename=None, start=None, stop=None, recursive=False, directories=False):
path = uri_to_path(path)
if not filename and recursive:
return listrecursive(path)
if filename:
if os.path.isdir(path):
... | [
"\n List files specified by dataPath.\n\n Datapath may include a single wildcard ('*') in the filename specifier.\n\n Returns sorted list of absolute path strings.\n "
] |
Please provide a description of the function:def parse_query(query, delim='/'):
key = ''
prefix = ''
postfix = ''
parsed = urlparse(query)
query = parsed.path.lstrip(delim)
bucket = parsed.netloc
if not parsed.scheme.lower() in ('', "gs", "s3", "s3n"):
... | [
"\n Parse a boto query\n "
] |
Please provide a description of the function:def retrieve_keys(bucket, key, prefix='', postfix='', delim='/',
directories=False, recursive=False):
if key and prefix:
assert key.endswith(delim)
key += prefix
# check whether key is a directory
if... | [
"\n Retrieve keys from a bucket\n "
] |
Please provide a description of the function:def getfiles(self, path, ext=None, start=None, stop=None, recursive=False):
from .utils import connection_with_anon, connection_with_gs
parse = BotoClient.parse_query(path)
scheme = parse[0]
bucket_name = parse[1]
if scheme... | [
"\n Get scheme, bucket, and keys for a set of files\n "
] |
Please provide a description of the function:def list(self, dataPath, ext=None, start=None, stop=None, recursive=False):
scheme, bucket_name, keylist = self.getfiles(
dataPath, ext=ext, start=start, stop=stop, recursive=recursive)
return ["%s:///%s/%s" % (scheme, bucket_name, key) ... | [
"\n List files from remote storage\n "
] |
Please provide a description of the function:def read(self, path, ext=None, start=None, stop=None, recursive=False, npartitions=None):
from .utils import connection_with_anon, connection_with_gs
path = addextension(path, ext)
scheme, bucket_name, keylist = self.getfiles(
pa... | [
"\n Sets up Spark RDD across S3 or GS objects specified by dataPath.\n\n Returns RDD of <string bucket keyname, string buffer> k/v pairs.\n "
] |
Please provide a description of the function:def getkeys(self, path, filename=None, directories=False, recursive=False):
from .utils import connection_with_anon, connection_with_gs
parse = BotoClient.parse_query(path)
scheme = parse[0]
bucket_name = parse[1]
key = pars... | [
"\n Get matching keys for a path\n "
] |
Please provide a description of the function:def getkey(self, path, filename=None):
scheme, keys = self.getkeys(path, filename=filename)
try:
key = next(keys)
except StopIteration:
raise FileNotFoundError("Could not find object for: '%s'" % path)
# we ex... | [
"\n Get single matching key for a path\n "
] |
Please provide a description of the function:def list(self, path, filename=None, start=None, stop=None, recursive=False, directories=False):
storageScheme, keys = self.getkeys(
path, filename=filename, directories=directories, recursive=recursive)
keys = [storageScheme + ":///" + ke... | [
"\n List objects specified by path.\n\n Returns sorted list of 'gs://' or 's3n://' URIs.\n "
] |
Please provide a description of the function:def read(self, path, filename=None, offset=None, size=-1):
storageScheme, key = self.getkey(path, filename=filename)
if offset or (size > -1):
if not offset:
offset = 0
if size > -1:
sizeStr = ... | [
"\n Read a file specified by path.\n "
] |
Please provide a description of the function:def open(self, path, filename=None):
scheme, key = self.getkey(path, filename=filename)
return BotoReadFileHandle(scheme, key) | [
"\n Open a file specified by path.\n "
] |
Please provide a description of the function:def check_path(path, credentials=None):
from thunder.readers import get_file_reader
reader = get_file_reader(path)(credentials=credentials)
existing = reader.list(path, directories=True)
if existing:
raise ValueError('Path %s appears to already e... | [
"\n Check that specified output path does not already exist\n\n The ValueError message will suggest calling with overwrite=True;\n this function is expected to be called from the various output methods\n that accept an 'overwrite' keyword argument.\n "
] |
Please provide a description of the function:def connection_with_anon(credentials, anon=True):
from boto.s3.connection import S3Connection
from boto.exception import NoAuthHandlerFound
try:
conn = S3Connection(aws_access_key_id=credentials['access'],
aws_secret_acce... | [
"\n Connect to S3 with automatic handling for anonymous access.\n\n Parameters\n ----------\n credentials : dict\n AWS access key ('access') and secret access key ('secret')\n\n anon : boolean, optional, default = True\n Whether to make an anonymous connection if credentials fail to aut... |
Please provide a description of the function:def activate(self, path, isdirectory):
from .utils import connection_with_anon, connection_with_gs
parsed = BotoClient.parse_query(path)
scheme = parsed[0]
bucket_name = parsed[1]
key = parsed[2]
if scheme == 's3' o... | [
"\n Set up a boto connection.\n "
] |
Please provide a description of the function:def topng(images, path, prefix="image", overwrite=False, credentials=None):
value_shape = images.value_shape
if not len(value_shape) in [2, 3]:
raise ValueError("Only 2D or 3D images can be exported to png, "
"images are %d-dimen... | [
"\n Write out PNG files for 2d image data.\n\n See also\n --------\n thunder.data.images.topng\n "
] |
Please provide a description of the function:def tobinary(images, path, prefix="image", overwrite=False, credentials=None):
from thunder.writers import get_parallel_writer
def tobuffer(kv):
key, img = kv
fname = prefix + "-" + "%05d.bin" % int(key)
return fname, img.copy()
wri... | [
"\n Write out images as binary files.\n\n See also\n --------\n thunder.data.images.tobinary\n "
] |
Please provide a description of the function:def yearInfo2yearDay(yearInfo):
'''calculate the days in a lunar year from the lunar year's info
>>> yearInfo2yearDay(0) # no leap month, and every month has 29 days.
348
>>> yearInfo2yearDay(1) # 1 leap month, and every month has 29 days.
377
>>> ye... | [] |
Please provide a description of the function:def fromSolarDate(year, month, day):
'''
>>> LunarDate.fromSolarDate(1900, 1, 31)
LunarDate(1900, 1, 1, 0)
>>> LunarDate.fromSolarDate(2008, 10, 2)
LunarDate(2008, 9, 4, 0)
>>> LunarDate.fromSolarDate(1976, 10, 1)
Lunar... | [] |
Please provide a description of the function:def toSolarDate(self):
'''
>>> LunarDate(1900, 1, 1).toSolarDate()
datetime.date(1900, 1, 31)
>>> LunarDate(2008, 9, 4).toSolarDate()
datetime.date(2008, 10, 2)
>>> LunarDate(1976, 8, 8, 1).toSolarDate()
datetime.date(1... | [] |
Please provide a description of the function:def getContext(context):
context = aq_parent(aq_base(context))
if not context or IBrowserView.providedBy(context):
return getSite()
return context | [
"Return a safe context.\n In case a IBrowserView was passed (e.g. due to a 404 page), return the\n portal object.\n "
] |
Please provide a description of the function:def cleanupFilename(self, name):
context = self.context
id = ''
name = name.replace('\\', '/') # Fixup Windows filenames
name = name.split('/')[-1] # Throw away any path part.
for c in name:
if c.isalnum() or c ... | [
"Generate a unique id which doesn't match the system generated ids"
] |
Please provide a description of the function:def parse_data_slots(value):
value = unquote(value)
if '>' in value:
wrappers, children = value.split('>', 1)
else:
wrappers = value
children = ''
if '*' in children:
prepends, appends = children.split('*', 1)
else:
... | [
"Parse data-slots value into slots used to wrap node, prepend to node or\n append to node.\n\n >>> parse_data_slots('')\n ([], [], [])\n\n >>> parse_data_slots('foo bar')\n (['foo', 'bar'], [], [])\n\n >>> parse_data_slots('foo bar > foobar')\n (['foo', 'bar'], ['foobar'], [])... |
Please provide a description of the function:def cook_layout(layout, ajax):
# Fix XHTML layouts with CR[+LF] line endings
layout = re.sub('\r', '\n', re.sub('\r\n', '\n', layout))
# Parse layout
if isinstance(layout, six.text_type):
result = getHTMLSerializer([layout.encode('utf-8')], enco... | [
"Return main_template compatible layout"
] |
Please provide a description of the function:def existing(self):
catalog = api.portal.get_tool('portal_catalog')
results = []
layout_path = self._get_layout_path(
self.request.form.get('layout', '')
)
for brain in catalog(layout=layout_path):
resu... | [
" find existing content assigned to this layout"
] |
Please provide a description of the function:def latex2png(snippet, outfile):
pngimage = os.path.join(IMAGEDIR, outfile + '.png')
environment = os.environ
environment['openout_any'] = 'a'
environment['shell_escape_commands'] = \
"bibtex,bibtex8,kpsewhich,makeindex,mpost,repstopdf,gregorio"
... | [
"Compiles a LaTeX snippet to png"
] |
Please provide a description of the function:def gabc(elem, doc):
if type(elem) == Code and "gabc" in elem.classes:
if doc.format == "latex":
if elem.identifier == "":
label = ""
else:
label = '\\label{' + elem.identifier + '}'
return ... | [
"Handle gabc file inclusion and gabc code block."
] |
Please provide a description of the function:def load(input_stream=None):
if input_stream is None:
input_stream = io.open(sys.stdin.fileno()) if py2 else io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
# Load JSON and validate it
doc = json.load(input_stream, object_pairs_hook=from_json)... | [
"\n Load JSON-encoded document and return a :class:`.Doc` element.\n\n The JSON input will be read from :data:`sys.stdin` unless an alternative\n text stream is given (a file handle).\n\n To load from a file, you can do:\n\n >>> import panflute as pf\n >>> with open('some-document.json', e... |
Please provide a description of the function:def dump(doc, output_stream=None):
assert type(doc) == Doc, "panflute.dump needs input of type panflute.Doc"
if output_stream is None:
sys.stdout = codecs.getwriter("utf-8")(sys.stdout) if py2 else codecs.getwriter("utf-8")(sys.stdout.detach())
... | [
"\n Dump a :class:`.Doc` object into a JSON-encoded text string.\n\n The output will be sent to :data:`sys.stdout` unless an alternative\n text stream is given.\n\n To dump to :data:`sys.stdout` just do:\n\n >>> import panflute as pf\n >>> doc = pf.Doc(Para(Str('a'))) # Create sample docu... |
Please provide a description of the function:def run_filters(actions,
prepare=None, finalize=None,
input_stream=None, output_stream=None,
doc=None,
**kwargs):
load_and_dump = (doc is None)
if load_and_dump:
doc = load(input_stream=in... | [
"\n Receive a Pandoc document from the input stream (default is stdin),\n walk through it applying the functions in *actions* to each element,\n and write it back to the output stream (default is stdout).\n\n Notes:\n\n - It receives and writes the Pandoc documents as JSON--encoded strings;\n th... |
Please provide a description of the function:def load_reader_options():
options = os.environ['PANDOC_READER_OPTIONS']
options = json.loads(options, object_pairs_hook=OrderedDict)
return options | [
"\n Retrieve Pandoc Reader options from the environment\n "
] |
Please provide a description of the function:def gabc(key, value, fmt, meta): # pylint:disable=I0011,W0613
if key == 'Code':
[[ident, classes, kvs], contents] = value # pylint:disable=I0011,W0612
kvs = {key: value for key, value in kvs}
if "gabc" in classes:
... | [
"Handle gabc file inclusion and gabc code block."
] |
Please provide a description of the function:def yaml_filter(element, doc, tag=None, function=None, tags=None,
strict_yaml=False):
'''
Convenience function for parsing code blocks with YAML options
This function is useful to create a filter that applies to
code blocks that have specific... | [
"\n Replace code blocks of class 'foo' with # horizontal rules\n "
] |
Please provide a description of the function:def stringify(element, newlines=True):
def attach_str(e, doc, answer):
if hasattr(e, 'text'):
ans = e.text
elif isinstance(e, HorizontalSpaces):
ans = ' '
elif isinstance(e, VerticalSpaces) and newlines:
a... | [
"\n Return the raw text version of an elements (and its children element).\n\n Example:\n\n >>> from panflute import *\n >>> e1 = Emph(Str('Hello'), Space, Str('world!'))\n >>> e2 = Strong(Str('Bye!'))\n >>> para = Para(e1, Space, e2)\n >>> stringify(para)\n 'Hello wo... |
Please provide a description of the function:def _get_metadata(self, key='', default=None, builtin=True):
# Retrieve metadata
assert isinstance(key, str)
meta = self.metadata
# Retrieve specific key
if key:
for k in key.split('.'):
if isinstance(meta, MetaMap) and k in met... | [
"\n get_metadata([key, default, simple])\n\n Retrieve metadata with nested keys separated by dots.\n\n This is useful to avoid repeatedly checking if a dict exists, as\n the frontmatter might not have the keys that we expect.\n\n With ``builtin=True`` (the default), it will convert the results to\n ... |
Please provide a description of the function:def shell(args, wait=True, msg=None):
# Fix Windows error if passed a string
if isinstance(args, str):
args = shlex.split(args, posix=(os.name != "nt"))
if os.name == "nt":
args = [arg.replace('/', '\\') for arg in args]
if wait... | [
"\n Execute the external command and get its exitcode, stdout and stderr.\n "
] |
Please provide a description of the function:def run_pandoc(text='', args=None):
if args is None:
args = []
pandoc_path = which('pandoc')
if pandoc_path is None or not os.path.exists(pandoc_path):
raise OSError("Path to pandoc executable does not exists")
proc = Popen([pandoc_pat... | [
"\n Low level function that calls Pandoc with (optionally)\n some input text and/or arguments\n "
] |
Please provide a description of the function:def convert_text(text,
input_format='markdown',
output_format='panflute',
standalone=False,
extra_args=None):
if input_format == 'panflute':
# Problem:
# We need a Doc element, bu... | [
"\n Convert formatted text (usually markdown) by calling Pandoc internally\n\n The default output format ('panflute') will return a tree\n of Pandoc elements. When combined with 'standalone=True', the tree root\n will be a 'Doc' element.\n\n Example:\n\n >>> from panflute import *\n >>>... |
Please provide a description of the function:def _replace_keyword(self, keyword, replacement, count=0):
def replace_with_inline(e, doc):
if type(e) == Str and e.text == keyword:
doc.num_matches += 1
if not count or doc.num_matches <= count:
return replacement
... | [
"\n replace_keyword(keyword, replacement[, count])\n\n Walk through the element and its children\n and look for Str() objects that contains\n exactly the keyword. Then, replace it.\n\n Usually applied to an entire document (a :class:`.Doc` element)\n\n Note: If the replacement is a block, it canno... |
Please provide a description of the function:def get_option(options=None, local_tag=None, doc=None, doc_tag=None, default=None, error_on_none=True):
variable = None
# element level
if options is not None and local_tag is not None:
if local_tag in options and options[local_tag] is not None:... | [
" fetch an option variable, \n from either a local (element) level option/attribute tag, \n document level metadata tag,\n or a default\n\n :type options: ``dict``\n :type local_tag: ``str``\n :type doc: :class:`Doc`\n :type doc_tag: ``str``\n :type default: ``any``\n :type error_on... |
Please provide a description of the function:def _set_content(self, value, oktypes):
if value is None:
value = []
self._content = ListContainer(*value, oktypes=oktypes, parent=self) | [
"\n Similar to content.setter but when there are no existing oktypes\n "
] |
Please provide a description of the function:def container(self):
if self.parent is None:
return None
elif self.location is None:
return self.parent.content
else:
container = getattr(self.parent, self.location)
if isinstance(container, (Li... | [
"\n Rarely used attribute that returns the ``ListContainer`` or\n ``DictContainer`` that contains the element\n (or returns None if no such container exist)\n\n :rtype: ``ListContainer`` | ``DictContainer`` | ``None``\n "
] |
Please provide a description of the function:def offset(self, n):
idx = self.index
if idx is not None:
sibling = idx + n
container = self.container
if 0 <= sibling < len(container):
return container[sibling] | [
"\n Return a sibling element offset by n\n\n :rtype: :class:`Element` | ``None``\n "
] |
Please provide a description of the function:def ancestor(self, n):
if not isinstance(n, int) or n < 1:
raise TypeError('Ancestor needs to be positive, received', n)
if n == 1 or self.parent is None:
return self.parent
else:
return self.parent.ancest... | [
"\n Return the n-th ancestor.\n Note that ``elem.ancestor(1) == elem.parent``\n\n :rtype: :class:`Element` | ``None``\n "
] |
Please provide a description of the function:def doc(self):
guess = self
while guess is not None and guess.tag != 'Doc':
guess = guess.parent # If no parent, this will be None
return guess | [
"\n Return the root Doc element (if there is one)\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.