id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
228,900
sony/nnabla
python/src/nnabla/monitor.py
plot_series
def plot_series(filename, plot_kwargs=None): '''Plot series data from MonitorSeries output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is required. ''' import matplotlib.pyplot as plt if plot_kwargs is None: plot_kwargs = {} data = np.genfromtxt(filename, dtype='i8,f4', names=['k', 'v']) index = data['k'] values = data['v'] plt.plot(index, values, **plot_kwargs)
python
def plot_series(filename, plot_kwargs=None): '''Plot series data from MonitorSeries output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is required. ''' import matplotlib.pyplot as plt if plot_kwargs is None: plot_kwargs = {} data = np.genfromtxt(filename, dtype='i8,f4', names=['k', 'v']) index = data['k'] values = data['v'] plt.plot(index, values, **plot_kwargs)
[ "def", "plot_series", "(", "filename", ",", "plot_kwargs", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "plot_kwargs", "is", "None", ":", "plot_kwargs", "=", "{", "}", "data", "=", "np", ".", "genfromtxt", "(", "filename", ",", "dtype", "=", "'i8,f4'", ",", "names", "=", "[", "'k'", ",", "'v'", "]", ")", "index", "=", "data", "[", "'k'", "]", "values", "=", "data", "[", "'v'", "]", "plt", ".", "plot", "(", "index", ",", "values", ",", "*", "*", "plot_kwargs", ")" ]
Plot series data from MonitorSeries output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is required.
[ "Plot", "series", "data", "from", "MonitorSeries", "output", "text", "file", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/monitor.py#L378-L398
228,901
sony/nnabla
python/src/nnabla/monitor.py
plot_time_elapsed
def plot_time_elapsed(filename, elapsed=False, unit='s', plot_kwargs=None): '''Plot series data from MonitorTimeElapsed output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. elapsed (bool): If ``True``, it plots the total elapsed time. unit (str): Time unit chosen from ``'s'``, ``'m'``, ``'h'``, or ``'d'``. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is required. ''' import matplotlib.pyplot as plt if plot_kwargs is None: plot_kwargs = {} data_column = 3 if elapsed else 1 data = np.genfromtxt(filename, dtype='i8,f4', usecols=(0, data_column), names=['k', 'v']) index = data['k'] values = data['v'] if unit == 's': pass elif unit == 'm': values /= 60 elif unit == 'h': values /= 3600 elif unit == 'd': values /= 3600 * 24 else: raise ValueError('The argument `unit` must be chosen from {s|m|h|d}.') plt.plot(index, values, **plot_kwargs)
python
def plot_time_elapsed(filename, elapsed=False, unit='s', plot_kwargs=None): '''Plot series data from MonitorTimeElapsed output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. elapsed (bool): If ``True``, it plots the total elapsed time. unit (str): Time unit chosen from ``'s'``, ``'m'``, ``'h'``, or ``'d'``. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is required. ''' import matplotlib.pyplot as plt if plot_kwargs is None: plot_kwargs = {} data_column = 3 if elapsed else 1 data = np.genfromtxt(filename, dtype='i8,f4', usecols=(0, data_column), names=['k', 'v']) index = data['k'] values = data['v'] if unit == 's': pass elif unit == 'm': values /= 60 elif unit == 'h': values /= 3600 elif unit == 'd': values /= 3600 * 24 else: raise ValueError('The argument `unit` must be chosen from {s|m|h|d}.') plt.plot(index, values, **plot_kwargs)
[ "def", "plot_time_elapsed", "(", "filename", ",", "elapsed", "=", "False", ",", "unit", "=", "'s'", ",", "plot_kwargs", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "plot_kwargs", "is", "None", ":", "plot_kwargs", "=", "{", "}", "data_column", "=", "3", "if", "elapsed", "else", "1", "data", "=", "np", ".", "genfromtxt", "(", "filename", ",", "dtype", "=", "'i8,f4'", ",", "usecols", "=", "(", "0", ",", "data_column", ")", ",", "names", "=", "[", "'k'", ",", "'v'", "]", ")", "index", "=", "data", "[", "'k'", "]", "values", "=", "data", "[", "'v'", "]", "if", "unit", "==", "'s'", ":", "pass", "elif", "unit", "==", "'m'", ":", "values", "/=", "60", "elif", "unit", "==", "'h'", ":", "values", "/=", "3600", "elif", "unit", "==", "'d'", ":", "values", "/=", "3600", "*", "24", "else", ":", "raise", "ValueError", "(", "'The argument `unit` must be chosen from {s|m|h|d}.'", ")", "plt", ".", "plot", "(", "index", ",", "values", ",", "*", "*", "plot_kwargs", ")" ]
Plot series data from MonitorTimeElapsed output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. elapsed (bool): If ``True``, it plots the total elapsed time. unit (str): Time unit chosen from ``'s'``, ``'m'``, ``'h'``, or ``'d'``. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is required.
[ "Plot", "series", "data", "from", "MonitorTimeElapsed", "output", "text", "file", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/monitor.py#L401-L436
228,902
sony/nnabla
python/src/nnabla/monitor.py
MonitorSeries.add
def add(self, index, value): """Add a value to the series. Args: index (int): Index. value (float): Value. """ self.buf.append(value) if (index - self.flush_at) < self.interval: return value = np.mean(self.buf) if self.verbose: logger.info("iter={} {{{}}}={}".format(index, self.name, value)) if self.fd is not None: print("{} {:g}".format(index, value), file=self.fd) self.flush_at = index self.buf = []
python
def add(self, index, value): """Add a value to the series. Args: index (int): Index. value (float): Value. """ self.buf.append(value) if (index - self.flush_at) < self.interval: return value = np.mean(self.buf) if self.verbose: logger.info("iter={} {{{}}}={}".format(index, self.name, value)) if self.fd is not None: print("{} {:g}".format(index, value), file=self.fd) self.flush_at = index self.buf = []
[ "def", "add", "(", "self", ",", "index", ",", "value", ")", ":", "self", ".", "buf", ".", "append", "(", "value", ")", "if", "(", "index", "-", "self", ".", "flush_at", ")", "<", "self", ".", "interval", ":", "return", "value", "=", "np", ".", "mean", "(", "self", ".", "buf", ")", "if", "self", ".", "verbose", ":", "logger", ".", "info", "(", "\"iter={} {{{}}}={}\"", ".", "format", "(", "index", ",", "self", ".", "name", ",", "value", ")", ")", "if", "self", ".", "fd", "is", "not", "None", ":", "print", "(", "\"{} {:g}\"", ".", "format", "(", "index", ",", "value", ")", ",", "file", "=", "self", ".", "fd", ")", "self", ".", "flush_at", "=", "index", "self", ".", "buf", "=", "[", "]" ]
Add a value to the series. Args: index (int): Index. value (float): Value.
[ "Add", "a", "value", "to", "the", "series", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/monitor.py#L83-L100
228,903
sony/nnabla
python/src/nnabla/monitor.py
MonitorTimeElapsed.add
def add(self, index): """Calculate time elapsed from the point previously called this method or this object is created to this is called. Args: index (int): Index to be displayed, and be used to take intervals. """ if (index - self.flush_at) < self.interval: return now = time.time() elapsed = now - self.lap elapsed_total = now - self.start it = index - self.flush_at self.lap = now if self.verbose: logger.info("iter={} {{{}}}={}[sec/{}iter] {}[sec]".format( index, self.name, elapsed, it, elapsed_total)) if self.fd is not None: print("{} {} {} {}".format(index, elapsed, it, elapsed_total), file=self.fd) self.flush_at = index
python
def add(self, index): """Calculate time elapsed from the point previously called this method or this object is created to this is called. Args: index (int): Index to be displayed, and be used to take intervals. """ if (index - self.flush_at) < self.interval: return now = time.time() elapsed = now - self.lap elapsed_total = now - self.start it = index - self.flush_at self.lap = now if self.verbose: logger.info("iter={} {{{}}}={}[sec/{}iter] {}[sec]".format( index, self.name, elapsed, it, elapsed_total)) if self.fd is not None: print("{} {} {} {}".format(index, elapsed, it, elapsed_total), file=self.fd) self.flush_at = index
[ "def", "add", "(", "self", ",", "index", ")", ":", "if", "(", "index", "-", "self", ".", "flush_at", ")", "<", "self", ".", "interval", ":", "return", "now", "=", "time", ".", "time", "(", ")", "elapsed", "=", "now", "-", "self", ".", "lap", "elapsed_total", "=", "now", "-", "self", ".", "start", "it", "=", "index", "-", "self", ".", "flush_at", "self", ".", "lap", "=", "now", "if", "self", ".", "verbose", ":", "logger", ".", "info", "(", "\"iter={} {{{}}}={}[sec/{}iter] {}[sec]\"", ".", "format", "(", "index", ",", "self", ".", "name", ",", "elapsed", ",", "it", ",", "elapsed_total", ")", ")", "if", "self", ".", "fd", "is", "not", "None", ":", "print", "(", "\"{} {} {} {}\"", ".", "format", "(", "index", ",", "elapsed", ",", "it", ",", "elapsed_total", ")", ",", "file", "=", "self", ".", "fd", ")", "self", ".", "flush_at", "=", "index" ]
Calculate time elapsed from the point previously called this method or this object is created to this is called. Args: index (int): Index to be displayed, and be used to take intervals.
[ "Calculate", "time", "elapsed", "from", "the", "point", "previously", "called", "this", "method", "or", "this", "object", "is", "created", "to", "this", "is", "called", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/monitor.py#L145-L166
228,904
sony/nnabla
python/src/nnabla/monitor.py
MonitorImage.add
def add(self, index, var): """Add a minibatch of images to the monitor. Args: index (int): Index. var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`): A minibatch of images with ``(N, ..., C, H, W)`` format. If C == 2, blue channel is appended with ones. If C > 3, the array will be sliced to remove C > 3 sub-array. """ import nnabla as nn from nnabla.utils.image_utils import imsave if index != 0 and (index + 1) % self.interval != 0: return if isinstance(var, nn.Variable): data = var.d.copy() elif isinstance(var, nn.NdArray): data = var.data.copy() else: assert isinstance(var, np.ndarray) data = var.copy() assert data.ndim > 2 channels = data.shape[-3] data = data.reshape(-1, *data.shape[-3:]) data = data[:min(data.shape[0], self.num_images)] data = self.normalize_method(data) if channels > 3: data = data[:, :3] elif channels == 2: data = np.concatenate( [data, np.ones((data.shape[0], 1) + data.shape[-2:])], axis=1) path_tmpl = os.path.join(self.save_dir, '{:06d}-{}.png') for j in range(min(self.num_images, data.shape[0])): img = data[j].transpose(1, 2, 0) if img.shape[-1] == 1: img = img[..., 0] path = path_tmpl.format(index, '{:03d}'.format(j)) imsave(path, img) if self.verbose: logger.info("iter={} {{{}}} are written to {}.".format( index, self.name, path_tmpl.format(index, '*')))
python
def add(self, index, var): """Add a minibatch of images to the monitor. Args: index (int): Index. var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`): A minibatch of images with ``(N, ..., C, H, W)`` format. If C == 2, blue channel is appended with ones. If C > 3, the array will be sliced to remove C > 3 sub-array. """ import nnabla as nn from nnabla.utils.image_utils import imsave if index != 0 and (index + 1) % self.interval != 0: return if isinstance(var, nn.Variable): data = var.d.copy() elif isinstance(var, nn.NdArray): data = var.data.copy() else: assert isinstance(var, np.ndarray) data = var.copy() assert data.ndim > 2 channels = data.shape[-3] data = data.reshape(-1, *data.shape[-3:]) data = data[:min(data.shape[0], self.num_images)] data = self.normalize_method(data) if channels > 3: data = data[:, :3] elif channels == 2: data = np.concatenate( [data, np.ones((data.shape[0], 1) + data.shape[-2:])], axis=1) path_tmpl = os.path.join(self.save_dir, '{:06d}-{}.png') for j in range(min(self.num_images, data.shape[0])): img = data[j].transpose(1, 2, 0) if img.shape[-1] == 1: img = img[..., 0] path = path_tmpl.format(index, '{:03d}'.format(j)) imsave(path, img) if self.verbose: logger.info("iter={} {{{}}} are written to {}.".format( index, self.name, path_tmpl.format(index, '*')))
[ "def", "add", "(", "self", ",", "index", ",", "var", ")", ":", "import", "nnabla", "as", "nn", "from", "nnabla", ".", "utils", ".", "image_utils", "import", "imsave", "if", "index", "!=", "0", "and", "(", "index", "+", "1", ")", "%", "self", ".", "interval", "!=", "0", ":", "return", "if", "isinstance", "(", "var", ",", "nn", ".", "Variable", ")", ":", "data", "=", "var", ".", "d", ".", "copy", "(", ")", "elif", "isinstance", "(", "var", ",", "nn", ".", "NdArray", ")", ":", "data", "=", "var", ".", "data", ".", "copy", "(", ")", "else", ":", "assert", "isinstance", "(", "var", ",", "np", ".", "ndarray", ")", "data", "=", "var", ".", "copy", "(", ")", "assert", "data", ".", "ndim", ">", "2", "channels", "=", "data", ".", "shape", "[", "-", "3", "]", "data", "=", "data", ".", "reshape", "(", "-", "1", ",", "*", "data", ".", "shape", "[", "-", "3", ":", "]", ")", "data", "=", "data", "[", ":", "min", "(", "data", ".", "shape", "[", "0", "]", ",", "self", ".", "num_images", ")", "]", "data", "=", "self", ".", "normalize_method", "(", "data", ")", "if", "channels", ">", "3", ":", "data", "=", "data", "[", ":", ",", ":", "3", "]", "elif", "channels", "==", "2", ":", "data", "=", "np", ".", "concatenate", "(", "[", "data", ",", "np", ".", "ones", "(", "(", "data", ".", "shape", "[", "0", "]", ",", "1", ")", "+", "data", ".", "shape", "[", "-", "2", ":", "]", ")", "]", ",", "axis", "=", "1", ")", "path_tmpl", "=", "os", ".", "path", ".", "join", "(", "self", ".", "save_dir", ",", "'{:06d}-{}.png'", ")", "for", "j", "in", "range", "(", "min", "(", "self", ".", "num_images", ",", "data", ".", "shape", "[", "0", "]", ")", ")", ":", "img", "=", "data", "[", "j", "]", ".", "transpose", "(", "1", ",", "2", ",", "0", ")", "if", "img", ".", "shape", "[", "-", "1", "]", "==", "1", ":", "img", "=", "img", "[", "...", ",", "0", "]", "path", "=", "path_tmpl", ".", "format", "(", "index", ",", "'{:03d}'", ".", "format", "(", "j", ")", ")", "imsave", "(", "path", ",", "img", ")", "if", "self", ".", "verbose", ":", "logger", ".", "info", "(", "\"iter={} {{{}}} are written to {}.\"", ".", "format", "(", "index", ",", "self", ".", "name", ",", "path_tmpl", ".", "format", "(", "index", ",", "'*'", ")", ")", ")" ]
Add a minibatch of images to the monitor. Args: index (int): Index. var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`): A minibatch of images with ``(N, ..., C, H, W)`` format. If C == 2, blue channel is appended with ones. If C > 3, the array will be sliced to remove C > 3 sub-array.
[ "Add", "a", "minibatch", "of", "images", "to", "the", "monitor", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/monitor.py#L222-L263
228,905
sony/nnabla
python/src/nnabla/utils/data_iterator.py
data_iterator_simple
def data_iterator_simple(load_func, num_examples, batch_size, shuffle=False, rng=None, with_memory_cache=True, with_file_cache=True, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[]): """A generator that ``yield`` s minibatch data as a tuple, as defined in ``load_func`` . It can unlimitedly yield minibatches at your request, queried from the provided data. Args: load_func (function): Takes a single argument `i`, an index of an example in your dataset to be loaded, and returns a tuple of data. Every call by any index `i` must return a tuple of arrays with the same shape. num_examples (int): Number of examples in your dataset. Random sequence of indexes is generated according to this number. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator. Here is an example of `load_func` which returns an image and a label of a classification dataset. .. code-block:: python import numpy as np from nnabla.utils.image_utils import imread image_paths = load_image_paths() labels = load_labels() def my_load_func(i): ''' Returns: image: c x h x w array label: 0-shape array ''' img = imread(image_paths[i]).astype('float32') return np.rollaxis(img, 2), np.array(labels[i]) """ return data_iterator(SimpleDataSource(load_func, num_examples, shuffle=shuffle, rng=rng), batch_size=batch_size, with_memory_cache=with_memory_cache, with_file_cache=with_file_cache, cache_dir=cache_dir, epoch_begin_callbacks=epoch_begin_callbacks, epoch_end_callbacks=epoch_end_callbacks)
python
def data_iterator_simple(load_func, num_examples, batch_size, shuffle=False, rng=None, with_memory_cache=True, with_file_cache=True, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[]): """A generator that ``yield`` s minibatch data as a tuple, as defined in ``load_func`` . It can unlimitedly yield minibatches at your request, queried from the provided data. Args: load_func (function): Takes a single argument `i`, an index of an example in your dataset to be loaded, and returns a tuple of data. Every call by any index `i` must return a tuple of arrays with the same shape. num_examples (int): Number of examples in your dataset. Random sequence of indexes is generated according to this number. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator. Here is an example of `load_func` which returns an image and a label of a classification dataset. .. code-block:: python import numpy as np from nnabla.utils.image_utils import imread image_paths = load_image_paths() labels = load_labels() def my_load_func(i): ''' Returns: image: c x h x w array label: 0-shape array ''' img = imread(image_paths[i]).astype('float32') return np.rollaxis(img, 2), np.array(labels[i]) """ return data_iterator(SimpleDataSource(load_func, num_examples, shuffle=shuffle, rng=rng), batch_size=batch_size, with_memory_cache=with_memory_cache, with_file_cache=with_file_cache, cache_dir=cache_dir, epoch_begin_callbacks=epoch_begin_callbacks, epoch_end_callbacks=epoch_end_callbacks)
[ "def", "data_iterator_simple", "(", "load_func", ",", "num_examples", ",", "batch_size", ",", "shuffle", "=", "False", ",", "rng", "=", "None", ",", "with_memory_cache", "=", "True", ",", "with_file_cache", "=", "True", ",", "cache_dir", "=", "None", ",", "epoch_begin_callbacks", "=", "[", "]", ",", "epoch_end_callbacks", "=", "[", "]", ")", ":", "return", "data_iterator", "(", "SimpleDataSource", "(", "load_func", ",", "num_examples", ",", "shuffle", "=", "shuffle", ",", "rng", "=", "rng", ")", ",", "batch_size", "=", "batch_size", ",", "with_memory_cache", "=", "with_memory_cache", ",", "with_file_cache", "=", "with_file_cache", ",", "cache_dir", "=", "cache_dir", ",", "epoch_begin_callbacks", "=", "epoch_begin_callbacks", ",", "epoch_end_callbacks", "=", "epoch_end_callbacks", ")" ]
A generator that ``yield`` s minibatch data as a tuple, as defined in ``load_func`` . It can unlimitedly yield minibatches at your request, queried from the provided data. Args: load_func (function): Takes a single argument `i`, an index of an example in your dataset to be loaded, and returns a tuple of data. Every call by any index `i` must return a tuple of arrays with the same shape. num_examples (int): Number of examples in your dataset. Random sequence of indexes is generated according to this number. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator. Here is an example of `load_func` which returns an image and a label of a classification dataset. .. code-block:: python import numpy as np from nnabla.utils.image_utils import imread image_paths = load_image_paths() labels = load_labels() def my_load_func(i): ''' Returns: image: c x h x w array label: 0-shape array ''' img = imread(image_paths[i]).astype('float32') return np.rollaxis(img, 2), np.array(labels[i])
[ "A", "generator", "that", "yield", "s", "minibatch", "data", "as", "a", "tuple", "as", "defined", "in", "load_func", ".", "It", "can", "unlimitedly", "yield", "minibatches", "at", "your", "request", "queried", "from", "the", "provided", "data", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/data_iterator.py#L426-L511
228,906
sony/nnabla
python/src/nnabla/utils/data_iterator.py
data_iterator_csv_dataset
def data_iterator_csv_dataset(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, with_file_cache=True, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[]): '''data_iterator_csv_dataset Get data directly from a dataset provided as a CSV file. You can read files located on the local file system, http(s) servers or Amazon AWS S3 storage. For example, .. code-block:: python batch = data_iterator_csv_dataset('CSV_FILE.csv', batch_size, shuffle=True) Args: uri (str): Location of dataset CSV file. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. normalize (bool): If True, each sample in the data gets normalized by a factor of 255. Default is True. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator ''' ds = CsvDataSource(uri, shuffle=shuffle, rng=rng, normalize=normalize) return data_iterator(ds, batch_size=batch_size, with_memory_cache=with_memory_cache, with_file_cache=with_file_cache, cache_dir=cache_dir, epoch_begin_callbacks=epoch_begin_callbacks, epoch_end_callbacks=epoch_end_callbacks)
python
def data_iterator_csv_dataset(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, with_file_cache=True, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[]): '''data_iterator_csv_dataset Get data directly from a dataset provided as a CSV file. You can read files located on the local file system, http(s) servers or Amazon AWS S3 storage. For example, .. code-block:: python batch = data_iterator_csv_dataset('CSV_FILE.csv', batch_size, shuffle=True) Args: uri (str): Location of dataset CSV file. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. normalize (bool): If True, each sample in the data gets normalized by a factor of 255. Default is True. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator ''' ds = CsvDataSource(uri, shuffle=shuffle, rng=rng, normalize=normalize) return data_iterator(ds, batch_size=batch_size, with_memory_cache=with_memory_cache, with_file_cache=with_file_cache, cache_dir=cache_dir, epoch_begin_callbacks=epoch_begin_callbacks, epoch_end_callbacks=epoch_end_callbacks)
[ "def", "data_iterator_csv_dataset", "(", "uri", ",", "batch_size", ",", "shuffle", "=", "False", ",", "rng", "=", "None", ",", "normalize", "=", "True", ",", "with_memory_cache", "=", "True", ",", "with_file_cache", "=", "True", ",", "cache_dir", "=", "None", ",", "epoch_begin_callbacks", "=", "[", "]", ",", "epoch_end_callbacks", "=", "[", "]", ")", ":", "ds", "=", "CsvDataSource", "(", "uri", ",", "shuffle", "=", "shuffle", ",", "rng", "=", "rng", ",", "normalize", "=", "normalize", ")", "return", "data_iterator", "(", "ds", ",", "batch_size", "=", "batch_size", ",", "with_memory_cache", "=", "with_memory_cache", ",", "with_file_cache", "=", "with_file_cache", ",", "cache_dir", "=", "cache_dir", ",", "epoch_begin_callbacks", "=", "epoch_begin_callbacks", ",", "epoch_end_callbacks", "=", "epoch_end_callbacks", ")" ]
data_iterator_csv_dataset Get data directly from a dataset provided as a CSV file. You can read files located on the local file system, http(s) servers or Amazon AWS S3 storage. For example, .. code-block:: python batch = data_iterator_csv_dataset('CSV_FILE.csv', batch_size, shuffle=True) Args: uri (str): Location of dataset CSV file. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. normalize (bool): If True, each sample in the data gets normalized by a factor of 255. Default is True. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator
[ "data_iterator_csv_dataset", "Get", "data", "directly", "from", "a", "dataset", "provided", "as", "a", "CSV", "file", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/data_iterator.py#L514-L585
228,907
sony/nnabla
python/src/nnabla/utils/data_iterator.py
data_iterator_cache
def data_iterator_cache(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, epoch_begin_callbacks=[], epoch_end_callbacks=[]): '''data_iterator_cache Get data from the cache directory. Cache files are read from the local file system. For example, .. code-block:: python batch = data_iterator_cache('CACHE_DIR', batch_size, shuffle=True) Args: uri (str): Location of directory with cache files. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. normalize (bool): If True, each sample in the data gets normalized by a factor of 255. Default is True. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator ''' ds = CacheDataSource(uri, shuffle=shuffle, rng=rng, normalize=normalize) return data_iterator(ds, batch_size=batch_size, with_memory_cache=with_memory_cache, epoch_begin_callbacks=epoch_begin_callbacks, epoch_end_callbacks=epoch_end_callbacks)
python
def data_iterator_cache(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, epoch_begin_callbacks=[], epoch_end_callbacks=[]): '''data_iterator_cache Get data from the cache directory. Cache files are read from the local file system. For example, .. code-block:: python batch = data_iterator_cache('CACHE_DIR', batch_size, shuffle=True) Args: uri (str): Location of directory with cache files. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. normalize (bool): If True, each sample in the data gets normalized by a factor of 255. Default is True. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator ''' ds = CacheDataSource(uri, shuffle=shuffle, rng=rng, normalize=normalize) return data_iterator(ds, batch_size=batch_size, with_memory_cache=with_memory_cache, epoch_begin_callbacks=epoch_begin_callbacks, epoch_end_callbacks=epoch_end_callbacks)
[ "def", "data_iterator_cache", "(", "uri", ",", "batch_size", ",", "shuffle", "=", "False", ",", "rng", "=", "None", ",", "normalize", "=", "True", ",", "with_memory_cache", "=", "True", ",", "epoch_begin_callbacks", "=", "[", "]", ",", "epoch_end_callbacks", "=", "[", "]", ")", ":", "ds", "=", "CacheDataSource", "(", "uri", ",", "shuffle", "=", "shuffle", ",", "rng", "=", "rng", ",", "normalize", "=", "normalize", ")", "return", "data_iterator", "(", "ds", ",", "batch_size", "=", "batch_size", ",", "with_memory_cache", "=", "with_memory_cache", ",", "epoch_begin_callbacks", "=", "epoch_begin_callbacks", ",", "epoch_end_callbacks", "=", "epoch_end_callbacks", ")" ]
data_iterator_cache Get data from the cache directory. Cache files are read from the local file system. For example, .. code-block:: python batch = data_iterator_cache('CACHE_DIR', batch_size, shuffle=True) Args: uri (str): Location of directory with cache files. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. normalize (bool): If True, each sample in the data gets normalized by a factor of 255. Default is True. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator
[ "data_iterator_cache", "Get", "data", "from", "the", "cache", "directory", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/data_iterator.py#L588-L643
228,908
sony/nnabla
python/src/nnabla/utils/data_iterator.py
data_iterator_concat_datasets
def data_iterator_concat_datasets(data_source_list, batch_size, shuffle=False, rng=None, with_memory_cache=True, with_file_cache=False, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[]): '''data_iterator_concat_datasets Get data from multiple datasets. For example, .. code-block:: python batch = data_iterator_concat_datasets([DataSource0, DataSource1, ...], batch_size) Args: data_source_list (list of DataSource): list of datasets. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator ''' ds = ConcatDataSource(data_source_list, shuffle=shuffle, rng=rng) return data_iterator(ds, batch_size=batch_size, with_memory_cache=with_memory_cache, with_file_cache=with_file_cache, epoch_begin_callbacks=epoch_begin_callbacks, epoch_end_callbacks=epoch_end_callbacks)
python
def data_iterator_concat_datasets(data_source_list, batch_size, shuffle=False, rng=None, with_memory_cache=True, with_file_cache=False, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[]): '''data_iterator_concat_datasets Get data from multiple datasets. For example, .. code-block:: python batch = data_iterator_concat_datasets([DataSource0, DataSource1, ...], batch_size) Args: data_source_list (list of DataSource): list of datasets. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator ''' ds = ConcatDataSource(data_source_list, shuffle=shuffle, rng=rng) return data_iterator(ds, batch_size=batch_size, with_memory_cache=with_memory_cache, with_file_cache=with_file_cache, epoch_begin_callbacks=epoch_begin_callbacks, epoch_end_callbacks=epoch_end_callbacks)
[ "def", "data_iterator_concat_datasets", "(", "data_source_list", ",", "batch_size", ",", "shuffle", "=", "False", ",", "rng", "=", "None", ",", "with_memory_cache", "=", "True", ",", "with_file_cache", "=", "False", ",", "cache_dir", "=", "None", ",", "epoch_begin_callbacks", "=", "[", "]", ",", "epoch_end_callbacks", "=", "[", "]", ")", ":", "ds", "=", "ConcatDataSource", "(", "data_source_list", ",", "shuffle", "=", "shuffle", ",", "rng", "=", "rng", ")", "return", "data_iterator", "(", "ds", ",", "batch_size", "=", "batch_size", ",", "with_memory_cache", "=", "with_memory_cache", ",", "with_file_cache", "=", "with_file_cache", ",", "epoch_begin_callbacks", "=", "epoch_begin_callbacks", ",", "epoch_end_callbacks", "=", "epoch_end_callbacks", ")" ]
data_iterator_concat_datasets Get data from multiple datasets. For example, .. code-block:: python batch = data_iterator_concat_datasets([DataSource0, DataSource1, ...], batch_size) Args: data_source_list (list of DataSource): list of datasets. batch_size (int): Size of data unit. shuffle (bool): Indicates whether the dataset is shuffled or not. Default value is False. rng (None or :obj:`numpy.random.RandomState`): Numpy random number generator. with_memory_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithMemoryCache` to wrap ``data_source``. It is a good idea to set this as true unless data_source provides on-memory data. Default value is True. with_file_cache (bool): If ``True``, use :py:class:`.data_source.DataSourceWithFileCache` to wrap ``data_source``. If ``data_source`` is slow, enabling this option a is good idea. Default value is False. cache_dir (str): Location of file_cache. If this value is None, :py:class:`.data_source.DataSourceWithFileCache` creates file caches implicitly on temporary directory and erases them all when data_iterator is finished. Otherwise, :py:class:`.data_source.DataSourceWithFileCache` keeps created cache. Default is None. epoch_begin_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the beginning of an epoch. epoch_end_callbacks (list of functions): An item is a function which takes an epoch index as an argument. These are called at the end of an epoch. Returns: :py:class:`DataIterator <nnabla.utils.data_iterator.DataIterator>`: Instance of DataIterator
[ "data_iterator_concat_datasets", "Get", "data", "from", "multiple", "datasets", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/data_iterator.py#L646-L709
228,909
sony/nnabla
python/src/nnabla/utils/data_iterator.py
DataIterator.slice
def slice(self, rng, num_of_slices=None, slice_pos=None, slice_start=None, slice_end=None, cache_dir=None): ''' Slices the data iterator so that newly generated data iterator has access to limited portion of the original data. Args: rng (numpy.random.RandomState): Random generator for Initializer. num_of_slices(int): Total number of slices to be made. Muts be used together with `slice_pos`. slice_pos(int): Position of the slice to be assigned to the new data iterator. Must be used together with `num_of_slices`. slice_start(int): Starting position of the range to be sliced into new data iterator. Must be used together with `slice_end`. slice_end(int) : End position of the range to be sliced into new data iterator. Must be used together with `slice_start`. cache_dir(str) : Directory to save cache files Example: .. code-block:: python from nnabla.utils.data_iterator import data_iterator_simple import numpy as np def load_func1(index): d = np.ones((2, 2)) * index return d di = data_iterator_simple(load_func1, 1000, batch_size=3) di_s1 = di.slice(None, num_of_slices=10, slice_pos=0) di_s2 = di.slice(None, num_of_slices=10, slice_pos=1) di_s3 = di.slice(None, slice_start=100, slice_end=200) di_s4 = di.slice(None, slice_start=300, slice_end=400) ''' if num_of_slices is not None and slice_pos is not None and slice_start is None and slice_end is None: size = self._size // num_of_slices amount = self._size % num_of_slices slice_start = slice_pos * size if slice_pos < amount: slice_start += slice_pos else: slice_start += amount slice_end = slice_start + size if slice_end > self._size: slice_start -= (slice_end - self._size) slice_end = self._size elif num_of_slices is None and slice_pos is None and slice_start is not None and slice_end is not None: pass else: logger.critical( 'You must specify position(num_of_slice and slice_pos) or range(slice_start and slice_end).') return None if cache_dir is None: ds = self._data_source while '_data_source' in dir(ds): if '_cache_dir' in dir(ds): cache_dir = ds._cache_dir ds = ds._data_source if cache_dir is None: return DataIterator( DataSourceWithMemoryCache( SlicedDataSource( self._data_source, self._data_source.shuffle, slice_start=slice_start, slice_end=slice_end), shuffle=self._shuffle, rng=rng), self._batch_size) else: return DataIterator( DataSourceWithMemoryCache( DataSourceWithFileCache( SlicedDataSource( self._data_source, self._data_source.shuffle, slice_start=slice_start, slice_end=slice_end), cache_dir=cache_dir, cache_file_name_prefix='cache_sliced_{:08d}_{:08d}'.format( slice_start, slice_end), shuffle=self._shuffle, rng=rng), shuffle=self._shuffle, rng=rng), self._batch_size)
python
def slice(self, rng, num_of_slices=None, slice_pos=None, slice_start=None, slice_end=None, cache_dir=None): ''' Slices the data iterator so that newly generated data iterator has access to limited portion of the original data. Args: rng (numpy.random.RandomState): Random generator for Initializer. num_of_slices(int): Total number of slices to be made. Muts be used together with `slice_pos`. slice_pos(int): Position of the slice to be assigned to the new data iterator. Must be used together with `num_of_slices`. slice_start(int): Starting position of the range to be sliced into new data iterator. Must be used together with `slice_end`. slice_end(int) : End position of the range to be sliced into new data iterator. Must be used together with `slice_start`. cache_dir(str) : Directory to save cache files Example: .. code-block:: python from nnabla.utils.data_iterator import data_iterator_simple import numpy as np def load_func1(index): d = np.ones((2, 2)) * index return d di = data_iterator_simple(load_func1, 1000, batch_size=3) di_s1 = di.slice(None, num_of_slices=10, slice_pos=0) di_s2 = di.slice(None, num_of_slices=10, slice_pos=1) di_s3 = di.slice(None, slice_start=100, slice_end=200) di_s4 = di.slice(None, slice_start=300, slice_end=400) ''' if num_of_slices is not None and slice_pos is not None and slice_start is None and slice_end is None: size = self._size // num_of_slices amount = self._size % num_of_slices slice_start = slice_pos * size if slice_pos < amount: slice_start += slice_pos else: slice_start += amount slice_end = slice_start + size if slice_end > self._size: slice_start -= (slice_end - self._size) slice_end = self._size elif num_of_slices is None and slice_pos is None and slice_start is not None and slice_end is not None: pass else: logger.critical( 'You must specify position(num_of_slice and slice_pos) or range(slice_start and slice_end).') return None if cache_dir is None: ds = self._data_source while '_data_source' in dir(ds): if '_cache_dir' in dir(ds): cache_dir = ds._cache_dir ds = ds._data_source if cache_dir is None: return DataIterator( DataSourceWithMemoryCache( SlicedDataSource( self._data_source, self._data_source.shuffle, slice_start=slice_start, slice_end=slice_end), shuffle=self._shuffle, rng=rng), self._batch_size) else: return DataIterator( DataSourceWithMemoryCache( DataSourceWithFileCache( SlicedDataSource( self._data_source, self._data_source.shuffle, slice_start=slice_start, slice_end=slice_end), cache_dir=cache_dir, cache_file_name_prefix='cache_sliced_{:08d}_{:08d}'.format( slice_start, slice_end), shuffle=self._shuffle, rng=rng), shuffle=self._shuffle, rng=rng), self._batch_size)
[ "def", "slice", "(", "self", ",", "rng", ",", "num_of_slices", "=", "None", ",", "slice_pos", "=", "None", ",", "slice_start", "=", "None", ",", "slice_end", "=", "None", ",", "cache_dir", "=", "None", ")", ":", "if", "num_of_slices", "is", "not", "None", "and", "slice_pos", "is", "not", "None", "and", "slice_start", "is", "None", "and", "slice_end", "is", "None", ":", "size", "=", "self", ".", "_size", "//", "num_of_slices", "amount", "=", "self", ".", "_size", "%", "num_of_slices", "slice_start", "=", "slice_pos", "*", "size", "if", "slice_pos", "<", "amount", ":", "slice_start", "+=", "slice_pos", "else", ":", "slice_start", "+=", "amount", "slice_end", "=", "slice_start", "+", "size", "if", "slice_end", ">", "self", ".", "_size", ":", "slice_start", "-=", "(", "slice_end", "-", "self", ".", "_size", ")", "slice_end", "=", "self", ".", "_size", "elif", "num_of_slices", "is", "None", "and", "slice_pos", "is", "None", "and", "slice_start", "is", "not", "None", "and", "slice_end", "is", "not", "None", ":", "pass", "else", ":", "logger", ".", "critical", "(", "'You must specify position(num_of_slice and slice_pos) or range(slice_start and slice_end).'", ")", "return", "None", "if", "cache_dir", "is", "None", ":", "ds", "=", "self", ".", "_data_source", "while", "'_data_source'", "in", "dir", "(", "ds", ")", ":", "if", "'_cache_dir'", "in", "dir", "(", "ds", ")", ":", "cache_dir", "=", "ds", ".", "_cache_dir", "ds", "=", "ds", ".", "_data_source", "if", "cache_dir", "is", "None", ":", "return", "DataIterator", "(", "DataSourceWithMemoryCache", "(", "SlicedDataSource", "(", "self", ".", "_data_source", ",", "self", ".", "_data_source", ".", "shuffle", ",", "slice_start", "=", "slice_start", ",", "slice_end", "=", "slice_end", ")", ",", "shuffle", "=", "self", ".", "_shuffle", ",", "rng", "=", "rng", ")", ",", "self", ".", "_batch_size", ")", "else", ":", "return", "DataIterator", "(", "DataSourceWithMemoryCache", "(", "DataSourceWithFileCache", "(", "SlicedDataSource", "(", "self", ".", "_data_source", ",", "self", ".", "_data_source", ".", "shuffle", ",", "slice_start", "=", "slice_start", ",", "slice_end", "=", "slice_end", ")", ",", "cache_dir", "=", "cache_dir", ",", "cache_file_name_prefix", "=", "'cache_sliced_{:08d}_{:08d}'", ".", "format", "(", "slice_start", ",", "slice_end", ")", ",", "shuffle", "=", "self", ".", "_shuffle", ",", "rng", "=", "rng", ")", ",", "shuffle", "=", "self", ".", "_shuffle", ",", "rng", "=", "rng", ")", ",", "self", ".", "_batch_size", ")" ]
Slices the data iterator so that newly generated data iterator has access to limited portion of the original data. Args: rng (numpy.random.RandomState): Random generator for Initializer. num_of_slices(int): Total number of slices to be made. Muts be used together with `slice_pos`. slice_pos(int): Position of the slice to be assigned to the new data iterator. Must be used together with `num_of_slices`. slice_start(int): Starting position of the range to be sliced into new data iterator. Must be used together with `slice_end`. slice_end(int) : End position of the range to be sliced into new data iterator. Must be used together with `slice_start`. cache_dir(str) : Directory to save cache files Example: .. code-block:: python from nnabla.utils.data_iterator import data_iterator_simple import numpy as np def load_func1(index): d = np.ones((2, 2)) * index return d di = data_iterator_simple(load_func1, 1000, batch_size=3) di_s1 = di.slice(None, num_of_slices=10, slice_pos=0) di_s2 = di.slice(None, num_of_slices=10, slice_pos=1) di_s3 = di.slice(None, slice_start=100, slice_end=200) di_s4 = di.slice(None, slice_start=300, slice_end=400)
[ "Slices", "the", "data", "iterator", "so", "that", "newly", "generated", "data", "iterator", "has", "access", "to", "limited", "portion", "of", "the", "original", "data", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/data_iterator.py#L230-L320
228,910
sony/nnabla
python/src/nnabla/auto_forward.py
auto_forward
def auto_forward(auto=True): """ Context for dynamic graph execution mode. Args: auto (bool): Whether forward computation is executed during a computation graph construction. Returns: bool """ global __auto_forward_state prev = __auto_forward_state __auto_forward_state = auto yield __auto_forward_state = prev
python
def auto_forward(auto=True): """ Context for dynamic graph execution mode. Args: auto (bool): Whether forward computation is executed during a computation graph construction. Returns: bool """ global __auto_forward_state prev = __auto_forward_state __auto_forward_state = auto yield __auto_forward_state = prev
[ "def", "auto_forward", "(", "auto", "=", "True", ")", ":", "global", "__auto_forward_state", "prev", "=", "__auto_forward_state", "__auto_forward_state", "=", "auto", "yield", "__auto_forward_state", "=", "prev" ]
Context for dynamic graph execution mode. Args: auto (bool): Whether forward computation is executed during a computation graph construction. Returns: bool
[ "Context", "for", "dynamic", "graph", "execution", "mode", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/auto_forward.py#L23-L38
228,911
sony/nnabla
python/src/nnabla/utils/function_profile.py
FunctionProfile.print_stats
def print_stats(self, reset=True): '''Manually print profiling result. Args: reset (bool): If False is specified, the profiling statistics so far is maintained. If ``True`` (default), :obj:`~reset_stats` is called to reset the profiling statistics. ''' if not self.ncalls: return stats = self.stats code = self.fn.__code__ print('--- Function Profiling ---') print('File "{}", line {}, function {}'.format( code.co_filename, code.co_firstlineno, self.fn.__name__)) stats.sort_stats(*self.sort_keys) stats.print_stats(*self.print_restrictions) print('--------------------------') if reset: self.reset_stats()
python
def print_stats(self, reset=True): '''Manually print profiling result. Args: reset (bool): If False is specified, the profiling statistics so far is maintained. If ``True`` (default), :obj:`~reset_stats` is called to reset the profiling statistics. ''' if not self.ncalls: return stats = self.stats code = self.fn.__code__ print('--- Function Profiling ---') print('File "{}", line {}, function {}'.format( code.co_filename, code.co_firstlineno, self.fn.__name__)) stats.sort_stats(*self.sort_keys) stats.print_stats(*self.print_restrictions) print('--------------------------') if reset: self.reset_stats()
[ "def", "print_stats", "(", "self", ",", "reset", "=", "True", ")", ":", "if", "not", "self", ".", "ncalls", ":", "return", "stats", "=", "self", ".", "stats", "code", "=", "self", ".", "fn", ".", "__code__", "print", "(", "'--- Function Profiling ---'", ")", "print", "(", "'File \"{}\", line {}, function {}'", ".", "format", "(", "code", ".", "co_filename", ",", "code", ".", "co_firstlineno", ",", "self", ".", "fn", ".", "__name__", ")", ")", "stats", ".", "sort_stats", "(", "*", "self", ".", "sort_keys", ")", "stats", ".", "print_stats", "(", "*", "self", ".", "print_restrictions", ")", "print", "(", "'--------------------------'", ")", "if", "reset", ":", "self", ".", "reset_stats", "(", ")" ]
Manually print profiling result. Args: reset (bool): If False is specified, the profiling statistics so far is maintained. If ``True`` (default), :obj:`~reset_stats` is called to reset the profiling statistics.
[ "Manually", "print", "profiling", "result", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/function_profile.py#L87-L111
228,912
sony/nnabla
python/src/nnabla/models/utils.py
get_model_home
def get_model_home(): ''' Returns a root folder path for downloading models. ''' d = os.path.join(get_data_home(), 'nnp_models') if not os.path.isdir(d): os.makedirs(d) return d
python
def get_model_home(): ''' Returns a root folder path for downloading models. ''' d = os.path.join(get_data_home(), 'nnp_models') if not os.path.isdir(d): os.makedirs(d) return d
[ "def", "get_model_home", "(", ")", ":", "d", "=", "os", ".", "path", ".", "join", "(", "get_data_home", "(", ")", ",", "'nnp_models'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "d", ")", ":", "os", ".", "makedirs", "(", "d", ")", "return", "d" ]
Returns a root folder path for downloading models.
[ "Returns", "a", "root", "folder", "path", "for", "downloading", "models", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/models/utils.py#L23-L30
228,913
sony/nnabla
python/src/nnabla/models/utils.py
get_model_url_base
def get_model_url_base(): ''' Returns a root folder for models. ''' url_base = get_model_url_base_from_env() if url_base is not None: logger.info('NNBLA_MODELS_URL_BASE is set as {}.'.format(url_base)) else: url_base = 'https://nnabla.org/pretrained-models/nnp_models/' return url_base
python
def get_model_url_base(): ''' Returns a root folder for models. ''' url_base = get_model_url_base_from_env() if url_base is not None: logger.info('NNBLA_MODELS_URL_BASE is set as {}.'.format(url_base)) else: url_base = 'https://nnabla.org/pretrained-models/nnp_models/' return url_base
[ "def", "get_model_url_base", "(", ")", ":", "url_base", "=", "get_model_url_base_from_env", "(", ")", "if", "url_base", "is", "not", "None", ":", "logger", ".", "info", "(", "'NNBLA_MODELS_URL_BASE is set as {}.'", ".", "format", "(", "url_base", ")", ")", "else", ":", "url_base", "=", "'https://nnabla.org/pretrained-models/nnp_models/'", "return", "url_base" ]
Returns a root folder for models.
[ "Returns", "a", "root", "folder", "for", "models", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/models/utils.py#L41-L50
228,914
sony/nnabla
python/src/nnabla/utils/data_source_loader.py
load_image_imread
def load_image_imread(file, shape=None, max_range=1.0): ''' Load image from file like object. :param file: Image contents :type file: file like object. :param shape: shape of output array e.g. (3, 128, 192) : n_color, height, width. :type shape: tuple of int :param float max_range: the value of return array ranges from 0 to `max_range`. :return: numpy array ''' img255 = imread( file) # return value is from zero to 255 (even if the image has 16-bitdepth.) if len(img255.shape) == 2: # gray image height, width = img255.shape if shape is None: out_height, out_width, out_n_color = height, width, 1 else: out_n_color, out_height, out_width = shape assert(out_n_color == 1) if out_height != height or out_width != width: # imresize returns 0 to 255 image. img255 = imresize(img255, (out_height, out_width)) img255 = img255.reshape((out_n_color, out_height, out_width)) elif len(img255.shape) == 3: # RGB image height, width, n_color = img255.shape if shape is None: out_height, out_width, out_n_color = height, width, n_color else: out_n_color, out_height, out_width = shape assert(out_n_color == n_color) if out_height != height or out_width != width or out_n_color != n_color: # imresize returns 0 to 255 image. img255 = imresize(img255, (out_height, out_width, out_n_color)) img255 = img255.transpose(2, 0, 1) if max_range < 0 or max_range == 255.0: return img255 else: return img255 * (max_range / 255.0)
python
def load_image_imread(file, shape=None, max_range=1.0): ''' Load image from file like object. :param file: Image contents :type file: file like object. :param shape: shape of output array e.g. (3, 128, 192) : n_color, height, width. :type shape: tuple of int :param float max_range: the value of return array ranges from 0 to `max_range`. :return: numpy array ''' img255 = imread( file) # return value is from zero to 255 (even if the image has 16-bitdepth.) if len(img255.shape) == 2: # gray image height, width = img255.shape if shape is None: out_height, out_width, out_n_color = height, width, 1 else: out_n_color, out_height, out_width = shape assert(out_n_color == 1) if out_height != height or out_width != width: # imresize returns 0 to 255 image. img255 = imresize(img255, (out_height, out_width)) img255 = img255.reshape((out_n_color, out_height, out_width)) elif len(img255.shape) == 3: # RGB image height, width, n_color = img255.shape if shape is None: out_height, out_width, out_n_color = height, width, n_color else: out_n_color, out_height, out_width = shape assert(out_n_color == n_color) if out_height != height or out_width != width or out_n_color != n_color: # imresize returns 0 to 255 image. img255 = imresize(img255, (out_height, out_width, out_n_color)) img255 = img255.transpose(2, 0, 1) if max_range < 0 or max_range == 255.0: return img255 else: return img255 * (max_range / 255.0)
[ "def", "load_image_imread", "(", "file", ",", "shape", "=", "None", ",", "max_range", "=", "1.0", ")", ":", "img255", "=", "imread", "(", "file", ")", "# return value is from zero to 255 (even if the image has 16-bitdepth.)", "if", "len", "(", "img255", ".", "shape", ")", "==", "2", ":", "# gray image", "height", ",", "width", "=", "img255", ".", "shape", "if", "shape", "is", "None", ":", "out_height", ",", "out_width", ",", "out_n_color", "=", "height", ",", "width", ",", "1", "else", ":", "out_n_color", ",", "out_height", ",", "out_width", "=", "shape", "assert", "(", "out_n_color", "==", "1", ")", "if", "out_height", "!=", "height", "or", "out_width", "!=", "width", ":", "# imresize returns 0 to 255 image.", "img255", "=", "imresize", "(", "img255", ",", "(", "out_height", ",", "out_width", ")", ")", "img255", "=", "img255", ".", "reshape", "(", "(", "out_n_color", ",", "out_height", ",", "out_width", ")", ")", "elif", "len", "(", "img255", ".", "shape", ")", "==", "3", ":", "# RGB image", "height", ",", "width", ",", "n_color", "=", "img255", ".", "shape", "if", "shape", "is", "None", ":", "out_height", ",", "out_width", ",", "out_n_color", "=", "height", ",", "width", ",", "n_color", "else", ":", "out_n_color", ",", "out_height", ",", "out_width", "=", "shape", "assert", "(", "out_n_color", "==", "n_color", ")", "if", "out_height", "!=", "height", "or", "out_width", "!=", "width", "or", "out_n_color", "!=", "n_color", ":", "# imresize returns 0 to 255 image.", "img255", "=", "imresize", "(", "img255", ",", "(", "out_height", ",", "out_width", ",", "out_n_color", ")", ")", "img255", "=", "img255", ".", "transpose", "(", "2", ",", "0", ",", "1", ")", "if", "max_range", "<", "0", "or", "max_range", "==", "255.0", ":", "return", "img255", "else", ":", "return", "img255", "*", "(", "max_range", "/", "255.0", ")" ]
Load image from file like object. :param file: Image contents :type file: file like object. :param shape: shape of output array e.g. (3, 128, 192) : n_color, height, width. :type shape: tuple of int :param float max_range: the value of return array ranges from 0 to `max_range`. :return: numpy array
[ "Load", "image", "from", "file", "like", "object", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/data_source_loader.py#L195-L238
228,915
sony/nnabla
python/src/nnabla/utils/data_source_loader.py
load_csv
def load_csv(file, shape=None, normalize=False): """ Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array """ value_list = [] if six.PY2: for row in csv.reader(file): value_list.append(list(map(float, row))) elif six.PY34: for row in csv.reader([l.decode('utf-8') for l in file.readlines()]): value_list.append(list(map(float, row))) if shape is None: return numpy.array(value_list) else: return numpy.array(value_list).reshape(shape)
python
def load_csv(file, shape=None, normalize=False): """ Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array """ value_list = [] if six.PY2: for row in csv.reader(file): value_list.append(list(map(float, row))) elif six.PY34: for row in csv.reader([l.decode('utf-8') for l in file.readlines()]): value_list.append(list(map(float, row))) if shape is None: return numpy.array(value_list) else: return numpy.array(value_list).reshape(shape)
[ "def", "load_csv", "(", "file", ",", "shape", "=", "None", ",", "normalize", "=", "False", ")", ":", "value_list", "=", "[", "]", "if", "six", ".", "PY2", ":", "for", "row", "in", "csv", ".", "reader", "(", "file", ")", ":", "value_list", ".", "append", "(", "list", "(", "map", "(", "float", ",", "row", ")", ")", ")", "elif", "six", ".", "PY34", ":", "for", "row", "in", "csv", ".", "reader", "(", "[", "l", ".", "decode", "(", "'utf-8'", ")", "for", "l", "in", "file", ".", "readlines", "(", ")", "]", ")", ":", "value_list", ".", "append", "(", "list", "(", "map", "(", "float", ",", "row", ")", ")", ")", "if", "shape", "is", "None", ":", "return", "numpy", ".", "array", "(", "value_list", ")", "else", ":", "return", "numpy", ".", "array", "(", "value_list", ")", ".", "reshape", "(", "shape", ")" ]
Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array
[ "Load", "CSV", "file", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/data_source_loader.py#L346-L367
228,916
sony/nnabla
python/src/nnabla/experimental/viewers.py
SimpleGraph.save
def save(self, vleaf, fpath, cleanup=False, format=None): """Save the graph to a given file path. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanup (`bool`): Clean up the source file after rendering. Default is False. format (str): Force overwrite ``format`` (``'pdf', 'png', ...)``) configuration. """ graph = self.create_graphviz_digraph(vleaf, format=format) graph.render(fpath, cleanup=cleanup)
python
def save(self, vleaf, fpath, cleanup=False, format=None): """Save the graph to a given file path. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanup (`bool`): Clean up the source file after rendering. Default is False. format (str): Force overwrite ``format`` (``'pdf', 'png', ...)``) configuration. """ graph = self.create_graphviz_digraph(vleaf, format=format) graph.render(fpath, cleanup=cleanup)
[ "def", "save", "(", "self", ",", "vleaf", ",", "fpath", ",", "cleanup", "=", "False", ",", "format", "=", "None", ")", ":", "graph", "=", "self", ".", "create_graphviz_digraph", "(", "vleaf", ",", "format", "=", "format", ")", "graph", ".", "render", "(", "fpath", ",", "cleanup", "=", "cleanup", ")" ]
Save the graph to a given file path. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanup (`bool`): Clean up the source file after rendering. Default is False. format (str): Force overwrite ``format`` (``'pdf', 'png', ...)``) configuration.
[ "Save", "the", "graph", "to", "a", "given", "file", "path", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/experimental/viewers.py#L180-L192
228,917
sony/nnabla
python/src/nnabla/experimental/viewers.py
SimpleGraph.view
def view(self, vleaf, fpath=None, cleanup=True, format=None): """View the graph. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanup (`bool`): Clean up the source file after rendering. Default is True. format (str): Force overwrite ``format`` (``'pdf', 'png', ...)``) configuration. """ graph = self.create_graphviz_digraph(vleaf, format=format) graph.view(fpath, cleanup=cleanup)
python
def view(self, vleaf, fpath=None, cleanup=True, format=None): """View the graph. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanup (`bool`): Clean up the source file after rendering. Default is True. format (str): Force overwrite ``format`` (``'pdf', 'png', ...)``) configuration. """ graph = self.create_graphviz_digraph(vleaf, format=format) graph.view(fpath, cleanup=cleanup)
[ "def", "view", "(", "self", ",", "vleaf", ",", "fpath", "=", "None", ",", "cleanup", "=", "True", ",", "format", "=", "None", ")", ":", "graph", "=", "self", ".", "create_graphviz_digraph", "(", "vleaf", ",", "format", "=", "format", ")", "graph", ".", "view", "(", "fpath", ",", "cleanup", "=", "cleanup", ")" ]
View the graph. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanup (`bool`): Clean up the source file after rendering. Default is True. format (str): Force overwrite ``format`` (``'pdf', 'png', ...)``) configuration.
[ "View", "the", "graph", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/experimental/viewers.py#L194-L206
228,918
sony/nnabla
python/src/nnabla/experimental/parametric_function_class/module.py
Module.get_modules
def get_modules(self, memo=None, prefix=""): """Get modules. This function is internally used as the helper method for other methods. Args: memo (set, optional): Module set in order to memorize to visit. prefix (str, optional): Prefix to a specific parameter name. Yields: `Module`: The module class. """ if memo is None: memo = set() if self not in memo: memo.add(self) yield prefix, self for k, v in self.__dict__.items(): if not isinstance(v, Module): continue name, module = k, v submodule_prefix = "{}/{}".format(prefix, name) if prefix != "" else name for m in module.get_modules(memo, submodule_prefix): yield m
python
def get_modules(self, memo=None, prefix=""): """Get modules. This function is internally used as the helper method for other methods. Args: memo (set, optional): Module set in order to memorize to visit. prefix (str, optional): Prefix to a specific parameter name. Yields: `Module`: The module class. """ if memo is None: memo = set() if self not in memo: memo.add(self) yield prefix, self for k, v in self.__dict__.items(): if not isinstance(v, Module): continue name, module = k, v submodule_prefix = "{}/{}".format(prefix, name) if prefix != "" else name for m in module.get_modules(memo, submodule_prefix): yield m
[ "def", "get_modules", "(", "self", ",", "memo", "=", "None", ",", "prefix", "=", "\"\"", ")", ":", "if", "memo", "is", "None", ":", "memo", "=", "set", "(", ")", "if", "self", "not", "in", "memo", ":", "memo", ".", "add", "(", "self", ")", "yield", "prefix", ",", "self", "for", "k", ",", "v", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "v", ",", "Module", ")", ":", "continue", "name", ",", "module", "=", "k", ",", "v", "submodule_prefix", "=", "\"{}/{}\"", ".", "format", "(", "prefix", ",", "name", ")", "if", "prefix", "!=", "\"\"", "else", "name", "for", "m", "in", "module", ".", "get_modules", "(", "memo", ",", "submodule_prefix", ")", ":", "yield", "m" ]
Get modules. This function is internally used as the helper method for other methods. Args: memo (set, optional): Module set in order to memorize to visit. prefix (str, optional): Prefix to a specific parameter name. Yields: `Module`: The module class.
[ "Get", "modules", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/experimental/parametric_function_class/module.py#L58-L83
228,919
jazzband/django-push-notifications
push_notifications/fields.py
HexIntegerField.get_prep_value
def get_prep_value(self, value): """ Return the integer value to be stored from the hex string """ if value is None or value == "": return None if isinstance(value, six.string_types): value = _hex_string_to_unsigned_integer(value) if _using_signed_storage(): value = _unsigned_to_signed_integer(value) return value
python
def get_prep_value(self, value): """ Return the integer value to be stored from the hex string """ if value is None or value == "": return None if isinstance(value, six.string_types): value = _hex_string_to_unsigned_integer(value) if _using_signed_storage(): value = _unsigned_to_signed_integer(value) return value
[ "def", "get_prep_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", "or", "value", "==", "\"\"", ":", "return", "None", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "_hex_string_to_unsigned_integer", "(", "value", ")", "if", "_using_signed_storage", "(", ")", ":", "value", "=", "_unsigned_to_signed_integer", "(", "value", ")", "return", "value" ]
Return the integer value to be stored from the hex string
[ "Return", "the", "integer", "value", "to", "be", "stored", "from", "the", "hex", "string" ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/fields.py#L91-L99
228,920
jazzband/django-push-notifications
push_notifications/fields.py
HexIntegerField.from_db_value
def from_db_value(self, value, expression, connection, context): """ Return an unsigned int representation from all db backends """ if value is None: return value if _using_signed_storage(): value = _signed_to_unsigned_integer(value) return value
python
def from_db_value(self, value, expression, connection, context): """ Return an unsigned int representation from all db backends """ if value is None: return value if _using_signed_storage(): value = _signed_to_unsigned_integer(value) return value
[ "def", "from_db_value", "(", "self", ",", "value", ",", "expression", ",", "connection", ",", "context", ")", ":", "if", "value", "is", "None", ":", "return", "value", "if", "_using_signed_storage", "(", ")", ":", "value", "=", "_signed_to_unsigned_integer", "(", "value", ")", "return", "value" ]
Return an unsigned int representation from all db backends
[ "Return", "an", "unsigned", "int", "representation", "from", "all", "db", "backends" ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/fields.py#L101-L107
228,921
jazzband/django-push-notifications
push_notifications/fields.py
HexIntegerField.to_python
def to_python(self, value): """ Return a str representation of the hexadecimal """ if isinstance(value, six.string_types): return value if value is None: return value return _unsigned_integer_to_hex_string(value)
python
def to_python(self, value): """ Return a str representation of the hexadecimal """ if isinstance(value, six.string_types): return value if value is None: return value return _unsigned_integer_to_hex_string(value)
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "value", "if", "value", "is", "None", ":", "return", "value", "return", "_unsigned_integer_to_hex_string", "(", "value", ")" ]
Return a str representation of the hexadecimal
[ "Return", "a", "str", "representation", "of", "the", "hexadecimal" ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/fields.py#L109-L115
228,922
jazzband/django-push-notifications
push_notifications/apns.py
apns_send_bulk_message
def apns_send_bulk_message( registration_ids, alert, application_id=None, certfile=None, **kwargs ): """ Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won"t be included in the notification. You will need to pass None to this for silent notifications. """ results = _apns_send( registration_ids, alert, batch=True, application_id=application_id, certfile=certfile, **kwargs ) inactive_tokens = [token for token, result in results.items() if result == "Unregistered"] models.APNSDevice.objects.filter(registration_id__in=inactive_tokens).update(active=False) return results
python
def apns_send_bulk_message( registration_ids, alert, application_id=None, certfile=None, **kwargs ): """ Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won"t be included in the notification. You will need to pass None to this for silent notifications. """ results = _apns_send( registration_ids, alert, batch=True, application_id=application_id, certfile=certfile, **kwargs ) inactive_tokens = [token for token, result in results.items() if result == "Unregistered"] models.APNSDevice.objects.filter(registration_id__in=inactive_tokens).update(active=False) return results
[ "def", "apns_send_bulk_message", "(", "registration_ids", ",", "alert", ",", "application_id", "=", "None", ",", "certfile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "results", "=", "_apns_send", "(", "registration_ids", ",", "alert", ",", "batch", "=", "True", ",", "application_id", "=", "application_id", ",", "certfile", "=", "certfile", ",", "*", "*", "kwargs", ")", "inactive_tokens", "=", "[", "token", "for", "token", ",", "result", "in", "results", ".", "items", "(", ")", "if", "result", "==", "\"Unregistered\"", "]", "models", ".", "APNSDevice", ".", "objects", ".", "filter", "(", "registration_id__in", "=", "inactive_tokens", ")", ".", "update", "(", "active", "=", "False", ")", "return", "results" ]
Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won"t be included in the notification. You will need to pass None to this for silent notifications.
[ "Sends", "an", "APNS", "notification", "to", "one", "or", "more", "registration_ids", ".", "The", "registration_ids", "argument", "needs", "to", "be", "a", "list", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/apns.py#L123-L141
228,923
jazzband/django-push-notifications
push_notifications/gcm.py
_cm_send_request
def _cm_send_request( registration_ids, data, cloud_type="GCM", application_id=None, use_fcm_notifications=True, **kwargs ): """ Sends a FCM or GCM notification to one or more registration_ids as json data. The registration_ids needs to be a list. """ payload = {"registration_ids": registration_ids} if registration_ids else {} data = data.copy() # If using FCM, optionnally autodiscovers notification related keys # https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages if cloud_type == "FCM" and use_fcm_notifications: notification_payload = {} if "message" in data: notification_payload["body"] = data.pop("message", None) for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS: value_from_extra = data.pop(key, None) if value_from_extra: notification_payload[key] = value_from_extra value_from_kwargs = kwargs.pop(key, None) if value_from_kwargs: notification_payload[key] = value_from_kwargs if notification_payload: payload["notification"] = notification_payload if data: payload["data"] = data # Attach any additional non falsy keyword args (targets, options) # See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1 payload.update({ k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS) }) # Sort the keys for deterministic output (useful for tests) json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8") # Sends requests and handles the response if cloud_type == "GCM": response = json.loads(_gcm_send( json_payload, "application/json", application_id=application_id )) elif cloud_type == "FCM": response = json.loads(_fcm_send( json_payload, "application/json", application_id=application_id )) else: raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type)) return _cm_handle_response(registration_ids, response, cloud_type, application_id)
python
def _cm_send_request( registration_ids, data, cloud_type="GCM", application_id=None, use_fcm_notifications=True, **kwargs ): """ Sends a FCM or GCM notification to one or more registration_ids as json data. The registration_ids needs to be a list. """ payload = {"registration_ids": registration_ids} if registration_ids else {} data = data.copy() # If using FCM, optionnally autodiscovers notification related keys # https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages if cloud_type == "FCM" and use_fcm_notifications: notification_payload = {} if "message" in data: notification_payload["body"] = data.pop("message", None) for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS: value_from_extra = data.pop(key, None) if value_from_extra: notification_payload[key] = value_from_extra value_from_kwargs = kwargs.pop(key, None) if value_from_kwargs: notification_payload[key] = value_from_kwargs if notification_payload: payload["notification"] = notification_payload if data: payload["data"] = data # Attach any additional non falsy keyword args (targets, options) # See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1 payload.update({ k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS) }) # Sort the keys for deterministic output (useful for tests) json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8") # Sends requests and handles the response if cloud_type == "GCM": response = json.loads(_gcm_send( json_payload, "application/json", application_id=application_id )) elif cloud_type == "FCM": response = json.loads(_fcm_send( json_payload, "application/json", application_id=application_id )) else: raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type)) return _cm_handle_response(registration_ids, response, cloud_type, application_id)
[ "def", "_cm_send_request", "(", "registration_ids", ",", "data", ",", "cloud_type", "=", "\"GCM\"", ",", "application_id", "=", "None", ",", "use_fcm_notifications", "=", "True", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "\"registration_ids\"", ":", "registration_ids", "}", "if", "registration_ids", "else", "{", "}", "data", "=", "data", ".", "copy", "(", ")", "# If using FCM, optionnally autodiscovers notification related keys", "# https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages", "if", "cloud_type", "==", "\"FCM\"", "and", "use_fcm_notifications", ":", "notification_payload", "=", "{", "}", "if", "\"message\"", "in", "data", ":", "notification_payload", "[", "\"body\"", "]", "=", "data", ".", "pop", "(", "\"message\"", ",", "None", ")", "for", "key", "in", "FCM_NOTIFICATIONS_PAYLOAD_KEYS", ":", "value_from_extra", "=", "data", ".", "pop", "(", "key", ",", "None", ")", "if", "value_from_extra", ":", "notification_payload", "[", "key", "]", "=", "value_from_extra", "value_from_kwargs", "=", "kwargs", ".", "pop", "(", "key", ",", "None", ")", "if", "value_from_kwargs", ":", "notification_payload", "[", "key", "]", "=", "value_from_kwargs", "if", "notification_payload", ":", "payload", "[", "\"notification\"", "]", "=", "notification_payload", "if", "data", ":", "payload", "[", "\"data\"", "]", "=", "data", "# Attach any additional non falsy keyword args (targets, options)", "# See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1", "payload", ".", "update", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "v", "and", "(", "k", "in", "FCM_TARGETS_KEYS", "or", "k", "in", "FCM_OPTIONS_KEYS", ")", "}", ")", "# Sort the keys for deterministic output (useful for tests)", "json_payload", "=", "json", ".", "dumps", "(", "payload", ",", "separators", "=", "(", "\",\"", ",", "\":\"", ")", ",", "sort_keys", "=", "True", ")", ".", "encode", "(", "\"utf-8\"", ")", "# Sends requests and handles the response", "if", "cloud_type", "==", "\"GCM\"", ":", "response", "=", "json", ".", "loads", "(", "_gcm_send", "(", "json_payload", ",", "\"application/json\"", ",", "application_id", "=", "application_id", ")", ")", "elif", "cloud_type", "==", "\"FCM\"", ":", "response", "=", "json", ".", "loads", "(", "_fcm_send", "(", "json_payload", ",", "\"application/json\"", ",", "application_id", "=", "application_id", ")", ")", "else", ":", "raise", "ImproperlyConfigured", "(", "\"cloud_type must be FCM or GCM not %s\"", "%", "str", "(", "cloud_type", ")", ")", "return", "_cm_handle_response", "(", "registration_ids", ",", "response", ",", "cloud_type", ",", "application_id", ")" ]
Sends a FCM or GCM notification to one or more registration_ids as json data. The registration_ids needs to be a list.
[ "Sends", "a", "FCM", "or", "GCM", "notification", "to", "one", "or", "more", "registration_ids", "as", "json", "data", ".", "The", "registration_ids", "needs", "to", "be", "a", "list", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/gcm.py#L111-L164
228,924
jazzband/django-push-notifications
push_notifications/gcm.py
_cm_handle_canonical_id
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type): """ Handle situation when FCM server response contains canonical ID """ devices = GCMDevice.objects.filter(cloud_message_type=cloud_type) if devices.filter(registration_id=canonical_id, active=True).exists(): devices.filter(registration_id=current_id).update(active=False) else: devices.filter(registration_id=current_id).update(registration_id=canonical_id)
python
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type): """ Handle situation when FCM server response contains canonical ID """ devices = GCMDevice.objects.filter(cloud_message_type=cloud_type) if devices.filter(registration_id=canonical_id, active=True).exists(): devices.filter(registration_id=current_id).update(active=False) else: devices.filter(registration_id=current_id).update(registration_id=canonical_id)
[ "def", "_cm_handle_canonical_id", "(", "canonical_id", ",", "current_id", ",", "cloud_type", ")", ":", "devices", "=", "GCMDevice", ".", "objects", ".", "filter", "(", "cloud_message_type", "=", "cloud_type", ")", "if", "devices", ".", "filter", "(", "registration_id", "=", "canonical_id", ",", "active", "=", "True", ")", ".", "exists", "(", ")", ":", "devices", ".", "filter", "(", "registration_id", "=", "current_id", ")", ".", "update", "(", "active", "=", "False", ")", "else", ":", "devices", ".", "filter", "(", "registration_id", "=", "current_id", ")", ".", "update", "(", "registration_id", "=", "canonical_id", ")" ]
Handle situation when FCM server response contains canonical ID
[ "Handle", "situation", "when", "FCM", "server", "response", "contains", "canonical", "ID" ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/gcm.py#L167-L175
228,925
jazzband/django-push-notifications
push_notifications/conf/app.py
AppConfig._validate_applications
def _validate_applications(self, apps): """Validate the application collection""" for application_id, application_config in apps.items(): self._validate_config(application_id, application_config) application_config["APPLICATION_ID"] = application_id
python
def _validate_applications(self, apps): """Validate the application collection""" for application_id, application_config in apps.items(): self._validate_config(application_id, application_config) application_config["APPLICATION_ID"] = application_id
[ "def", "_validate_applications", "(", "self", ",", "apps", ")", ":", "for", "application_id", ",", "application_config", "in", "apps", ".", "items", "(", ")", ":", "self", ".", "_validate_config", "(", "application_id", ",", "application_config", ")", "application_config", "[", "\"APPLICATION_ID\"", "]", "=", "application_id" ]
Validate the application collection
[ "Validate", "the", "application", "collection" ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L78-L83
228,926
jazzband/django-push-notifications
push_notifications/conf/app.py
AppConfig._validate_apns_certificate
def _validate_apns_certificate(self, certfile): """Validate the APNS certificate at startup.""" try: with open(certfile, "r") as f: content = f.read() check_apns_certificate(content) except Exception as e: raise ImproperlyConfigured( "The APNS certificate file at %r is not readable: %s" % (certfile, e) )
python
def _validate_apns_certificate(self, certfile): """Validate the APNS certificate at startup.""" try: with open(certfile, "r") as f: content = f.read() check_apns_certificate(content) except Exception as e: raise ImproperlyConfigured( "The APNS certificate file at %r is not readable: %s" % (certfile, e) )
[ "def", "_validate_apns_certificate", "(", "self", ",", "certfile", ")", ":", "try", ":", "with", "open", "(", "certfile", ",", "\"r\"", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "check_apns_certificate", "(", "content", ")", "except", "Exception", "as", "e", ":", "raise", "ImproperlyConfigured", "(", "\"The APNS certificate file at %r is not readable: %s\"", "%", "(", "certfile", ",", "e", ")", ")" ]
Validate the APNS certificate at startup.
[ "Validate", "the", "APNS", "certificate", "at", "startup", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L136-L146
228,927
jazzband/django-push-notifications
push_notifications/conf/app.py
AppConfig._validate_allowed_settings
def _validate_allowed_settings(self, application_id, application_config, allowed_settings): """Confirm only allowed settings are present.""" for setting_key in application_config.keys(): if setting_key not in allowed_settings: raise ImproperlyConfigured( "Platform {}, app {} does not support the setting: {}.".format( application_config["PLATFORM"], application_id, setting_key ) )
python
def _validate_allowed_settings(self, application_id, application_config, allowed_settings): """Confirm only allowed settings are present.""" for setting_key in application_config.keys(): if setting_key not in allowed_settings: raise ImproperlyConfigured( "Platform {}, app {} does not support the setting: {}.".format( application_config["PLATFORM"], application_id, setting_key ) )
[ "def", "_validate_allowed_settings", "(", "self", ",", "application_id", ",", "application_config", ",", "allowed_settings", ")", ":", "for", "setting_key", "in", "application_config", ".", "keys", "(", ")", ":", "if", "setting_key", "not", "in", "allowed_settings", ":", "raise", "ImproperlyConfigured", "(", "\"Platform {}, app {} does not support the setting: {}.\"", ".", "format", "(", "application_config", "[", "\"PLATFORM\"", "]", ",", "application_id", ",", "setting_key", ")", ")" ]
Confirm only allowed settings are present.
[ "Confirm", "only", "allowed", "settings", "are", "present", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L203-L212
228,928
jazzband/django-push-notifications
push_notifications/conf/app.py
AppConfig._validate_required_settings
def _validate_required_settings( self, application_id, application_config, required_settings ): """All required keys must be present""" for setting_key in required_settings: if setting_key not in application_config.keys(): raise ImproperlyConfigured( MISSING_SETTING.format( application_id=application_id, setting=setting_key ) )
python
def _validate_required_settings( self, application_id, application_config, required_settings ): """All required keys must be present""" for setting_key in required_settings: if setting_key not in application_config.keys(): raise ImproperlyConfigured( MISSING_SETTING.format( application_id=application_id, setting=setting_key ) )
[ "def", "_validate_required_settings", "(", "self", ",", "application_id", ",", "application_config", ",", "required_settings", ")", ":", "for", "setting_key", "in", "required_settings", ":", "if", "setting_key", "not", "in", "application_config", ".", "keys", "(", ")", ":", "raise", "ImproperlyConfigured", "(", "MISSING_SETTING", ".", "format", "(", "application_id", "=", "application_id", ",", "setting", "=", "setting_key", ")", ")" ]
All required keys must be present
[ "All", "required", "keys", "must", "be", "present" ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L214-L225
228,929
jazzband/django-push-notifications
push_notifications/conf/app.py
AppConfig._get_application_settings
def _get_application_settings(self, application_id, platform, settings_key): """ Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value or raises ImproperlyConfigured. """ if not application_id: conf_cls = "push_notifications.conf.AppConfig" raise ImproperlyConfigured( "{} requires the application_id be specified at all times.".format(conf_cls) ) # verify that the application config exists app_config = self._settings.get("APPLICATIONS").get(application_id, None) if app_config is None: raise ImproperlyConfigured( "No application configured with application_id: {}.".format(application_id) ) # fetch a setting for the incorrect type of platform if app_config.get("PLATFORM") != platform: raise ImproperlyConfigured( SETTING_MISMATCH.format( application_id=application_id, platform=app_config.get("PLATFORM"), setting=settings_key ) ) # finally, try to fetch the setting if settings_key not in app_config: raise ImproperlyConfigured( MISSING_SETTING.format( application_id=application_id, setting=settings_key ) ) return app_config.get(settings_key)
python
def _get_application_settings(self, application_id, platform, settings_key): """ Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value or raises ImproperlyConfigured. """ if not application_id: conf_cls = "push_notifications.conf.AppConfig" raise ImproperlyConfigured( "{} requires the application_id be specified at all times.".format(conf_cls) ) # verify that the application config exists app_config = self._settings.get("APPLICATIONS").get(application_id, None) if app_config is None: raise ImproperlyConfigured( "No application configured with application_id: {}.".format(application_id) ) # fetch a setting for the incorrect type of platform if app_config.get("PLATFORM") != platform: raise ImproperlyConfigured( SETTING_MISMATCH.format( application_id=application_id, platform=app_config.get("PLATFORM"), setting=settings_key ) ) # finally, try to fetch the setting if settings_key not in app_config: raise ImproperlyConfigured( MISSING_SETTING.format( application_id=application_id, setting=settings_key ) ) return app_config.get(settings_key)
[ "def", "_get_application_settings", "(", "self", ",", "application_id", ",", "platform", ",", "settings_key", ")", ":", "if", "not", "application_id", ":", "conf_cls", "=", "\"push_notifications.conf.AppConfig\"", "raise", "ImproperlyConfigured", "(", "\"{} requires the application_id be specified at all times.\"", ".", "format", "(", "conf_cls", ")", ")", "# verify that the application config exists", "app_config", "=", "self", ".", "_settings", ".", "get", "(", "\"APPLICATIONS\"", ")", ".", "get", "(", "application_id", ",", "None", ")", "if", "app_config", "is", "None", ":", "raise", "ImproperlyConfigured", "(", "\"No application configured with application_id: {}.\"", ".", "format", "(", "application_id", ")", ")", "# fetch a setting for the incorrect type of platform", "if", "app_config", ".", "get", "(", "\"PLATFORM\"", ")", "!=", "platform", ":", "raise", "ImproperlyConfigured", "(", "SETTING_MISMATCH", ".", "format", "(", "application_id", "=", "application_id", ",", "platform", "=", "app_config", ".", "get", "(", "\"PLATFORM\"", ")", ",", "setting", "=", "settings_key", ")", ")", "# finally, try to fetch the setting", "if", "settings_key", "not", "in", "app_config", ":", "raise", "ImproperlyConfigured", "(", "MISSING_SETTING", ".", "format", "(", "application_id", "=", "application_id", ",", "setting", "=", "settings_key", ")", ")", "return", "app_config", ".", "get", "(", "settings_key", ")" ]
Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value or raises ImproperlyConfigured.
[ "Walks", "through", "PUSH_NOTIFICATIONS_SETTINGS", "to", "find", "the", "correct", "setting", "value", "or", "raises", "ImproperlyConfigured", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/conf/app.py#L227-L264
228,930
jazzband/django-push-notifications
push_notifications/wns.py
_wns_authenticate
def _wns_authenticate(scope="notify.windows.com", application_id=None): """ Requests an Access token for WNS communication. :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'} """ client_id = get_manager().get_wns_package_security_id(application_id) client_secret = get_manager().get_wns_secret_key(application_id) if not client_id: raise ImproperlyConfigured( 'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.' ) if not client_secret: raise ImproperlyConfigured( 'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.' ) headers = { "Content-Type": "application/x-www-form-urlencoded", } params = { "grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret, "scope": scope, } data = urlencode(params).encode("utf-8") request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers) try: response = urlopen(request) except HTTPError as err: if err.code == 400: # One of your settings is probably jacked up. # https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245 raise WNSAuthenticationError("Authentication failed, check your WNS settings.") raise err oauth_data = response.read().decode("utf-8") try: oauth_data = json.loads(oauth_data) except Exception: # Upstream WNS issue raise WNSAuthenticationError("Received invalid JSON data from WNS.") access_token = oauth_data.get("access_token") if not access_token: # Upstream WNS issue raise WNSAuthenticationError("Access token missing from WNS response.") return access_token
python
def _wns_authenticate(scope="notify.windows.com", application_id=None): """ Requests an Access token for WNS communication. :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'} """ client_id = get_manager().get_wns_package_security_id(application_id) client_secret = get_manager().get_wns_secret_key(application_id) if not client_id: raise ImproperlyConfigured( 'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_PACKAGE_SECURITY_ID"] to use WNS.' ) if not client_secret: raise ImproperlyConfigured( 'You need to set PUSH_NOTIFICATIONS_SETTINGS["WNS_SECRET_KEY"] to use WNS.' ) headers = { "Content-Type": "application/x-www-form-urlencoded", } params = { "grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret, "scope": scope, } data = urlencode(params).encode("utf-8") request = Request(SETTINGS["WNS_ACCESS_URL"], data=data, headers=headers) try: response = urlopen(request) except HTTPError as err: if err.code == 400: # One of your settings is probably jacked up. # https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245 raise WNSAuthenticationError("Authentication failed, check your WNS settings.") raise err oauth_data = response.read().decode("utf-8") try: oauth_data = json.loads(oauth_data) except Exception: # Upstream WNS issue raise WNSAuthenticationError("Received invalid JSON data from WNS.") access_token = oauth_data.get("access_token") if not access_token: # Upstream WNS issue raise WNSAuthenticationError("Access token missing from WNS response.") return access_token
[ "def", "_wns_authenticate", "(", "scope", "=", "\"notify.windows.com\"", ",", "application_id", "=", "None", ")", ":", "client_id", "=", "get_manager", "(", ")", ".", "get_wns_package_security_id", "(", "application_id", ")", "client_secret", "=", "get_manager", "(", ")", ".", "get_wns_secret_key", "(", "application_id", ")", "if", "not", "client_id", ":", "raise", "ImproperlyConfigured", "(", "'You need to set PUSH_NOTIFICATIONS_SETTINGS[\"WNS_PACKAGE_SECURITY_ID\"] to use WNS.'", ")", "if", "not", "client_secret", ":", "raise", "ImproperlyConfigured", "(", "'You need to set PUSH_NOTIFICATIONS_SETTINGS[\"WNS_SECRET_KEY\"] to use WNS.'", ")", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "}", "params", "=", "{", "\"grant_type\"", ":", "\"client_credentials\"", ",", "\"client_id\"", ":", "client_id", ",", "\"client_secret\"", ":", "client_secret", ",", "\"scope\"", ":", "scope", ",", "}", "data", "=", "urlencode", "(", "params", ")", ".", "encode", "(", "\"utf-8\"", ")", "request", "=", "Request", "(", "SETTINGS", "[", "\"WNS_ACCESS_URL\"", "]", ",", "data", "=", "data", ",", "headers", "=", "headers", ")", "try", ":", "response", "=", "urlopen", "(", "request", ")", "except", "HTTPError", "as", "err", ":", "if", "err", ".", "code", "==", "400", ":", "# One of your settings is probably jacked up.", "# https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868245", "raise", "WNSAuthenticationError", "(", "\"Authentication failed, check your WNS settings.\"", ")", "raise", "err", "oauth_data", "=", "response", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "try", ":", "oauth_data", "=", "json", ".", "loads", "(", "oauth_data", ")", "except", "Exception", ":", "# Upstream WNS issue", "raise", "WNSAuthenticationError", "(", "\"Received invalid JSON data from WNS.\"", ")", "access_token", "=", "oauth_data", ".", "get", "(", "\"access_token\"", ")", "if", "not", "access_token", ":", "# Upstream WNS issue", "raise", "WNSAuthenticationError", "(", "\"Access token missing from WNS response.\"", ")", "return", "access_token" ]
Requests an Access token for WNS communication. :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'}
[ "Requests", "an", "Access", "token", "for", "WNS", "communication", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L31-L82
228,931
jazzband/django-push-notifications
push_notifications/wns.py
_wns_send
def _wns_send(uri, data, wns_type="wns/toast", application_id=None): """ Sends a notification data and authentication to WNS. :param uri: str: The device's unique notification URI :param data: dict: The notification data to be sent. :return: """ access_token = _wns_authenticate(application_id=application_id) content_type = "text/xml" if wns_type == "wns/raw": content_type = "application/octet-stream" headers = { # content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw) "Content-Type": content_type, "Authorization": "Bearer %s" % (access_token), "X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw } if type(data) is str: data = data.encode("utf-8") request = Request(uri, data, headers) # A lot of things can happen, let them know which one. try: response = urlopen(request) except HTTPError as err: if err.code == 400: msg = "One or more headers were specified incorrectly or conflict with another header." elif err.code == 401: msg = "The cloud service did not present a valid authentication ticket." elif err.code == 403: msg = "The cloud service is not authorized to send a notification to this URI." elif err.code == 404: msg = "The channel URI is not valid or is not recognized by WNS." elif err.code == 405: msg = "Invalid method. Only POST or DELETE is allowed." elif err.code == 406: msg = "The cloud service exceeded its throttle limit" elif err.code == 410: msg = "The channel expired." elif err.code == 413: msg = "The notification payload exceeds the 500 byte limit." elif err.code == 500: msg = "An internal failure caused notification delivery to fail." elif err.code == 503: msg = "The server is currently unavailable." else: raise err raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg)) return response.read().decode("utf-8")
python
def _wns_send(uri, data, wns_type="wns/toast", application_id=None): """ Sends a notification data and authentication to WNS. :param uri: str: The device's unique notification URI :param data: dict: The notification data to be sent. :return: """ access_token = _wns_authenticate(application_id=application_id) content_type = "text/xml" if wns_type == "wns/raw": content_type = "application/octet-stream" headers = { # content_type is "text/xml" (toast/badge/tile) | "application/octet-stream" (raw) "Content-Type": content_type, "Authorization": "Bearer %s" % (access_token), "X-WNS-Type": wns_type, # wns/toast | wns/badge | wns/tile | wns/raw } if type(data) is str: data = data.encode("utf-8") request = Request(uri, data, headers) # A lot of things can happen, let them know which one. try: response = urlopen(request) except HTTPError as err: if err.code == 400: msg = "One or more headers were specified incorrectly or conflict with another header." elif err.code == 401: msg = "The cloud service did not present a valid authentication ticket." elif err.code == 403: msg = "The cloud service is not authorized to send a notification to this URI." elif err.code == 404: msg = "The channel URI is not valid or is not recognized by WNS." elif err.code == 405: msg = "Invalid method. Only POST or DELETE is allowed." elif err.code == 406: msg = "The cloud service exceeded its throttle limit" elif err.code == 410: msg = "The channel expired." elif err.code == 413: msg = "The notification payload exceeds the 500 byte limit." elif err.code == 500: msg = "An internal failure caused notification delivery to fail." elif err.code == 503: msg = "The server is currently unavailable." else: raise err raise WNSNotificationResponseError("HTTP %i: %s" % (err.code, msg)) return response.read().decode("utf-8")
[ "def", "_wns_send", "(", "uri", ",", "data", ",", "wns_type", "=", "\"wns/toast\"", ",", "application_id", "=", "None", ")", ":", "access_token", "=", "_wns_authenticate", "(", "application_id", "=", "application_id", ")", "content_type", "=", "\"text/xml\"", "if", "wns_type", "==", "\"wns/raw\"", ":", "content_type", "=", "\"application/octet-stream\"", "headers", "=", "{", "# content_type is \"text/xml\" (toast/badge/tile) | \"application/octet-stream\" (raw)", "\"Content-Type\"", ":", "content_type", ",", "\"Authorization\"", ":", "\"Bearer %s\"", "%", "(", "access_token", ")", ",", "\"X-WNS-Type\"", ":", "wns_type", ",", "# wns/toast | wns/badge | wns/tile | wns/raw", "}", "if", "type", "(", "data", ")", "is", "str", ":", "data", "=", "data", ".", "encode", "(", "\"utf-8\"", ")", "request", "=", "Request", "(", "uri", ",", "data", ",", "headers", ")", "# A lot of things can happen, let them know which one.", "try", ":", "response", "=", "urlopen", "(", "request", ")", "except", "HTTPError", "as", "err", ":", "if", "err", ".", "code", "==", "400", ":", "msg", "=", "\"One or more headers were specified incorrectly or conflict with another header.\"", "elif", "err", ".", "code", "==", "401", ":", "msg", "=", "\"The cloud service did not present a valid authentication ticket.\"", "elif", "err", ".", "code", "==", "403", ":", "msg", "=", "\"The cloud service is not authorized to send a notification to this URI.\"", "elif", "err", ".", "code", "==", "404", ":", "msg", "=", "\"The channel URI is not valid or is not recognized by WNS.\"", "elif", "err", ".", "code", "==", "405", ":", "msg", "=", "\"Invalid method. Only POST or DELETE is allowed.\"", "elif", "err", ".", "code", "==", "406", ":", "msg", "=", "\"The cloud service exceeded its throttle limit\"", "elif", "err", ".", "code", "==", "410", ":", "msg", "=", "\"The channel expired.\"", "elif", "err", ".", "code", "==", "413", ":", "msg", "=", "\"The notification payload exceeds the 500 byte limit.\"", "elif", "err", ".", "code", "==", "500", ":", "msg", "=", "\"An internal failure caused notification delivery to fail.\"", "elif", "err", ".", "code", "==", "503", ":", "msg", "=", "\"The server is currently unavailable.\"", "else", ":", "raise", "err", "raise", "WNSNotificationResponseError", "(", "\"HTTP %i: %s\"", "%", "(", "err", ".", "code", ",", "msg", ")", ")", "return", "response", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")" ]
Sends a notification data and authentication to WNS. :param uri: str: The device's unique notification URI :param data: dict: The notification data to be sent. :return:
[ "Sends", "a", "notification", "data", "and", "authentication", "to", "WNS", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L85-L139
228,932
jazzband/django-push-notifications
push_notifications/wns.py
_wns_prepare_toast
def _wns_prepare_toast(data, **kwargs): """ Creates the xml tree for a `toast` notification :param data: dict: The notification data to be converted to an xml tree. { "text": ["Title text", "Message Text", "Another message!"], "image": ["src1", "src2"], } :return: str """ root = ET.Element("toast") visual = ET.SubElement(root, "visual") binding = ET.SubElement(visual, "binding") binding.attrib["template"] = kwargs.pop("template", "ToastText01") if "text" in data: for count, item in enumerate(data["text"], start=1): elem = ET.SubElement(binding, "text") elem.text = item elem.attrib["id"] = str(count) if "image" in data: for count, item in enumerate(data["image"], start=1): elem = ET.SubElement(binding, "img") elem.attrib["src"] = item elem.attrib["id"] = str(count) return ET.tostring(root)
python
def _wns_prepare_toast(data, **kwargs): """ Creates the xml tree for a `toast` notification :param data: dict: The notification data to be converted to an xml tree. { "text": ["Title text", "Message Text", "Another message!"], "image": ["src1", "src2"], } :return: str """ root = ET.Element("toast") visual = ET.SubElement(root, "visual") binding = ET.SubElement(visual, "binding") binding.attrib["template"] = kwargs.pop("template", "ToastText01") if "text" in data: for count, item in enumerate(data["text"], start=1): elem = ET.SubElement(binding, "text") elem.text = item elem.attrib["id"] = str(count) if "image" in data: for count, item in enumerate(data["image"], start=1): elem = ET.SubElement(binding, "img") elem.attrib["src"] = item elem.attrib["id"] = str(count) return ET.tostring(root)
[ "def", "_wns_prepare_toast", "(", "data", ",", "*", "*", "kwargs", ")", ":", "root", "=", "ET", ".", "Element", "(", "\"toast\"", ")", "visual", "=", "ET", ".", "SubElement", "(", "root", ",", "\"visual\"", ")", "binding", "=", "ET", ".", "SubElement", "(", "visual", ",", "\"binding\"", ")", "binding", ".", "attrib", "[", "\"template\"", "]", "=", "kwargs", ".", "pop", "(", "\"template\"", ",", "\"ToastText01\"", ")", "if", "\"text\"", "in", "data", ":", "for", "count", ",", "item", "in", "enumerate", "(", "data", "[", "\"text\"", "]", ",", "start", "=", "1", ")", ":", "elem", "=", "ET", ".", "SubElement", "(", "binding", ",", "\"text\"", ")", "elem", ".", "text", "=", "item", "elem", ".", "attrib", "[", "\"id\"", "]", "=", "str", "(", "count", ")", "if", "\"image\"", "in", "data", ":", "for", "count", ",", "item", "in", "enumerate", "(", "data", "[", "\"image\"", "]", ",", "start", "=", "1", ")", ":", "elem", "=", "ET", ".", "SubElement", "(", "binding", ",", "\"img\"", ")", "elem", ".", "attrib", "[", "\"src\"", "]", "=", "item", "elem", ".", "attrib", "[", "\"id\"", "]", "=", "str", "(", "count", ")", "return", "ET", ".", "tostring", "(", "root", ")" ]
Creates the xml tree for a `toast` notification :param data: dict: The notification data to be converted to an xml tree. { "text": ["Title text", "Message Text", "Another message!"], "image": ["src1", "src2"], } :return: str
[ "Creates", "the", "xml", "tree", "for", "a", "toast", "notification" ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L142-L169
228,933
jazzband/django-push-notifications
push_notifications/wns.py
wns_send_bulk_message
def wns_send_bulk_message( uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs ): """ WNS doesn't support bulk notification, so we loop through each uri. :param uri_list: list: A list of uris the notification will be sent to. :param message: str: The notification data to be sent. :param xml_data: dict: A dictionary containing data to be converted to an xml tree. :param raw_data: str: Data to be sent via a `raw` notification. """ res = [] if uri_list: for uri in uri_list: r = wns_send_message( uri=uri, message=message, xml_data=xml_data, raw_data=raw_data, application_id=application_id, **kwargs ) res.append(r) return res
python
def wns_send_bulk_message( uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs ): """ WNS doesn't support bulk notification, so we loop through each uri. :param uri_list: list: A list of uris the notification will be sent to. :param message: str: The notification data to be sent. :param xml_data: dict: A dictionary containing data to be converted to an xml tree. :param raw_data: str: Data to be sent via a `raw` notification. """ res = [] if uri_list: for uri in uri_list: r = wns_send_message( uri=uri, message=message, xml_data=xml_data, raw_data=raw_data, application_id=application_id, **kwargs ) res.append(r) return res
[ "def", "wns_send_bulk_message", "(", "uri_list", ",", "message", "=", "None", ",", "xml_data", "=", "None", ",", "raw_data", "=", "None", ",", "application_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "res", "=", "[", "]", "if", "uri_list", ":", "for", "uri", "in", "uri_list", ":", "r", "=", "wns_send_message", "(", "uri", "=", "uri", ",", "message", "=", "message", ",", "xml_data", "=", "xml_data", ",", "raw_data", "=", "raw_data", ",", "application_id", "=", "application_id", ",", "*", "*", "kwargs", ")", "res", ".", "append", "(", "r", ")", "return", "res" ]
WNS doesn't support bulk notification, so we loop through each uri. :param uri_list: list: A list of uris the notification will be sent to. :param message: str: The notification data to be sent. :param xml_data: dict: A dictionary containing data to be converted to an xml tree. :param raw_data: str: Data to be sent via a `raw` notification.
[ "WNS", "doesn", "t", "support", "bulk", "notification", "so", "we", "loop", "through", "each", "uri", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L237-L256
228,934
jazzband/django-push-notifications
push_notifications/wns.py
_add_sub_elements_from_dict
def _add_sub_elements_from_dict(parent, sub_dict): """ Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"example": { "attrs": { "key1": "value1", ... }, ... }} """ for key, value in sub_dict.items(): if isinstance(value, list): for repeated_element in value: sub_element = ET.SubElement(parent, key) _add_element_attrs(sub_element, repeated_element.get("attrs", {})) children = repeated_element.get("children", None) if isinstance(children, dict): _add_sub_elements_from_dict(sub_element, children) elif isinstance(children, str): sub_element.text = children else: sub_element = ET.SubElement(parent, key) _add_element_attrs(sub_element, value.get("attrs", {})) children = value.get("children", None) if isinstance(children, dict): _add_sub_elements_from_dict(sub_element, children) elif isinstance(children, str): sub_element.text = children
python
def _add_sub_elements_from_dict(parent, sub_dict): """ Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"example": { "attrs": { "key1": "value1", ... }, ... }} """ for key, value in sub_dict.items(): if isinstance(value, list): for repeated_element in value: sub_element = ET.SubElement(parent, key) _add_element_attrs(sub_element, repeated_element.get("attrs", {})) children = repeated_element.get("children", None) if isinstance(children, dict): _add_sub_elements_from_dict(sub_element, children) elif isinstance(children, str): sub_element.text = children else: sub_element = ET.SubElement(parent, key) _add_element_attrs(sub_element, value.get("attrs", {})) children = value.get("children", None) if isinstance(children, dict): _add_sub_elements_from_dict(sub_element, children) elif isinstance(children, str): sub_element.text = children
[ "def", "_add_sub_elements_from_dict", "(", "parent", ",", "sub_dict", ")", ":", "for", "key", ",", "value", "in", "sub_dict", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "repeated_element", "in", "value", ":", "sub_element", "=", "ET", ".", "SubElement", "(", "parent", ",", "key", ")", "_add_element_attrs", "(", "sub_element", ",", "repeated_element", ".", "get", "(", "\"attrs\"", ",", "{", "}", ")", ")", "children", "=", "repeated_element", ".", "get", "(", "\"children\"", ",", "None", ")", "if", "isinstance", "(", "children", ",", "dict", ")", ":", "_add_sub_elements_from_dict", "(", "sub_element", ",", "children", ")", "elif", "isinstance", "(", "children", ",", "str", ")", ":", "sub_element", ".", "text", "=", "children", "else", ":", "sub_element", "=", "ET", ".", "SubElement", "(", "parent", ",", "key", ")", "_add_element_attrs", "(", "sub_element", ",", "value", ".", "get", "(", "\"attrs\"", ",", "{", "}", ")", ")", "children", "=", "value", ".", "get", "(", "\"children\"", ",", "None", ")", "if", "isinstance", "(", "children", ",", "dict", ")", ":", "_add_sub_elements_from_dict", "(", "sub_element", ",", "children", ")", "elif", "isinstance", "(", "children", ",", "str", ")", ":", "sub_element", ".", "text", "=", "children" ]
Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"example": { "attrs": { "key1": "value1", ... }, ... }}
[ "Add", "SubElements", "to", "the", "parent", "element", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L325-L357
228,935
jazzband/django-push-notifications
push_notifications/wns.py
_add_element_attrs
def _add_element_attrs(elem, attrs): """ Add attributes to the given element. :param elem: ElementTree.Element: The element the attributes are being added to. :param attrs: dict: A dictionary of attributes. e.g.: {"attribute1": "value", "attribute2": "another"} :return: ElementTree.Element """ for attr, value in attrs.items(): elem.attrib[attr] = value return elem
python
def _add_element_attrs(elem, attrs): """ Add attributes to the given element. :param elem: ElementTree.Element: The element the attributes are being added to. :param attrs: dict: A dictionary of attributes. e.g.: {"attribute1": "value", "attribute2": "another"} :return: ElementTree.Element """ for attr, value in attrs.items(): elem.attrib[attr] = value return elem
[ "def", "_add_element_attrs", "(", "elem", ",", "attrs", ")", ":", "for", "attr", ",", "value", "in", "attrs", ".", "items", "(", ")", ":", "elem", ".", "attrib", "[", "attr", "]", "=", "value", "return", "elem" ]
Add attributes to the given element. :param elem: ElementTree.Element: The element the attributes are being added to. :param attrs: dict: A dictionary of attributes. e.g.: {"attribute1": "value", "attribute2": "another"} :return: ElementTree.Element
[ "Add", "attributes", "to", "the", "given", "element", "." ]
c4a0d710711fa27bfb6533c0bf3468cb67a62679
https://github.com/jazzband/django-push-notifications/blob/c4a0d710711fa27bfb6533c0bf3468cb67a62679/push_notifications/wns.py#L360-L371
228,936
skydive-project/skydive
contrib/python/api/skydive/websocket/client.py
WSClient.login
def login(self, host_spec="", username="", password=""): """ Authenticate with infrastructure via the Skydive analyzer This method will also set the authentication cookie to be used in the future requests :param host_spec: Host IP and port (e.g. 192.168.10.1:8082) :type host_spec: string :param username: Username to use for login :type username: string :param password: Password to use for login :type password: string :return: True on successful authentication, False otherwise """ warnings.warn( "shouldn't use this function anymore ! use connect which handles" "handles authentication directly.", DeprecationWarning ) scheme = "http" if not host_spec: u = urlparse(self.endpoint) host_spec = u.netloc if u.scheme == "wss": scheme = "https" if self.username: username = self.username if self.password: password = self.password auth = Authenticate(host_spec, scheme=scheme, username=username, password=password) try: auth.login() cookie = 'authtok={}'.format(auth.authtok) if self.cookies: self.cookies.append(cookie) else: self.cookies = [cookie, ] return True except Exception: return False
python
def login(self, host_spec="", username="", password=""): """ Authenticate with infrastructure via the Skydive analyzer This method will also set the authentication cookie to be used in the future requests :param host_spec: Host IP and port (e.g. 192.168.10.1:8082) :type host_spec: string :param username: Username to use for login :type username: string :param password: Password to use for login :type password: string :return: True on successful authentication, False otherwise """ warnings.warn( "shouldn't use this function anymore ! use connect which handles" "handles authentication directly.", DeprecationWarning ) scheme = "http" if not host_spec: u = urlparse(self.endpoint) host_spec = u.netloc if u.scheme == "wss": scheme = "https" if self.username: username = self.username if self.password: password = self.password auth = Authenticate(host_spec, scheme=scheme, username=username, password=password) try: auth.login() cookie = 'authtok={}'.format(auth.authtok) if self.cookies: self.cookies.append(cookie) else: self.cookies = [cookie, ] return True except Exception: return False
[ "def", "login", "(", "self", ",", "host_spec", "=", "\"\"", ",", "username", "=", "\"\"", ",", "password", "=", "\"\"", ")", ":", "warnings", ".", "warn", "(", "\"shouldn't use this function anymore ! use connect which handles\"", "\"handles authentication directly.\"", ",", "DeprecationWarning", ")", "scheme", "=", "\"http\"", "if", "not", "host_spec", ":", "u", "=", "urlparse", "(", "self", ".", "endpoint", ")", "host_spec", "=", "u", ".", "netloc", "if", "u", ".", "scheme", "==", "\"wss\"", ":", "scheme", "=", "\"https\"", "if", "self", ".", "username", ":", "username", "=", "self", ".", "username", "if", "self", ".", "password", ":", "password", "=", "self", ".", "password", "auth", "=", "Authenticate", "(", "host_spec", ",", "scheme", "=", "scheme", ",", "username", "=", "username", ",", "password", "=", "password", ")", "try", ":", "auth", ".", "login", "(", ")", "cookie", "=", "'authtok={}'", ".", "format", "(", "auth", ".", "authtok", ")", "if", "self", ".", "cookies", ":", "self", ".", "cookies", ".", "append", "(", "cookie", ")", "else", ":", "self", ".", "cookies", "=", "[", "cookie", ",", "]", "return", "True", "except", "Exception", ":", "return", "False" ]
Authenticate with infrastructure via the Skydive analyzer This method will also set the authentication cookie to be used in the future requests :param host_spec: Host IP and port (e.g. 192.168.10.1:8082) :type host_spec: string :param username: Username to use for login :type username: string :param password: Password to use for login :type password: string :return: True on successful authentication, False otherwise
[ "Authenticate", "with", "infrastructure", "via", "the", "Skydive", "analyzer" ]
9a68cc2213bb2f756fbf27a13f060805f2a47025
https://github.com/skydive-project/skydive/blob/9a68cc2213bb2f756fbf27a13f060805f2a47025/contrib/python/api/skydive/websocket/client.py#L228-L270
228,937
kivy/buildozer
buildozer/targets/android.py
TargetAndroid._sdkmanager
def _sdkmanager(self, *args, **kwargs): """Call the sdkmanager in our Android SDK with the given arguments.""" # Use the android-sdk dir as cwd by default kwargs['cwd'] = kwargs.get('cwd', self.android_sdk_dir) command = self.sdkmanager_path + ' ' + ' '.join(args) return_child = kwargs.pop('return_child', False) if return_child: return self.buildozer.cmd_expect(command, **kwargs) else: kwargs['get_stdout'] = kwargs.get('get_stdout', True) return self.buildozer.cmd(command, **kwargs)
python
def _sdkmanager(self, *args, **kwargs): """Call the sdkmanager in our Android SDK with the given arguments.""" # Use the android-sdk dir as cwd by default kwargs['cwd'] = kwargs.get('cwd', self.android_sdk_dir) command = self.sdkmanager_path + ' ' + ' '.join(args) return_child = kwargs.pop('return_child', False) if return_child: return self.buildozer.cmd_expect(command, **kwargs) else: kwargs['get_stdout'] = kwargs.get('get_stdout', True) return self.buildozer.cmd(command, **kwargs)
[ "def", "_sdkmanager", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Use the android-sdk dir as cwd by default", "kwargs", "[", "'cwd'", "]", "=", "kwargs", ".", "get", "(", "'cwd'", ",", "self", ".", "android_sdk_dir", ")", "command", "=", "self", ".", "sdkmanager_path", "+", "' '", "+", "' '", ".", "join", "(", "args", ")", "return_child", "=", "kwargs", ".", "pop", "(", "'return_child'", ",", "False", ")", "if", "return_child", ":", "return", "self", ".", "buildozer", ".", "cmd_expect", "(", "command", ",", "*", "*", "kwargs", ")", "else", ":", "kwargs", "[", "'get_stdout'", "]", "=", "kwargs", ".", "get", "(", "'get_stdout'", ",", "True", ")", "return", "self", ".", "buildozer", ".", "cmd", "(", "command", ",", "*", "*", "kwargs", ")" ]
Call the sdkmanager in our Android SDK with the given arguments.
[ "Call", "the", "sdkmanager", "in", "our", "Android", "SDK", "with", "the", "given", "arguments", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/android.py#L98-L108
228,938
kivy/buildozer
buildozer/targets/android.py
TargetAndroid._android_get_installed_platform_tools_version
def _android_get_installed_platform_tools_version(self): """ Crudely parse out the installed platform-tools version """ platform_tools_dir = os.path.join( self.android_sdk_dir, 'platform-tools') if not os.path.exists(platform_tools_dir): return None data_file = os.path.join(platform_tools_dir, 'source.properties') if not os.path.exists(data_file): return None with open(data_file, 'r') as fileh: lines = fileh.readlines() for line in lines: if line.startswith('Pkg.Revision='): break else: self.buildozer.error('Read {} but found no Pkg.Revision'.format(data_file)) # Don't actually exit, in case the build env is # okay. Something else will fault if it's important. return None revision = line.split('=')[1].strip() return revision
python
def _android_get_installed_platform_tools_version(self): """ Crudely parse out the installed platform-tools version """ platform_tools_dir = os.path.join( self.android_sdk_dir, 'platform-tools') if not os.path.exists(platform_tools_dir): return None data_file = os.path.join(platform_tools_dir, 'source.properties') if not os.path.exists(data_file): return None with open(data_file, 'r') as fileh: lines = fileh.readlines() for line in lines: if line.startswith('Pkg.Revision='): break else: self.buildozer.error('Read {} but found no Pkg.Revision'.format(data_file)) # Don't actually exit, in case the build env is # okay. Something else will fault if it's important. return None revision = line.split('=')[1].strip() return revision
[ "def", "_android_get_installed_platform_tools_version", "(", "self", ")", ":", "platform_tools_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "android_sdk_dir", ",", "'platform-tools'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "platform_tools_dir", ")", ":", "return", "None", "data_file", "=", "os", ".", "path", ".", "join", "(", "platform_tools_dir", ",", "'source.properties'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "data_file", ")", ":", "return", "None", "with", "open", "(", "data_file", ",", "'r'", ")", "as", "fileh", ":", "lines", "=", "fileh", ".", "readlines", "(", ")", "for", "line", "in", "lines", ":", "if", "line", ".", "startswith", "(", "'Pkg.Revision='", ")", ":", "break", "else", ":", "self", ".", "buildozer", ".", "error", "(", "'Read {} but found no Pkg.Revision'", ".", "format", "(", "data_file", ")", ")", "# Don't actually exit, in case the build env is", "# okay. Something else will fault if it's important.", "return", "None", "revision", "=", "line", ".", "split", "(", "'='", ")", "[", "1", "]", ".", "strip", "(", ")", "return", "revision" ]
Crudely parse out the installed platform-tools version
[ "Crudely", "parse", "out", "the", "installed", "platform", "-", "tools", "version" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/android.py#L424-L454
228,939
kivy/buildozer
buildozer/targets/android.py
TargetAndroid._android_update_sdk
def _android_update_sdk(self, *sdkmanager_commands): """Update the tools and package-tools if possible""" auto_accept_license = self.buildozer.config.getbooldefault( 'app', 'android.accept_sdk_license', False) if auto_accept_license: # `SIGPIPE` is not being reported somehow, but `EPIPE` is. # This leads to a stderr "Broken pipe" message which is harmless, # but doesn't look good on terminal, hence redirecting to /dev/null yes_command = 'yes 2>/dev/null' command = '{} | {} --licenses'.format( yes_command, self.sdkmanager_path) self.buildozer.cmd(command, cwd=self.android_sdk_dir) self._sdkmanager(*sdkmanager_commands)
python
def _android_update_sdk(self, *sdkmanager_commands): """Update the tools and package-tools if possible""" auto_accept_license = self.buildozer.config.getbooldefault( 'app', 'android.accept_sdk_license', False) if auto_accept_license: # `SIGPIPE` is not being reported somehow, but `EPIPE` is. # This leads to a stderr "Broken pipe" message which is harmless, # but doesn't look good on terminal, hence redirecting to /dev/null yes_command = 'yes 2>/dev/null' command = '{} | {} --licenses'.format( yes_command, self.sdkmanager_path) self.buildozer.cmd(command, cwd=self.android_sdk_dir) self._sdkmanager(*sdkmanager_commands)
[ "def", "_android_update_sdk", "(", "self", ",", "*", "sdkmanager_commands", ")", ":", "auto_accept_license", "=", "self", ".", "buildozer", ".", "config", ".", "getbooldefault", "(", "'app'", ",", "'android.accept_sdk_license'", ",", "False", ")", "if", "auto_accept_license", ":", "# `SIGPIPE` is not being reported somehow, but `EPIPE` is.", "# This leads to a stderr \"Broken pipe\" message which is harmless,", "# but doesn't look good on terminal, hence redirecting to /dev/null", "yes_command", "=", "'yes 2>/dev/null'", "command", "=", "'{} | {} --licenses'", ".", "format", "(", "yes_command", ",", "self", ".", "sdkmanager_path", ")", "self", ".", "buildozer", ".", "cmd", "(", "command", ",", "cwd", "=", "self", ".", "android_sdk_dir", ")", "self", ".", "_sdkmanager", "(", "*", "sdkmanager_commands", ")" ]
Update the tools and package-tools if possible
[ "Update", "the", "tools", "and", "package", "-", "tools", "if", "possible" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/android.py#L457-L470
228,940
kivy/buildozer
buildozer/targets/android.py
TargetAndroid.cmd_logcat
def cmd_logcat(self, *args): '''Show the log from the device ''' self.check_requirements() serial = self.serials[0:] if not serial: return filters = self.buildozer.config.getrawdefault( "app", "android.logcat_filters", "", section_sep=":", split_char=" ") filters = " ".join(filters) self.buildozer.environ['ANDROID_SERIAL'] = serial[0] self.buildozer.cmd('{adb} logcat {filters}'.format(adb=self.adb_cmd, filters=filters), cwd=self.buildozer.global_platform_dir, show_output=True) self.buildozer.environ.pop('ANDROID_SERIAL', None)
python
def cmd_logcat(self, *args): '''Show the log from the device ''' self.check_requirements() serial = self.serials[0:] if not serial: return filters = self.buildozer.config.getrawdefault( "app", "android.logcat_filters", "", section_sep=":", split_char=" ") filters = " ".join(filters) self.buildozer.environ['ANDROID_SERIAL'] = serial[0] self.buildozer.cmd('{adb} logcat {filters}'.format(adb=self.adb_cmd, filters=filters), cwd=self.buildozer.global_platform_dir, show_output=True) self.buildozer.environ.pop('ANDROID_SERIAL', None)
[ "def", "cmd_logcat", "(", "self", ",", "*", "args", ")", ":", "self", ".", "check_requirements", "(", ")", "serial", "=", "self", ".", "serials", "[", "0", ":", "]", "if", "not", "serial", ":", "return", "filters", "=", "self", ".", "buildozer", ".", "config", ".", "getrawdefault", "(", "\"app\"", ",", "\"android.logcat_filters\"", ",", "\"\"", ",", "section_sep", "=", "\":\"", ",", "split_char", "=", "\" \"", ")", "filters", "=", "\" \"", ".", "join", "(", "filters", ")", "self", ".", "buildozer", ".", "environ", "[", "'ANDROID_SERIAL'", "]", "=", "serial", "[", "0", "]", "self", ".", "buildozer", ".", "cmd", "(", "'{adb} logcat {filters}'", ".", "format", "(", "adb", "=", "self", ".", "adb_cmd", ",", "filters", "=", "filters", ")", ",", "cwd", "=", "self", ".", "buildozer", ".", "global_platform_dir", ",", "show_output", "=", "True", ")", "self", ".", "buildozer", ".", "environ", ".", "pop", "(", "'ANDROID_SERIAL'", ",", "None", ")" ]
Show the log from the device
[ "Show", "the", "log", "from", "the", "device" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/android.py#L1203-L1218
228,941
kivy/buildozer
buildozer/target.py
Target.path_or_git_url
def path_or_git_url(self, repo, owner='kivy', branch='master', url_format='https://github.com/{owner}/{repo}.git', platform=None, squash_hyphen=True): """Get source location for a git checkout This method will check the `buildozer.spec` for the keys: {repo}_dir {repo}_url {repo}_branch and use them to determine the source location for a git checkout. If a `platform` is specified, {platform}.{repo} will be used as the base for the buildozer key `{repo}_dir` specifies a custom checkout location (relative to `buildozer.root_dir`). If present, `path` will be set to this value and `url`, `branch` will be set to None, None. Otherwise, `{repo}_url` and `{repo}_branch` will be examined. If no keys are present, the kwargs will be used to create a sensible default URL and branch. :Parameters: `repo`: str (required) name of repository to fetch. Used both for buildozer keys ({platform}.{repo}_dir|_url|_branch) and in building default git URL `branch`: str (default 'master') Specific branch to retrieve if none specified in buildozer.spec. `owner`: str owner of repo. `platform`: str or None platform prefix to use when retrieving `buildozer.spec` keys. If specified, key names will be {platform}.{repo} instead of just {repo} `squash_hyphen`: boolean if True, change '-' to '_' when looking for keys in buildozer.spec. This lets us keep backwards compatibility with old buildozer.spec files `url_format`: format string Used to construct default git URL. can use {repo} {owner} and {branch} if needed. :Returns: A Tuple (path, url, branch) where `path` Path to a custom git checkout. If specified, both `url` and `branch` will be None `url` URL of git repository from where code should be checked-out `branch` branch name (or tag) that should be used for the check-out. """ if squash_hyphen: key = repo.replace('-', '_') else: key = repo if platform: key = "{}.{}".format(platform, key) config = self.buildozer.config path = config.getdefault('app', '{}_dir'.format(key), None) if path is not None: path = join(self.buildozer.root_dir, path) url = None branch = None else: branch = config.getdefault('app', '{}_branch'.format(key), branch) default_url = url_format.format(owner=owner, repo=repo, branch=branch) url = config.getdefault('app', '{}_url'.format(key), default_url) if branch != 'master': url = "--branch {} {}".format(branch, url) return path, url, branch
python
def path_or_git_url(self, repo, owner='kivy', branch='master', url_format='https://github.com/{owner}/{repo}.git', platform=None, squash_hyphen=True): """Get source location for a git checkout This method will check the `buildozer.spec` for the keys: {repo}_dir {repo}_url {repo}_branch and use them to determine the source location for a git checkout. If a `platform` is specified, {platform}.{repo} will be used as the base for the buildozer key `{repo}_dir` specifies a custom checkout location (relative to `buildozer.root_dir`). If present, `path` will be set to this value and `url`, `branch` will be set to None, None. Otherwise, `{repo}_url` and `{repo}_branch` will be examined. If no keys are present, the kwargs will be used to create a sensible default URL and branch. :Parameters: `repo`: str (required) name of repository to fetch. Used both for buildozer keys ({platform}.{repo}_dir|_url|_branch) and in building default git URL `branch`: str (default 'master') Specific branch to retrieve if none specified in buildozer.spec. `owner`: str owner of repo. `platform`: str or None platform prefix to use when retrieving `buildozer.spec` keys. If specified, key names will be {platform}.{repo} instead of just {repo} `squash_hyphen`: boolean if True, change '-' to '_' when looking for keys in buildozer.spec. This lets us keep backwards compatibility with old buildozer.spec files `url_format`: format string Used to construct default git URL. can use {repo} {owner} and {branch} if needed. :Returns: A Tuple (path, url, branch) where `path` Path to a custom git checkout. If specified, both `url` and `branch` will be None `url` URL of git repository from where code should be checked-out `branch` branch name (or tag) that should be used for the check-out. """ if squash_hyphen: key = repo.replace('-', '_') else: key = repo if platform: key = "{}.{}".format(platform, key) config = self.buildozer.config path = config.getdefault('app', '{}_dir'.format(key), None) if path is not None: path = join(self.buildozer.root_dir, path) url = None branch = None else: branch = config.getdefault('app', '{}_branch'.format(key), branch) default_url = url_format.format(owner=owner, repo=repo, branch=branch) url = config.getdefault('app', '{}_url'.format(key), default_url) if branch != 'master': url = "--branch {} {}".format(branch, url) return path, url, branch
[ "def", "path_or_git_url", "(", "self", ",", "repo", ",", "owner", "=", "'kivy'", ",", "branch", "=", "'master'", ",", "url_format", "=", "'https://github.com/{owner}/{repo}.git'", ",", "platform", "=", "None", ",", "squash_hyphen", "=", "True", ")", ":", "if", "squash_hyphen", ":", "key", "=", "repo", ".", "replace", "(", "'-'", ",", "'_'", ")", "else", ":", "key", "=", "repo", "if", "platform", ":", "key", "=", "\"{}.{}\"", ".", "format", "(", "platform", ",", "key", ")", "config", "=", "self", ".", "buildozer", ".", "config", "path", "=", "config", ".", "getdefault", "(", "'app'", ",", "'{}_dir'", ".", "format", "(", "key", ")", ",", "None", ")", "if", "path", "is", "not", "None", ":", "path", "=", "join", "(", "self", ".", "buildozer", ".", "root_dir", ",", "path", ")", "url", "=", "None", "branch", "=", "None", "else", ":", "branch", "=", "config", ".", "getdefault", "(", "'app'", ",", "'{}_branch'", ".", "format", "(", "key", ")", ",", "branch", ")", "default_url", "=", "url_format", ".", "format", "(", "owner", "=", "owner", ",", "repo", "=", "repo", ",", "branch", "=", "branch", ")", "url", "=", "config", ".", "getdefault", "(", "'app'", ",", "'{}_url'", ".", "format", "(", "key", ")", ",", "default_url", ")", "if", "branch", "!=", "'master'", ":", "url", "=", "\"--branch {} {}\"", ".", "format", "(", "branch", ",", "url", ")", "return", "path", ",", "url", ",", "branch" ]
Get source location for a git checkout This method will check the `buildozer.spec` for the keys: {repo}_dir {repo}_url {repo}_branch and use them to determine the source location for a git checkout. If a `platform` is specified, {platform}.{repo} will be used as the base for the buildozer key `{repo}_dir` specifies a custom checkout location (relative to `buildozer.root_dir`). If present, `path` will be set to this value and `url`, `branch` will be set to None, None. Otherwise, `{repo}_url` and `{repo}_branch` will be examined. If no keys are present, the kwargs will be used to create a sensible default URL and branch. :Parameters: `repo`: str (required) name of repository to fetch. Used both for buildozer keys ({platform}.{repo}_dir|_url|_branch) and in building default git URL `branch`: str (default 'master') Specific branch to retrieve if none specified in buildozer.spec. `owner`: str owner of repo. `platform`: str or None platform prefix to use when retrieving `buildozer.spec` keys. If specified, key names will be {platform}.{repo} instead of just {repo} `squash_hyphen`: boolean if True, change '-' to '_' when looking for keys in buildozer.spec. This lets us keep backwards compatibility with old buildozer.spec files `url_format`: format string Used to construct default git URL. can use {repo} {owner} and {branch} if needed. :Returns: A Tuple (path, url, branch) where `path` Path to a custom git checkout. If specified, both `url` and `branch` will be None `url` URL of git repository from where code should be checked-out `branch` branch name (or tag) that should be used for the check-out.
[ "Get", "source", "location", "for", "a", "git", "checkout" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/target.py#L151-L230
228,942
kivy/buildozer
buildozer/target.py
Target.install_or_update_repo
def install_or_update_repo(self, repo, **kwargs): """Install or update a git repository into the platform directory. This will clone the contents of a git repository to `buildozer.platform_dir`. The location of this repo can be speficied via URL and branch name, or via a custom (local) directory name. :Parameters: **kwargs: Any valid arguments for :meth:`path_or_git_url` :Returns: fully qualified path to updated git repo """ cmd = self.buildozer.cmd install_dir = join(self.buildozer.platform_dir, repo) custom_dir, clone_url, clone_branch = self.path_or_git_url(repo, **kwargs) if not self.buildozer.file_exists(install_dir): if custom_dir: cmd('mkdir -p "{}"'.format(install_dir)) cmd('cp -a "{}"/* "{}"/'.format(custom_dir, install_dir)) else: cmd('git clone {}'.format(clone_url), cwd=self.buildozer.platform_dir) elif self.platform_update: if custom_dir: cmd('cp -a "{}"/* "{}"/'.format(custom_dir, install_dir)) else: cmd('git clean -dxf', cwd=install_dir) cmd('git pull origin {}'.format(clone_branch), cwd=install_dir) return install_dir
python
def install_or_update_repo(self, repo, **kwargs): """Install or update a git repository into the platform directory. This will clone the contents of a git repository to `buildozer.platform_dir`. The location of this repo can be speficied via URL and branch name, or via a custom (local) directory name. :Parameters: **kwargs: Any valid arguments for :meth:`path_or_git_url` :Returns: fully qualified path to updated git repo """ cmd = self.buildozer.cmd install_dir = join(self.buildozer.platform_dir, repo) custom_dir, clone_url, clone_branch = self.path_or_git_url(repo, **kwargs) if not self.buildozer.file_exists(install_dir): if custom_dir: cmd('mkdir -p "{}"'.format(install_dir)) cmd('cp -a "{}"/* "{}"/'.format(custom_dir, install_dir)) else: cmd('git clone {}'.format(clone_url), cwd=self.buildozer.platform_dir) elif self.platform_update: if custom_dir: cmd('cp -a "{}"/* "{}"/'.format(custom_dir, install_dir)) else: cmd('git clean -dxf', cwd=install_dir) cmd('git pull origin {}'.format(clone_branch), cwd=install_dir) return install_dir
[ "def", "install_or_update_repo", "(", "self", ",", "repo", ",", "*", "*", "kwargs", ")", ":", "cmd", "=", "self", ".", "buildozer", ".", "cmd", "install_dir", "=", "join", "(", "self", ".", "buildozer", ".", "platform_dir", ",", "repo", ")", "custom_dir", ",", "clone_url", ",", "clone_branch", "=", "self", ".", "path_or_git_url", "(", "repo", ",", "*", "*", "kwargs", ")", "if", "not", "self", ".", "buildozer", ".", "file_exists", "(", "install_dir", ")", ":", "if", "custom_dir", ":", "cmd", "(", "'mkdir -p \"{}\"'", ".", "format", "(", "install_dir", ")", ")", "cmd", "(", "'cp -a \"{}\"/* \"{}\"/'", ".", "format", "(", "custom_dir", ",", "install_dir", ")", ")", "else", ":", "cmd", "(", "'git clone {}'", ".", "format", "(", "clone_url", ")", ",", "cwd", "=", "self", ".", "buildozer", ".", "platform_dir", ")", "elif", "self", ".", "platform_update", ":", "if", "custom_dir", ":", "cmd", "(", "'cp -a \"{}\"/* \"{}\"/'", ".", "format", "(", "custom_dir", ",", "install_dir", ")", ")", "else", ":", "cmd", "(", "'git clean -dxf'", ",", "cwd", "=", "install_dir", ")", "cmd", "(", "'git pull origin {}'", ".", "format", "(", "clone_branch", ")", ",", "cwd", "=", "install_dir", ")", "return", "install_dir" ]
Install or update a git repository into the platform directory. This will clone the contents of a git repository to `buildozer.platform_dir`. The location of this repo can be speficied via URL and branch name, or via a custom (local) directory name. :Parameters: **kwargs: Any valid arguments for :meth:`path_or_git_url` :Returns: fully qualified path to updated git repo
[ "Install", "or", "update", "a", "git", "repository", "into", "the", "platform", "directory", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/target.py#L232-L263
228,943
kivy/buildozer
buildozer/__init__.py
set_config_token_from_env
def set_config_token_from_env(section, token, config): '''Given a config section and token, checks for an appropriate environment variable. If the variable exists, sets the config entry to its value. The environment variable checked is of the form SECTION_TOKEN, all upper case, with any dots replaced by underscores. Returns True if the environment variable exists and was used, or False otherwise. ''' env_var_name = ''.join([section.upper(), '_', token.upper().replace('.', '_')]) env_var = os.environ.get(env_var_name) if env_var is None: return False config.set(section, token, env_var) return True
python
def set_config_token_from_env(section, token, config): '''Given a config section and token, checks for an appropriate environment variable. If the variable exists, sets the config entry to its value. The environment variable checked is of the form SECTION_TOKEN, all upper case, with any dots replaced by underscores. Returns True if the environment variable exists and was used, or False otherwise. ''' env_var_name = ''.join([section.upper(), '_', token.upper().replace('.', '_')]) env_var = os.environ.get(env_var_name) if env_var is None: return False config.set(section, token, env_var) return True
[ "def", "set_config_token_from_env", "(", "section", ",", "token", ",", "config", ")", ":", "env_var_name", "=", "''", ".", "join", "(", "[", "section", ".", "upper", "(", ")", ",", "'_'", ",", "token", ".", "upper", "(", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", "]", ")", "env_var", "=", "os", ".", "environ", ".", "get", "(", "env_var_name", ")", "if", "env_var", "is", "None", ":", "return", "False", "config", ".", "set", "(", "section", ",", "token", ",", "env_var", ")", "return", "True" ]
Given a config section and token, checks for an appropriate environment variable. If the variable exists, sets the config entry to its value. The environment variable checked is of the form SECTION_TOKEN, all upper case, with any dots replaced by underscores. Returns True if the environment variable exists and was used, or False otherwise.
[ "Given", "a", "config", "section", "and", "token", "checks", "for", "an", "appropriate", "environment", "variable", ".", "If", "the", "variable", "exists", "sets", "the", "config", "entry", "to", "its", "value", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L1252-L1270
228,944
kivy/buildozer
buildozer/__init__.py
Buildozer.prepare_for_build
def prepare_for_build(self): '''Prepare the build. ''' assert(self.target is not None) if hasattr(self.target, '_build_prepared'): return self.info('Preparing build') self.info('Check requirements for {0}'.format(self.targetname)) self.target.check_requirements() self.info('Install platform') self.target.install_platform() self.info('Check application requirements') self.check_application_requirements() self.info('Check garden requirements') self.check_garden_requirements() self.info('Compile platform') self.target.compile_platform() # flag to prevent multiple build self.target._build_prepared = True
python
def prepare_for_build(self): '''Prepare the build. ''' assert(self.target is not None) if hasattr(self.target, '_build_prepared'): return self.info('Preparing build') self.info('Check requirements for {0}'.format(self.targetname)) self.target.check_requirements() self.info('Install platform') self.target.install_platform() self.info('Check application requirements') self.check_application_requirements() self.info('Check garden requirements') self.check_garden_requirements() self.info('Compile platform') self.target.compile_platform() # flag to prevent multiple build self.target._build_prepared = True
[ "def", "prepare_for_build", "(", "self", ")", ":", "assert", "(", "self", ".", "target", "is", "not", "None", ")", "if", "hasattr", "(", "self", ".", "target", ",", "'_build_prepared'", ")", ":", "return", "self", ".", "info", "(", "'Preparing build'", ")", "self", ".", "info", "(", "'Check requirements for {0}'", ".", "format", "(", "self", ".", "targetname", ")", ")", "self", ".", "target", ".", "check_requirements", "(", ")", "self", ".", "info", "(", "'Install platform'", ")", "self", ".", "target", ".", "install_platform", "(", ")", "self", ".", "info", "(", "'Check application requirements'", ")", "self", ".", "check_application_requirements", "(", ")", "self", ".", "info", "(", "'Check garden requirements'", ")", "self", ".", "check_garden_requirements", "(", ")", "self", ".", "info", "(", "'Compile platform'", ")", "self", ".", "target", ".", "compile_platform", "(", ")", "# flag to prevent multiple build", "self", ".", "target", ".", "_build_prepared", "=", "True" ]
Prepare the build.
[ "Prepare", "the", "build", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L173-L198
228,945
kivy/buildozer
buildozer/__init__.py
Buildozer.build
def build(self): '''Do the build. The target can set build_mode to 'release' or 'debug' before calling this method. (:meth:`prepare_for_build` must have been call before.) ''' assert(self.target is not None) assert(hasattr(self.target, '_build_prepared')) if hasattr(self.target, '_build_done'): return # increment the build number self.build_id = int(self.state.get('cache.build_id', '0')) + 1 self.state['cache.build_id'] = str(self.build_id) self.info('Build the application #{}'.format(self.build_id)) self.build_application() self.info('Package the application') self.target.build_package() # flag to prevent multiple build self.target._build_done = True
python
def build(self): '''Do the build. The target can set build_mode to 'release' or 'debug' before calling this method. (:meth:`prepare_for_build` must have been call before.) ''' assert(self.target is not None) assert(hasattr(self.target, '_build_prepared')) if hasattr(self.target, '_build_done'): return # increment the build number self.build_id = int(self.state.get('cache.build_id', '0')) + 1 self.state['cache.build_id'] = str(self.build_id) self.info('Build the application #{}'.format(self.build_id)) self.build_application() self.info('Package the application') self.target.build_package() # flag to prevent multiple build self.target._build_done = True
[ "def", "build", "(", "self", ")", ":", "assert", "(", "self", ".", "target", "is", "not", "None", ")", "assert", "(", "hasattr", "(", "self", ".", "target", ",", "'_build_prepared'", ")", ")", "if", "hasattr", "(", "self", ".", "target", ",", "'_build_done'", ")", ":", "return", "# increment the build number", "self", ".", "build_id", "=", "int", "(", "self", ".", "state", ".", "get", "(", "'cache.build_id'", ",", "'0'", ")", ")", "+", "1", "self", ".", "state", "[", "'cache.build_id'", "]", "=", "str", "(", "self", ".", "build_id", ")", "self", ".", "info", "(", "'Build the application #{}'", ".", "format", "(", "self", ".", "build_id", ")", ")", "self", ".", "build_application", "(", ")", "self", ".", "info", "(", "'Package the application'", ")", "self", ".", "target", ".", "build_package", "(", ")", "# flag to prevent multiple build", "self", ".", "target", ".", "_build_done", "=", "True" ]
Do the build. The target can set build_mode to 'release' or 'debug' before calling this method. (:meth:`prepare_for_build` must have been call before.)
[ "Do", "the", "build", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L200-L225
228,946
kivy/buildozer
buildozer/__init__.py
Buildozer.log_env
def log_env(self, level, env): """dump env into debug logger in readable format""" self.log(level, "ENVIRONMENT:") for k, v in env.items(): self.log(level, " {} = {}".format(k, pformat(v)))
python
def log_env(self, level, env): """dump env into debug logger in readable format""" self.log(level, "ENVIRONMENT:") for k, v in env.items(): self.log(level, " {} = {}".format(k, pformat(v)))
[ "def", "log_env", "(", "self", ",", "level", ",", "env", ")", ":", "self", ".", "log", "(", "level", ",", "\"ENVIRONMENT:\"", ")", "for", "k", ",", "v", "in", "env", ".", "items", "(", ")", ":", "self", ".", "log", "(", "level", ",", "\" {} = {}\"", ".", "format", "(", "k", ",", "pformat", "(", "v", ")", ")", ")" ]
dump env into debug logger in readable format
[ "dump", "env", "into", "debug", "logger", "in", "readable", "format" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L243-L247
228,947
kivy/buildozer
buildozer/__init__.py
Buildozer.check_configuration_tokens
def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' self.info('Check configuration tokens') self.migrate_configuration_tokens() get = self.config.getdefault errors = [] adderror = errors.append if not get('app', 'title', ''): adderror('[app] "title" is missing') if not get('app', 'source.dir', ''): adderror('[app] "source.dir" is missing') package_name = get('app', 'package.name', '') if not package_name: adderror('[app] "package.name" is missing') elif package_name[0] in map(str, range(10)): adderror('[app] "package.name" may not start with a number.') version = get('app', 'version', '') version_regex = get('app', 'version.regex', '') if not version and not version_regex: adderror('[app] One of "version" or "version.regex" must be set') if version and version_regex: adderror('[app] Conflict between "version" and "version.regex"' ', only one can be used.') if version_regex and not get('app', 'version.filename', ''): adderror('[app] "version.filename" is missing' ', required by "version.regex"') orientation = get('app', 'orientation', 'landscape') if orientation not in ('landscape', 'portrait', 'all', 'sensorLandscape'): adderror('[app] "orientation" have an invalid value') if errors: self.error('{0} error(s) found in the buildozer.spec'.format( len(errors))) for error in errors: print(error) exit(1)
python
def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' self.info('Check configuration tokens') self.migrate_configuration_tokens() get = self.config.getdefault errors = [] adderror = errors.append if not get('app', 'title', ''): adderror('[app] "title" is missing') if not get('app', 'source.dir', ''): adderror('[app] "source.dir" is missing') package_name = get('app', 'package.name', '') if not package_name: adderror('[app] "package.name" is missing') elif package_name[0] in map(str, range(10)): adderror('[app] "package.name" may not start with a number.') version = get('app', 'version', '') version_regex = get('app', 'version.regex', '') if not version and not version_regex: adderror('[app] One of "version" or "version.regex" must be set') if version and version_regex: adderror('[app] Conflict between "version" and "version.regex"' ', only one can be used.') if version_regex and not get('app', 'version.filename', ''): adderror('[app] "version.filename" is missing' ', required by "version.regex"') orientation = get('app', 'orientation', 'landscape') if orientation not in ('landscape', 'portrait', 'all', 'sensorLandscape'): adderror('[app] "orientation" have an invalid value') if errors: self.error('{0} error(s) found in the buildozer.spec'.format( len(errors))) for error in errors: print(error) exit(1)
[ "def", "check_configuration_tokens", "(", "self", ")", ":", "self", ".", "info", "(", "'Check configuration tokens'", ")", "self", ".", "migrate_configuration_tokens", "(", ")", "get", "=", "self", ".", "config", ".", "getdefault", "errors", "=", "[", "]", "adderror", "=", "errors", ".", "append", "if", "not", "get", "(", "'app'", ",", "'title'", ",", "''", ")", ":", "adderror", "(", "'[app] \"title\" is missing'", ")", "if", "not", "get", "(", "'app'", ",", "'source.dir'", ",", "''", ")", ":", "adderror", "(", "'[app] \"source.dir\" is missing'", ")", "package_name", "=", "get", "(", "'app'", ",", "'package.name'", ",", "''", ")", "if", "not", "package_name", ":", "adderror", "(", "'[app] \"package.name\" is missing'", ")", "elif", "package_name", "[", "0", "]", "in", "map", "(", "str", ",", "range", "(", "10", ")", ")", ":", "adderror", "(", "'[app] \"package.name\" may not start with a number.'", ")", "version", "=", "get", "(", "'app'", ",", "'version'", ",", "''", ")", "version_regex", "=", "get", "(", "'app'", ",", "'version.regex'", ",", "''", ")", "if", "not", "version", "and", "not", "version_regex", ":", "adderror", "(", "'[app] One of \"version\" or \"version.regex\" must be set'", ")", "if", "version", "and", "version_regex", ":", "adderror", "(", "'[app] Conflict between \"version\" and \"version.regex\"'", "', only one can be used.'", ")", "if", "version_regex", "and", "not", "get", "(", "'app'", ",", "'version.filename'", ",", "''", ")", ":", "adderror", "(", "'[app] \"version.filename\" is missing'", "', required by \"version.regex\"'", ")", "orientation", "=", "get", "(", "'app'", ",", "'orientation'", ",", "'landscape'", ")", "if", "orientation", "not", "in", "(", "'landscape'", ",", "'portrait'", ",", "'all'", ",", "'sensorLandscape'", ")", ":", "adderror", "(", "'[app] \"orientation\" have an invalid value'", ")", "if", "errors", ":", "self", ".", "error", "(", "'{0} error(s) found in the buildozer.spec'", ".", "format", "(", "len", "(", "errors", ")", ")", ")", "for", "error", "in", "errors", ":", "print", "(", "error", ")", "exit", "(", "1", ")" ]
Ensure the spec file is 'correct'.
[ "Ensure", "the", "spec", "file", "is", "correct", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L398-L437
228,948
kivy/buildozer
buildozer/__init__.py
Buildozer.check_application_requirements
def check_application_requirements(self): '''Ensure the application requirements are all available and ready to be packaged as well. ''' requirements = self.config.getlist('app', 'requirements', '') target_available_packages = self.target.get_available_packages() if target_available_packages is True: # target handles all packages! return # remove all the requirements that the target can compile onlyname = lambda x: x.split('==')[0] # noqa: E731 requirements = [x for x in requirements if onlyname(x) not in target_available_packages] if requirements and hasattr(sys, 'real_prefix'): e = self.error e('virtualenv is needed to install pure-Python modules, but') e('virtualenv does not support nesting, and you are running') e('buildozer in one. Please run buildozer outside of a') e('virtualenv instead.') exit(1) # did we already installed the libs ? if ( exists(self.applibs_dir) and self.state.get('cache.applibs', '') == requirements ): self.debug('Application requirements already installed, pass') return # recreate applibs self.rmdir(self.applibs_dir) self.mkdir(self.applibs_dir) # ok now check the availability of all requirements for requirement in requirements: self._install_application_requirement(requirement) # everything goes as expected, save this state! self.state['cache.applibs'] = requirements
python
def check_application_requirements(self): '''Ensure the application requirements are all available and ready to be packaged as well. ''' requirements = self.config.getlist('app', 'requirements', '') target_available_packages = self.target.get_available_packages() if target_available_packages is True: # target handles all packages! return # remove all the requirements that the target can compile onlyname = lambda x: x.split('==')[0] # noqa: E731 requirements = [x for x in requirements if onlyname(x) not in target_available_packages] if requirements and hasattr(sys, 'real_prefix'): e = self.error e('virtualenv is needed to install pure-Python modules, but') e('virtualenv does not support nesting, and you are running') e('buildozer in one. Please run buildozer outside of a') e('virtualenv instead.') exit(1) # did we already installed the libs ? if ( exists(self.applibs_dir) and self.state.get('cache.applibs', '') == requirements ): self.debug('Application requirements already installed, pass') return # recreate applibs self.rmdir(self.applibs_dir) self.mkdir(self.applibs_dir) # ok now check the availability of all requirements for requirement in requirements: self._install_application_requirement(requirement) # everything goes as expected, save this state! self.state['cache.applibs'] = requirements
[ "def", "check_application_requirements", "(", "self", ")", ":", "requirements", "=", "self", ".", "config", ".", "getlist", "(", "'app'", ",", "'requirements'", ",", "''", ")", "target_available_packages", "=", "self", ".", "target", ".", "get_available_packages", "(", ")", "if", "target_available_packages", "is", "True", ":", "# target handles all packages!", "return", "# remove all the requirements that the target can compile", "onlyname", "=", "lambda", "x", ":", "x", ".", "split", "(", "'=='", ")", "[", "0", "]", "# noqa: E731", "requirements", "=", "[", "x", "for", "x", "in", "requirements", "if", "onlyname", "(", "x", ")", "not", "in", "target_available_packages", "]", "if", "requirements", "and", "hasattr", "(", "sys", ",", "'real_prefix'", ")", ":", "e", "=", "self", ".", "error", "e", "(", "'virtualenv is needed to install pure-Python modules, but'", ")", "e", "(", "'virtualenv does not support nesting, and you are running'", ")", "e", "(", "'buildozer in one. Please run buildozer outside of a'", ")", "e", "(", "'virtualenv instead.'", ")", "exit", "(", "1", ")", "# did we already installed the libs ?", "if", "(", "exists", "(", "self", ".", "applibs_dir", ")", "and", "self", ".", "state", ".", "get", "(", "'cache.applibs'", ",", "''", ")", "==", "requirements", ")", ":", "self", ".", "debug", "(", "'Application requirements already installed, pass'", ")", "return", "# recreate applibs", "self", ".", "rmdir", "(", "self", ".", "applibs_dir", ")", "self", ".", "mkdir", "(", "self", ".", "applibs_dir", ")", "# ok now check the availability of all requirements", "for", "requirement", "in", "requirements", ":", "self", ".", "_install_application_requirement", "(", "requirement", ")", "# everything goes as expected, save this state!", "self", ".", "state", "[", "'cache.applibs'", "]", "=", "requirements" ]
Ensure the application requirements are all available and ready to be packaged as well.
[ "Ensure", "the", "application", "requirements", "are", "all", "available", "and", "ready", "to", "be", "packaged", "as", "well", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L488-L528
228,949
kivy/buildozer
buildozer/__init__.py
Buildozer.check_garden_requirements
def check_garden_requirements(self): '''Ensure required garden packages are available to be included. ''' garden_requirements = self.config.getlist('app', 'garden_requirements', '') # have we installed the garden packages? if exists(self.gardenlibs_dir) and \ self.state.get('cache.gardenlibs', '') == garden_requirements: self.debug('Garden requirements already installed, pass') return # we're going to reinstall all the garden libs. self.rmdir(self.gardenlibs_dir) # but if we don't have requirements, or if the user removed everything, # don't do anything. if not garden_requirements: self.state['cache.gardenlibs'] = garden_requirements return self._ensure_virtualenv() self.cmd('pip install Kivy-Garden==0.1.1', env=self.env_venv) # recreate gardenlibs self.mkdir(self.gardenlibs_dir) for requirement in garden_requirements: self._install_garden_package(requirement) # save gardenlibs state self.state['cache.gardenlibs'] = garden_requirements
python
def check_garden_requirements(self): '''Ensure required garden packages are available to be included. ''' garden_requirements = self.config.getlist('app', 'garden_requirements', '') # have we installed the garden packages? if exists(self.gardenlibs_dir) and \ self.state.get('cache.gardenlibs', '') == garden_requirements: self.debug('Garden requirements already installed, pass') return # we're going to reinstall all the garden libs. self.rmdir(self.gardenlibs_dir) # but if we don't have requirements, or if the user removed everything, # don't do anything. if not garden_requirements: self.state['cache.gardenlibs'] = garden_requirements return self._ensure_virtualenv() self.cmd('pip install Kivy-Garden==0.1.1', env=self.env_venv) # recreate gardenlibs self.mkdir(self.gardenlibs_dir) for requirement in garden_requirements: self._install_garden_package(requirement) # save gardenlibs state self.state['cache.gardenlibs'] = garden_requirements
[ "def", "check_garden_requirements", "(", "self", ")", ":", "garden_requirements", "=", "self", ".", "config", ".", "getlist", "(", "'app'", ",", "'garden_requirements'", ",", "''", ")", "# have we installed the garden packages?", "if", "exists", "(", "self", ".", "gardenlibs_dir", ")", "and", "self", ".", "state", ".", "get", "(", "'cache.gardenlibs'", ",", "''", ")", "==", "garden_requirements", ":", "self", ".", "debug", "(", "'Garden requirements already installed, pass'", ")", "return", "# we're going to reinstall all the garden libs.", "self", ".", "rmdir", "(", "self", ".", "gardenlibs_dir", ")", "# but if we don't have requirements, or if the user removed everything,", "# don't do anything.", "if", "not", "garden_requirements", ":", "self", ".", "state", "[", "'cache.gardenlibs'", "]", "=", "garden_requirements", "return", "self", ".", "_ensure_virtualenv", "(", ")", "self", ".", "cmd", "(", "'pip install Kivy-Garden==0.1.1'", ",", "env", "=", "self", ".", "env_venv", ")", "# recreate gardenlibs", "self", ".", "mkdir", "(", "self", ".", "gardenlibs_dir", ")", "for", "requirement", "in", "garden_requirements", ":", "self", ".", "_install_garden_package", "(", "requirement", ")", "# save gardenlibs state", "self", ".", "state", "[", "'cache.gardenlibs'", "]", "=", "garden_requirements" ]
Ensure required garden packages are available to be included.
[ "Ensure", "required", "garden", "packages", "are", "available", "to", "be", "included", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L537-L568
228,950
kivy/buildozer
buildozer/__init__.py
Buildozer.cmd_init
def cmd_init(self, *args): '''Create a initial buildozer.spec in the current directory ''' if exists('buildozer.spec'): print('ERROR: You already have a buildozer.spec file.') exit(1) copyfile(join(dirname(__file__), 'default.spec'), 'buildozer.spec') print('File buildozer.spec created, ready to customize!')
python
def cmd_init(self, *args): '''Create a initial buildozer.spec in the current directory ''' if exists('buildozer.spec'): print('ERROR: You already have a buildozer.spec file.') exit(1) copyfile(join(dirname(__file__), 'default.spec'), 'buildozer.spec') print('File buildozer.spec created, ready to customize!')
[ "def", "cmd_init", "(", "self", ",", "*", "args", ")", ":", "if", "exists", "(", "'buildozer.spec'", ")", ":", "print", "(", "'ERROR: You already have a buildozer.spec file.'", ")", "exit", "(", "1", ")", "copyfile", "(", "join", "(", "dirname", "(", "__file__", ")", ",", "'default.spec'", ")", ",", "'buildozer.spec'", ")", "print", "(", "'File buildozer.spec created, ready to customize!'", ")" ]
Create a initial buildozer.spec in the current directory
[ "Create", "a", "initial", "buildozer", ".", "spec", "in", "the", "current", "directory" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L1090-L1097
228,951
kivy/buildozer
buildozer/__init__.py
Buildozer.cmd_distclean
def cmd_distclean(self, *args): '''Clean the whole Buildozer environment. ''' print("Warning: Your ndk, sdk and all other cached packages will be" " removed. Continue? (y/n)") if sys.stdin.readline().lower()[0] == 'y': self.info('Clean the global build directory') if not exists(self.global_buildozer_dir): return rmtree(self.global_buildozer_dir)
python
def cmd_distclean(self, *args): '''Clean the whole Buildozer environment. ''' print("Warning: Your ndk, sdk and all other cached packages will be" " removed. Continue? (y/n)") if sys.stdin.readline().lower()[0] == 'y': self.info('Clean the global build directory') if not exists(self.global_buildozer_dir): return rmtree(self.global_buildozer_dir)
[ "def", "cmd_distclean", "(", "self", ",", "*", "args", ")", ":", "print", "(", "\"Warning: Your ndk, sdk and all other cached packages will be\"", "\" removed. Continue? (y/n)\"", ")", "if", "sys", ".", "stdin", ".", "readline", "(", ")", ".", "lower", "(", ")", "[", "0", "]", "==", "'y'", ":", "self", ".", "info", "(", "'Clean the global build directory'", ")", "if", "not", "exists", "(", "self", ".", "global_buildozer_dir", ")", ":", "return", "rmtree", "(", "self", ".", "global_buildozer_dir", ")" ]
Clean the whole Buildozer environment.
[ "Clean", "the", "whole", "Buildozer", "environment", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L1099-L1108
228,952
kivy/buildozer
buildozer/__init__.py
Buildozer.cmd_serve
def cmd_serve(self, *args): '''Serve the bin directory via SimpleHTTPServer ''' try: from http.server import SimpleHTTPRequestHandler from socketserver import TCPServer except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler from SocketServer import TCPServer os.chdir(self.bin_dir) handler = SimpleHTTPRequestHandler httpd = TCPServer(("", SIMPLE_HTTP_SERVER_PORT), handler) print("Serving via HTTP at port {}".format(SIMPLE_HTTP_SERVER_PORT)) print("Press Ctrl+c to quit serving.") httpd.serve_forever()
python
def cmd_serve(self, *args): '''Serve the bin directory via SimpleHTTPServer ''' try: from http.server import SimpleHTTPRequestHandler from socketserver import TCPServer except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler from SocketServer import TCPServer os.chdir(self.bin_dir) handler = SimpleHTTPRequestHandler httpd = TCPServer(("", SIMPLE_HTTP_SERVER_PORT), handler) print("Serving via HTTP at port {}".format(SIMPLE_HTTP_SERVER_PORT)) print("Press Ctrl+c to quit serving.") httpd.serve_forever()
[ "def", "cmd_serve", "(", "self", ",", "*", "args", ")", ":", "try", ":", "from", "http", ".", "server", "import", "SimpleHTTPRequestHandler", "from", "socketserver", "import", "TCPServer", "except", "ImportError", ":", "from", "SimpleHTTPServer", "import", "SimpleHTTPRequestHandler", "from", "SocketServer", "import", "TCPServer", "os", ".", "chdir", "(", "self", ".", "bin_dir", ")", "handler", "=", "SimpleHTTPRequestHandler", "httpd", "=", "TCPServer", "(", "(", "\"\"", ",", "SIMPLE_HTTP_SERVER_PORT", ")", ",", "handler", ")", "print", "(", "\"Serving via HTTP at port {}\"", ".", "format", "(", "SIMPLE_HTTP_SERVER_PORT", ")", ")", "print", "(", "\"Press Ctrl+c to quit serving.\"", ")", "httpd", ".", "serve_forever", "(", ")" ]
Serve the bin directory via SimpleHTTPServer
[ "Serve", "the", "bin", "directory", "via", "SimpleHTTPServer" ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L1126-L1141
228,953
kivy/buildozer
buildozer/targets/ios.py
TargetIos.cmd_xcode
def cmd_xcode(self, *args): '''Open the xcode project. ''' app_name = self.buildozer.namify(self.buildozer.config.get('app', 'package.name')) app_name = app_name.lower() ios_dir = ios_dir = join(self.buildozer.platform_dir, 'kivy-ios') self.buildozer.cmd('open {}.xcodeproj'.format( app_name), cwd=join(ios_dir, '{}-ios'.format(app_name)))
python
def cmd_xcode(self, *args): '''Open the xcode project. ''' app_name = self.buildozer.namify(self.buildozer.config.get('app', 'package.name')) app_name = app_name.lower() ios_dir = ios_dir = join(self.buildozer.platform_dir, 'kivy-ios') self.buildozer.cmd('open {}.xcodeproj'.format( app_name), cwd=join(ios_dir, '{}-ios'.format(app_name)))
[ "def", "cmd_xcode", "(", "self", ",", "*", "args", ")", ":", "app_name", "=", "self", ".", "buildozer", ".", "namify", "(", "self", ".", "buildozer", ".", "config", ".", "get", "(", "'app'", ",", "'package.name'", ")", ")", "app_name", "=", "app_name", ".", "lower", "(", ")", "ios_dir", "=", "ios_dir", "=", "join", "(", "self", ".", "buildozer", ".", "platform_dir", ",", "'kivy-ios'", ")", "self", ".", "buildozer", ".", "cmd", "(", "'open {}.xcodeproj'", ".", "format", "(", "app_name", ")", ",", "cwd", "=", "join", "(", "ios_dir", ",", "'{}-ios'", ".", "format", "(", "app_name", ")", ")", ")" ]
Open the xcode project.
[ "Open", "the", "xcode", "project", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/ios.py#L264-L273
228,954
kivy/buildozer
buildozer/targets/ios.py
TargetIos.cmd_list_identities
def cmd_list_identities(self, *args): '''List the available identities to use for signing. ''' identities = self._get_available_identities() print('Available identities:') for x in identities: print(' - {}'.format(x))
python
def cmd_list_identities(self, *args): '''List the available identities to use for signing. ''' identities = self._get_available_identities() print('Available identities:') for x in identities: print(' - {}'.format(x))
[ "def", "cmd_list_identities", "(", "self", ",", "*", "args", ")", ":", "identities", "=", "self", ".", "_get_available_identities", "(", ")", "print", "(", "'Available identities:'", ")", "for", "x", "in", "identities", ":", "print", "(", "' - {}'", ".", "format", "(", "x", ")", ")" ]
List the available identities to use for signing.
[ "List", "the", "available", "identities", "to", "use", "for", "signing", "." ]
586152c6ce2b6cde4d5a081d9711f9cb037a901c
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/ios.py#L337-L343
228,955
kevin1024/vcrpy
vcr/cassette.py
CassetteContextDecorator._handle_generator
def _handle_generator(self, fn): """Wraps a generator so that we're inside the cassette context for the duration of the generator. """ with self as cassette: coroutine = fn(cassette) # We don't need to catch StopIteration. The caller (Tornado's # gen.coroutine, for example) will handle that. to_yield = next(coroutine) while True: try: to_send = yield to_yield except Exception: to_yield = coroutine.throw(*sys.exc_info()) else: try: to_yield = coroutine.send(to_send) except StopIteration: break
python
def _handle_generator(self, fn): """Wraps a generator so that we're inside the cassette context for the duration of the generator. """ with self as cassette: coroutine = fn(cassette) # We don't need to catch StopIteration. The caller (Tornado's # gen.coroutine, for example) will handle that. to_yield = next(coroutine) while True: try: to_send = yield to_yield except Exception: to_yield = coroutine.throw(*sys.exc_info()) else: try: to_yield = coroutine.send(to_send) except StopIteration: break
[ "def", "_handle_generator", "(", "self", ",", "fn", ")", ":", "with", "self", "as", "cassette", ":", "coroutine", "=", "fn", "(", "cassette", ")", "# We don't need to catch StopIteration. The caller (Tornado's", "# gen.coroutine, for example) will handle that.", "to_yield", "=", "next", "(", "coroutine", ")", "while", "True", ":", "try", ":", "to_send", "=", "yield", "to_yield", "except", "Exception", ":", "to_yield", "=", "coroutine", ".", "throw", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "try", ":", "to_yield", "=", "coroutine", ".", "send", "(", "to_send", ")", "except", "StopIteration", ":", "break" ]
Wraps a generator so that we're inside the cassette context for the duration of the generator.
[ "Wraps", "a", "generator", "so", "that", "we", "re", "inside", "the", "cassette", "context", "for", "the", "duration", "of", "the", "generator", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L126-L144
228,956
kevin1024/vcrpy
vcr/cassette.py
Cassette.append
def append(self, request, response): """Add a request, response pair to this cassette""" request = self._before_record_request(request) if not request: return # Deepcopy is here because mutation of `response` will corrupt the # real response. response = copy.deepcopy(response) response = self._before_record_response(response) if response is None: return self.data.append((request, response)) self.dirty = True
python
def append(self, request, response): """Add a request, response pair to this cassette""" request = self._before_record_request(request) if not request: return # Deepcopy is here because mutation of `response` will corrupt the # real response. response = copy.deepcopy(response) response = self._before_record_response(response) if response is None: return self.data.append((request, response)) self.dirty = True
[ "def", "append", "(", "self", ",", "request", ",", "response", ")", ":", "request", "=", "self", ".", "_before_record_request", "(", "request", ")", "if", "not", "request", ":", "return", "# Deepcopy is here because mutation of `response` will corrupt the", "# real response.", "response", "=", "copy", ".", "deepcopy", "(", "response", ")", "response", "=", "self", ".", "_before_record_response", "(", "response", ")", "if", "response", "is", "None", ":", "return", "self", ".", "data", ".", "append", "(", "(", "request", ",", "response", ")", ")", "self", ".", "dirty", "=", "True" ]
Add a request, response pair to this cassette
[ "Add", "a", "request", "response", "pair", "to", "this", "cassette" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L226-L238
228,957
kevin1024/vcrpy
vcr/cassette.py
Cassette._responses
def _responses(self, request): """ internal API, returns an iterator with all responses matching the request. """ request = self._before_record_request(request) for index, (stored_request, response) in enumerate(self.data): if requests_match(request, stored_request, self._match_on): yield index, response
python
def _responses(self, request): """ internal API, returns an iterator with all responses matching the request. """ request = self._before_record_request(request) for index, (stored_request, response) in enumerate(self.data): if requests_match(request, stored_request, self._match_on): yield index, response
[ "def", "_responses", "(", "self", ",", "request", ")", ":", "request", "=", "self", ".", "_before_record_request", "(", "request", ")", "for", "index", ",", "(", "stored_request", ",", "response", ")", "in", "enumerate", "(", "self", ".", "data", ")", ":", "if", "requests_match", "(", "request", ",", "stored_request", ",", "self", ".", "_match_on", ")", ":", "yield", "index", ",", "response" ]
internal API, returns an iterator with all responses matching the request.
[ "internal", "API", "returns", "an", "iterator", "with", "all", "responses", "matching", "the", "request", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L243-L251
228,958
kevin1024/vcrpy
vcr/cassette.py
Cassette.play_response
def play_response(self, request): """ Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played """ for index, response in self._responses(request): if self.play_counts[index] == 0: self.play_counts[index] += 1 return response # The cassette doesn't contain the request asked for. raise UnhandledHTTPRequestError( "The cassette (%r) doesn't contain the request (%r) asked for" % (self._path, request) )
python
def play_response(self, request): """ Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played """ for index, response in self._responses(request): if self.play_counts[index] == 0: self.play_counts[index] += 1 return response # The cassette doesn't contain the request asked for. raise UnhandledHTTPRequestError( "The cassette (%r) doesn't contain the request (%r) asked for" % (self._path, request) )
[ "def", "play_response", "(", "self", ",", "request", ")", ":", "for", "index", ",", "response", "in", "self", ".", "_responses", "(", "request", ")", ":", "if", "self", ".", "play_counts", "[", "index", "]", "==", "0", ":", "self", ".", "play_counts", "[", "index", "]", "+=", "1", "return", "response", "# The cassette doesn't contain the request asked for.", "raise", "UnhandledHTTPRequestError", "(", "\"The cassette (%r) doesn't contain the request (%r) asked for\"", "%", "(", "self", ".", "_path", ",", "request", ")", ")" ]
Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played
[ "Get", "the", "response", "corresponding", "to", "a", "request", "but", "only", "if", "it", "hasn", "t", "been", "played", "back", "before", "and", "mark", "it", "as", "played" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L259-L272
228,959
kevin1024/vcrpy
vcr/cassette.py
Cassette.responses_of
def responses_of(self, request): """ Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API. """ responses = [response for index, response in self._responses(request)] if responses: return responses # The cassette doesn't contain the request asked for. raise UnhandledHTTPRequestError( "The cassette (%r) doesn't contain the request (%r) asked for" % (self._path, request) )
python
def responses_of(self, request): """ Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API. """ responses = [response for index, response in self._responses(request)] if responses: return responses # The cassette doesn't contain the request asked for. raise UnhandledHTTPRequestError( "The cassette (%r) doesn't contain the request (%r) asked for" % (self._path, request) )
[ "def", "responses_of", "(", "self", ",", "request", ")", ":", "responses", "=", "[", "response", "for", "index", ",", "response", "in", "self", ".", "_responses", "(", "request", ")", "]", "if", "responses", ":", "return", "responses", "# The cassette doesn't contain the request asked for.", "raise", "UnhandledHTTPRequestError", "(", "\"The cassette (%r) doesn't contain the request (%r) asked for\"", "%", "(", "self", ".", "_path", ",", "request", ")", ")" ]
Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API.
[ "Find", "the", "responses", "corresponding", "to", "a", "request", ".", "This", "function", "isn", "t", "actually", "used", "by", "VCR", "internally", "but", "is", "provided", "as", "an", "external", "API", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/cassette.py#L274-L288
228,960
kevin1024/vcrpy
vcr/stubs/__init__.py
parse_headers
def parse_headers(header_list): """ Convert headers from our serialized dict with lists for keys to a HTTPMessage """ header_string = b"" for key, values in header_list.items(): for v in values: header_string += \ key.encode('utf-8') + b":" + v.encode('utf-8') + b"\r\n" return compat.get_httpmessage(header_string)
python
def parse_headers(header_list): """ Convert headers from our serialized dict with lists for keys to a HTTPMessage """ header_string = b"" for key, values in header_list.items(): for v in values: header_string += \ key.encode('utf-8') + b":" + v.encode('utf-8') + b"\r\n" return compat.get_httpmessage(header_string)
[ "def", "parse_headers", "(", "header_list", ")", ":", "header_string", "=", "b\"\"", "for", "key", ",", "values", "in", "header_list", ".", "items", "(", ")", ":", "for", "v", "in", "values", ":", "header_string", "+=", "key", ".", "encode", "(", "'utf-8'", ")", "+", "b\":\"", "+", "v", ".", "encode", "(", "'utf-8'", ")", "+", "b\"\\r\\n\"", "return", "compat", ".", "get_httpmessage", "(", "header_string", ")" ]
Convert headers from our serialized dict with lists for keys to a HTTPMessage
[ "Convert", "headers", "from", "our", "serialized", "dict", "with", "lists", "for", "keys", "to", "a", "HTTPMessage" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L40-L50
228,961
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection._uri
def _uri(self, url): """Returns request absolute URI""" if url and not url.startswith('/'): # Then this must be a proxy request. return url uri = "{0}://{1}{2}{3}".format( self._protocol, self.real_connection.host, self._port_postfix(), url, ) return uri
python
def _uri(self, url): """Returns request absolute URI""" if url and not url.startswith('/'): # Then this must be a proxy request. return url uri = "{0}://{1}{2}{3}".format( self._protocol, self.real_connection.host, self._port_postfix(), url, ) return uri
[ "def", "_uri", "(", "self", ",", "url", ")", ":", "if", "url", "and", "not", "url", ".", "startswith", "(", "'/'", ")", ":", "# Then this must be a proxy request.", "return", "url", "uri", "=", "\"{0}://{1}{2}{3}\"", ".", "format", "(", "self", ".", "_protocol", ",", "self", ".", "real_connection", ".", "host", ",", "self", ".", "_port_postfix", "(", ")", ",", "url", ",", ")", "return", "uri" ]
Returns request absolute URI
[ "Returns", "request", "absolute", "URI" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L137-L148
228,962
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection._url
def _url(self, uri): """Returns request selector url from absolute URI""" prefix = "{}://{}{}".format( self._protocol, self.real_connection.host, self._port_postfix(), ) return uri.replace(prefix, '', 1)
python
def _url(self, uri): """Returns request selector url from absolute URI""" prefix = "{}://{}{}".format( self._protocol, self.real_connection.host, self._port_postfix(), ) return uri.replace(prefix, '', 1)
[ "def", "_url", "(", "self", ",", "uri", ")", ":", "prefix", "=", "\"{}://{}{}\"", ".", "format", "(", "self", ".", "_protocol", ",", "self", ".", "real_connection", ".", "host", ",", "self", ".", "_port_postfix", "(", ")", ",", ")", "return", "uri", ".", "replace", "(", "prefix", ",", "''", ",", "1", ")" ]
Returns request selector url from absolute URI
[ "Returns", "request", "selector", "url", "from", "absolute", "URI" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L150-L157
228,963
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection.request
def request(self, method, url, body=None, headers=None, *args, **kwargs): '''Persist the request metadata in self._vcr_request''' self._vcr_request = Request( method=method, uri=self._uri(url), body=body, headers=headers or {} ) log.debug('Got {}'.format(self._vcr_request)) # Note: The request may not actually be finished at this point, so # I'm not sending the actual request until getresponse(). This # allows me to compare the entire length of the response to see if it # exists in the cassette. self._sock = VCRFakeSocket()
python
def request(self, method, url, body=None, headers=None, *args, **kwargs): '''Persist the request metadata in self._vcr_request''' self._vcr_request = Request( method=method, uri=self._uri(url), body=body, headers=headers or {} ) log.debug('Got {}'.format(self._vcr_request)) # Note: The request may not actually be finished at this point, so # I'm not sending the actual request until getresponse(). This # allows me to compare the entire length of the response to see if it # exists in the cassette. self._sock = VCRFakeSocket()
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_vcr_request", "=", "Request", "(", "method", "=", "method", ",", "uri", "=", "self", ".", "_uri", "(", "url", ")", ",", "body", "=", "body", ",", "headers", "=", "headers", "or", "{", "}", ")", "log", ".", "debug", "(", "'Got {}'", ".", "format", "(", "self", ".", "_vcr_request", ")", ")", "# Note: The request may not actually be finished at this point, so", "# I'm not sending the actual request until getresponse(). This", "# allows me to compare the entire length of the response to see if it", "# exists in the cassette.", "self", ".", "_sock", "=", "VCRFakeSocket", "(", ")" ]
Persist the request metadata in self._vcr_request
[ "Persist", "the", "request", "metadata", "in", "self", ".", "_vcr_request" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L159-L174
228,964
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection.getresponse
def getresponse(self, _=False, **kwargs): '''Retrieve the response''' # Check to see if the cassette has a response for this request. If so, # then return it if self.cassette.can_play_response_for(self._vcr_request): log.info( "Playing response for {} from cassette".format( self._vcr_request ) ) response = self.cassette.play_response(self._vcr_request) return VCRHTTPResponse(response) else: if self.cassette.write_protected and self.cassette.filter_request( self._vcr_request ): raise CannotOverwriteExistingCassetteException( "No match for the request (%r) was found. " "Can't overwrite existing cassette (%r) in " "your current record mode (%r)." % (self._vcr_request, self.cassette._path, self.cassette.record_mode) ) # Otherwise, we should send the request, then get the response # and return it. log.info( "{} not in cassette, sending to real server".format( self._vcr_request ) ) # This is imported here to avoid circular import. # TODO(@IvanMalison): Refactor to allow normal import. from vcr.patch import force_reset with force_reset(): self.real_connection.request( method=self._vcr_request.method, url=self._url(self._vcr_request.uri), body=self._vcr_request.body, headers=self._vcr_request.headers, ) # get the response response = self.real_connection.getresponse() # put the response into the cassette response = { 'status': { 'code': response.status, 'message': response.reason }, 'headers': serialize_headers(response), 'body': {'string': response.read()}, } self.cassette.append(self._vcr_request, response) return VCRHTTPResponse(response)
python
def getresponse(self, _=False, **kwargs): '''Retrieve the response''' # Check to see if the cassette has a response for this request. If so, # then return it if self.cassette.can_play_response_for(self._vcr_request): log.info( "Playing response for {} from cassette".format( self._vcr_request ) ) response = self.cassette.play_response(self._vcr_request) return VCRHTTPResponse(response) else: if self.cassette.write_protected and self.cassette.filter_request( self._vcr_request ): raise CannotOverwriteExistingCassetteException( "No match for the request (%r) was found. " "Can't overwrite existing cassette (%r) in " "your current record mode (%r)." % (self._vcr_request, self.cassette._path, self.cassette.record_mode) ) # Otherwise, we should send the request, then get the response # and return it. log.info( "{} not in cassette, sending to real server".format( self._vcr_request ) ) # This is imported here to avoid circular import. # TODO(@IvanMalison): Refactor to allow normal import. from vcr.patch import force_reset with force_reset(): self.real_connection.request( method=self._vcr_request.method, url=self._url(self._vcr_request.uri), body=self._vcr_request.body, headers=self._vcr_request.headers, ) # get the response response = self.real_connection.getresponse() # put the response into the cassette response = { 'status': { 'code': response.status, 'message': response.reason }, 'headers': serialize_headers(response), 'body': {'string': response.read()}, } self.cassette.append(self._vcr_request, response) return VCRHTTPResponse(response)
[ "def", "getresponse", "(", "self", ",", "_", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Check to see if the cassette has a response for this request. If so,", "# then return it", "if", "self", ".", "cassette", ".", "can_play_response_for", "(", "self", ".", "_vcr_request", ")", ":", "log", ".", "info", "(", "\"Playing response for {} from cassette\"", ".", "format", "(", "self", ".", "_vcr_request", ")", ")", "response", "=", "self", ".", "cassette", ".", "play_response", "(", "self", ".", "_vcr_request", ")", "return", "VCRHTTPResponse", "(", "response", ")", "else", ":", "if", "self", ".", "cassette", ".", "write_protected", "and", "self", ".", "cassette", ".", "filter_request", "(", "self", ".", "_vcr_request", ")", ":", "raise", "CannotOverwriteExistingCassetteException", "(", "\"No match for the request (%r) was found. \"", "\"Can't overwrite existing cassette (%r) in \"", "\"your current record mode (%r).\"", "%", "(", "self", ".", "_vcr_request", ",", "self", ".", "cassette", ".", "_path", ",", "self", ".", "cassette", ".", "record_mode", ")", ")", "# Otherwise, we should send the request, then get the response", "# and return it.", "log", ".", "info", "(", "\"{} not in cassette, sending to real server\"", ".", "format", "(", "self", ".", "_vcr_request", ")", ")", "# This is imported here to avoid circular import.", "# TODO(@IvanMalison): Refactor to allow normal import.", "from", "vcr", ".", "patch", "import", "force_reset", "with", "force_reset", "(", ")", ":", "self", ".", "real_connection", ".", "request", "(", "method", "=", "self", ".", "_vcr_request", ".", "method", ",", "url", "=", "self", ".", "_url", "(", "self", ".", "_vcr_request", ".", "uri", ")", ",", "body", "=", "self", ".", "_vcr_request", ".", "body", ",", "headers", "=", "self", ".", "_vcr_request", ".", "headers", ",", ")", "# get the response", "response", "=", "self", ".", "real_connection", ".", "getresponse", "(", ")", "# put the response into the cassette", "response", "=", "{", "'status'", ":", "{", "'code'", ":", "response", ".", "status", ",", "'message'", ":", "response", ".", "reason", "}", ",", "'headers'", ":", "serialize_headers", "(", "response", ")", ",", "'body'", ":", "{", "'string'", ":", "response", ".", "read", "(", ")", "}", ",", "}", "self", ".", "cassette", ".", "append", "(", "self", ".", "_vcr_request", ",", "response", ")", "return", "VCRHTTPResponse", "(", "response", ")" ]
Retrieve the response
[ "Retrieve", "the", "response" ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L216-L272
228,965
kevin1024/vcrpy
vcr/stubs/__init__.py
VCRConnection.connect
def connect(self, *args, **kwargs): """ httplib2 uses this. Connects to the server I'm assuming. Only pass to the baseclass if we don't have a recorded response and are not write-protected. """ if hasattr(self, '_vcr_request') and \ self.cassette.can_play_response_for(self._vcr_request): # We already have a response we are going to play, don't # actually connect return if self.cassette.write_protected: # Cassette is write-protected, don't actually connect return from vcr.patch import force_reset with force_reset(): return self.real_connection.connect(*args, **kwargs) self._sock = VCRFakeSocket()
python
def connect(self, *args, **kwargs): """ httplib2 uses this. Connects to the server I'm assuming. Only pass to the baseclass if we don't have a recorded response and are not write-protected. """ if hasattr(self, '_vcr_request') and \ self.cassette.can_play_response_for(self._vcr_request): # We already have a response we are going to play, don't # actually connect return if self.cassette.write_protected: # Cassette is write-protected, don't actually connect return from vcr.patch import force_reset with force_reset(): return self.real_connection.connect(*args, **kwargs) self._sock = VCRFakeSocket()
[ "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "'_vcr_request'", ")", "and", "self", ".", "cassette", ".", "can_play_response_for", "(", "self", ".", "_vcr_request", ")", ":", "# We already have a response we are going to play, don't", "# actually connect", "return", "if", "self", ".", "cassette", ".", "write_protected", ":", "# Cassette is write-protected, don't actually connect", "return", "from", "vcr", ".", "patch", "import", "force_reset", "with", "force_reset", "(", ")", ":", "return", "self", ".", "real_connection", ".", "connect", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_sock", "=", "VCRFakeSocket", "(", ")" ]
httplib2 uses this. Connects to the server I'm assuming. Only pass to the baseclass if we don't have a recorded response and are not write-protected.
[ "httplib2", "uses", "this", ".", "Connects", "to", "the", "server", "I", "m", "assuming", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L277-L299
228,966
kevin1024/vcrpy
vcr/patch.py
CassettePatcherBuilder._recursively_apply_get_cassette_subclass
def _recursively_apply_get_cassette_subclass(self, replacement_dict_or_obj): """One of the subtleties of this class is that it does not directly replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a subclass of the aforementioned class that has the `cassette` class attribute assigned to `self._cassette`. This behavior is necessary to properly support nested cassette contexts. This function exists to ensure that we use the same class object (reference) to patch everything that replaces VCRRequestHTTP[S]Connection, but that we can talk about patching them with the raw references instead, and without worrying about exactly where the subclass with the relevant value for `cassette` is first created. The function is recursive because it looks in to dictionaries and replaces class values at any depth with the subclass described in the previous paragraph. """ if isinstance(replacement_dict_or_obj, dict): for key, replacement_obj in replacement_dict_or_obj.items(): replacement_obj = self._recursively_apply_get_cassette_subclass( replacement_obj) replacement_dict_or_obj[key] = replacement_obj return replacement_dict_or_obj if hasattr(replacement_dict_or_obj, 'cassette'): replacement_dict_or_obj = self._get_cassette_subclass( replacement_dict_or_obj) return replacement_dict_or_obj
python
def _recursively_apply_get_cassette_subclass(self, replacement_dict_or_obj): """One of the subtleties of this class is that it does not directly replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a subclass of the aforementioned class that has the `cassette` class attribute assigned to `self._cassette`. This behavior is necessary to properly support nested cassette contexts. This function exists to ensure that we use the same class object (reference) to patch everything that replaces VCRRequestHTTP[S]Connection, but that we can talk about patching them with the raw references instead, and without worrying about exactly where the subclass with the relevant value for `cassette` is first created. The function is recursive because it looks in to dictionaries and replaces class values at any depth with the subclass described in the previous paragraph. """ if isinstance(replacement_dict_or_obj, dict): for key, replacement_obj in replacement_dict_or_obj.items(): replacement_obj = self._recursively_apply_get_cassette_subclass( replacement_obj) replacement_dict_or_obj[key] = replacement_obj return replacement_dict_or_obj if hasattr(replacement_dict_or_obj, 'cassette'): replacement_dict_or_obj = self._get_cassette_subclass( replacement_dict_or_obj) return replacement_dict_or_obj
[ "def", "_recursively_apply_get_cassette_subclass", "(", "self", ",", "replacement_dict_or_obj", ")", ":", "if", "isinstance", "(", "replacement_dict_or_obj", ",", "dict", ")", ":", "for", "key", ",", "replacement_obj", "in", "replacement_dict_or_obj", ".", "items", "(", ")", ":", "replacement_obj", "=", "self", ".", "_recursively_apply_get_cassette_subclass", "(", "replacement_obj", ")", "replacement_dict_or_obj", "[", "key", "]", "=", "replacement_obj", "return", "replacement_dict_or_obj", "if", "hasattr", "(", "replacement_dict_or_obj", ",", "'cassette'", ")", ":", "replacement_dict_or_obj", "=", "self", ".", "_get_cassette_subclass", "(", "replacement_dict_or_obj", ")", "return", "replacement_dict_or_obj" ]
One of the subtleties of this class is that it does not directly replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a subclass of the aforementioned class that has the `cassette` class attribute assigned to `self._cassette`. This behavior is necessary to properly support nested cassette contexts. This function exists to ensure that we use the same class object (reference) to patch everything that replaces VCRRequestHTTP[S]Connection, but that we can talk about patching them with the raw references instead, and without worrying about exactly where the subclass with the relevant value for `cassette` is first created. The function is recursive because it looks in to dictionaries and replaces class values at any depth with the subclass described in the previous paragraph.
[ "One", "of", "the", "subtleties", "of", "this", "class", "is", "that", "it", "does", "not", "directly", "replace", "HTTPSConnection", "with", "VCRRequestsHTTPSConnection", "but", "a", "subclass", "of", "the", "aforementioned", "class", "that", "has", "the", "cassette", "class", "attribute", "assigned", "to", "self", ".", "_cassette", ".", "This", "behavior", "is", "necessary", "to", "properly", "support", "nested", "cassette", "contexts", "." ]
114fcd29b43c55896aaa6a6613bc7766f2707c8b
https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/patch.py#L131-L158
228,967
pymupdf/PyMuPDF
fitz/fitz.py
_Widget_fontdict
def _Widget_fontdict(): """Turns the above font definitions into a dictionary. Assumes certain line breaks and spaces. """ flist = Widget_fontobjects[2:-2].splitlines() fdict = {} for f in flist: k, v = f.split(" ") fdict[k[1:]] = v return fdict
python
def _Widget_fontdict(): """Turns the above font definitions into a dictionary. Assumes certain line breaks and spaces. """ flist = Widget_fontobjects[2:-2].splitlines() fdict = {} for f in flist: k, v = f.split(" ") fdict[k[1:]] = v return fdict
[ "def", "_Widget_fontdict", "(", ")", ":", "flist", "=", "Widget_fontobjects", "[", "2", ":", "-", "2", "]", ".", "splitlines", "(", ")", "fdict", "=", "{", "}", "for", "f", "in", "flist", ":", "k", ",", "v", "=", "f", ".", "split", "(", "\" \"", ")", "fdict", "[", "k", "[", "1", ":", "]", "]", "=", "v", "return", "fdict" ]
Turns the above font definitions into a dictionary. Assumes certain line breaks and spaces.
[ "Turns", "the", "above", "font", "definitions", "into", "a", "dictionary", ".", "Assumes", "certain", "line", "breaks", "and", "spaces", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1008-L1016
228,968
pymupdf/PyMuPDF
fitz/fitz.py
getTextlength
def getTextlength(text, fontname="helv", fontsize=11, encoding=0): """Calculate length of a string for a given built-in font. Args: fontname: name of the font. fontsize: size of font in points. encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic). Returns: (float) length of text. """ fontname = fontname.lower() basename = Base14_fontdict.get(fontname, None) glyphs = None if basename == "Symbol": glyphs = symbol_glyphs if basename == "ZapfDingbats": glyphs = zapf_glyphs if glyphs is not None: w = sum([glyphs[ord(c)][1] if ord(c)<256 else glyphs[183][1] for c in text]) return w * fontsize if fontname in Base14_fontdict.keys(): return TOOLS.measure_string(text, Base14_fontdict[fontname], fontsize, encoding) if fontname in ["china-t", "china-s", "china-ts", "china-ss", "japan", "japan-s", "korea", "korea-s"]: return len(text) * fontsize raise ValueError("Font '%s' is unsupported" % fontname)
python
def getTextlength(text, fontname="helv", fontsize=11, encoding=0): """Calculate length of a string for a given built-in font. Args: fontname: name of the font. fontsize: size of font in points. encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic). Returns: (float) length of text. """ fontname = fontname.lower() basename = Base14_fontdict.get(fontname, None) glyphs = None if basename == "Symbol": glyphs = symbol_glyphs if basename == "ZapfDingbats": glyphs = zapf_glyphs if glyphs is not None: w = sum([glyphs[ord(c)][1] if ord(c)<256 else glyphs[183][1] for c in text]) return w * fontsize if fontname in Base14_fontdict.keys(): return TOOLS.measure_string(text, Base14_fontdict[fontname], fontsize, encoding) if fontname in ["china-t", "china-s", "china-ts", "china-ss", "japan", "japan-s", "korea", "korea-s"]: return len(text) * fontsize raise ValueError("Font '%s' is unsupported" % fontname)
[ "def", "getTextlength", "(", "text", ",", "fontname", "=", "\"helv\"", ",", "fontsize", "=", "11", ",", "encoding", "=", "0", ")", ":", "fontname", "=", "fontname", ".", "lower", "(", ")", "basename", "=", "Base14_fontdict", ".", "get", "(", "fontname", ",", "None", ")", "glyphs", "=", "None", "if", "basename", "==", "\"Symbol\"", ":", "glyphs", "=", "symbol_glyphs", "if", "basename", "==", "\"ZapfDingbats\"", ":", "glyphs", "=", "zapf_glyphs", "if", "glyphs", "is", "not", "None", ":", "w", "=", "sum", "(", "[", "glyphs", "[", "ord", "(", "c", ")", "]", "[", "1", "]", "if", "ord", "(", "c", ")", "<", "256", "else", "glyphs", "[", "183", "]", "[", "1", "]", "for", "c", "in", "text", "]", ")", "return", "w", "*", "fontsize", "if", "fontname", "in", "Base14_fontdict", ".", "keys", "(", ")", ":", "return", "TOOLS", ".", "measure_string", "(", "text", ",", "Base14_fontdict", "[", "fontname", "]", ",", "fontsize", ",", "encoding", ")", "if", "fontname", "in", "[", "\"china-t\"", ",", "\"china-s\"", ",", "\"china-ts\"", ",", "\"china-ss\"", ",", "\"japan\"", ",", "\"japan-s\"", ",", "\"korea\"", ",", "\"korea-s\"", "]", ":", "return", "len", "(", "text", ")", "*", "fontsize", "raise", "ValueError", "(", "\"Font '%s' is unsupported\"", "%", "fontname", ")" ]
Calculate length of a string for a given built-in font. Args: fontname: name of the font. fontsize: size of font in points. encoding: encoding to use (0=Latin, 1=Greek, 2=Cyrillic). Returns: (float) length of text.
[ "Calculate", "length", "of", "a", "string", "for", "a", "given", "built", "-", "in", "font", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1242-L1273
228,969
pymupdf/PyMuPDF
fitz/fitz.py
getPDFstr
def getPDFstr(s): """ Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the UTF-16BE encoding of the original. """ if not bool(s): return "()" def make_utf16be(s): r = hexlify(bytearray([254, 255]) + bytearray(s, "UTF-16BE")) t = r if fitz_py2 else r.decode() return "<" + t + ">" # brackets indicate hex # following either returns original string with mixed-in # octal numbers \nnn if outside ASCII range, or: # exits with utf-16be BOM version of the string r = "" for c in s: oc = ord(c) if oc > 255: # shortcut if beyond code range return make_utf16be(s) if oc > 31 and oc < 127: if c in ("(", ")", "\\"): r += "\\" r += c continue if oc > 127: r += "\\" + oct(oc)[-3:] continue if oc < 8 or oc > 13 or oc == 11 or c == 127: r += "\\267" # indicate unsupported char continue if oc == 8: r += "\\b" elif oc == 9: r += "\\t" elif oc == 10: r += "\\n" elif oc == 12: r += "\\f" elif oc == 13: r += "\\r" return "(" + r + ")"
python
def getPDFstr(s): """ Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the UTF-16BE encoding of the original. """ if not bool(s): return "()" def make_utf16be(s): r = hexlify(bytearray([254, 255]) + bytearray(s, "UTF-16BE")) t = r if fitz_py2 else r.decode() return "<" + t + ">" # brackets indicate hex # following either returns original string with mixed-in # octal numbers \nnn if outside ASCII range, or: # exits with utf-16be BOM version of the string r = "" for c in s: oc = ord(c) if oc > 255: # shortcut if beyond code range return make_utf16be(s) if oc > 31 and oc < 127: if c in ("(", ")", "\\"): r += "\\" r += c continue if oc > 127: r += "\\" + oct(oc)[-3:] continue if oc < 8 or oc > 13 or oc == 11 or c == 127: r += "\\267" # indicate unsupported char continue if oc == 8: r += "\\b" elif oc == 9: r += "\\t" elif oc == 10: r += "\\n" elif oc == 12: r += "\\f" elif oc == 13: r += "\\r" return "(" + r + ")"
[ "def", "getPDFstr", "(", "s", ")", ":", "if", "not", "bool", "(", "s", ")", ":", "return", "\"()\"", "def", "make_utf16be", "(", "s", ")", ":", "r", "=", "hexlify", "(", "bytearray", "(", "[", "254", ",", "255", "]", ")", "+", "bytearray", "(", "s", ",", "\"UTF-16BE\"", ")", ")", "t", "=", "r", "if", "fitz_py2", "else", "r", ".", "decode", "(", ")", "return", "\"<\"", "+", "t", "+", "\">\"", "# brackets indicate hex", "# following either returns original string with mixed-in ", "# octal numbers \\nnn if outside ASCII range, or:", "# exits with utf-16be BOM version of the string", "r", "=", "\"\"", "for", "c", "in", "s", ":", "oc", "=", "ord", "(", "c", ")", "if", "oc", ">", "255", ":", "# shortcut if beyond code range", "return", "make_utf16be", "(", "s", ")", "if", "oc", ">", "31", "and", "oc", "<", "127", ":", "if", "c", "in", "(", "\"(\"", ",", "\")\"", ",", "\"\\\\\"", ")", ":", "r", "+=", "\"\\\\\"", "r", "+=", "c", "continue", "if", "oc", ">", "127", ":", "r", "+=", "\"\\\\\"", "+", "oct", "(", "oc", ")", "[", "-", "3", ":", "]", "continue", "if", "oc", "<", "8", "or", "oc", ">", "13", "or", "oc", "==", "11", "or", "c", "==", "127", ":", "r", "+=", "\"\\\\267\"", "# indicate unsupported char", "continue", "if", "oc", "==", "8", ":", "r", "+=", "\"\\\\b\"", "elif", "oc", "==", "9", ":", "r", "+=", "\"\\\\t\"", "elif", "oc", "==", "10", ":", "r", "+=", "\"\\\\n\"", "elif", "oc", "==", "12", ":", "r", "+=", "\"\\\\f\"", "elif", "oc", "==", "13", ":", "r", "+=", "\"\\\\r\"", "return", "\"(\"", "+", "r", "+", "\")\"" ]
Return a PDF string depending on its coding. Notes: If only ascii then "(original)" is returned, else if only 8 bit chars then "(original)" with interspersed octal strings \nnn is returned, else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the UTF-16BE encoding of the original.
[ "Return", "a", "PDF", "string", "depending", "on", "its", "coding", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1464-L1516
228,970
pymupdf/PyMuPDF
fitz/fitz.py
CheckFont
def CheckFont(page, fontname): """Return an entry in the page's font list if reference name matches. """ for f in page.getFontList(): if f[4] == fontname: return f if f[3].lower() == fontname.lower(): return f return None
python
def CheckFont(page, fontname): """Return an entry in the page's font list if reference name matches. """ for f in page.getFontList(): if f[4] == fontname: return f if f[3].lower() == fontname.lower(): return f return None
[ "def", "CheckFont", "(", "page", ",", "fontname", ")", ":", "for", "f", "in", "page", ".", "getFontList", "(", ")", ":", "if", "f", "[", "4", "]", "==", "fontname", ":", "return", "f", "if", "f", "[", "3", "]", ".", "lower", "(", ")", "==", "fontname", ".", "lower", "(", ")", ":", "return", "f", "return", "None" ]
Return an entry in the page's font list if reference name matches.
[ "Return", "an", "entry", "in", "the", "page", "s", "font", "list", "if", "reference", "name", "matches", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1669-L1677
228,971
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.invert
def invert(self, src=None): """Calculate the inverted matrix. Return 0 if successful and replace current one. Else return 1 and do nothing. """ if src is None: dst = TOOLS._invert_matrix(self) else: dst = TOOLS._invert_matrix(src) if dst[0] == 1: return 1 self.a, self.b, self.c, self.d, self.e, self.f = dst[1] return 0
python
def invert(self, src=None): """Calculate the inverted matrix. Return 0 if successful and replace current one. Else return 1 and do nothing. """ if src is None: dst = TOOLS._invert_matrix(self) else: dst = TOOLS._invert_matrix(src) if dst[0] == 1: return 1 self.a, self.b, self.c, self.d, self.e, self.f = dst[1] return 0
[ "def", "invert", "(", "self", ",", "src", "=", "None", ")", ":", "if", "src", "is", "None", ":", "dst", "=", "TOOLS", ".", "_invert_matrix", "(", "self", ")", "else", ":", "dst", "=", "TOOLS", ".", "_invert_matrix", "(", "src", ")", "if", "dst", "[", "0", "]", "==", "1", ":", "return", "1", "self", ".", "a", ",", "self", ".", "b", ",", "self", ".", "c", ",", "self", ".", "d", ",", "self", ".", "e", ",", "self", ".", "f", "=", "dst", "[", "1", "]", "return", "0" ]
Calculate the inverted matrix. Return 0 if successful and replace current one. Else return 1 and do nothing.
[ "Calculate", "the", "inverted", "matrix", ".", "Return", "0", "if", "successful", "and", "replace", "current", "one", ".", "Else", "return", "1", "and", "do", "nothing", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L158-L169
228,972
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.preTranslate
def preTranslate(self, tx, ty): """Calculate pre translation and replace current matrix.""" self.e += tx * self.a + ty * self.c self.f += tx * self.b + ty * self.d return self
python
def preTranslate(self, tx, ty): """Calculate pre translation and replace current matrix.""" self.e += tx * self.a + ty * self.c self.f += tx * self.b + ty * self.d return self
[ "def", "preTranslate", "(", "self", ",", "tx", ",", "ty", ")", ":", "self", ".", "e", "+=", "tx", "*", "self", ".", "a", "+", "ty", "*", "self", ".", "c", "self", ".", "f", "+=", "tx", "*", "self", ".", "b", "+", "ty", "*", "self", ".", "d", "return", "self" ]
Calculate pre translation and replace current matrix.
[ "Calculate", "pre", "translation", "and", "replace", "current", "matrix", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L171-L175
228,973
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.preScale
def preScale(self, sx, sy): """Calculate pre scaling and replace current matrix.""" self.a *= sx self.b *= sx self.c *= sy self.d *= sy return self
python
def preScale(self, sx, sy): """Calculate pre scaling and replace current matrix.""" self.a *= sx self.b *= sx self.c *= sy self.d *= sy return self
[ "def", "preScale", "(", "self", ",", "sx", ",", "sy", ")", ":", "self", ".", "a", "*=", "sx", "self", ".", "b", "*=", "sx", "self", ".", "c", "*=", "sy", "self", ".", "d", "*=", "sy", "return", "self" ]
Calculate pre scaling and replace current matrix.
[ "Calculate", "pre", "scaling", "and", "replace", "current", "matrix", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L177-L183
228,974
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.preShear
def preShear(self, h, v): """Calculate pre shearing and replace current matrix.""" a, b = self.a, self.b self.a += v * self.c self.b += v * self.d self.c += h * a self.d += h * b return self
python
def preShear(self, h, v): """Calculate pre shearing and replace current matrix.""" a, b = self.a, self.b self.a += v * self.c self.b += v * self.d self.c += h * a self.d += h * b return self
[ "def", "preShear", "(", "self", ",", "h", ",", "v", ")", ":", "a", ",", "b", "=", "self", ".", "a", ",", "self", ".", "b", "self", ".", "a", "+=", "v", "*", "self", ".", "c", "self", ".", "b", "+=", "v", "*", "self", ".", "d", "self", ".", "c", "+=", "h", "*", "a", "self", ".", "d", "+=", "h", "*", "b", "return", "self" ]
Calculate pre shearing and replace current matrix.
[ "Calculate", "pre", "shearing", "and", "replace", "current", "matrix", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L185-L192
228,975
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.preRotate
def preRotate(self, theta): """Calculate pre rotation and replace current matrix.""" while theta < 0: theta += 360 while theta >= 360: theta -= 360 epsilon = 1e-5 if abs(0 - theta) < epsilon: pass elif abs(90.0 - theta) < epsilon: a = self.a b = self.b self.a = self.c self.b = self.d self.c = -a self.d = -b elif abs(180.0 - theta) < epsilon: self.a = -self.a self.b = -self.b self.c = -self.c self.d = -self.d elif abs(270.0 - theta) < epsilon: a = self.a b = self.b self.a = -self.c self.b = -self.d self.c = a self.d = b else: rad = math.radians(theta) s = round(math.sin(rad), 12) c = round(math.cos(rad), 12) a = self.a b = self.b self.a = c * a + s * self.c self.b = c * b + s * self.d self.c =-s * a + c * self.c self.d =-s * b + c * self.d return self
python
def preRotate(self, theta): """Calculate pre rotation and replace current matrix.""" while theta < 0: theta += 360 while theta >= 360: theta -= 360 epsilon = 1e-5 if abs(0 - theta) < epsilon: pass elif abs(90.0 - theta) < epsilon: a = self.a b = self.b self.a = self.c self.b = self.d self.c = -a self.d = -b elif abs(180.0 - theta) < epsilon: self.a = -self.a self.b = -self.b self.c = -self.c self.d = -self.d elif abs(270.0 - theta) < epsilon: a = self.a b = self.b self.a = -self.c self.b = -self.d self.c = a self.d = b else: rad = math.radians(theta) s = round(math.sin(rad), 12) c = round(math.cos(rad), 12) a = self.a b = self.b self.a = c * a + s * self.c self.b = c * b + s * self.d self.c =-s * a + c * self.c self.d =-s * b + c * self.d return self
[ "def", "preRotate", "(", "self", ",", "theta", ")", ":", "while", "theta", "<", "0", ":", "theta", "+=", "360", "while", "theta", ">=", "360", ":", "theta", "-=", "360", "epsilon", "=", "1e-5", "if", "abs", "(", "0", "-", "theta", ")", "<", "epsilon", ":", "pass", "elif", "abs", "(", "90.0", "-", "theta", ")", "<", "epsilon", ":", "a", "=", "self", ".", "a", "b", "=", "self", ".", "b", "self", ".", "a", "=", "self", ".", "c", "self", ".", "b", "=", "self", ".", "d", "self", ".", "c", "=", "-", "a", "self", ".", "d", "=", "-", "b", "elif", "abs", "(", "180.0", "-", "theta", ")", "<", "epsilon", ":", "self", ".", "a", "=", "-", "self", ".", "a", "self", ".", "b", "=", "-", "self", ".", "b", "self", ".", "c", "=", "-", "self", ".", "c", "self", ".", "d", "=", "-", "self", ".", "d", "elif", "abs", "(", "270.0", "-", "theta", ")", "<", "epsilon", ":", "a", "=", "self", ".", "a", "b", "=", "self", ".", "b", "self", ".", "a", "=", "-", "self", ".", "c", "self", ".", "b", "=", "-", "self", ".", "d", "self", ".", "c", "=", "a", "self", ".", "d", "=", "b", "else", ":", "rad", "=", "math", ".", "radians", "(", "theta", ")", "s", "=", "round", "(", "math", ".", "sin", "(", "rad", ")", ",", "12", ")", "c", "=", "round", "(", "math", ".", "cos", "(", "rad", ")", ",", "12", ")", "a", "=", "self", ".", "a", "b", "=", "self", ".", "b", "self", ".", "a", "=", "c", "*", "a", "+", "s", "*", "self", ".", "c", "self", ".", "b", "=", "c", "*", "b", "+", "s", "*", "self", ".", "d", "self", ".", "c", "=", "-", "s", "*", "a", "+", "c", "*", "self", ".", "c", "self", ".", "d", "=", "-", "s", "*", "b", "+", "c", "*", "self", ".", "d", "return", "self" ]
Calculate pre rotation and replace current matrix.
[ "Calculate", "pre", "rotation", "and", "replace", "current", "matrix", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L194-L235
228,976
pymupdf/PyMuPDF
fitz/fitz.py
Matrix.concat
def concat(self, one, two): """Multiply two matrices and replace current one.""" if not len(one) == len(two) == 6: raise ValueError("bad sequ. length") self.a, self.b, self.c, self.d, self.e, self.f = TOOLS._concat_matrix(one, two) return self
python
def concat(self, one, two): """Multiply two matrices and replace current one.""" if not len(one) == len(two) == 6: raise ValueError("bad sequ. length") self.a, self.b, self.c, self.d, self.e, self.f = TOOLS._concat_matrix(one, two) return self
[ "def", "concat", "(", "self", ",", "one", ",", "two", ")", ":", "if", "not", "len", "(", "one", ")", "==", "len", "(", "two", ")", "==", "6", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "a", ",", "self", ".", "b", ",", "self", ".", "c", ",", "self", ".", "d", ",", "self", ".", "e", ",", "self", ".", "f", "=", "TOOLS", ".", "_concat_matrix", "(", "one", ",", "two", ")", "return", "self" ]
Multiply two matrices and replace current one.
[ "Multiply", "two", "matrices", "and", "replace", "current", "one", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L237-L242
228,977
pymupdf/PyMuPDF
fitz/fitz.py
Point.transform
def transform(self, m): """Replace point by its transformation with matrix-like m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.x, self.y = TOOLS._transform_point(self, m) return self
python
def transform(self, m): """Replace point by its transformation with matrix-like m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.x, self.y = TOOLS._transform_point(self, m) return self
[ "def", "transform", "(", "self", ",", "m", ")", ":", "if", "len", "(", "m", ")", "!=", "6", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x", ",", "self", ".", "y", "=", "TOOLS", ".", "_transform_point", "(", "self", ",", "m", ")", "return", "self" ]
Replace point by its transformation with matrix-like m.
[ "Replace", "point", "by", "its", "transformation", "with", "matrix", "-", "like", "m", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L386-L391
228,978
pymupdf/PyMuPDF
fitz/fitz.py
Point.unit
def unit(self): """Return unit vector of a point.""" s = self.x * self.x + self.y * self.y if s < 1e-5: return Point(0,0) s = math.sqrt(s) return Point(self.x / s, self.y / s)
python
def unit(self): """Return unit vector of a point.""" s = self.x * self.x + self.y * self.y if s < 1e-5: return Point(0,0) s = math.sqrt(s) return Point(self.x / s, self.y / s)
[ "def", "unit", "(", "self", ")", ":", "s", "=", "self", ".", "x", "*", "self", ".", "x", "+", "self", ".", "y", "*", "self", ".", "y", "if", "s", "<", "1e-5", ":", "return", "Point", "(", "0", ",", "0", ")", "s", "=", "math", ".", "sqrt", "(", "s", ")", "return", "Point", "(", "self", ".", "x", "/", "s", ",", "self", ".", "y", "/", "s", ")" ]
Return unit vector of a point.
[ "Return", "unit", "vector", "of", "a", "point", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L394-L400
228,979
pymupdf/PyMuPDF
fitz/fitz.py
Point.abs_unit
def abs_unit(self): """Return unit vector of a point with positive coordinates.""" s = self.x * self.x + self.y * self.y if s < 1e-5: return Point(0,0) s = math.sqrt(s) return Point(abs(self.x) / s, abs(self.y) / s)
python
def abs_unit(self): """Return unit vector of a point with positive coordinates.""" s = self.x * self.x + self.y * self.y if s < 1e-5: return Point(0,0) s = math.sqrt(s) return Point(abs(self.x) / s, abs(self.y) / s)
[ "def", "abs_unit", "(", "self", ")", ":", "s", "=", "self", ".", "x", "*", "self", ".", "x", "+", "self", ".", "y", "*", "self", ".", "y", "if", "s", "<", "1e-5", ":", "return", "Point", "(", "0", ",", "0", ")", "s", "=", "math", ".", "sqrt", "(", "s", ")", "return", "Point", "(", "abs", "(", "self", ".", "x", ")", "/", "s", ",", "abs", "(", "self", ".", "y", ")", "/", "s", ")" ]
Return unit vector of a point with positive coordinates.
[ "Return", "unit", "vector", "of", "a", "point", "with", "positive", "coordinates", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L403-L409
228,980
pymupdf/PyMuPDF
fitz/fitz.py
Point.distance_to
def distance_to(self, *args): """Return the distance to a rectangle or another point.""" if not len(args) > 0: raise ValueError("at least one parameter must be given") x = args[0] if len(args) > 1: unit = args[1] else: unit = "px" u = {"px": (1.,1.), "in": (1.,72.), "cm": (2.54, 72.), "mm": (25.4, 72.)} f = u[unit][0] / u[unit][1] if type(x) is Point: return abs(self - x) * f # from here on, x is a rectangle # as a safeguard, make a finite copy of it r = Rect(x.top_left, x.top_left) r = r | x.bottom_right if self in r: return 0.0 if self.x > r.x1: if self.y >= r.y1: return self.distance_to(r.bottom_right, unit) elif self.y <= r.y0: return self.distance_to(r.top_right, unit) else: return (self.x - r.x1) * f elif r.x0 <= self.x <= r.x1: if self.y >= r.y1: return (self.y - r.y1) * f else: return (r.y0 - self.y) * f else: if self.y >= r.y1: return self.distance_to(r.bottom_left, unit) elif self.y <= r.y0: return self.distance_to(r.top_left, unit) else: return (r.x0 - self.x) * f
python
def distance_to(self, *args): """Return the distance to a rectangle or another point.""" if not len(args) > 0: raise ValueError("at least one parameter must be given") x = args[0] if len(args) > 1: unit = args[1] else: unit = "px" u = {"px": (1.,1.), "in": (1.,72.), "cm": (2.54, 72.), "mm": (25.4, 72.)} f = u[unit][0] / u[unit][1] if type(x) is Point: return abs(self - x) * f # from here on, x is a rectangle # as a safeguard, make a finite copy of it r = Rect(x.top_left, x.top_left) r = r | x.bottom_right if self in r: return 0.0 if self.x > r.x1: if self.y >= r.y1: return self.distance_to(r.bottom_right, unit) elif self.y <= r.y0: return self.distance_to(r.top_right, unit) else: return (self.x - r.x1) * f elif r.x0 <= self.x <= r.x1: if self.y >= r.y1: return (self.y - r.y1) * f else: return (r.y0 - self.y) * f else: if self.y >= r.y1: return self.distance_to(r.bottom_left, unit) elif self.y <= r.y0: return self.distance_to(r.top_left, unit) else: return (r.x0 - self.x) * f
[ "def", "distance_to", "(", "self", ",", "*", "args", ")", ":", "if", "not", "len", "(", "args", ")", ">", "0", ":", "raise", "ValueError", "(", "\"at least one parameter must be given\"", ")", "x", "=", "args", "[", "0", "]", "if", "len", "(", "args", ")", ">", "1", ":", "unit", "=", "args", "[", "1", "]", "else", ":", "unit", "=", "\"px\"", "u", "=", "{", "\"px\"", ":", "(", "1.", ",", "1.", ")", ",", "\"in\"", ":", "(", "1.", ",", "72.", ")", ",", "\"cm\"", ":", "(", "2.54", ",", "72.", ")", ",", "\"mm\"", ":", "(", "25.4", ",", "72.", ")", "}", "f", "=", "u", "[", "unit", "]", "[", "0", "]", "/", "u", "[", "unit", "]", "[", "1", "]", "if", "type", "(", "x", ")", "is", "Point", ":", "return", "abs", "(", "self", "-", "x", ")", "*", "f", "# from here on, x is a rectangle", "# as a safeguard, make a finite copy of it", "r", "=", "Rect", "(", "x", ".", "top_left", ",", "x", ".", "top_left", ")", "r", "=", "r", "|", "x", ".", "bottom_right", "if", "self", "in", "r", ":", "return", "0.0", "if", "self", ".", "x", ">", "r", ".", "x1", ":", "if", "self", ".", "y", ">=", "r", ".", "y1", ":", "return", "self", ".", "distance_to", "(", "r", ".", "bottom_right", ",", "unit", ")", "elif", "self", ".", "y", "<=", "r", ".", "y0", ":", "return", "self", ".", "distance_to", "(", "r", ".", "top_right", ",", "unit", ")", "else", ":", "return", "(", "self", ".", "x", "-", "r", ".", "x1", ")", "*", "f", "elif", "r", ".", "x0", "<=", "self", ".", "x", "<=", "r", ".", "x1", ":", "if", "self", ".", "y", ">=", "r", ".", "y1", ":", "return", "(", "self", ".", "y", "-", "r", ".", "y1", ")", "*", "f", "else", ":", "return", "(", "r", ".", "y0", "-", "self", ".", "y", ")", "*", "f", "else", ":", "if", "self", ".", "y", ">=", "r", ".", "y1", ":", "return", "self", ".", "distance_to", "(", "r", ".", "bottom_left", ",", "unit", ")", "elif", "self", ".", "y", "<=", "r", ".", "y0", ":", "return", "self", ".", "distance_to", "(", "r", ".", "top_left", ",", "unit", ")", "else", ":", "return", "(", "r", ".", "x0", "-", "self", ".", "x", ")", "*", "f" ]
Return the distance to a rectangle or another point.
[ "Return", "the", "distance", "to", "a", "rectangle", "or", "another", "point", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L411-L451
228,981
pymupdf/PyMuPDF
fitz/fitz.py
Rect.normalize
def normalize(self): """Replace rectangle with its finite version.""" if self.x1 < self.x0: self.x0, self.x1 = self.x1, self.x0 if self.y1 < self.y0: self.y0, self.y1 = self.y1, self.y0 return self
python
def normalize(self): """Replace rectangle with its finite version.""" if self.x1 < self.x0: self.x0, self.x1 = self.x1, self.x0 if self.y1 < self.y0: self.y0, self.y1 = self.y1, self.y0 return self
[ "def", "normalize", "(", "self", ")", ":", "if", "self", ".", "x1", "<", "self", ".", "x0", ":", "self", ".", "x0", ",", "self", ".", "x1", "=", "self", ".", "x1", ",", "self", ".", "x0", "if", "self", ".", "y1", "<", "self", ".", "y0", ":", "self", ".", "y0", ",", "self", ".", "y1", "=", "self", ".", "y1", ",", "self", ".", "y0", "return", "self" ]
Replace rectangle with its finite version.
[ "Replace", "rectangle", "with", "its", "finite", "version", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L572-L578
228,982
pymupdf/PyMuPDF
fitz/fitz.py
Rect.isEmpty
def isEmpty(self): """Check if rectangle area is empty.""" return self.x0 == self.x1 or self.y0 == self.y1
python
def isEmpty(self): """Check if rectangle area is empty.""" return self.x0 == self.x1 or self.y0 == self.y1
[ "def", "isEmpty", "(", "self", ")", ":", "return", "self", ".", "x0", "==", "self", ".", "x1", "or", "self", ".", "y0", "==", "self", ".", "y1" ]
Check if rectangle area is empty.
[ "Check", "if", "rectangle", "area", "is", "empty", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L581-L583
228,983
pymupdf/PyMuPDF
fitz/fitz.py
Rect.isInfinite
def isInfinite(self): """Check if rectangle is infinite.""" return self.x0 > self.x1 or self.y0 > self.y1
python
def isInfinite(self): """Check if rectangle is infinite.""" return self.x0 > self.x1 or self.y0 > self.y1
[ "def", "isInfinite", "(", "self", ")", ":", "return", "self", ".", "x0", ">", "self", ".", "x1", "or", "self", ".", "y0", ">", "self", ".", "y1" ]
Check if rectangle is infinite.
[ "Check", "if", "rectangle", "is", "infinite", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L586-L588
228,984
pymupdf/PyMuPDF
fitz/fitz.py
Rect.includePoint
def includePoint(self, p): """Extend rectangle to include point p.""" if not len(p) == 2: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._include_point_in_rect(self, p) return self
python
def includePoint(self, p): """Extend rectangle to include point p.""" if not len(p) == 2: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._include_point_in_rect(self, p) return self
[ "def", "includePoint", "(", "self", ",", "p", ")", ":", "if", "not", "len", "(", "p", ")", "==", "2", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", ".", "y1", "=", "TOOLS", ".", "_include_point_in_rect", "(", "self", ",", "p", ")", "return", "self" ]
Extend rectangle to include point p.
[ "Extend", "rectangle", "to", "include", "point", "p", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L624-L629
228,985
pymupdf/PyMuPDF
fitz/fitz.py
Rect.includeRect
def includeRect(self, r): """Extend rectangle to include rectangle r.""" if not len(r) == 4: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._union_rect(self, r) return self
python
def includeRect(self, r): """Extend rectangle to include rectangle r.""" if not len(r) == 4: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._union_rect(self, r) return self
[ "def", "includeRect", "(", "self", ",", "r", ")", ":", "if", "not", "len", "(", "r", ")", "==", "4", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", ".", "y1", "=", "TOOLS", ".", "_union_rect", "(", "self", ",", "r", ")", "return", "self" ]
Extend rectangle to include rectangle r.
[ "Extend", "rectangle", "to", "include", "rectangle", "r", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L631-L636
228,986
pymupdf/PyMuPDF
fitz/fitz.py
Rect.intersect
def intersect(self, r): """Restrict self to common area with rectangle r.""" if not len(r) == 4: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._intersect_rect(self, r) return self
python
def intersect(self, r): """Restrict self to common area with rectangle r.""" if not len(r) == 4: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._intersect_rect(self, r) return self
[ "def", "intersect", "(", "self", ",", "r", ")", ":", "if", "not", "len", "(", "r", ")", "==", "4", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", ".", "y1", "=", "TOOLS", ".", "_intersect_rect", "(", "self", ",", "r", ")", "return", "self" ]
Restrict self to common area with rectangle r.
[ "Restrict", "self", "to", "common", "area", "with", "rectangle", "r", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L638-L643
228,987
pymupdf/PyMuPDF
fitz/fitz.py
Rect.transform
def transform(self, m): """Replace rectangle with its transformation by matrix m.""" if not len(m) == 6: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._transform_rect(self, m) return self
python
def transform(self, m): """Replace rectangle with its transformation by matrix m.""" if not len(m) == 6: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._transform_rect(self, m) return self
[ "def", "transform", "(", "self", ",", "m", ")", ":", "if", "not", "len", "(", "m", ")", "==", "6", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", ".", "y1", "=", "TOOLS", ".", "_transform_rect", "(", "self", ",", "m", ")", "return", "self" ]
Replace rectangle with its transformation by matrix m.
[ "Replace", "rectangle", "with", "its", "transformation", "by", "matrix", "m", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L645-L650
228,988
pymupdf/PyMuPDF
fitz/fitz.py
Rect.intersects
def intersects(self, x): """Check if intersection with rectangle x is not empty.""" r1 = Rect(x) if self.isEmpty or self.isInfinite or r1.isEmpty: return False r = Rect(self) if r.intersect(r1).isEmpty: return False return True
python
def intersects(self, x): """Check if intersection with rectangle x is not empty.""" r1 = Rect(x) if self.isEmpty or self.isInfinite or r1.isEmpty: return False r = Rect(self) if r.intersect(r1).isEmpty: return False return True
[ "def", "intersects", "(", "self", ",", "x", ")", ":", "r1", "=", "Rect", "(", "x", ")", "if", "self", ".", "isEmpty", "or", "self", ".", "isInfinite", "or", "r1", ".", "isEmpty", ":", "return", "False", "r", "=", "Rect", "(", "self", ")", "if", "r", ".", "intersect", "(", "r1", ")", ".", "isEmpty", ":", "return", "False", "return", "True" ]
Check if intersection with rectangle x is not empty.
[ "Check", "if", "intersection", "with", "rectangle", "x", "is", "not", "empty", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L766-L774
228,989
pymupdf/PyMuPDF
fitz/fitz.py
Quad.isRectangular
def isRectangular(self): """Check if quad is rectangular. """ # if any two of the 4 corners are equal return false upper = (self.ur - self.ul).unit if not bool(upper): return False right = (self.lr - self.ur).unit if not bool(right): return False left = (self.ll - self.ul).unit if not bool(left): return False lower = (self.lr - self.ll).unit if not bool(lower): return False eps = 1e-5 # we now have 4 sides of length 1. If 3 of them have 90 deg angles, # then it is a rectangle -- we check via scalar product == 0 return abs(sum(map(lambda x,y: x*y, upper, right))) <= eps and \ abs(sum(map(lambda x,y: x*y, upper, left))) <= eps and \ abs(sum(map(lambda x,y: x*y, left, lower))) <= eps
python
def isRectangular(self): """Check if quad is rectangular. """ # if any two of the 4 corners are equal return false upper = (self.ur - self.ul).unit if not bool(upper): return False right = (self.lr - self.ur).unit if not bool(right): return False left = (self.ll - self.ul).unit if not bool(left): return False lower = (self.lr - self.ll).unit if not bool(lower): return False eps = 1e-5 # we now have 4 sides of length 1. If 3 of them have 90 deg angles, # then it is a rectangle -- we check via scalar product == 0 return abs(sum(map(lambda x,y: x*y, upper, right))) <= eps and \ abs(sum(map(lambda x,y: x*y, upper, left))) <= eps and \ abs(sum(map(lambda x,y: x*y, left, lower))) <= eps
[ "def", "isRectangular", "(", "self", ")", ":", "# if any two of the 4 corners are equal return false", "upper", "=", "(", "self", ".", "ur", "-", "self", ".", "ul", ")", ".", "unit", "if", "not", "bool", "(", "upper", ")", ":", "return", "False", "right", "=", "(", "self", ".", "lr", "-", "self", ".", "ur", ")", ".", "unit", "if", "not", "bool", "(", "right", ")", ":", "return", "False", "left", "=", "(", "self", ".", "ll", "-", "self", ".", "ul", ")", ".", "unit", "if", "not", "bool", "(", "left", ")", ":", "return", "False", "lower", "=", "(", "self", ".", "lr", "-", "self", ".", "ll", ")", ".", "unit", "if", "not", "bool", "(", "lower", ")", ":", "return", "False", "eps", "=", "1e-5", "# we now have 4 sides of length 1. If 3 of them have 90 deg angles,", "# then it is a rectangle -- we check via scalar product == 0", "return", "abs", "(", "sum", "(", "map", "(", "lambda", "x", ",", "y", ":", "x", "*", "y", ",", "upper", ",", "right", ")", ")", ")", "<=", "eps", "and", "abs", "(", "sum", "(", "map", "(", "lambda", "x", ",", "y", ":", "x", "*", "y", ",", "upper", ",", "left", ")", ")", ")", "<=", "eps", "and", "abs", "(", "sum", "(", "map", "(", "lambda", "x", ",", "y", ":", "x", "*", "y", ",", "left", ",", "lower", ")", ")", ")", "<=", "eps" ]
Check if quad is rectangular.
[ "Check", "if", "quad", "is", "rectangular", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L879-L900
228,990
pymupdf/PyMuPDF
fitz/fitz.py
Quad.transform
def transform(self, m): """Replace quad by its transformation with matrix m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.ul *= m self.ur *= m self.ll *= m self.lr *= m return self
python
def transform(self, m): """Replace quad by its transformation with matrix m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.ul *= m self.ur *= m self.ll *= m self.lr *= m return self
[ "def", "transform", "(", "self", ",", "m", ")", ":", "if", "len", "(", "m", ")", "!=", "6", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "ul", "*=", "m", "self", ".", "ur", "*=", "m", "self", ".", "ll", "*=", "m", "self", ".", "lr", "*=", "m", "return", "self" ]
Replace quad by its transformation with matrix m.
[ "Replace", "quad", "by", "its", "transformation", "with", "matrix", "m", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L968-L976
228,991
pymupdf/PyMuPDF
fitz/fitz.py
Widget._validate
def _validate(self): """Validate the class entries. """ checker = (self._check0, self._check1, self._check2, self._check3, self._check4, self._check5) if not 0 <= self.field_type <= 5: raise NotImplementedError("unsupported widget type") if type(self.rect) is not Rect: raise ValueError("invalid rect") if self.rect.isInfinite or self.rect.isEmpty: raise ValueError("rect must be finite and not empty") if not self.field_name: raise ValueError("field name missing") if self.border_color: if not len(self.border_color) in range(1,5) or \ type(self.border_color) not in (list, tuple): raise ValueError("border_color must be 1 - 4 floats") if self.fill_color: if not len(self.fill_color) in range(1,5) or \ type(self.fill_color) not in (list, tuple): raise ValueError("fill_color must be 1 - 4 floats") if not self.text_color: self.text_color = (0, 0, 0) if not len(self.text_color) in range(1,5) or \ type(self.text_color) not in (list, tuple): raise ValueError("text_color must be 1 - 4 floats") if not self.border_width: self.border_width = 0 if not self.text_fontsize: self.text_fontsize = 0 checker[self.field_type]()
python
def _validate(self): """Validate the class entries. """ checker = (self._check0, self._check1, self._check2, self._check3, self._check4, self._check5) if not 0 <= self.field_type <= 5: raise NotImplementedError("unsupported widget type") if type(self.rect) is not Rect: raise ValueError("invalid rect") if self.rect.isInfinite or self.rect.isEmpty: raise ValueError("rect must be finite and not empty") if not self.field_name: raise ValueError("field name missing") if self.border_color: if not len(self.border_color) in range(1,5) or \ type(self.border_color) not in (list, tuple): raise ValueError("border_color must be 1 - 4 floats") if self.fill_color: if not len(self.fill_color) in range(1,5) or \ type(self.fill_color) not in (list, tuple): raise ValueError("fill_color must be 1 - 4 floats") if not self.text_color: self.text_color = (0, 0, 0) if not len(self.text_color) in range(1,5) or \ type(self.text_color) not in (list, tuple): raise ValueError("text_color must be 1 - 4 floats") if not self.border_width: self.border_width = 0 if not self.text_fontsize: self.text_fontsize = 0 checker[self.field_type]()
[ "def", "_validate", "(", "self", ")", ":", "checker", "=", "(", "self", ".", "_check0", ",", "self", ".", "_check1", ",", "self", ".", "_check2", ",", "self", ".", "_check3", ",", "self", ".", "_check4", ",", "self", ".", "_check5", ")", "if", "not", "0", "<=", "self", ".", "field_type", "<=", "5", ":", "raise", "NotImplementedError", "(", "\"unsupported widget type\"", ")", "if", "type", "(", "self", ".", "rect", ")", "is", "not", "Rect", ":", "raise", "ValueError", "(", "\"invalid rect\"", ")", "if", "self", ".", "rect", ".", "isInfinite", "or", "self", ".", "rect", ".", "isEmpty", ":", "raise", "ValueError", "(", "\"rect must be finite and not empty\"", ")", "if", "not", "self", ".", "field_name", ":", "raise", "ValueError", "(", "\"field name missing\"", ")", "if", "self", ".", "border_color", ":", "if", "not", "len", "(", "self", ".", "border_color", ")", "in", "range", "(", "1", ",", "5", ")", "or", "type", "(", "self", ".", "border_color", ")", "not", "in", "(", "list", ",", "tuple", ")", ":", "raise", "ValueError", "(", "\"border_color must be 1 - 4 floats\"", ")", "if", "self", ".", "fill_color", ":", "if", "not", "len", "(", "self", ".", "fill_color", ")", "in", "range", "(", "1", ",", "5", ")", "or", "type", "(", "self", ".", "fill_color", ")", "not", "in", "(", "list", ",", "tuple", ")", ":", "raise", "ValueError", "(", "\"fill_color must be 1 - 4 floats\"", ")", "if", "not", "self", ".", "text_color", ":", "self", ".", "text_color", "=", "(", "0", ",", "0", ",", "0", ")", "if", "not", "len", "(", "self", ".", "text_color", ")", "in", "range", "(", "1", ",", "5", ")", "or", "type", "(", "self", ".", "text_color", ")", "not", "in", "(", "list", ",", "tuple", ")", ":", "raise", "ValueError", "(", "\"text_color must be 1 - 4 floats\"", ")", "if", "not", "self", ".", "border_width", ":", "self", ".", "border_width", "=", "0", "if", "not", "self", ".", "text_fontsize", ":", "self", ".", "text_fontsize", "=", "0", "checker", "[", "self", ".", "field_type", "]", "(", ")" ]
Validate the class entries.
[ "Validate", "the", "class", "entries", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1047-L1083
228,992
pymupdf/PyMuPDF
fitz/fitz.py
Widget._adjust_font
def _adjust_font(self): """Ensure the font name is from our list and correctly spelled. """ fnames = [k for k in Widget_fontdict.keys()] fl = list(map(str.lower, fnames)) if (not self.text_font) or self.text_font.lower() not in fl: self.text_font = "helv" i = fl.index(self.text_font.lower()) self.text_font = fnames[i] return
python
def _adjust_font(self): """Ensure the font name is from our list and correctly spelled. """ fnames = [k for k in Widget_fontdict.keys()] fl = list(map(str.lower, fnames)) if (not self.text_font) or self.text_font.lower() not in fl: self.text_font = "helv" i = fl.index(self.text_font.lower()) self.text_font = fnames[i] return
[ "def", "_adjust_font", "(", "self", ")", ":", "fnames", "=", "[", "k", "for", "k", "in", "Widget_fontdict", ".", "keys", "(", ")", "]", "fl", "=", "list", "(", "map", "(", "str", ".", "lower", ",", "fnames", ")", ")", "if", "(", "not", "self", ".", "text_font", ")", "or", "self", ".", "text_font", ".", "lower", "(", ")", "not", "in", "fl", ":", "self", ".", "text_font", "=", "\"helv\"", "i", "=", "fl", ".", "index", "(", "self", ".", "text_font", ".", "lower", "(", ")", ")", "self", ".", "text_font", "=", "fnames", "[", "i", "]", "return" ]
Ensure the font name is from our list and correctly spelled.
[ "Ensure", "the", "font", "name", "is", "from", "our", "list", "and", "correctly", "spelled", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1085-L1094
228,993
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileCount
def embeddedFileCount(self): """Return number of embedded files.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileCount(self)
python
def embeddedFileCount(self): """Return number of embedded files.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileCount(self)
[ "def", "embeddedFileCount", "(", "self", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileCount", "(", "self", ")" ]
Return number of embedded files.
[ "Return", "number", "of", "embedded", "files", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1906-L1911
228,994
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileDel
def embeddedFileDel(self, name): """Delete embedded file by name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileDel(self, name)
python
def embeddedFileDel(self, name): """Delete embedded file by name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileDel(self, name)
[ "def", "embeddedFileDel", "(", "self", ",", "name", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileDel", "(", "self", ",", "name", ")" ]
Delete embedded file by name.
[ "Delete", "embedded", "file", "by", "name", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1914-L1919
228,995
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileInfo
def embeddedFileInfo(self, id): """Retrieve embedded file information given its entry number or name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileInfo(self, id)
python
def embeddedFileInfo(self, id): """Retrieve embedded file information given its entry number or name.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileInfo(self, id)
[ "def", "embeddedFileInfo", "(", "self", ",", "id", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileInfo", "(", "self", ",", "id", ")" ]
Retrieve embedded file information given its entry number or name.
[ "Retrieve", "embedded", "file", "information", "given", "its", "entry", "number", "or", "name", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1922-L1927
228,996
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileUpd
def embeddedFileUpd(self, id, buffer=None, filename=None, ufilename=None, desc=None): """Change an embedded file given its entry number or name.""" return _fitz.Document_embeddedFileUpd(self, id, buffer, filename, ufilename, desc)
python
def embeddedFileUpd(self, id, buffer=None, filename=None, ufilename=None, desc=None): """Change an embedded file given its entry number or name.""" return _fitz.Document_embeddedFileUpd(self, id, buffer, filename, ufilename, desc)
[ "def", "embeddedFileUpd", "(", "self", ",", "id", ",", "buffer", "=", "None", ",", "filename", "=", "None", ",", "ufilename", "=", "None", ",", "desc", "=", "None", ")", ":", "return", "_fitz", ".", "Document_embeddedFileUpd", "(", "self", ",", "id", ",", "buffer", ",", "filename", ",", "ufilename", ",", "desc", ")" ]
Change an embedded file given its entry number or name.
[ "Change", "an", "embedded", "file", "given", "its", "entry", "number", "or", "name", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1930-L1932
228,997
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileGet
def embeddedFileGet(self, id): """Retrieve embedded file content by name or by number.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileGet(self, id)
python
def embeddedFileGet(self, id): """Retrieve embedded file content by name or by number.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileGet(self, id)
[ "def", "embeddedFileGet", "(", "self", ",", "id", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileGet", "(", "self", ",", "id", ")" ]
Retrieve embedded file content by name or by number.
[ "Retrieve", "embedded", "file", "content", "by", "name", "or", "by", "number", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1940-L1945
228,998
pymupdf/PyMuPDF
fitz/fitz.py
Document.embeddedFileAdd
def embeddedFileAdd(self, buffer, name, filename=None, ufilename=None, desc=None): """Embed a new file.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileAdd(self, buffer, name, filename, ufilename, desc)
python
def embeddedFileAdd(self, buffer, name, filename=None, ufilename=None, desc=None): """Embed a new file.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileAdd(self, buffer, name, filename, ufilename, desc)
[ "def", "embeddedFileAdd", "(", "self", ",", "buffer", ",", "name", ",", "filename", "=", "None", ",", "ufilename", "=", "None", ",", "desc", "=", "None", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_embeddedFileAdd", "(", "self", ",", "buffer", ",", "name", ",", "filename", ",", "ufilename", ",", "desc", ")" ]
Embed a new file.
[ "Embed", "a", "new", "file", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1948-L1955
228,999
pymupdf/PyMuPDF
fitz/fitz.py
Document.convertToPDF
def convertToPDF(self, from_page=0, to_page=-1, rotate=0): """Convert document to PDF selecting page range and optional rotation. Output bytes object.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_convertToPDF(self, from_page, to_page, rotate)
python
def convertToPDF(self, from_page=0, to_page=-1, rotate=0): """Convert document to PDF selecting page range and optional rotation. Output bytes object.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_convertToPDF(self, from_page, to_page, rotate)
[ "def", "convertToPDF", "(", "self", ",", "from_page", "=", "0", ",", "to_page", "=", "-", "1", ",", "rotate", "=", "0", ")", ":", "if", "self", ".", "isClosed", "or", "self", ".", "isEncrypted", ":", "raise", "ValueError", "(", "\"operation illegal for closed / encrypted doc\"", ")", "return", "_fitz", ".", "Document_convertToPDF", "(", "self", ",", "from_page", ",", "to_page", ",", "rotate", ")" ]
Convert document to PDF selecting page range and optional rotation. Output bytes object.
[ "Convert", "document", "to", "PDF", "selecting", "page", "range", "and", "optional", "rotation", ".", "Output", "bytes", "object", "." ]
917f2d83482510e26ba0ff01fd2392c26f3a8e90
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L1958-L1963