docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Gets an item's thumbnail and saves it to disk.
Args:
itemId (str): The item's ID.
fileName (str): The name of the output image.
fileName (str): The directory on disk where to save the thumbnail.
Returns:
dict: The result from :py:func:`arcrest.man... | def getThumbnailForItem(self, itemId, fileName, filePath):
admin = None
item = None
try:
admin = arcrest.manageorg.Administration(securityHandler=self._securityHandler)
item = admin.content.getItem(itemId = itemId)
return item.saveThumbnail(fileName=... | 470,745 |
Does the inverse of config parsing by taking parsed values and
converting them back to a string representing config file contents.
Args:
default_flow_style: defines serialization format (see PyYAML docs) | def serialize(self, items, default_flow_style=False):
# lazy-import so there's no dependency on yaml unless this class is used
yaml = self._load_yaml()
# it looks like ordering can't be preserved: http://pyyaml.org/ticket/29
items = dict(items)
return yaml.dump(items, ... | 470,876 |
Write the given settings to output files.
Args:
parsed_namespace: namespace object created within parse_known_args()
output_file_paths: any number of file paths to write the config to
exit_after: whether to exit the program after writing the config files | def write_config_file(self, parsed_namespace, output_file_paths, exit_after=False):
for output_file_path in output_file_paths:
# validate the output file path
try:
with open(output_file_path, "w") as output_file:
pass
except IOErro... | 470,880 |
Compute a commandline arg key to be used for a config file setting
that doesn't correspond to any defined configargparse arg (and so
doesn't have a user-specified commandline arg key).
Args:
key: The config file key that was being set. | def get_command_line_key_for_unknown_config_file_setting(self, key):
key_without_prefix_chars = key.strip(self.prefix_chars)
command_line_key = self.prefix_chars[0]*2 + key_without_prefix_chars
return command_line_key | 470,881 |
Converts the given settings back to a dictionary that can be passed
to ConfigFormatParser.serialize(..).
Args:
source_to_settings: the dictionary described in parse_known_args()
parsed_namespace: namespace object created within parse_known_args()
Returns:
an ... | def get_items_for_config_file_output(self, source_to_settings,
parsed_namespace):
config_file_items = OrderedDict()
for source, settings in source_to_settings.items():
if source == _COMMAND_LINE_SOURCE_KEY:
_, existing_command... | 470,882 |
Converts a config file or env var key + value to a list of
commandline args to append to the commandline.
Args:
action: The argparse Action object for this setting, or None if this
config file setting doesn't correspond to any defined
configargparse arg.
... | def convert_item_to_command_line_arg(self, action, key, value):
args = []
if action is None:
command_line_key = \
self.get_command_line_key_for_unknown_config_file_setting(key)
else:
command_line_key = action.option_strings[-1]
# handle ... | 470,883 |
Tries to parse config file path(s) from within command_line_args.
Returns a list of opened config files, including files specified on the
commandline as well as any default_config_files specified in the
constructor that are present on disk.
Args:
command_line_args: List of a... | def _open_config_files(self, command_line_args):
# open any default config files
config_files = [open(f) for files in map(glob.glob, map(os.path.expanduser, self._default_config_files))
for f in files]
# list actions with is_config_file_arg=True. Its possible th... | 470,885 |
Gets a parser.
Args:
segmenter (str): Segmenter to use.
options (:obj:`dict`, optional): Optional settings.
Returns:
Parser (:obj:`budou.parser.Parser`)
Raises:
ValueError: If unsupported segmenter is specified. | def get_parser(segmenter, **options):
if segmenter == 'nlapi':
return NLAPIParser(**options)
elif segmenter == 'mecab':
return MecabParser()
elif segmenter == 'tinysegmenter':
return TinysegmenterParser()
else:
raise ValueError('Segmenter {} is not supported.'.format(segmenter)) | 471,602 |
Parses attributes,
Args:
attributes (dict): Input attributes.
classname (:obj:`str`, optional): Class name of output SPAN tags.
Returns:
Parsed attributes. (dict) | def parse_attributes(attributes=None, classname=None):
if not attributes:
attributes = {}
attributes.setdefault('class', DEFAULT_CLASS_NAME)
# If `classname` is specified, it overwrites `class` property in `attributes`.
if classname:
attributes['class'] = classname
return attributes | 471,603 |
Removes unnecessary break lines and white spaces.
Args:
source (str): Input sentence.
Returns:
Preprocessed sentence. (str) | def preprocess(source):
doc = html5lib.parseFragment(source)
source = ET.tostring(doc, encoding='utf-8', method='text').decode('utf-8')
source = source.replace(u'\n', u'').strip()
source = re.sub(r'\s\s+', u' ', source)
return source | 471,604 |
Returns a chunk list from the given sentence.
Args:
source (str): Source string to segment.
language (:obj:`str`, optional): A language code.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`)
Raises:
ValueError: If :obj:`language` is given and it is not included in
... | def segment(self, source, language=None):
if language and not language in self.supported_languages:
raise ValueError(
'Language {} is not supported by NLAPI segmenter'.format(language))
chunks = ChunkList()
results = tinysegmenter.tokenize(source)
seek = 0
for word in results:
... | 471,606 |
Returns a chunk list from the given sentence.
Args:
source (str): Source string to segment.
language (:obj:`str`, optional): A language code.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`)
Raises:
ValueError: If :obj:`language` is given and it is not included in
... | def segment(self, source, language=None):
if language and not language in self.supported_languages:
raise ValueError(
'Language {} is not supported by MeCab segmenter'.format(language))
chunks = ChunkList()
seek = 0
source_str = source.encode('utf-8') if six.PY2 else source
res... | 471,612 |
Gets a Natural Language API parser by authenticating the API.
**This method is deprecated.** Please use :obj:`budou.get_parser` to obtain a
parser instead.
Args:
json_path (:obj:`str`, optional): The file path to the service account's
credentials.
Returns:
Parser. (:obj:`budou.parser.NLAPIPar... | def authenticate(json_path=None):
msg = ('budou.authentication() is deprecated. '
'Please use budou.get_parser() to obtain a parser instead.')
warnings.warn(msg, DeprecationWarning)
parser = get_parser('nlapi', credentials_path=json_path)
return parser | 471,615 |
Returns a chunk list from the given sentence.
Args:
source (str): Source string to segment.
language (:obj:`str`, optional): A language code.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`)
Raises:
ValueError: If :obj:`language` is given and it is not included in
... | def segment(self, source, language=None):
if language and not language in self.supported_languages:
raise ValueError(
'Language {} is not supported by NLAPI segmenter'.format(language))
chunks, language = self._get_source_chunks(source, language=language)
if self.use_entity:
enti... | 471,627 |
Returns a chunk list retrieved from Syntax Analysis results.
Args:
input_text (str): Text to annotate.
language (:obj:`str`, optional): Language of the text.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`) | def _get_source_chunks(self, input_text, language=None):
chunks = ChunkList()
seek = 0
result = self._get_annotations(input_text, language=language)
tokens = result['tokens']
language = result['language']
for i, token in enumerate(tokens):
word = token['text']['content']
begin_o... | 471,628 |
Groups chunks by entities retrieved from NL API Entity Analysis.
Args:
chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed.
entities (:obj:`list` of :obj:`dict`): List of entities.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`) | def _group_chunks_by_entities(self, chunks, entities):
for entity in entities:
chunks_to_concat = chunks.get_overlaps(
entity['beginOffset'], len(entity['content']))
if not chunks_to_concat:
continue
new_chunk_word = u''.join([chunk.word for chunk in chunks_to_concat])
... | 471,629 |
Returns the list of annotations retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
Results in a dictionary. :code:`tokens` contains the list of annotations
and :code:`language` contains the inferred language from the in... | def _get_annotations(self, text, language=''):
body = {
'document': {
'type': 'PLAIN_TEXT',
'content': text,
},
'features': {
'extract_syntax': True,
},
'encodingType': 'UTF32',
}
if language:
body['document']['language']... | 471,630 |
Returns the list of entities retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
List of entities. | def _get_entities(self, text, language=''):
body = {
'document': {
'type': 'PLAIN_TEXT',
'content': text,
},
'encodingType': 'UTF32',
}
if language:
body['document']['language'] = language
request = self.service.documents().analyzeEntities(body... | 471,631 |
Gets a value by a key.
Args:
key (str): Key to retrieve the value.
Returns: Retrieved value. | def get(self, key):
self._create_file_if_none_exists()
with open(self.filename, 'rb') as file_object:
cache_pickle = pickle.load(file_object)
val = cache_pickle.get(key, None)
return val | 471,632 |
Sets a value in a key.
Args:
key (str): Key for the value.
val: Value to set.
Returns:
Retrieved value. | def set(self, key, val):
self._create_file_if_none_exists()
with open(self.filename, 'r+b') as file_object:
cache_pickle = pickle.load(file_object)
cache_pickle[key] = val
file_object.seek(0)
pickle.dump(cache_pickle, file_object) | 471,633 |
Returns chunks overlapped with the given range.
Args:
offset (int): Begin offset of the range.
length (int): Length of the range.
Returns:
Overlapped chunks. (:obj:`budou.chunk.ChunkList`) | def get_overlaps(self, offset, length):
# In case entity's offset points to a space just before the entity.
if ''.join([chunk.word for chunk in self])[offset] == ' ':
offset += 1
index = 0
result = ChunkList()
for chunk in self:
if offset < index + len(chunk.word) and index < offset... | 471,643 |
Swaps old consecutive chunks with new chunk.
Args:
old_chunks (:obj:`budou.chunk.ChunkList`): List of consecutive Chunks to
be removed.
new_chunk (:obj:`budou.chunk.Chunk`): A Chunk to be inserted. | def swap(self, old_chunks, new_chunk):
indexes = [self.index(chunk) for chunk in old_chunks]
del self[indexes[0]:indexes[-1] + 1]
self.insert(indexes[0], new_chunk) | 471,644 |
Concatenates chunks based on each chunk's dependency.
Args:
direction (bool): Direction of concatenation process. True for forward. | def _concatenate_inner(self, direction):
tmp_bucket = []
source_chunks = self if direction else self[::-1]
target_chunks = ChunkList()
for chunk in source_chunks:
if (
# if the chunk has matched dependency, do concatenation.
chunk.dependency == direction or
# if ... | 471,646 |
Returns concatenated HTML code with SPAN tag.
Args:
attributes (dict): A map of name-value pairs for attributes of output
SPAN tags.
max_length (:obj:`int`, optional): Maximum length of span enclosed chunk.
Returns:
The organized HTML code. (str) | def html_serialize(self, attributes, max_length=None):
doc = ET.Element('span')
for chunk in self:
if (chunk.has_cjk() and
not (max_length and len(chunk.word) > max_length)):
ele = ET.Element('span')
ele.text = chunk.word
for key, val in attributes.items():
... | 471,648 |
Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.
Returns:
str: The encoding of the file. | def determine_encoding(path, default=None):
byte_order_marks = (
('utf-8-sig', (codecs.BOM_UTF8, )),
('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)),
('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)),
)
try:
with open(path, 'rb') as infile:
raw =... | 471,665 |
Makes sure that a file was opened with some valid encoding.
Arguments:
fileobj (file): The file-object.
mode (str, optional): The mode in which to re-open the file.
fallback_encoding (str, optional): The encoding in which to re-open
the file if it does not specify an encoding it... | def reopen_encoded(fileobj, mode='r', fallback_encoding=None):
encoding = determine_encoding(fileobj.name, fallback_encoding)
fileobj.close()
return open(fileobj.name, mode, encoding=encoding) | 471,666 |
Remove lines that are part of the Project Gutenberg header or footer.
Note: this function is a port of the C++ utility by Johannes Krugel. The
original version of the code can be found at:
http://www14.in.tum.de/spp1307/src/strip_headers.cpp
Args:
text (unicode): The body of the text to clean u... | def strip_headers(text):
lines = text.splitlines()
sep = str(os.linesep)
out = []
i = 0
footer_found = False
ignore_section = False
for line in lines:
reset = False
if i <= 600:
# Check if the header ends here
if any(line.startswith(token) for ... | 471,668 |
r"""Returns the size of input dimension and output dimension, given `shape`.
Args:
shape: A list of integers.
Returns:
fan_in: An int. The value of input dimension.
fan_out: An int. The value of output dimension. | def _get_fans(shape):
r
if len(shape) == 2:
fan_in = shape[0]
fan_out = shape[1]
elif len(shape) == 4 or len(shape) == 5:
# assuming convolution kernels (2D or 3D).
kernel_size = np.prod(shape[:2])
fan_in = shape[-2] * kernel_size
fan_out = shape[-1] * kernel_... | 472,084 |
r"""Decorates a function `func` as sg_producer_func.
Args:
func: A function to decorate. | def sg_producer_func(func):
r
@wraps(func)
def wrapper(**kwargs):
r
# default option
opt = tf.sg_opt(kwargs) + tf.sg_opt(dtypes=[tf.sg_floatx], capacity=32, num_threads=1)
# source queue list check
assert opt.source is not None, 'source is mandatory.'
if typ... | 472,095 |
r"""Applies layer normalization.
Normalizes the last dimension of the tensor `x`.
Args:
x: A `Tensor`.
gamma: A constant `Tensor`. Scale parameter. Default is 1.
beta: A constant `Tensor`. Offset parameter. Default is 0.
Returns:
A `Tensor` with the same shape as `x`. | def _ln_rnn(x, gamma, beta):
r
# calc layer mean, variance for final axis
mean, variance = tf.nn.moments(x, axes=[len(x.get_shape()) - 1], keep_dims=True)
# apply layer normalization
x = (x - mean) / tf.sqrt(variance + tf.sg_eps)
# apply parameter
return gamma * x + beta | 472,106 |
r"""Casts a tensor to a new type.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
dtype : The destination type.
name : If provided, it replaces current tensor's name
Returns:
A `Tensor` or `SparseTensor` ... | def sg_cast(tensor, opt):
r
assert opt.dtype is not None, 'dtype is mandatory.'
return tf.cast(tensor, opt.dtype, name=opt.name) | 472,116 |
r"""Casts a tensor to floatx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name : If provided, it replaces current tensor's name
Returns:
A `Tensor` or `SparseTensor` with same shape as `tensor`. | def sg_float(tensor, opt):
r
return tf.cast(tensor, tf.sg_floatx, name=opt.name) | 472,117 |
r"""Casts a tensor to intx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A `Tensor` or `SparseTensor` with same shape as `tensor`. | def sg_int(tensor, opt):
r
return tf.cast(tensor, tf.sg_intx, name=opt.name) | 472,118 |
r"""Inserts a new axis.
See tf.expand_dims() in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : Dimension to expand. Default is -1.
name: If provided, it replaces current tensor's name.
Returns:
A `Tensor`. | def sg_expand_dims(tensor, opt):
r
opt += tf.sg_opt(axis=-1)
return tf.expand_dims(tensor, opt.axis, name=opt.name) | 472,119 |
r"""Removes axis of size 1 from the shape of a tensor.
See `tf.squeeze()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer.
axis to remove. Default is -1.
name: If provided, it replaces cur... | def sg_squeeze(tensor, opt):
r
opt += tf.sg_opt(axis=[-1])
opt.axis = opt.axis if isinstance(opt.axis, (tuple, list)) else [opt.axis]
return tf.squeeze(tensor, opt.axis, name=opt.name) | 472,120 |
r"""Reshapes a tensor to `batch_size x -1`.
See `tf.reshape()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A 2-D tensor. | def sg_flatten(tensor, opt):
r
dim = np.prod(tensor.get_shape().as_list()[1:])
return tf.reshape(tensor, [-1, dim], name=opt.name) | 472,121 |
r"""Reshapes a tensor.
See `tf.reshape()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
shape: A tuple/list of integers. The destination shape.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`. | def sg_reshape(tensor, opt):
r
assert opt.shape is not None, 'shape is mandatory.'
return tf.reshape(tensor, opt.shape, name=opt.name) | 472,122 |
r"""Permutes the dimensions according to `opt.perm`.
See `tf.transpose()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
perm: A permutation of the dimensions of `tensor`. The target shape.
name: If provided, replace current tensor's name.
Returns... | def sg_transpose(tensor, opt):
r
assert opt.perm is not None, 'perm is mandatory'
return tf.transpose(tensor, opt.perm, name=opt.name) | 472,123 |
r"""Returns the indices of the maximum values along the specified axis.
See `tf.argmax()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis: Target axis. Default is the last one.
name: If provided, replace current tensor's name.
Returns:
... | def sg_argmax(tensor, opt):
r
opt += tf.sg_opt(axis=tensor.get_shape().ndims-1)
return tf.argmax(tensor, opt.axis, opt.name) | 472,124 |
r"""Returns the indices of the minimum values along the specified axis.
See `tf.argin()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis: Target axis. Default is the last one.
name: If provided, replace current tensor's name.
Returns:
A ... | def sg_argmin(tensor, opt):
r
opt += tf.sg_opt(axis=tensor.get_shape().ndims - 1)
return tf.argmin(tensor, opt.axis, opt.name) | 472,125 |
r"""Concatenates tensors along a axis.
See `tf.concat()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
target: A `Tensor`. Must have the same rank as `tensor`, and
all dimensions except `opt.dim` must be equal.
axis : Target axis. Default is... | def sg_concat(tensor, opt):
r
assert opt.target is not None, 'target is mandatory.'
opt += tf.sg_opt(axis=tensor.get_shape().ndims-1)
target = opt.target if isinstance(opt.target, (tuple, list)) else [opt.target]
return tf.concat([tensor] + target, opt.axis, name=opt.name) | 472,126 |
r"""Converts a tensor into a one-hot tensor.
See `tf.one_hot()` in tensorflow.
Args:
tensor: A `Tensor` ( automatically given by chain )
opt:
depth: The number of classes.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`. | def sg_one_hot(tensor, opt):
r
assert opt.depth is not None, 'depth is mandatory.'
return tf.one_hot(tensor, opt.depth, name=opt.name) | 472,127 |
r"""Converts a dense tensor into a sparse tensor.
See `tf.SparseTensor()` in tensorflow.
Args:
tensor: A `Tensor` with zero-padding (automatically given by chain).
opt:
name: If provided, replace current tensor's name.
Returns:
A `SparseTensor`. | def sg_to_sparse(tensor, opt):
r
indices = tf.where(tf.not_equal(tensor.sg_float(), 0.))
return tf.SparseTensor(indices=indices,
values=tf.gather_nd(tensor, indices) - 1, # for zero-based index
dense_shape=tf.shape(tensor).sg_cast(dtype=tf.int64)) | 472,128 |
r"""Log transform a dense tensor
See `tf.log()` in tensorflow.
Args:
tensor: A `Tensor` ( automatically given by chain )
opt:
name: If provided, replace current tensor's name.
Returns:
A `Tensor`. | def sg_log(tensor, opt):
r
return tf.log(tensor + tf.sg_eps, name=opt.name) | 472,129 |
r"""Computes the sum of elements across axis of a tensor.
See `tf.reduce_sum()` in tensorflow.
Args:
tensor: A `Tensor` with zero-padding (automatically given by chain).
opt:
axis: A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced d... | def sg_sum(tensor, opt):
r
return tf.reduce_sum(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | 472,130 |
r"""Computes the mean of elements across axis of a tensor.
See `tf.reduce_mean()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with ... | def sg_mean(tensor, opt):
r
return tf.reduce_mean(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | 472,131 |
r"""Computes the product of elements across axis of a tensor.
See `tf.reduce_prod()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with l... | def sg_prod(tensor, opt):
r
return tf.reduce_prod(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | 472,132 |
r"""Computes the minimum of elements across axis of a tensor.
See `tf.reduce_min()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with le... | def sg_min(tensor, opt):
r
return tf.reduce_min(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | 472,133 |
r"""Computes the maximum of elements across axis of a tensor.
See `tf.reduce_max()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with le... | def sg_max(tensor, opt):
r
return tf.reduce_max(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | 472,134 |
r"""Computes the "logical and" of elements across axis of a tensor.
See `tf.reduce_all()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensio... | def sg_all(tensor, opt):
r
return tf.reduce_all(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | 472,135 |
r"""Computes the "logical or" of elements across axis of a tensor.
See `tf.reduce_any()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions wi... | def sg_any(tensor, opt):
r
return tf.reduce_any(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | 472,136 |
r"""Looks up the `tensor`, which is the embedding matrix.
Args:
tensor: A tensor ( automatically given by chain )
opt:
emb: A 2-D `Tensor`. An embedding matrix.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`. | def sg_lookup(tensor, opt):
r
assert opt.emb is not None, 'emb is mandatory.'
return tf.nn.embedding_lookup(opt.emb, tensor, name=opt.name) | 472,139 |
r""" Periodic shuffle transformation for SubPixel CNN.
(see [Shi et al. 2016](http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Shi_Real-Time_Single_Image_CVPR_2016_paper.pdf)
Args:
tensor: A tensor (automatically given by chain).
opt:
factor: factor to multiply s... | def sg_periodic_shuffle(tensor, opt):
r
# default factor
opt += tf.sg_opt(factor=2)
# get current shape
batch, row, col, channel = tensor.get_shape().as_list()
# get target channel num
channel_target = channel // (opt.factor * opt.factor)
channel_factor = channel // channel_target
... | 472,141 |
r"""Returns accuracy of predictions.
Args:
tensor: A `Tensor`. Probability distributions or unscaled prediction scores.
opt:
target: A 'Tensor`. Labels.
Returns:
A `Tensor` of the same shape as `tensor`. Each value will be 1 if correct else 0.
For example,
... | def sg_accuracy(tensor, opt):
r
assert opt.target is not None, 'target is mandatory.'
opt += tf.sg_opt(k=1)
# # calc accuracy
out = tf.identity(tf.equal(tensor.sg_argmax(), tf.cast(opt.target, tf.int64)).sg_float(), name='acc')
# out = tf.identity(tf.nn.in_top_k(tensor, opt.target, opt.k).sg_fl... | 472,145 |
r""" Decorates a function `func` so that it can be a sugar function.
Sugar function can be used in a chainable manner.
Args:
func: function to decorate
Returns:
A sugar function. | def sg_sugar_func(func):
r
@wraps(func)
def wrapper(tensor, **kwargs):
# call sugar function
out = func(tensor, tf.sg_opt(kwargs))
# save node info for reuse
out._sugar = tf.sg_opt(func=func, arg=tf.sg_opt(kwargs)+sg_get_context(), prev=tensor)
# inject reuse function... | 472,149 |
r"""Decorates a function `func` as a sg_layer function.
Args:
func: function to decorate | def sg_layer_func(func):
r
@wraps(func)
def wrapper(tensor, **kwargs):
r
from . import sg_initializer as init
from . import sg_activation
# kwargs parsing
opt = tf.sg_opt(kwargs) + sg_get_context()
# set default argument
try:
shape = ten... | 472,150 |
r"""Decorates function as sg_rnn_layer functions.
Args:
func: function to decorate | def sg_rnn_layer_func(func):
r
@wraps(func)
def wrapper(tensor, **kwargs):
r
# kwargs parsing
opt = tf.sg_opt(kwargs) + sg_get_context()
# set default argument
try:
shape = tensor.get_shape().as_list()
# dropout off
opt += tf.sg_o... | 472,151 |
r""" Reconstruct computational graph of `tensor` so all the parameters
can be reused and replace its input tensor with `opt.input`.
Args:
tensor: A `Tensor` (automatically given by chaining).
**opt:
input: A `Tensor` that will replace the original input tensor.
Returns:
Reconstru... | def sg_reuse(tensor, **opt):
r
opt = tf.sg_opt(opt)
assert hasattr(tensor, '_sugar'), 'cannot reuse this node.'
assert opt.input is not None, 'input is mandatory.'
# get all nodes in this graph
nodes, prev = [tensor], tensor._sugar.prev
while prev is not None:
nodes = [prev] + nodes... | 472,152 |
r"""Creates a placeholder.
Args:
shape: A tuple/list of integers. If an integers is given, it will turn to a list.
dtype: A data type. Default is float32.
name: A name for the placeholder.
Returns:
A wrapped placeholder `Tensor`. | def sg_input(shape=None, dtype=sg_floatx, name=None):
r
if shape is None:
return tf.placeholder(dtype, shape=None, name=name)
else:
if not isinstance(shape, (list, tuple)):
shape = [shape]
return tf.placeholder(dtype, shape=[None] + list(shape), name=name) | 472,153 |
r"""Converts all functions in the given Python module to sugar functions
so that they can be used in a chainable manner.
Args:
path: A string. Path to the Python module
mod_name: A string. The name of the Python module to inject.
Returns:
None | def sg_inject(path, mod_name):
r
# import module
import sys
if path not in list(sys.path):
sys.path.append(path)
globals()[mod_name] = importlib.import_module(mod_name)
# find functions
for func_name in dir(globals()[mod_name]):
if isinstance(globals()[mod_name].__dict__.get(... | 472,154 |
r"""Context helper for queue routines.
Args:
sess: A session to open queues. If not specified, a new session is created.
Returns:
None | def sg_queue_context(sess=None):
r
# default session
sess = tf.get_default_session() if sess is None else sess
# thread coordinator
coord = tf.train.Coordinator()
try:
# start queue thread
threads = tf.train.start_queue_runners(sess, coord)
yield
finally:
# ... | 472,155 |
r"""Decorates function as multiple gpu support towers.
Args:
func: function to decorate | def sg_parallel(func):
r
@wraps(func)
def wrapper(**kwargs):
r
# parse option
opt = tf.sg_opt(kwargs)
# loop for all available GPUs
res = []
for i in range(sg_gpus()):
# specify device
with tf.device('/gpu:%d' % i):
# g... | 472,156 |
r"""Defines command line options
Args:
**kwargs:
key: A name for the option.
value : Default value or a tuple of (default value, description).
Returns:
None
For example,
```
# Either of the following two lines will define `--n_epoch` command line argument and set its ... | def sg_arg_def(**kwargs):
r
for k, v in kwargs.items():
if type(v) is tuple or type(v) is list:
v, c = v[0], v[1]
else:
c = k
if type(v) is str:
tf.app.flags.DEFINE_string(k, v, c)
elif type(v) is int:
tf.app.flags.DEFINE_integer(k,... | 472,158 |
r"""Register `tensor` to summary report as `loss`
Args:
tensor: A `Tensor` to log as loss
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
None | def sg_summary_loss(tensor, prefix='losses', name=None):
r
# defaults
prefix = '' if prefix is None else prefix + '/'
# summary name
name = prefix + _pretty_name(tensor) if name is None else prefix + name
# summary statistics
_scalar(name, tf.reduce_mean(tensor))
_histogram(name + '-h', ... | 472,159 |
r"""Register `tensor` to summary report as `gradient`
Args:
tensor: A `Tensor` to log as gradient
gradient: A 0-D `Tensor`. A gradient to log
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
... | def sg_summary_gradient(tensor, gradient, prefix=None, name=None):
r
# defaults
prefix = '' if prefix is None else prefix + '/'
# summary name
name = prefix + _pretty_name(tensor) if name is None else prefix + name
# summary statistics
# noinspection PyBroadException
_scalar(name + '/gra... | 472,160 |
r"""Register `tensor` to summary report as `activation`
Args:
tensor: A `Tensor` to log as activation
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
None | def sg_summary_activation(tensor, prefix=None, name=None):
r
# defaults
prefix = '' if prefix is None else prefix + '/'
# summary name
name = prefix + _pretty_name(tensor) if name is None else prefix + name
# summary statistics
_scalar(name + '/ratio',
tf.reduce_mean(tf.cast(tf.g... | 472,161 |
r"""Register `tensor` to summary report as `parameters`
Args:
tensor: A `Tensor` to log as parameters
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
None | def sg_summary_param(tensor, prefix=None, name=None):
r
# defaults
prefix = '' if prefix is None else prefix + '/'
# summary name
name = prefix + _pretty_name(tensor) if name is None else prefix + name
# summary statistics
_scalar(name + '/abs', tf.reduce_mean(tf.abs(tensor)))
_histogram... | 472,162 |
r"""Register `tensor` to summary report as `image`
Args:
tensor: A tensor to log as image
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
None | def sg_summary_image(tensor, prefix=None, name=None):
r
# defaults
prefix = '' if prefix is None else prefix + '/'
# summary name
name = prefix + _pretty_name(tensor) if name is None else prefix + name
# summary statistics
if not tf.get_variable_scope().reuse:
tf.summary.image(name +... | 472,163 |
r"""Register `tensor` to summary report as audio
Args:
tensor: A `Tensor` to log as audio
sample_rate : An int. Sample rate to report. Default is 16000.
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
R... | def sg_summary_audio(tensor, sample_rate=16000, prefix=None, name=None):
r
# defaults
prefix = '' if prefix is None else prefix + '/'
# summary name
name = prefix + _pretty_name(tensor) if name is None else prefix + name
# summary statistics
if not tf.get_variable_scope().reuse:
tf.s... | 472,164 |
r""""See [Xu, et al. 2015](https://arxiv.org/pdf/1505.00853v2.pdf)
Args:
x: A tensor
opt:
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type and shape as `x`. | def sg_leaky_relu(x, opt):
r
return tf.where(tf.greater(x, 0), x, 0.01 * x, name=opt.name) | 472,178 |
r""" Initializes session variables.
Args:
sess: Session to initialize. | def sg_init(sess):
r
# initialize variables
sess.run(tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())) | 472,184 |
r""" Restores previously saved variables.
Args:
sess: A `Session` to use to restore the parameters.
save_path: Path where parameters were previously saved.
category: A `String` to filter variables starts with given category.
Returns: | def sg_restore(sess, save_path, category=''):
r
# to list
if not isinstance(category, (tuple, list)):
category = [category]
# make variable list to load
var_list = {}
for cat in category:
for t in tf.global_variables():
if t.name.startswith(cat):
var_... | 472,186 |
r""" Decorates a function `func` as sg_train_func.
Args:
func: A function to decorate | def sg_train_func(func):
r
@wraps(func)
def wrapper(**kwargs):
r
opt = tf.sg_opt(kwargs)
# default training options
opt += tf.sg_opt(lr=0.001,
save_dir='asset/train',
max_ep=1000, ep_size=100000,
save... | 472,188 |
r""" Get regularizer losss
Args:
scale: A scalar. A weight applied to regularizer loss | def sg_regularizer_loss(scale=1.0):
r
return scale * tf.reduce_mean(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) | 472,189 |
r"""Returns batch queues from the whole data.
Args:
data_list: A list of ndarrays. Every array must have the same size in the first dimension.
batch_size: An integer.
name: A name for the operations (optional).
Returns:
A list of tensors of `batch_size`. | def _data_to_tensor(data_list, batch_size, name=None):
r
# convert to constant tensor
const_list = [tf.constant(data) for data in data_list]
# create queue from constant tensor
queue_list = tf.train.slice_input_producer(const_list, capacity=batch_size*128, name=name)
# create batch queue
r... | 472,196 |
Example process for testing.
Inputs:
-------
file1
raster file
Parameters:
-----------
Output:
-------
np.ndarray | def execute(mp):
# Reading and writing data works like this:
with mp.open("file1", resampling="bilinear") as raster_file:
if raster_file.is_empty():
return "empty"
# This assures a transparent tile instead of a pink error tile
# is returned when using mapchete se... | 472,299 |
Read, stretch and return raster data.
Inputs:
-------
raster
raster file
Parameters:
-----------
resampling : str
rasterio.Resampling method
scale_method : str
- dtype_scale: use dtype minimum and maximum values
- minmax_scale: use dataset bands minimum and ... | def execute(
mp,
resampling="nearest",
scale_method=None,
scales_minmax=None
):
with mp.open("raster", resampling=resampling) as raster_file:
# exit if input tile is empty
if raster_file.is_empty():
return "empty"
# actually read data and iterate through ba... | 472,354 |
Read a window of an input vector dataset.
Also clips geometry.
Parameters:
-----------
input_file : string
path to vector file
tile : ``Tile``
tile extent to read data from
validity_check : bool
checks if reprojected geometry is valid and throws ``RuntimeError`` if
... | def read_vector_window(input_files, tile, validity_check=True):
if not isinstance(input_files, list):
input_files = [input_files]
return [
feature
for feature in chain.from_iterable([
_read_vector_window(path, tile, validity_check=validity_check)
for path in ... | 472,409 |
Yield single part geometries if geom is multipart, otherwise yield geom.
Parameters:
-----------
geom : shapely geometry
Returns:
--------
shapely single part geometries | def multipart_to_singleparts(geom):
if isinstance(geom, base.BaseGeometry):
if hasattr(geom, "geoms"):
for subgeom in geom:
yield subgeom
else:
yield geom | 472,414 |
Check if file exists either remote or local.
Parameters:
-----------
path : path to file
Returns:
--------
exists : bool | def path_exists(path):
if path.startswith(("http://", "https://")):
try:
urlopen(path).info()
return True
except HTTPError as e:
if e.code == 404:
return False
else:
raise
elif path.startswith("s3://"):
... | 472,425 |
Return absolute path if path is local.
Parameters:
-----------
path : path to file
base_dir : base directory used for absolute path
Returns:
--------
absolute path | def absolute_path(path=None, base_dir=None):
if path_is_remote(path):
return path
else:
if os.path.isabs(path):
return path
else:
if base_dir is None or not os.path.isabs(base_dir):
raise TypeError("base_dir must be an absolute path.")
... | 472,426 |
Return relative path if path is local.
Parameters:
-----------
path : path to file
base_dir : directory where path sould be relative to
Returns:
--------
relative path | def relative_path(path=None, base_dir=None):
if path_is_remote(path) or not os.path.isabs(path):
return path
else:
return os.path.relpath(path, base_dir) | 472,427 |
Lists all of the files in the given base directory, optionally only
including whose extension(s) match the ext string/list of strings.
This is non-recursive.
Args:
base_path: The directory in which to search.
ext: The extension(s) to match in the given directory. If None, this
m... | def list_files(base_path, ext=None):
if not os.path.isdir(base_path):
raise ValueError("Path does not exist: %s" % base_path)
files = []
for entry in os.listdir(base_path):
if os.path.isfile(os.path.join(base_path, entry)):
_, entry_ext = os.path.splitext(entry)
... | 472,435 |
Strips whitespace from the string values of the given dictionary (recursively).
Args:
d: A dictionary object.
Returns:
A new dictionary object, whose string values' whitespace has been stripped out. | def dict_strip(d):
_d = deepcopy(d)
for k, v in iteritems(d):
if isinstance(v, str):
_d[k] = v.strip()
elif isinstance(v, dict):
_d[k] = dict_strip(v)
return _d | 472,450 |
Recursively strips the plain text out of the given XML etree element up to the desired depth.
Args:
el: The etree element to scan.
max_depth: The depth to which to recursively strip text (default: 0).
cur_depth: The current recursive depth to which we've scanned so far.
Returns:
... | def strip_el_text(el, max_depth=0, cur_depth=0):
# text in front of any child elements
el_text = strip_str(el.text if el.text is not None else "")
if cur_depth < max_depth:
for child in el:
el_text += " "+strip_el_text(child, max_depth=max_depth, cur_depth=cur_depth+1)
else:
... | 472,451 |
Runs through the array and returns the elements that contain
more than one duplicate
Args:
array: The array to check for duplicates.
Returns:
Array of the elements that are duplicates. Returns empty list if
there are no duplicates. | def find_duplicates_in_array(array):
duplicates = []
non_duplicates = []
if len(array) != len(set(array)):
for item in array:
if item not in non_duplicates:
non_duplicates.append(item)
elif item in non_duplicates and item not in duplicates:
... | 472,453 |
Constructor.
Args:
message: An optional message to override the predefined error message.
orig_exc: The original exception from which this error was generated.
context: An optional ErrorContext instance to provide additional information during
error rendering... | def __init__(self, message=None, orig_exc=None, context=None):
self.orig_exc = orig_exc
if message is not None:
self.error_message = message
elif orig_exc is not None:
# derive the error message from the original exception
self.error_message = "%s" % ... | 472,457 |
Constructor.
Args:
data_path: The full path to where the database files can be found.
models: Loaded model/field data.
encoding: The encoding to load files as ('utf-8', etc). If 'None', will
default to the system-preferred default encoding.
... | def __init__(self, data_path, models, encoding=None, markdown_config=None,
error_context=None):
self.encoding = encoding
self.tables = dict()
self.data_path = data_path
self.models = models
self.markdown_config = markdown_config
self.error_context = e... | 472,488 |
Creates the table for the given model.
Args:
model: A StatikModel instance.
Returns:
A SQLAlchemy model instance for the table corresponding to this
particular model. | def create_model_table(self, model):
try:
return db_model_factory(self.Base, model, self.models)
except Exception as exc:
raise ModelError(
model.name,
message="failed to create in-memory table.",
orig_exc=exc,
... | 472,493 |
Constructor.
Args:
path: The full filesystem path to the base of the project. | def __init__(self, path, **kwargs):
self.error_context = kwargs.pop('error_context', None)
self.error_context = self.error_context or StatikErrorContext()
if 'config' in kwargs and isinstance(kwargs['config'], dict):
logger.debug("Loading project configuration from construc... | 472,503 |
Recursively dumps the result of our processing into files within the
given output path.
Args:
result: The in-memory result of our processing.
output_path: Full path to the folder into which to dump the files.
Returns:
The number of files generated (integer). | def dump_in_memory_result(self, result, output_path):
file_count = 0
logger.debug("Dumping in-memory processing results to output folder: %s", output_path)
for k, v in iteritems(result):
cur_output_path = os.path.join(output_path, k)
if isinstance(v, dict):
... | 472,510 |
Constructor.
Args:
project: The project to which this template engine relates. | def __init__(self, project, error_context=None):
self.project = project
self.error_context = error_context or StatikErrorContext()
self.supported_providers = project.config.template_providers
if project.safe_mode:
self.supported_providers = [provider for provider in ... | 472,544 |
Attempts to load the relevant template from our templating system/environment.
Args:
name: The name of the template to load.
Return:
On success, a StatikTemplate object that can be used to render content. | def load_template(self, name):
# hopefully speeds up loading of templates a little, especially when loaded multiple times
if name in self.cached_templates:
logger.debug("Using cached template: %s", name)
return self.cached_templates[name]
logger.debug("Attemptin... | 472,547 |
Creates a template from the given string based on the specified provider or the provider with
highest precedence.
Args:
s: The string to convert to a template.
provider_name: The name of the provider to use to create the template. | def create_template(self, s, provider_name=None):
if provider_name is None:
provider_name = self.supported_providers[0]
return template_exception_handler(
lambda: self.get_provider(provider_name).create_template(s),
self.error_context
) | 472,548 |
Constructor.
Args:
engine: The StatikTemplateEngine to which this template provider belongs. | def __init__(self, engine):
super(StatikJinjaTemplateProvider, self).__init__(engine)
project = engine.project
logger.debug("Instantiating Jinja2 template provider")
# now load our template tags
self.templatetags_path = os.path.join(project.path, project.TEMPLATETAGS_D... | 472,552 |
Constructor.
Args:
provider: The provider that created this template.
template: The Jinja2 template to wrap. | def __init__(self, provider, template, **kwargs):
super(StatikJinjaTemplate, self).__init__(template.filename, **kwargs)
self.provider = provider
self.template = template | 472,555 |
Helper function to build a field from the given field name and
type.
Args:
model_name: The name of the model for which we're building this field.
field_name: The name of the field to build.
field_type: A string indicator as to which field type must be built.
all_models: A list c... | def construct_field(model_name, field_name, field_type, all_models, **kwargs):
field_type_parts = field_type.split('->')
_field_type = field_type_parts[0].strip().split('[]')[0].strip()
back_populates = field_type_parts[1].strip() if len(field_type_parts) > 1 else None
error_context = kwargs.pop('e... | 472,563 |
Instantiates a Paginator instance for database queries.
Args:
db_query: The SQLAlchemy database query to paginate.
items_per_page: The desired number of items per page.
offset: The number of items to skip when paginating.
start_page: The number of the first page when reporting on pa... | def paginate(db_query, items_per_page, offset=0, start_page=1):
return Paginator(db_query, items_per_page, offset=offset, start_page=start_page) | 472,569 |
Constructor.
Args:
paginator: The parent paginator object.
number: The number of this page (starting from 1).
items: A list of items to belong to this page. | def __init__(self, paginator, number, items):
self.paginator = paginator
self.number = number
self.number0 = number - 1 # for zero-indexed pagination
self.items = items
self.count = len(items)
# copy the paginator variables
self.total_items = paginator... | 472,571 |
Constructor.
Args:
db_query: The database query to execute. | def __init__(self, db_query, items_per_page, offset=0, start_page=1):
self.db_query = db_query
self.items_per_page = items_per_page
self.offset = offset
self.start_page = start_page
self.total_items = db_query.count() - offset
self.total_pages = int(math.ceil(fl... | 472,574 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.