code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import logging
logging.basicConfig(level=logging.DEBUG)
import pytest
from hpolib.benchmarks.nas.nasbench_201 import ImageNetNasBench201Benchmark, Cifar100NasBench201Benchmark, \
Cifar10ValidNasBench201Benchmark, Cifar10NasBench201Benchmark as Cifar10NasBench201BenchmarkContainer
from hpolib.benchmarks.nas.nasbench_201 import Cifar10NasBench201Benchmark
from hpolib.util.container_utils import disable_container_debug, enable_container_debug
@pytest.fixture(scope='module')
def enable_debug():
enable_container_debug()
yield
disable_container_debug()
def test_nasbench201_cifar10valid(enable_debug):
b = Cifar10ValidNasBench201Benchmark(rng=0)
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result['function_value'] == pytest.approx(0.411, abs=0.1)
assert result['cost'] == pytest.approx(6650.88, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
assert result['info']['train_cost'] == result['cost']
def test_nasbench201_cifar100(enable_debug):
b = Cifar100NasBench201Benchmark(rng=0)
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result is not None
assert result['function_value'] == pytest.approx(7.8259, abs=0.1)
assert result['cost'] == pytest.approx(13301.76, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
assert result['info']['train_cost'] == result['cost']
def test_nasbench201_Image(enable_debug):
b = ImageNetNasBench201Benchmark(rng=0)
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result is not None
assert result['function_value'] == pytest.approx(62.858, abs=0.1)
assert result['cost'] == pytest.approx(40357.56, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
assert result['info']['train_cost'] == result['cost']
def test_nasbench201_cifar10_container(enable_debug):
b = Cifar10NasBench201BenchmarkContainer(rng=0)
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result is not None
assert result['function_value'] == pytest.approx(0.5019, abs=0.1)
assert result['cost'] == pytest.approx(13301.76, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
def test_nasbench201_cifar10():
b = Cifar10NasBench201Benchmark(rng=0)
assert b.data is not None
assert len(b.get_meta_information()) == 2
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result is not None
assert result['function_value'] == pytest.approx(0.5019, abs=0.1)
assert result['cost'] == pytest.approx(13301.76, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
result_test = b.objective_function_test(configuration=config, fidelity=fidelity)
assert result['info']['train_precision'] == result_test['info']['train_precision']
assert result['info']['train_cost'] == result_test['info']['train_cost']
assert result['info']['train_losses'] == result_test['info']['train_losses']
assert result['info']['eval_precision'] == result_test['info']['eval_precision']
assert result['info']['eval_losses'] == result_test['info']['eval_losses']
assert result['info']['eval_cost'] == result_test['info']['eval_cost']
assert result_test['cost'] > result['cost']
result_lower = b.objective_function(configuration=config, fidelity={'epoch': 100},
data_seed=(777, 888, 999))
assert result['cost'] > result_lower['cost']
with pytest.raises(ValueError):
b.objective_function(configuration=config, fidelity={'epoch': 200}, data_seed=0.1)
with pytest.raises(AssertionError):
b.objective_function(configuration=config, fidelity=fidelity, data_seed=0.1)
with pytest.raises(AssertionError):
b.objective_function(configuration=config, fidelity=fidelity, data_seed=0)
with pytest.raises(AssertionError):
b.objective_function(configuration=config, fidelity=fidelity, data_seed=[777, 881])
with pytest.raises(AssertionError):
b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 881))
def test_nasbench201_fidelity_space():
fs = Cifar10NasBench201Benchmark(rng=0).get_fidelity_space()
assert len(fs.get_hyperparameters()) == 1
def test_nasbench201_config():
cs = Cifar10NasBench201Benchmark(rng=0).get_configuration_space(seed=0)
c = cs.sample_configuration()
func = Cifar10NasBench201Benchmark.config_to_structure_func(4)
struct = func(c)
assert struct.__repr__() == '_Structure(4 nodes with |avg_pool_3x3~0|+|none~0|nor_conv_3x3~1|+' \
'|nor_conv_3x3~0|nor_conv_3x3~1|skip_connect~2|)'
assert len(struct) == 4
assert struct[0] == (('avg_pool_3x3', 0),)
struct_str = struct.tostr()
assert struct_str == '|avg_pool_3x3~0|+|none~0|nor_conv_3x3~1|+|nor_conv_3x3~0|nor_conv_3x3~1|skip_connect~2|' | tests/test_nasbench_201.py | import logging
logging.basicConfig(level=logging.DEBUG)
import pytest
from hpolib.benchmarks.nas.nasbench_201 import ImageNetNasBench201Benchmark, Cifar100NasBench201Benchmark, \
Cifar10ValidNasBench201Benchmark, Cifar10NasBench201Benchmark as Cifar10NasBench201BenchmarkContainer
from hpolib.benchmarks.nas.nasbench_201 import Cifar10NasBench201Benchmark
from hpolib.util.container_utils import disable_container_debug, enable_container_debug
@pytest.fixture(scope='module')
def enable_debug():
enable_container_debug()
yield
disable_container_debug()
def test_nasbench201_cifar10valid(enable_debug):
b = Cifar10ValidNasBench201Benchmark(rng=0)
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result['function_value'] == pytest.approx(0.411, abs=0.1)
assert result['cost'] == pytest.approx(6650.88, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
assert result['info']['train_cost'] == result['cost']
def test_nasbench201_cifar100(enable_debug):
b = Cifar100NasBench201Benchmark(rng=0)
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result is not None
assert result['function_value'] == pytest.approx(7.8259, abs=0.1)
assert result['cost'] == pytest.approx(13301.76, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
assert result['info']['train_cost'] == result['cost']
def test_nasbench201_Image(enable_debug):
b = ImageNetNasBench201Benchmark(rng=0)
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result is not None
assert result['function_value'] == pytest.approx(62.858, abs=0.1)
assert result['cost'] == pytest.approx(40357.56, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
assert result['info']['train_cost'] == result['cost']
def test_nasbench201_cifar10_container(enable_debug):
b = Cifar10NasBench201BenchmarkContainer(rng=0)
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result is not None
assert result['function_value'] == pytest.approx(0.5019, abs=0.1)
assert result['cost'] == pytest.approx(13301.76, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
def test_nasbench201_cifar10():
b = Cifar10NasBench201Benchmark(rng=0)
assert b.data is not None
assert len(b.get_meta_information()) == 2
cs = b.get_configuration_space(seed=0)
config = cs.sample_configuration()
fidelity = {'epoch': 199}
result = b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 888, 999))
assert result is not None
assert result['function_value'] == pytest.approx(0.5019, abs=0.1)
assert result['cost'] == pytest.approx(13301.76, abs=0.1)
assert result['info']['train_precision'] == result['function_value']
result_test = b.objective_function_test(configuration=config, fidelity=fidelity)
assert result['info']['train_precision'] == result_test['info']['train_precision']
assert result['info']['train_cost'] == result_test['info']['train_cost']
assert result['info']['train_losses'] == result_test['info']['train_losses']
assert result['info']['eval_precision'] == result_test['info']['eval_precision']
assert result['info']['eval_losses'] == result_test['info']['eval_losses']
assert result['info']['eval_cost'] == result_test['info']['eval_cost']
assert result_test['cost'] > result['cost']
result_lower = b.objective_function(configuration=config, fidelity={'epoch': 100},
data_seed=(777, 888, 999))
assert result['cost'] > result_lower['cost']
with pytest.raises(ValueError):
b.objective_function(configuration=config, fidelity={'epoch': 200}, data_seed=0.1)
with pytest.raises(AssertionError):
b.objective_function(configuration=config, fidelity=fidelity, data_seed=0.1)
with pytest.raises(AssertionError):
b.objective_function(configuration=config, fidelity=fidelity, data_seed=0)
with pytest.raises(AssertionError):
b.objective_function(configuration=config, fidelity=fidelity, data_seed=[777, 881])
with pytest.raises(AssertionError):
b.objective_function(configuration=config, fidelity=fidelity, data_seed=(777, 881))
def test_nasbench201_fidelity_space():
fs = Cifar10NasBench201Benchmark(rng=0).get_fidelity_space()
assert len(fs.get_hyperparameters()) == 1
def test_nasbench201_config():
cs = Cifar10NasBench201Benchmark(rng=0).get_configuration_space(seed=0)
c = cs.sample_configuration()
func = Cifar10NasBench201Benchmark.config_to_structure_func(4)
struct = func(c)
assert struct.__repr__() == '_Structure(4 nodes with |avg_pool_3x3~0|+|none~0|nor_conv_3x3~1|+' \
'|nor_conv_3x3~0|nor_conv_3x3~1|skip_connect~2|)'
assert len(struct) == 4
assert struct[0] == (('avg_pool_3x3', 0),)
struct_str = struct.tostr()
assert struct_str == '|avg_pool_3x3~0|+|none~0|nor_conv_3x3~1|+|nor_conv_3x3~0|nor_conv_3x3~1|skip_connect~2|' | 0.498535 | 0.54819 |
import numpy as np
from .pyramid import Pyramid
from .filters import parse_filter
from .c.wrapper import corrDn, upConv
class WaveletPyramid(Pyramid):
"""Multiscale wavelet pyramid
Parameters
----------
image : `array_like`
1d or 2d image upon which to construct to the pyramid.
height : 'auto' or `int`.
The height of the pyramid. If 'auto', will automatically determine based on the size of
`image`.
filter_name : {'binomN', 'haar', 'qmf8', 'qmf12', 'qmf16', 'daub2', 'daub3', 'daub4', 'qmf5',
'qmf9', 'qmf13'}
name of filter to use when constructing pyramid. All scaled so L-2 norm is 1.0
* `'binomN'` - binomial coefficient filter of order N-1
* `'haar'` - Haar wavelet
* `'qmf8'`, `'qmf12'`, `'qmf16'` - Symmetric Quadrature Mirror Filters [1]_
* `'daub2'`, `'daub3'`, `'daub4'` - Daubechies wavelet [2]_
* `'qmf5'`, `'qmf9'`, `'qmf13'` - Symmetric Quadrature Mirror Filters [3]_, [4]_
edge_type : {'circular', 'reflect1', 'reflect2', 'repeat', 'zero', 'extend', 'dont-compute'}
Specifies how to handle edges. Options are:
* `'circular'` - circular convolution
* `'reflect1'` - reflect about the edge pixels
* `'reflect2'` - reflect, doubling the edge pixels
* `'repeat'` - repeat the edge pixels
* `'zero'` - assume values of zero outside image boundary
* `'extend'` - reflect and invert
* `'dont-compute'` - zero output when filter overhangs imput boundaries.
Attributes
----------
image : `array_like`
The input image used to construct the pyramid.
image_size : `tuple`
The size of the input image.
pyr_type : `str` or `None`
Human-readable string specifying the type of pyramid. For base class, is None.
edge_type : `str`
Specifies how edges were handled.
pyr_coeffs : `dict`
Dictionary containing the coefficients of the pyramid. Keys are `(level, band)` tuples and
values are 1d or 2d numpy arrays (same number of dimensions as the input image)
pyr_size : `dict`
Dictionary containing the sizes of the pyramid coefficients. Keys are `(level, band)`
tuples and values are tuples.
is_complex : `bool`
Whether the coefficients are complex- or real-valued. Only `SteerablePyramidFreq` can have
a value of True, all others must be False.
References
----------
.. [1] <NAME>, "A filter family designed for use in quadrature mirror filter banks",
Proc. ICASSP, pp 291-294, 1980.
.. [2] <NAME>, "Orthonormal bases of compactly supported wavelets", Commun. Pure Appl.
Math, vol. 42, pp 909-996, 1988.
.. [3] <NAME>, "Orthogonal sub-band image transforms", PhD Thesis, MIT Dept. of Elec.
Eng. and Comp. Sci. May 1988. Also available as: MIT Media Laboratory Vision and Modeling
Technical Report #100.
.. [4] <NAME> and <NAME>, "Subband image coding", Subband Transforms, chapter 4,
ed. <NAME>, Kluwer Academic Publishers, Norwell, MA, 1990, pp 143--192.
"""
def __init__(self, image, height='auto', filter_name='qmf9', edge_type='reflect1'):
super().__init__(image=image, edge_type=edge_type)
self.pyr_type = 'Wavelet'
self.filters = {}
self.filters['lo_filter'] = parse_filter(filter_name, normalize=False)
self.filters["hi_filter"] = WaveletPyramid._modulate_flip(self.filters['lo_filter'])
assert self.filters['lo_filter'].shape == self.filters['hi_filter'].shape
# Stagger sampling if filter is odd-length
self.stagger = (self.filters['lo_filter'].size + 1) % 2
self._set_num_scales('lo_filter', height)
# compute the number of channels per level
if min(self.image.shape) == 1:
self.num_orientations = 1
else:
self.num_orientations = 3
self._build_pyr()
def _modulate_flip(lo_filter):
'''construct QMF/Wavelet highpass filter from lowpass filter
modulate by (-1)^n, reverse order (and shift by one, which is handled by the convolution
routines). This is an extension of the original definition of QMF's (e.g., see
Simoncelli90).
Parameters
----------
lo_filter : `array_like`
one-dimensional array (or effectively 1d array) containing the lowpass filter to
convert into the highpass filter.
Returns
-------
hi_filter : `np.array`
The highpass filter constructed from the lowpass filter, same shape as the lowpass
filter.
'''
# check lo_filter is effectively 1D
lo_filter_shape = lo_filter.shape
assert lo_filter.size == max(lo_filter_shape)
lo_filter = lo_filter.flatten()
ind = np.arange(lo_filter.size, 0, -1) - (lo_filter.size + 1) // 2
hi_filter = lo_filter[::-1] * (-1.0) ** ind
return hi_filter.reshape(lo_filter_shape)
def _build_next(self, image):
"""Build the next level fo the Wavelet pyramid
Should not be called by users directly, this is a helper function to construct the pyramid.
Parameters
----------
image : `array_like`
image to use to construct next level.
Returns
-------
lolo : `array_like`
This is the result of applying the lowpass filter once if `image` is 1d, twice if it's
2d. It's downsampled by a factor of two from the original `image`.
hi_tuple : `tuple`
If `image` is 1d, this just contains `hihi`, the result of applying the highpass filter
. If `image` is 2d, it is `(lohi, hilo, hihi)`, the result of applying the lowpass then
the highpass, the highpass then the lowpass, and the highpass twice. All will be
downsampled by a factor of two from the original `image`.
"""
if image.shape[1] == 1:
lolo = corrDn(image=image, filt=self.filters['lo_filter'], edge_type=self.edge_type, step=(2, 1), start=(self.stagger, 0))
hihi = corrDn(image=image, filt=self.filters['hi_filter'], edge_type=self.edge_type, step=(2, 1), start=(1, 0))
return lolo, (hihi, )
elif image.shape[0] == 1:
lolo = corrDn(image=image, filt=self.filters['lo_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, self.stagger))
hihi = corrDn(image=image, filt=self.filters['hi_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, 1))
return lolo, (hihi, )
else:
lo = corrDn(image=image, filt=self.filters['lo_filter'], edge_type=self.edge_type, step=(2, 1), start=(self.stagger, 0))
hi = corrDn(image=image, filt=self.filters['hi_filter'], edge_type=self.edge_type, step=(2, 1), start=(1, 0))
lolo = corrDn(image=lo, filt=self.filters['lo_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, self.stagger))
lohi = corrDn(image=hi, filt=self.filters['lo_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, self.stagger))
hilo = corrDn(image=lo, filt=self.filters['hi_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, 1))
hihi = corrDn(image=hi, filt=self.filters['hi_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, 1))
return lolo, (lohi, hilo, hihi)
def _build_pyr(self):
im = self.image
for lev in range(self.num_scales):
im, higher_bands = self._build_next(im)
for j, band in enumerate(higher_bands):
self.pyr_coeffs[(lev, j)] = band
self.pyr_size[(lev, j)] = band.shape
self.pyr_coeffs['residual_lowpass'] = im
self.pyr_size['residual_lowpass'] = im.shape
def _recon_prev(self, image, lev, recon_keys, output_size, lo_filter, hi_filter, edge_type,
stagger):
"""Reconstruct the previous level of the pyramid.
Should not be called by users directly, this is a helper function for reconstructing the
input image using pyramid coefficients.
"""
if self.num_orientations == 1:
if output_size[0] == 1:
recon = upConv(image=image, filt=lo_filter.T, edge_type=edge_type, step=(1, 2), start=(0, stagger), stop=output_size)
if (lev, 0) in recon_keys:
recon += upConv(image=self.pyr_coeffs[(lev, 0)], filt=hi_filter.T, edge_type=edge_type, step=(1, 2), start=(0, 1), stop=output_size)
elif output_size[1] == 1:
recon = upConv(image=image, filt=lo_filter, edge_type=edge_type, step=(2, 1), start=(stagger, 0), stop=output_size)
if (lev, 0) in recon_keys:
recon += upConv(image=self.pyr_coeffs[(lev, 0)], filt=hi_filter, edge_type=edge_type, step=(2, 1), start=(1, 0), stop=output_size)
else:
lo_size = ([self.pyr_size[(lev, 1)][0], output_size[1]])
hi_size = ([self.pyr_size[(lev, 0)][0], output_size[1]])
tmp_recon = upConv(image=image, filt=lo_filter.T, edge_type=edge_type, step=(1, 2), start=(0, stagger), stop=lo_size)
recon = upConv(image=tmp_recon, filt=lo_filter, edge_type=edge_type, step=(2, 1), start=(stagger, 0), stop=output_size)
bands_recon_dict = {
0: [{'filt': lo_filter.T, 'start': (0, stagger), 'stop': hi_size},
{'filt': hi_filter, 'start': (1, 0)}],
1: [{'filt': hi_filter.T, 'start': (0, 1), 'stop': lo_size},
{'filt': lo_filter, 'start': (stagger, 0)}],
2: [{'filt': hi_filter.T, 'start': (0, 1), 'stop': hi_size},
{'filt': hi_filter, 'start': (1, 0)}],
}
for band in range(self.num_orientations):
if (lev, band) in recon_keys:
tmp_recon = upConv(image=self.pyr_coeffs[(lev, band)], edge_type=edge_type, step=(1, 2), **bands_recon_dict[band][0])
recon += upConv(image=tmp_recon, edge_type=edge_type, step=(2, 1), stop=output_size, **bands_recon_dict[band][1])
return recon
def recon_pyr(self, filter_name=None, edge_type=None, levels='all', bands='all'):
"""Reconstruct the input image using pyramid coefficients.
This function reconstructs the input image using pyramid coefficients.
Parameters
----------
filter_name : {None, 'binomN', 'haar', 'qmf8', 'qmf12', 'qmf16', 'daub2', 'daub3', 'daub4',
'qmf5', 'qmf9', 'qmf13'}
name of filter to use for reconstruction. All scaled so L-2 norm is 1.0
* None (default) - use `self.filter_name`, the filter used to construct the pyramid.
* `'binomN'` - binomial coefficient filter of order N-1
* `'haar'` - Haar wavelet
* `'qmf8'`, `'qmf12'`, `'qmf16'` - Symmetric Quadrature Mirror Filters [1]_
* `'daub2'`, `'daub3'`, `'daub4'` - Daubechies wavelet [2]_
* `'qmf5'`, `'qmf9'`, `'qmf13'` - Symmetric Quadrature Mirror Filters [3]_, [4]_
edge_type : {None, 'circular', 'reflect1', 'reflect2', 'repeat', 'zero', 'extend',
'dont-compute'}
Specifies how to handle edges. Options are:
* None (default) - use `self.edge_type`, the edge_type used to construct the pyramid
* `'circular'` - circular convolution
* `'reflect1'` - reflect about the edge pixels
* `'reflect2'` - reflect, doubling the edge pixels
* `'repeat'` - repeat the edge pixels
* `'zero'` - assume values of zero outside image boundary
* `'extend'` - reflect and inverts
* `'dont-compute'` - zero output when filter overhangs imput boundaries.
levels : `list`, `int`, or {`'all'`, `'residual_highpass'`}
If `list` should contain some subset of integers from `0` to `self.num_scales-1`
(inclusive) and `'residual_lowpass'`. If `'all'`, returned value will contain all
valid levels. Otherwise, must be one of the valid levels.
bands : `list`, `int`, or `'all'`.
If list, should contain some subset of integers from `0` to `self.num_orientations-1`.
If `'all'`, returned value will contain all valid orientations. Otherwise, must be one
of the valid orientations.
Returns
-------
recon : `np.array`
The reconstructed image.
"""
# Optional args
if filter_name is None:
lo_filter = self.filters['lo_filter']
hi_filter = self.filters['hi_filter']
stagger = self.stagger
else:
lo_filter = parse_filter(filter_name, normalize=False)
hi_filter = WaveletPyramid._modulate_flip(lo_filter)
stagger = (lo_filter.size + 1) % 2
if edge_type is None:
edges = self.edge_type
else:
edges = edge_type
recon_keys = self._recon_keys(levels, bands)
# initialize reconstruction
if 'residual_lowpass' in recon_keys:
recon = self.pyr_coeffs['residual_lowpass']
else:
recon = np.zeros_like(self.pyr_coeffs['residual_lowpass'])
for lev in reversed(range(self.num_scales)):
if self.num_orientations == 1:
if lev == 0:
output_size = self.image.shape
else:
output_size = self.pyr_size[(lev-1, 0)]
else:
output_size = (self.pyr_size[(lev, 0)][0] + self.pyr_size[(lev, 1)][0],
self.pyr_size[(lev, 0)][1] + self.pyr_size[(lev, 1)][1])
recon = self._recon_prev(recon, lev, recon_keys, output_size, lo_filter,
hi_filter, edges, stagger)
return recon | pyrtools/pyramids/WaveletPyramid.py | import numpy as np
from .pyramid import Pyramid
from .filters import parse_filter
from .c.wrapper import corrDn, upConv
class WaveletPyramid(Pyramid):
"""Multiscale wavelet pyramid
Parameters
----------
image : `array_like`
1d or 2d image upon which to construct to the pyramid.
height : 'auto' or `int`.
The height of the pyramid. If 'auto', will automatically determine based on the size of
`image`.
filter_name : {'binomN', 'haar', 'qmf8', 'qmf12', 'qmf16', 'daub2', 'daub3', 'daub4', 'qmf5',
'qmf9', 'qmf13'}
name of filter to use when constructing pyramid. All scaled so L-2 norm is 1.0
* `'binomN'` - binomial coefficient filter of order N-1
* `'haar'` - Haar wavelet
* `'qmf8'`, `'qmf12'`, `'qmf16'` - Symmetric Quadrature Mirror Filters [1]_
* `'daub2'`, `'daub3'`, `'daub4'` - Daubechies wavelet [2]_
* `'qmf5'`, `'qmf9'`, `'qmf13'` - Symmetric Quadrature Mirror Filters [3]_, [4]_
edge_type : {'circular', 'reflect1', 'reflect2', 'repeat', 'zero', 'extend', 'dont-compute'}
Specifies how to handle edges. Options are:
* `'circular'` - circular convolution
* `'reflect1'` - reflect about the edge pixels
* `'reflect2'` - reflect, doubling the edge pixels
* `'repeat'` - repeat the edge pixels
* `'zero'` - assume values of zero outside image boundary
* `'extend'` - reflect and invert
* `'dont-compute'` - zero output when filter overhangs imput boundaries.
Attributes
----------
image : `array_like`
The input image used to construct the pyramid.
image_size : `tuple`
The size of the input image.
pyr_type : `str` or `None`
Human-readable string specifying the type of pyramid. For base class, is None.
edge_type : `str`
Specifies how edges were handled.
pyr_coeffs : `dict`
Dictionary containing the coefficients of the pyramid. Keys are `(level, band)` tuples and
values are 1d or 2d numpy arrays (same number of dimensions as the input image)
pyr_size : `dict`
Dictionary containing the sizes of the pyramid coefficients. Keys are `(level, band)`
tuples and values are tuples.
is_complex : `bool`
Whether the coefficients are complex- or real-valued. Only `SteerablePyramidFreq` can have
a value of True, all others must be False.
References
----------
.. [1] <NAME>, "A filter family designed for use in quadrature mirror filter banks",
Proc. ICASSP, pp 291-294, 1980.
.. [2] <NAME>, "Orthonormal bases of compactly supported wavelets", Commun. Pure Appl.
Math, vol. 42, pp 909-996, 1988.
.. [3] <NAME>, "Orthogonal sub-band image transforms", PhD Thesis, MIT Dept. of Elec.
Eng. and Comp. Sci. May 1988. Also available as: MIT Media Laboratory Vision and Modeling
Technical Report #100.
.. [4] <NAME> and <NAME>, "Subband image coding", Subband Transforms, chapter 4,
ed. <NAME>, Kluwer Academic Publishers, Norwell, MA, 1990, pp 143--192.
"""
def __init__(self, image, height='auto', filter_name='qmf9', edge_type='reflect1'):
super().__init__(image=image, edge_type=edge_type)
self.pyr_type = 'Wavelet'
self.filters = {}
self.filters['lo_filter'] = parse_filter(filter_name, normalize=False)
self.filters["hi_filter"] = WaveletPyramid._modulate_flip(self.filters['lo_filter'])
assert self.filters['lo_filter'].shape == self.filters['hi_filter'].shape
# Stagger sampling if filter is odd-length
self.stagger = (self.filters['lo_filter'].size + 1) % 2
self._set_num_scales('lo_filter', height)
# compute the number of channels per level
if min(self.image.shape) == 1:
self.num_orientations = 1
else:
self.num_orientations = 3
self._build_pyr()
def _modulate_flip(lo_filter):
'''construct QMF/Wavelet highpass filter from lowpass filter
modulate by (-1)^n, reverse order (and shift by one, which is handled by the convolution
routines). This is an extension of the original definition of QMF's (e.g., see
Simoncelli90).
Parameters
----------
lo_filter : `array_like`
one-dimensional array (or effectively 1d array) containing the lowpass filter to
convert into the highpass filter.
Returns
-------
hi_filter : `np.array`
The highpass filter constructed from the lowpass filter, same shape as the lowpass
filter.
'''
# check lo_filter is effectively 1D
lo_filter_shape = lo_filter.shape
assert lo_filter.size == max(lo_filter_shape)
lo_filter = lo_filter.flatten()
ind = np.arange(lo_filter.size, 0, -1) - (lo_filter.size + 1) // 2
hi_filter = lo_filter[::-1] * (-1.0) ** ind
return hi_filter.reshape(lo_filter_shape)
def _build_next(self, image):
"""Build the next level fo the Wavelet pyramid
Should not be called by users directly, this is a helper function to construct the pyramid.
Parameters
----------
image : `array_like`
image to use to construct next level.
Returns
-------
lolo : `array_like`
This is the result of applying the lowpass filter once if `image` is 1d, twice if it's
2d. It's downsampled by a factor of two from the original `image`.
hi_tuple : `tuple`
If `image` is 1d, this just contains `hihi`, the result of applying the highpass filter
. If `image` is 2d, it is `(lohi, hilo, hihi)`, the result of applying the lowpass then
the highpass, the highpass then the lowpass, and the highpass twice. All will be
downsampled by a factor of two from the original `image`.
"""
if image.shape[1] == 1:
lolo = corrDn(image=image, filt=self.filters['lo_filter'], edge_type=self.edge_type, step=(2, 1), start=(self.stagger, 0))
hihi = corrDn(image=image, filt=self.filters['hi_filter'], edge_type=self.edge_type, step=(2, 1), start=(1, 0))
return lolo, (hihi, )
elif image.shape[0] == 1:
lolo = corrDn(image=image, filt=self.filters['lo_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, self.stagger))
hihi = corrDn(image=image, filt=self.filters['hi_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, 1))
return lolo, (hihi, )
else:
lo = corrDn(image=image, filt=self.filters['lo_filter'], edge_type=self.edge_type, step=(2, 1), start=(self.stagger, 0))
hi = corrDn(image=image, filt=self.filters['hi_filter'], edge_type=self.edge_type, step=(2, 1), start=(1, 0))
lolo = corrDn(image=lo, filt=self.filters['lo_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, self.stagger))
lohi = corrDn(image=hi, filt=self.filters['lo_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, self.stagger))
hilo = corrDn(image=lo, filt=self.filters['hi_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, 1))
hihi = corrDn(image=hi, filt=self.filters['hi_filter'].T, edge_type=self.edge_type, step=(1, 2), start=(0, 1))
return lolo, (lohi, hilo, hihi)
def _build_pyr(self):
im = self.image
for lev in range(self.num_scales):
im, higher_bands = self._build_next(im)
for j, band in enumerate(higher_bands):
self.pyr_coeffs[(lev, j)] = band
self.pyr_size[(lev, j)] = band.shape
self.pyr_coeffs['residual_lowpass'] = im
self.pyr_size['residual_lowpass'] = im.shape
def _recon_prev(self, image, lev, recon_keys, output_size, lo_filter, hi_filter, edge_type,
stagger):
"""Reconstruct the previous level of the pyramid.
Should not be called by users directly, this is a helper function for reconstructing the
input image using pyramid coefficients.
"""
if self.num_orientations == 1:
if output_size[0] == 1:
recon = upConv(image=image, filt=lo_filter.T, edge_type=edge_type, step=(1, 2), start=(0, stagger), stop=output_size)
if (lev, 0) in recon_keys:
recon += upConv(image=self.pyr_coeffs[(lev, 0)], filt=hi_filter.T, edge_type=edge_type, step=(1, 2), start=(0, 1), stop=output_size)
elif output_size[1] == 1:
recon = upConv(image=image, filt=lo_filter, edge_type=edge_type, step=(2, 1), start=(stagger, 0), stop=output_size)
if (lev, 0) in recon_keys:
recon += upConv(image=self.pyr_coeffs[(lev, 0)], filt=hi_filter, edge_type=edge_type, step=(2, 1), start=(1, 0), stop=output_size)
else:
lo_size = ([self.pyr_size[(lev, 1)][0], output_size[1]])
hi_size = ([self.pyr_size[(lev, 0)][0], output_size[1]])
tmp_recon = upConv(image=image, filt=lo_filter.T, edge_type=edge_type, step=(1, 2), start=(0, stagger), stop=lo_size)
recon = upConv(image=tmp_recon, filt=lo_filter, edge_type=edge_type, step=(2, 1), start=(stagger, 0), stop=output_size)
bands_recon_dict = {
0: [{'filt': lo_filter.T, 'start': (0, stagger), 'stop': hi_size},
{'filt': hi_filter, 'start': (1, 0)}],
1: [{'filt': hi_filter.T, 'start': (0, 1), 'stop': lo_size},
{'filt': lo_filter, 'start': (stagger, 0)}],
2: [{'filt': hi_filter.T, 'start': (0, 1), 'stop': hi_size},
{'filt': hi_filter, 'start': (1, 0)}],
}
for band in range(self.num_orientations):
if (lev, band) in recon_keys:
tmp_recon = upConv(image=self.pyr_coeffs[(lev, band)], edge_type=edge_type, step=(1, 2), **bands_recon_dict[band][0])
recon += upConv(image=tmp_recon, edge_type=edge_type, step=(2, 1), stop=output_size, **bands_recon_dict[band][1])
return recon
def recon_pyr(self, filter_name=None, edge_type=None, levels='all', bands='all'):
"""Reconstruct the input image using pyramid coefficients.
This function reconstructs the input image using pyramid coefficients.
Parameters
----------
filter_name : {None, 'binomN', 'haar', 'qmf8', 'qmf12', 'qmf16', 'daub2', 'daub3', 'daub4',
'qmf5', 'qmf9', 'qmf13'}
name of filter to use for reconstruction. All scaled so L-2 norm is 1.0
* None (default) - use `self.filter_name`, the filter used to construct the pyramid.
* `'binomN'` - binomial coefficient filter of order N-1
* `'haar'` - Haar wavelet
* `'qmf8'`, `'qmf12'`, `'qmf16'` - Symmetric Quadrature Mirror Filters [1]_
* `'daub2'`, `'daub3'`, `'daub4'` - Daubechies wavelet [2]_
* `'qmf5'`, `'qmf9'`, `'qmf13'` - Symmetric Quadrature Mirror Filters [3]_, [4]_
edge_type : {None, 'circular', 'reflect1', 'reflect2', 'repeat', 'zero', 'extend',
'dont-compute'}
Specifies how to handle edges. Options are:
* None (default) - use `self.edge_type`, the edge_type used to construct the pyramid
* `'circular'` - circular convolution
* `'reflect1'` - reflect about the edge pixels
* `'reflect2'` - reflect, doubling the edge pixels
* `'repeat'` - repeat the edge pixels
* `'zero'` - assume values of zero outside image boundary
* `'extend'` - reflect and inverts
* `'dont-compute'` - zero output when filter overhangs imput boundaries.
levels : `list`, `int`, or {`'all'`, `'residual_highpass'`}
If `list` should contain some subset of integers from `0` to `self.num_scales-1`
(inclusive) and `'residual_lowpass'`. If `'all'`, returned value will contain all
valid levels. Otherwise, must be one of the valid levels.
bands : `list`, `int`, or `'all'`.
If list, should contain some subset of integers from `0` to `self.num_orientations-1`.
If `'all'`, returned value will contain all valid orientations. Otherwise, must be one
of the valid orientations.
Returns
-------
recon : `np.array`
The reconstructed image.
"""
# Optional args
if filter_name is None:
lo_filter = self.filters['lo_filter']
hi_filter = self.filters['hi_filter']
stagger = self.stagger
else:
lo_filter = parse_filter(filter_name, normalize=False)
hi_filter = WaveletPyramid._modulate_flip(lo_filter)
stagger = (lo_filter.size + 1) % 2
if edge_type is None:
edges = self.edge_type
else:
edges = edge_type
recon_keys = self._recon_keys(levels, bands)
# initialize reconstruction
if 'residual_lowpass' in recon_keys:
recon = self.pyr_coeffs['residual_lowpass']
else:
recon = np.zeros_like(self.pyr_coeffs['residual_lowpass'])
for lev in reversed(range(self.num_scales)):
if self.num_orientations == 1:
if lev == 0:
output_size = self.image.shape
else:
output_size = self.pyr_size[(lev-1, 0)]
else:
output_size = (self.pyr_size[(lev, 0)][0] + self.pyr_size[(lev, 1)][0],
self.pyr_size[(lev, 0)][1] + self.pyr_size[(lev, 1)][1])
recon = self._recon_prev(recon, lev, recon_keys, output_size, lo_filter,
hi_filter, edges, stagger)
return recon | 0.919728 | 0.746786 |
from datetime import datetime
from newsapi import NewsApiClient
from unittest.mock import patch
from os.path import join, dirname, realpath
from sentinel_connectors.historical import GoogleNewsHistoricalConnector
from sentinel_connectors.stream import GoogleNewsStreamConnector
from sentinel_connectors.gn_common import create_gn_mention_metadata
from sentinel_connectors.utils import read_jsonpickle
from sentinel_connectors.secrets_manager import GoogleNewsSecretsManager
MOCK_CONFIG = {"GOOGLE_NEWS_API_KEY": "XXX"}
def get_gn_articles():
gn_articles_path = join(dirname(realpath(__file__)), "gn-historical_comments.json")
return read_jsonpickle(gn_articles_path)
def mock_comments():
for comment in get_gn_articles():
yield comment
def mock_response():
gn_response_path = join(dirname(realpath(__file__)), "gn-example_response.json")
return read_jsonpickle(gn_response_path)
def mock_response_with_latest_article_removed():
response = mock_response()
response["articles"] = response["articles"][1:]
return response
def test_GoogleNewsHistoricalConnector_create_gn_metadata():
test_comment = get_gn_articles()[0]
result = create_gn_mention_metadata(test_comment)
assert result.author == "<NAME>, Xbox Live's Major Nelson"
assert result.news_source == "Majornelson.com"
def test_GoogleNewsHistoricalConnector_download_mentions():
with patch.object(
GoogleNewsHistoricalConnector, "_search_news", return_value=mock_comments()
), patch.object(GoogleNewsSecretsManager, "get_secrets", return_value=MOCK_CONFIG):
connector = GoogleNewsHistoricalConnector(GoogleNewsSecretsManager())
result = [
mention
for mention in connector.download_mentions(
keywords="microsoft",
since=datetime(2019, 4, 4),
until=datetime(2019, 4, 5),
)
]
expected = get_gn_articles()
assert len(result) == len(expected)
for r, e in zip(result, expected):
assert r.text == " ".join(
filter(None, [e["title"], e["description"], e["content"]])
)
assert r.url == e["url"]
assert r.metadata == create_gn_mention_metadata(e)
assert r.source == "google-news"
assert r.origin_date is not None
def test_GoogleNewsStreamConnector_download_mentions():
with patch.object(
GoogleNewsStreamConnector, "_listen_top_stories", return_value=mock_comments()
), patch.object(GoogleNewsSecretsManager, "get_secrets", return_value=MOCK_CONFIG):
connector = GoogleNewsStreamConnector(GoogleNewsSecretsManager())
result = [mention for mention in connector.stream_comments()]
expected = get_gn_articles()
assert len(result) == len(expected)
for r, e in zip(result, expected):
assert r.text == " ".join(
filter(None, [e["title"], e["description"], e["content"]])
)
assert r.url == e["url"]
assert r.metadata == create_gn_mention_metadata(e)
assert r.source == "google-news"
assert r.origin_date is not None
def test_GoogleNewsStreamConnector_duplicates_filtering():
@patch.object(
GoogleNewsStreamConnector, "_retrieve_news_sources", return_value="bbc.com"
)
def execute_test(mock_stream_connector):
with patch.object(
GoogleNewsSecretsManager, "get_secrets", return_value=MOCK_CONFIG
):
connector = GoogleNewsStreamConnector(GoogleNewsSecretsManager())
with patch.object(
NewsApiClient,
"get_top_headlines",
return_value=mock_response_with_latest_article_removed(),
):
# run first request to set time of latest retrieved article
first = connector._search_top_stories()
first = [x for x in first]
with patch.object(
NewsApiClient, "get_top_headlines", return_value=mock_response()
):
second = connector._search_top_stories()
assert len(second) == 1
assert second[0] == mock_response()["articles"][0]
execute_test() | sentinel_connectors/tests/test-connectors/test_gn.py | from datetime import datetime
from newsapi import NewsApiClient
from unittest.mock import patch
from os.path import join, dirname, realpath
from sentinel_connectors.historical import GoogleNewsHistoricalConnector
from sentinel_connectors.stream import GoogleNewsStreamConnector
from sentinel_connectors.gn_common import create_gn_mention_metadata
from sentinel_connectors.utils import read_jsonpickle
from sentinel_connectors.secrets_manager import GoogleNewsSecretsManager
MOCK_CONFIG = {"GOOGLE_NEWS_API_KEY": "XXX"}
def get_gn_articles():
gn_articles_path = join(dirname(realpath(__file__)), "gn-historical_comments.json")
return read_jsonpickle(gn_articles_path)
def mock_comments():
for comment in get_gn_articles():
yield comment
def mock_response():
gn_response_path = join(dirname(realpath(__file__)), "gn-example_response.json")
return read_jsonpickle(gn_response_path)
def mock_response_with_latest_article_removed():
response = mock_response()
response["articles"] = response["articles"][1:]
return response
def test_GoogleNewsHistoricalConnector_create_gn_metadata():
test_comment = get_gn_articles()[0]
result = create_gn_mention_metadata(test_comment)
assert result.author == "<NAME>, Xbox Live's Major Nelson"
assert result.news_source == "Majornelson.com"
def test_GoogleNewsHistoricalConnector_download_mentions():
with patch.object(
GoogleNewsHistoricalConnector, "_search_news", return_value=mock_comments()
), patch.object(GoogleNewsSecretsManager, "get_secrets", return_value=MOCK_CONFIG):
connector = GoogleNewsHistoricalConnector(GoogleNewsSecretsManager())
result = [
mention
for mention in connector.download_mentions(
keywords="microsoft",
since=datetime(2019, 4, 4),
until=datetime(2019, 4, 5),
)
]
expected = get_gn_articles()
assert len(result) == len(expected)
for r, e in zip(result, expected):
assert r.text == " ".join(
filter(None, [e["title"], e["description"], e["content"]])
)
assert r.url == e["url"]
assert r.metadata == create_gn_mention_metadata(e)
assert r.source == "google-news"
assert r.origin_date is not None
def test_GoogleNewsStreamConnector_download_mentions():
with patch.object(
GoogleNewsStreamConnector, "_listen_top_stories", return_value=mock_comments()
), patch.object(GoogleNewsSecretsManager, "get_secrets", return_value=MOCK_CONFIG):
connector = GoogleNewsStreamConnector(GoogleNewsSecretsManager())
result = [mention for mention in connector.stream_comments()]
expected = get_gn_articles()
assert len(result) == len(expected)
for r, e in zip(result, expected):
assert r.text == " ".join(
filter(None, [e["title"], e["description"], e["content"]])
)
assert r.url == e["url"]
assert r.metadata == create_gn_mention_metadata(e)
assert r.source == "google-news"
assert r.origin_date is not None
def test_GoogleNewsStreamConnector_duplicates_filtering():
@patch.object(
GoogleNewsStreamConnector, "_retrieve_news_sources", return_value="bbc.com"
)
def execute_test(mock_stream_connector):
with patch.object(
GoogleNewsSecretsManager, "get_secrets", return_value=MOCK_CONFIG
):
connector = GoogleNewsStreamConnector(GoogleNewsSecretsManager())
with patch.object(
NewsApiClient,
"get_top_headlines",
return_value=mock_response_with_latest_article_removed(),
):
# run first request to set time of latest retrieved article
first = connector._search_top_stories()
first = [x for x in first]
with patch.object(
NewsApiClient, "get_top_headlines", return_value=mock_response()
):
second = connector._search_top_stories()
assert len(second) == 1
assert second[0] == mock_response()["articles"][0]
execute_test() | 0.545044 | 0.310054 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['ObjectStorageBucket']
class ObjectStorageBucket(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
cert: Optional[pulumi.Input[pulumi.InputType['ObjectStorageBucketCertArgs']]] = None,
cluster: Optional[pulumi.Input[str]] = None,
label: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Provides a Linode Object Storage Bucket resource. This can be used to create, modify, and delete Linodes Object Storage Buckets.
## Example Usage
The following example shows how one might use this resource to create an Object Storage Bucket.
```python
import pulumi
import pulumi_linode as linode
primary = linode.get_object_storage_cluster(id="us-east-1")
foobar = linode.ObjectStorageBucket("foobar",
cluster=primary.id,
label="%s")
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] cluster: The cluster of the Linode Object Storage Bucket.
:param pulumi.Input[str] label: The label of the Linode Object Storage Bucket.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['cert'] = cert
if cluster is None:
raise TypeError("Missing required property 'cluster'")
__props__['cluster'] = cluster
if label is None:
raise TypeError("Missing required property 'label'")
__props__['label'] = label
super(ObjectStorageBucket, __self__).__init__(
'linode:index/objectStorageBucket:ObjectStorageBucket',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
cert: Optional[pulumi.Input[pulumi.InputType['ObjectStorageBucketCertArgs']]] = None,
cluster: Optional[pulumi.Input[str]] = None,
label: Optional[pulumi.Input[str]] = None) -> 'ObjectStorageBucket':
"""
Get an existing ObjectStorageBucket resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] cluster: The cluster of the Linode Object Storage Bucket.
:param pulumi.Input[str] label: The label of the Linode Object Storage Bucket.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["cert"] = cert
__props__["cluster"] = cluster
__props__["label"] = label
return ObjectStorageBucket(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def cert(self) -> pulumi.Output[Optional['outputs.ObjectStorageBucketCert']]:
return pulumi.get(self, "cert")
@property
@pulumi.getter
def cluster(self) -> pulumi.Output[str]:
"""
The cluster of the Linode Object Storage Bucket.
"""
return pulumi.get(self, "cluster")
@property
@pulumi.getter
def label(self) -> pulumi.Output[str]:
"""
The label of the Linode Object Storage Bucket.
"""
return pulumi.get(self, "label")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop | sdk/python/pulumi_linode/object_storage_bucket.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from . import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['ObjectStorageBucket']
class ObjectStorageBucket(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
cert: Optional[pulumi.Input[pulumi.InputType['ObjectStorageBucketCertArgs']]] = None,
cluster: Optional[pulumi.Input[str]] = None,
label: Optional[pulumi.Input[str]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Provides a Linode Object Storage Bucket resource. This can be used to create, modify, and delete Linodes Object Storage Buckets.
## Example Usage
The following example shows how one might use this resource to create an Object Storage Bucket.
```python
import pulumi
import pulumi_linode as linode
primary = linode.get_object_storage_cluster(id="us-east-1")
foobar = linode.ObjectStorageBucket("foobar",
cluster=primary.id,
label="%s")
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] cluster: The cluster of the Linode Object Storage Bucket.
:param pulumi.Input[str] label: The label of the Linode Object Storage Bucket.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['cert'] = cert
if cluster is None:
raise TypeError("Missing required property 'cluster'")
__props__['cluster'] = cluster
if label is None:
raise TypeError("Missing required property 'label'")
__props__['label'] = label
super(ObjectStorageBucket, __self__).__init__(
'linode:index/objectStorageBucket:ObjectStorageBucket',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
cert: Optional[pulumi.Input[pulumi.InputType['ObjectStorageBucketCertArgs']]] = None,
cluster: Optional[pulumi.Input[str]] = None,
label: Optional[pulumi.Input[str]] = None) -> 'ObjectStorageBucket':
"""
Get an existing ObjectStorageBucket resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] cluster: The cluster of the Linode Object Storage Bucket.
:param pulumi.Input[str] label: The label of the Linode Object Storage Bucket.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["cert"] = cert
__props__["cluster"] = cluster
__props__["label"] = label
return ObjectStorageBucket(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def cert(self) -> pulumi.Output[Optional['outputs.ObjectStorageBucketCert']]:
return pulumi.get(self, "cert")
@property
@pulumi.getter
def cluster(self) -> pulumi.Output[str]:
"""
The cluster of the Linode Object Storage Bucket.
"""
return pulumi.get(self, "cluster")
@property
@pulumi.getter
def label(self) -> pulumi.Output[str]:
"""
The label of the Linode Object Storage Bucket.
"""
return pulumi.get(self, "label")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop | 0.805135 | 0.193642 |
import sys
import argparse as ap
import numpy as np
from astropy.time import Time
from astropy.coordinates import (
SkyCoord,
EarthLocation
)
import astropy.units as u
# pylint: disable=invalid-name
# pylint: disable=redefined-outer-name
# pylint: disable=no-member
def argParse():
"""
Parse the command line arguments
Parameters
----------
None
Returns
-------
argparse argument object
Raises
------
None
"""
p = ap.ArgumentParser()
p.add_argument('input_times',
help='file containing list of times to convert')
p.add_argument('input_format',
help='type of time we are converting from',
choices=['jd', 'mjd', 'hjd', 'bjd'])
p.add_argument('input_timestamps',
help='type of input timestamps we have',
choices=['start', 'mid', 'end'])
p.add_argument('output_format',
help='type of time we are converting to',
choices=['jd', 'mjd', 'hjd', 'bjd'])
p.add_argument('ra',
type=str,
help='RA of target (HH:MM:SS.ss)')
p.add_argument('dec',
type=str,
help='Dec of target (DD:MM:SS.ss)')
p.add_argument('observatory',
help='Observatory where data was taken, e.g. '\
'lapalma, paranal, lasilla, SAAO')
p.add_argument('exptime',
type=float,
help='Exptime of observations')
return p.parse_args()
def getLightTravelTimes(ra, dec, time_to_correct):
"""
Get the light travel times to the helio- and
barycentres
Parameters
----------
ra : str
The Right Ascension of the target in hourangle
e.g. 16:00:00
dec : str
The Declination of the target in degrees
e.g. +20:00:00
time_to_correct : astropy.Time object
The time of observation to correct. The astropy.Time
object must have been initialised with an EarthLocation
Returns
-------
ltt_bary : float
The light travel time to the barycentre
ltt_helio : float
The light travel time to the heliocentre
Raises
------
None
"""
target = SkyCoord(ra, dec, unit=(u.hourangle, u.deg), frame='icrs')
ltt_bary = time_to_correct.light_travel_time(target)
ltt_helio = time_to_correct.light_travel_time(target, 'heliocentric')
return ltt_bary, ltt_helio
if __name__ == "__main__":
args = argParse()
# check for unnecessary conversion
if args.input_format == args.output_format and args.input_timestamps == 'mid':
print('No conversion needed, times are in requested format')
sys.exit(0)
# get the location of the observatory
location = EarthLocation.of_site(args.observatory)
# read in the input times - assumes first column if >1 col
tinp = np.loadtxt(args.input_times, usecols=[0], unpack=True)
# first correct the times to the mid-point, if required
# correction is assuming to be in units of half_exptime
correction = (args.exptime/2.)/60./60./24.
if args.input_timestamps == 'mid':
print('No timestamp correction needed')
elif args.input_timestamps == 'start':
print('Converting START --> MID')
tinp = tinp + correction
elif args.input_timestamps == 'end':
print('Converting END --> MID')
tinp = tinp - correction
# set up the astropy time inputs and convert them to JD-UTC-MID
if args.input_format == 'jd':
print('Input times in JD, applying no initial correction')
time_inp = Time(tinp, format='jd', scale='utc', location=location)
elif args.input_format == 'mjd':
print('Input times in MJD, applying no initial correction')
time_inp = Time(tinp, format='mjd', scale='utc', location=location)
elif args.input_format == 'hjd':
print('Input times in HJD, removing heliocentric correction')
time_inp = Time(tinp, format='jd', scale='utc', location=location)
_, ltt_helio = getLightTravelTimes(args.ra, args.dec, time_inp)
time_inp = Time(time_inp.utc - ltt_helio, format='jd', scale='utc', location=location)
elif args.input_format == 'bjd':
print('Input times in BJD, removing barycentric correction')
time_inp = Time(tinp, format='jd', scale='tdb', location=location)
ltt_bary, _ = getLightTravelTimes(args.ra, args.dec, time_inp)
time_inp = Time(time_inp.tdb - ltt_bary, format='jd', scale='tdb', location=location).utc
else:
print('Unknown input time format, exiting...')
sys.exit(1)
# now convert to the output format requested
if args.output_format == 'jd':
print('Output set to JD_UTC_MID, no further correction required')
new_time = time_inp.jd
elif args.output_format == 'mjd':
print('Output set to MJD_UTC_MID, correcting JD --> MJD')
new_time = time_inp.mjd
elif args.output_format == 'hjd':
print('Output set to HJD_UTC_MID, adding heliocentric correction')
_, ltt_helio = getLightTravelTimes(args.ra, args.dec, time_inp)
new_time = (time_inp + ltt_helio).value
elif args.output_format == 'bjd':
print('Output set to BJD_TDB_MID, adding barycentric correction')
ltt_bary, _ = getLightTravelTimes(args.ra, args.dec, time_inp)
new_time = (time_inp.tdb + ltt_bary).value
else:
print('Unknown output time format, exiting...')
# save out the new time file
np.savetxt('{}.{}'.format(args.input_times, args.output_format),
np.c_[new_time],
fmt='%.8f',
header=args.output_format) | convert_times.py | import sys
import argparse as ap
import numpy as np
from astropy.time import Time
from astropy.coordinates import (
SkyCoord,
EarthLocation
)
import astropy.units as u
# pylint: disable=invalid-name
# pylint: disable=redefined-outer-name
# pylint: disable=no-member
def argParse():
"""
Parse the command line arguments
Parameters
----------
None
Returns
-------
argparse argument object
Raises
------
None
"""
p = ap.ArgumentParser()
p.add_argument('input_times',
help='file containing list of times to convert')
p.add_argument('input_format',
help='type of time we are converting from',
choices=['jd', 'mjd', 'hjd', 'bjd'])
p.add_argument('input_timestamps',
help='type of input timestamps we have',
choices=['start', 'mid', 'end'])
p.add_argument('output_format',
help='type of time we are converting to',
choices=['jd', 'mjd', 'hjd', 'bjd'])
p.add_argument('ra',
type=str,
help='RA of target (HH:MM:SS.ss)')
p.add_argument('dec',
type=str,
help='Dec of target (DD:MM:SS.ss)')
p.add_argument('observatory',
help='Observatory where data was taken, e.g. '\
'lapalma, paranal, lasilla, SAAO')
p.add_argument('exptime',
type=float,
help='Exptime of observations')
return p.parse_args()
def getLightTravelTimes(ra, dec, time_to_correct):
"""
Get the light travel times to the helio- and
barycentres
Parameters
----------
ra : str
The Right Ascension of the target in hourangle
e.g. 16:00:00
dec : str
The Declination of the target in degrees
e.g. +20:00:00
time_to_correct : astropy.Time object
The time of observation to correct. The astropy.Time
object must have been initialised with an EarthLocation
Returns
-------
ltt_bary : float
The light travel time to the barycentre
ltt_helio : float
The light travel time to the heliocentre
Raises
------
None
"""
target = SkyCoord(ra, dec, unit=(u.hourangle, u.deg), frame='icrs')
ltt_bary = time_to_correct.light_travel_time(target)
ltt_helio = time_to_correct.light_travel_time(target, 'heliocentric')
return ltt_bary, ltt_helio
if __name__ == "__main__":
args = argParse()
# check for unnecessary conversion
if args.input_format == args.output_format and args.input_timestamps == 'mid':
print('No conversion needed, times are in requested format')
sys.exit(0)
# get the location of the observatory
location = EarthLocation.of_site(args.observatory)
# read in the input times - assumes first column if >1 col
tinp = np.loadtxt(args.input_times, usecols=[0], unpack=True)
# first correct the times to the mid-point, if required
# correction is assuming to be in units of half_exptime
correction = (args.exptime/2.)/60./60./24.
if args.input_timestamps == 'mid':
print('No timestamp correction needed')
elif args.input_timestamps == 'start':
print('Converting START --> MID')
tinp = tinp + correction
elif args.input_timestamps == 'end':
print('Converting END --> MID')
tinp = tinp - correction
# set up the astropy time inputs and convert them to JD-UTC-MID
if args.input_format == 'jd':
print('Input times in JD, applying no initial correction')
time_inp = Time(tinp, format='jd', scale='utc', location=location)
elif args.input_format == 'mjd':
print('Input times in MJD, applying no initial correction')
time_inp = Time(tinp, format='mjd', scale='utc', location=location)
elif args.input_format == 'hjd':
print('Input times in HJD, removing heliocentric correction')
time_inp = Time(tinp, format='jd', scale='utc', location=location)
_, ltt_helio = getLightTravelTimes(args.ra, args.dec, time_inp)
time_inp = Time(time_inp.utc - ltt_helio, format='jd', scale='utc', location=location)
elif args.input_format == 'bjd':
print('Input times in BJD, removing barycentric correction')
time_inp = Time(tinp, format='jd', scale='tdb', location=location)
ltt_bary, _ = getLightTravelTimes(args.ra, args.dec, time_inp)
time_inp = Time(time_inp.tdb - ltt_bary, format='jd', scale='tdb', location=location).utc
else:
print('Unknown input time format, exiting...')
sys.exit(1)
# now convert to the output format requested
if args.output_format == 'jd':
print('Output set to JD_UTC_MID, no further correction required')
new_time = time_inp.jd
elif args.output_format == 'mjd':
print('Output set to MJD_UTC_MID, correcting JD --> MJD')
new_time = time_inp.mjd
elif args.output_format == 'hjd':
print('Output set to HJD_UTC_MID, adding heliocentric correction')
_, ltt_helio = getLightTravelTimes(args.ra, args.dec, time_inp)
new_time = (time_inp + ltt_helio).value
elif args.output_format == 'bjd':
print('Output set to BJD_TDB_MID, adding barycentric correction')
ltt_bary, _ = getLightTravelTimes(args.ra, args.dec, time_inp)
new_time = (time_inp.tdb + ltt_bary).value
else:
print('Unknown output time format, exiting...')
# save out the new time file
np.savetxt('{}.{}'.format(args.input_times, args.output_format),
np.c_[new_time],
fmt='%.8f',
header=args.output_format) | 0.638272 | 0.362377 |
import logging as log
import boto3
try:
# These are installed only for the case of a dev instance
from moto import mock_ec2
from moto import mock_s3
import responses
except ImportError:
log.debug("Development library moto is not installed.")
from cloudbridge.cloud.base import BaseCloudProvider
from cloudbridge.cloud.base.helpers import get_env
from cloudbridge.cloud.interfaces import TestMockHelperMixin
from .services import AWSComputeService
from .services import AWSNetworkingService
from .services import AWSSecurityService
from .services import AWSStorageService
class AWSCloudProvider(BaseCloudProvider):
'''AWS cloud provider interface'''
PROVIDER_ID = 'aws'
AWS_INSTANCE_DATA_DEFAULT_URL = "http://cloudve.org/cb-aws-vmtypes.json"
def __init__(self, config):
super(AWSCloudProvider, self).__init__(config)
# Initialize cloud connection fields
# These are passed as-is to Boto
self.region_name = self._get_config_value('aws_region_name',
'us-east-1')
self.session_cfg = {
'aws_access_key_id': self._get_config_value(
'aws_access_key', get_env('AWS_ACCESS_KEY', None)),
'aws_secret_access_key': self._get_config_value(
'aws_secret_key', get_env('AWS_SECRET_KEY', None)),
'aws_session_token': self._get_config_value(
'aws_session_token', None)
}
self.ec2_cfg = {
'use_ssl': self._get_config_value('ec2_is_secure', True),
'verify': self._get_config_value('ec2_validate_certs', True),
'endpoint_url': self._get_config_value('ec2_endpoint_url', None)
}
self.s3_cfg = {
'use_ssl': self._get_config_value('s3_is_secure', True),
'verify': self._get_config_value('s3_validate_certs', True),
'endpoint_url': self._get_config_value('s3_endpoint_url', None)
}
# service connections, lazily initialized
self._session = None
self._ec2_conn = None
self._vpc_conn = None
self._s3_conn = None
# Initialize provider services
self._compute = AWSComputeService(self)
self._networking = AWSNetworkingService(self)
self._security = AWSSecurityService(self)
self._storage = AWSStorageService(self)
@property
def session(self):
'''Get a low-level session object or create one if needed'''
if not self._session:
if self.config.debug_mode:
boto3.set_stream_logger(level=log.DEBUG)
self._session = boto3.session.Session(
region_name=self.region_name, **self.session_cfg)
return self._session
@property
def ec2_conn(self):
if not self._ec2_conn:
self._ec2_conn = self._connect_ec2()
return self._ec2_conn
@property
def s3_conn(self):
if not self._s3_conn:
self._s3_conn = self._connect_s3()
return self._s3_conn
@property
def compute(self):
return self._compute
@property
def networking(self):
return self._networking
@property
def security(self):
return self._security
@property
def storage(self):
return self._storage
def _connect_ec2(self):
"""
Get a boto ec2 connection object.
"""
return self._connect_ec2_region(region_name=self.region_name)
def _connect_ec2_region(self, region_name=None):
'''Get an EC2 resource object'''
return self.session.resource(
'ec2', region_name=region_name, **self.ec2_cfg)
def _connect_s3(self):
'''Get an S3 resource object'''
return self.session.resource(
's3', region_name=self.region_name, **self.s3_cfg)
class MockAWSCloudProvider(AWSCloudProvider, TestMockHelperMixin):
def __init__(self, config):
super(MockAWSCloudProvider, self).__init__(config)
def setUpMock(self):
"""
Let Moto take over all socket communications
"""
self.ec2mock = mock_ec2()
self.ec2mock.start()
self.s3mock = mock_s3()
self.s3mock.start()
responses.add(
responses.GET,
self.AWS_INSTANCE_DATA_DEFAULT_URL,
body=u"""
[
{
"family": "General Purpose",
"enhanced_networking": false,
"vCPU": 1,
"generation": "current",
"ebs_iops": 0,
"network_performance": "Low",
"ebs_throughput": 0,
"vpc": {
"ips_per_eni": 2,
"max_enis": 2
},
"arch": [
"x86_64"
],
"linux_virtualization_types": [
"HVM"
],
"pricing": {
"us-east-1": {
"linux": {
"ondemand": "0.0058",
"reserved": {
"yrTerm1Convertible.allUpfront": "0.003881",
"yrTerm1Convertible.noUpfront": "0.0041",
"yrTerm1Convertible.partialUpfront": "0.003941",
"yrTerm1Standard.allUpfront": "0.003311",
"yrTerm1Standard.noUpfront": "0.0036",
"yrTerm1Standard.partialUpfront": "0.003412",
"yrTerm3Convertible.allUpfront": "0.002626",
"yrTerm3Convertible.noUpfront": "0.0029",
"yrTerm3Convertible.partialUpfront": "0.002632",
"yrTerm3Standard.allUpfront": "0.002169",
"yrTerm3Standard.noUpfront": "0.0025",
"yrTerm3Standard.partialUpfront": "0.002342"
}
}
}
},
"ebs_optimized": false,
"storage": null,
"max_bandwidth": 0,
"instance_type": "t2.nano",
"ECU": "variable",
"memory": 0.5,
"ebs_max_bandwidth": 0
}
]
""")
def tearDownMock(self):
"""
Stop Moto intercepting all socket communications
"""
self.s3mock.stop()
self.ec2mock.stop() | cloudbridge/cloud/providers/aws/provider.py | import logging as log
import boto3
try:
# These are installed only for the case of a dev instance
from moto import mock_ec2
from moto import mock_s3
import responses
except ImportError:
log.debug("Development library moto is not installed.")
from cloudbridge.cloud.base import BaseCloudProvider
from cloudbridge.cloud.base.helpers import get_env
from cloudbridge.cloud.interfaces import TestMockHelperMixin
from .services import AWSComputeService
from .services import AWSNetworkingService
from .services import AWSSecurityService
from .services import AWSStorageService
class AWSCloudProvider(BaseCloudProvider):
'''AWS cloud provider interface'''
PROVIDER_ID = 'aws'
AWS_INSTANCE_DATA_DEFAULT_URL = "http://cloudve.org/cb-aws-vmtypes.json"
def __init__(self, config):
super(AWSCloudProvider, self).__init__(config)
# Initialize cloud connection fields
# These are passed as-is to Boto
self.region_name = self._get_config_value('aws_region_name',
'us-east-1')
self.session_cfg = {
'aws_access_key_id': self._get_config_value(
'aws_access_key', get_env('AWS_ACCESS_KEY', None)),
'aws_secret_access_key': self._get_config_value(
'aws_secret_key', get_env('AWS_SECRET_KEY', None)),
'aws_session_token': self._get_config_value(
'aws_session_token', None)
}
self.ec2_cfg = {
'use_ssl': self._get_config_value('ec2_is_secure', True),
'verify': self._get_config_value('ec2_validate_certs', True),
'endpoint_url': self._get_config_value('ec2_endpoint_url', None)
}
self.s3_cfg = {
'use_ssl': self._get_config_value('s3_is_secure', True),
'verify': self._get_config_value('s3_validate_certs', True),
'endpoint_url': self._get_config_value('s3_endpoint_url', None)
}
# service connections, lazily initialized
self._session = None
self._ec2_conn = None
self._vpc_conn = None
self._s3_conn = None
# Initialize provider services
self._compute = AWSComputeService(self)
self._networking = AWSNetworkingService(self)
self._security = AWSSecurityService(self)
self._storage = AWSStorageService(self)
@property
def session(self):
'''Get a low-level session object or create one if needed'''
if not self._session:
if self.config.debug_mode:
boto3.set_stream_logger(level=log.DEBUG)
self._session = boto3.session.Session(
region_name=self.region_name, **self.session_cfg)
return self._session
@property
def ec2_conn(self):
if not self._ec2_conn:
self._ec2_conn = self._connect_ec2()
return self._ec2_conn
@property
def s3_conn(self):
if not self._s3_conn:
self._s3_conn = self._connect_s3()
return self._s3_conn
@property
def compute(self):
return self._compute
@property
def networking(self):
return self._networking
@property
def security(self):
return self._security
@property
def storage(self):
return self._storage
def _connect_ec2(self):
"""
Get a boto ec2 connection object.
"""
return self._connect_ec2_region(region_name=self.region_name)
def _connect_ec2_region(self, region_name=None):
'''Get an EC2 resource object'''
return self.session.resource(
'ec2', region_name=region_name, **self.ec2_cfg)
def _connect_s3(self):
'''Get an S3 resource object'''
return self.session.resource(
's3', region_name=self.region_name, **self.s3_cfg)
class MockAWSCloudProvider(AWSCloudProvider, TestMockHelperMixin):
def __init__(self, config):
super(MockAWSCloudProvider, self).__init__(config)
def setUpMock(self):
"""
Let Moto take over all socket communications
"""
self.ec2mock = mock_ec2()
self.ec2mock.start()
self.s3mock = mock_s3()
self.s3mock.start()
responses.add(
responses.GET,
self.AWS_INSTANCE_DATA_DEFAULT_URL,
body=u"""
[
{
"family": "General Purpose",
"enhanced_networking": false,
"vCPU": 1,
"generation": "current",
"ebs_iops": 0,
"network_performance": "Low",
"ebs_throughput": 0,
"vpc": {
"ips_per_eni": 2,
"max_enis": 2
},
"arch": [
"x86_64"
],
"linux_virtualization_types": [
"HVM"
],
"pricing": {
"us-east-1": {
"linux": {
"ondemand": "0.0058",
"reserved": {
"yrTerm1Convertible.allUpfront": "0.003881",
"yrTerm1Convertible.noUpfront": "0.0041",
"yrTerm1Convertible.partialUpfront": "0.003941",
"yrTerm1Standard.allUpfront": "0.003311",
"yrTerm1Standard.noUpfront": "0.0036",
"yrTerm1Standard.partialUpfront": "0.003412",
"yrTerm3Convertible.allUpfront": "0.002626",
"yrTerm3Convertible.noUpfront": "0.0029",
"yrTerm3Convertible.partialUpfront": "0.002632",
"yrTerm3Standard.allUpfront": "0.002169",
"yrTerm3Standard.noUpfront": "0.0025",
"yrTerm3Standard.partialUpfront": "0.002342"
}
}
}
},
"ebs_optimized": false,
"storage": null,
"max_bandwidth": 0,
"instance_type": "t2.nano",
"ECU": "variable",
"memory": 0.5,
"ebs_max_bandwidth": 0
}
]
""")
def tearDownMock(self):
"""
Stop Moto intercepting all socket communications
"""
self.s3mock.stop()
self.ec2mock.stop() | 0.608245 | 0.125923 |
import npc
from npc.commands import util
from npc.character import Character
import pytest
from tests.util import fixture_dir
def test_find_empty_dirs(tmp_path):
tmp_path.joinpath('empty1').mkdir()
tmp_path.joinpath('empty2').mkdir()
tmp_path.joinpath('not_empty').mkdir()
tmp_path.joinpath('not_empty', 'test.txt').write_text('.', 'utf-8')
result = list(util.find_empty_dirs(str(tmp_path)))
assert str(tmp_path / 'empty1') in result
assert str(tmp_path / 'empty2') in result
class TestSortCharacters:
@pytest.fixture
def characters(self):
return [
Character(name=['<NAME>'], group=['High Rollers'], type=['changeling'], motley=['dudes2']),
Character(name=['<NAME>'], group=['High Rollers'], type=['changeling'], motley=['dudes1']),
Character(name=['<NAME>'], group=['Low Rollers'], type=['changeling'], motley=['dudes3'])
]
def test_last(self, characters):
result = util.character_sorter.CharacterSorter(['last']).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
def test_first(self, characters):
result = util.character_sorter.CharacterSorter(['first']).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
def test_reverse(self, characters):
result = util.character_sorter.CharacterSorter(['-first']).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
def test_multiple_tags(self, characters):
result = util.character_sorter.CharacterSorter(['group', '-last']).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
def test_translated_sort(self, characters, prefs):
result = util.character_sorter.CharacterSorter(['type-unit'], prefs=prefs).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
class TestSmartOpen:
def test_with_named_file(self, tmpdir):
path = tmpdir.join('test.txt')
path.write_text('.', 'utf-8')
with util.smart_open(str(path)) as fobj:
fobj.write('hello friend')
assert path.read() == 'hello friend'
@pytest.mark.parametrize('arg', [None, '-'])
def test_using_stdout(self, capsys, arg):
with util.smart_open(arg) as writer:
writer.write('hello friend')
out, _ = capsys.readouterr()
assert out == 'hello friend' | tests/commands/test_cmd_util.py | import npc
from npc.commands import util
from npc.character import Character
import pytest
from tests.util import fixture_dir
def test_find_empty_dirs(tmp_path):
tmp_path.joinpath('empty1').mkdir()
tmp_path.joinpath('empty2').mkdir()
tmp_path.joinpath('not_empty').mkdir()
tmp_path.joinpath('not_empty', 'test.txt').write_text('.', 'utf-8')
result = list(util.find_empty_dirs(str(tmp_path)))
assert str(tmp_path / 'empty1') in result
assert str(tmp_path / 'empty2') in result
class TestSortCharacters:
@pytest.fixture
def characters(self):
return [
Character(name=['<NAME>'], group=['High Rollers'], type=['changeling'], motley=['dudes2']),
Character(name=['<NAME>'], group=['High Rollers'], type=['changeling'], motley=['dudes1']),
Character(name=['<NAME>'], group=['Low Rollers'], type=['changeling'], motley=['dudes3'])
]
def test_last(self, characters):
result = util.character_sorter.CharacterSorter(['last']).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
def test_first(self, characters):
result = util.character_sorter.CharacterSorter(['first']).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
def test_reverse(self, characters):
result = util.character_sorter.CharacterSorter(['-first']).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
def test_multiple_tags(self, characters):
result = util.character_sorter.CharacterSorter(['group', '-last']).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
def test_translated_sort(self, characters, prefs):
result = util.character_sorter.CharacterSorter(['type-unit'], prefs=prefs).sort(characters)
assert list(map(lambda c: c.tags('name').first_value(), result)) == ['<NAME>', '<NAME>', '<NAME>']
class TestSmartOpen:
def test_with_named_file(self, tmpdir):
path = tmpdir.join('test.txt')
path.write_text('.', 'utf-8')
with util.smart_open(str(path)) as fobj:
fobj.write('hello friend')
assert path.read() == 'hello friend'
@pytest.mark.parametrize('arg', [None, '-'])
def test_using_stdout(self, capsys, arg):
with util.smart_open(arg) as writer:
writer.write('hello friend')
out, _ = capsys.readouterr()
assert out == 'hello friend' | 0.336222 | 0.316211 |
import vtk
import h5py
import numpy as np
from vtk.util.vtkAlgorithm import VTKPythonAlgorithmBase
import otter.plugins.common as common
from otter.plugins.common.Reader import Reader
from otter.plugins.common.Reader import BlockInformation, VariableInformation
class PetscHDF5DataSetReader(VTKPythonAlgorithmBase):
"""
Reader for datasets produced by PETSc
"""
def __init__(self):
VTKPythonAlgorithmBase.__init__(
self,
nInputPorts=0,
nOutputPorts=1,
outputType='vtkMultiBlockDataSet')
self._file_name = ""
self._output = None
self._cell_dim = None
self._labels = {}
self._graph = {}
self._multi_idx = 0
self._cell_connectivity = None
self._block_info = None
self._sideset_info = None
def RequestData(self, request, in_info, out_info):
self._block_info = {}
self._sideset_info = {}
self._output = vtk.vtkMultiBlockDataSet.GetData(out_info)
self._readFile()
self._block_idx = 0
self._multi_idx = 0
self._buildBlocks()
self._buildFaceSets()
return 1
def _readFile(self):
f = h5py.File(self._file_name, 'r')
self._labels = {}
self._vertices = f['geometry']['vertices']
cells = np.reshape(f['topology']['cells'], -1)
cones = np.reshape(f['topology']['cones'], -1)
self._graph = {}
i = 0
j = 0
for c in cones:
lst = []
for k in range(c):
lst.append(cells[i])
i += 1
self._graph[j] = lst
j += 1
self._orientation = np.reshape(f['topology']['orientation'], -1)
labels = f['labels']
if 'celltype' in labels:
celltypes = labels['celltype']
self._cell_types = {}
self._dim_of_cell = {}
for ct in celltypes.keys():
indices = np.reshape(celltypes[ct]['indices'], -1)
for i in indices:
self._dim_of_cell[i] = ct
self._cell_types[int(ct)] = indices
self._vertex_idx = {}
for i, val in enumerate(self._cell_types[0]):
self._vertex_idx[val] = i
if 'Face Sets' in labels:
face_sets = labels['Face Sets']
self._labels['face_sets'] = {}
for fs in face_sets.keys():
indices = face_sets[fs]['indices']
self._labels['face_sets'][fs] = indices
if 'vertex_fields' in f:
self._vertex_fields = f['vertex_fields']
else:
self._vertex_fields = {}
if 'cell_fields' in f:
self._cell_fields = f['cell_fields']
else:
self._cell_fields = {}
self._cell_connectivity = f['viz']['topology']['cells']
def _buildBlocks(self):
block = vtk.vtkUnstructuredGrid()
dim = self._vertices.shape[1]
verts = self._cell_types[0]
n_points = len(verts)
point_array = vtk.vtkPoints()
point_array.Allocate(n_points)
for i in range(n_points):
pt = [0, 0, 0]
for j in range(dim):
pt[j] = self._vertices[i][j]
point_array.InsertPoint(i, pt)
block.SetPoints(point_array)
# FIXME: build this from cells and cones
n_cell_corners = self._cell_connectivity.attrs['cell_corners']
self._cell_dim = self._cell_connectivity.attrs['cell_dim']
c_conn = self._cell_connectivity
if self._cell_dim == 1:
if n_cell_corners == 2:
cell_array = self._buildCells(c_conn, "vtkLine", 2)
block.SetCells(vtk.VTK_LINE, cell_array)
elif self._cell_dim == 2:
if n_cell_corners == 3:
cell_array = self._buildCells(c_conn, "vtkTriangle", 3)
block.SetCells(vtk.VTK_TRIANGLE, cell_array)
elif n_cell_corners == 4:
cell_array = self._buildCells(c_conn, "vtkQuad", 4)
block.SetCells(vtk.VTK_QUAD, cell_array)
elif self._cell_dim == 3:
if n_cell_corners == 4:
cell_array = self._buildCells(c_conn, "vtkTetra", 4)
block.SetCells(vtk.VTK_TETRA, cell_array)
elif n_cell_corners == 6:
cell_array = self._buildCells(c_conn, "vtkWedge", 6)
block.SetCells(vtk.VTK_WEDGE, cell_array)
elif n_cell_corners == 8:
cell_array = self._buildCells(c_conn, "vtkHexahedron", 8)
block.SetCells(vtk.VTK_HEXAHEDRON, cell_array)
self._readVertexFields(block, self._vertex_fields)
self._readCellFields(block, self._cell_fields)
self._output.SetBlock(self._block_idx, block)
self._block_idx += 1
binfo = BlockInformation(object_type=0,
name="block",
number=self._multi_idx,
object_index=0,
multiblock_index=self._multi_idx)
self._block_info[0] = binfo
def _buildCells(self, cells, class_name, n_vertices):
n_cells = cells.shape[0]
cell_array = vtk.vtkCellArray()
cell_array.Allocate(n_cells)
for i in range(n_cells):
connectivity = cells[i]
ctor = getattr(vtk, class_name)
elem = ctor()
for j in range(n_vertices):
elem.GetPointIds().SetId(j, connectivity[j])
cell_array.InsertNextCell(elem)
return cell_array
def _buildFaceSets(self):
self._multi_idx += 1
j = 0
for (id, fs) in self._labels['face_sets'].items():
self._multi_idx += 1
block = self._buildFaceSet(fs)
self._output.SetBlock(self._block_idx, block)
self._block_idx += 1
binfo = BlockInformation(object_type=1,
name=str(id),
number=self._multi_idx,
object_index=j,
multiblock_index=self._multi_idx)
self._sideset_info[id] = binfo
j += 1
def _buildFaceSet(self, face_set):
dim = self._vertices.shape[1]
if dim == 2:
block = vtk.vtkUnstructuredGrid()
edge_ids = np.reshape(face_set, -1)
pt_ids = {}
for eid in edge_ids:
node_ids = self._graph[eid]
for nid in node_ids:
pt_ids[nid] = 1
point_array = vtk.vtkPoints()
point_array.Allocate(len(pt_ids))
for i in pt_ids:
vert_idx = self._vertex_idx[i]
pt = [0, 0, 0]
for j in range(dim):
pt[j] = self._vertices[vert_idx][j]
point_array.InsertPoint(i, pt)
block.SetPoints(point_array)
cell_array = vtk.vtkCellArray()
for eid in edge_ids:
node_ids = self._graph[eid]
elem = vtk.vtkLine()
elem.GetPointIds().SetId(0, node_ids[0])
elem.GetPointIds().SetId(1, node_ids[1])
cell_array.InsertNextCell(elem)
block.SetCells(vtk.VTK_LINE, cell_array)
return block
elif dim == 3:
block = vtk.vtkUnstructuredGrid()
face_ids = np.reshape(face_set, -1)
pt_ids = {}
for fid in face_ids:
edge_ids = self._graph[fid]
for eid in edge_ids:
node_ids = self._graph[eid]
for nid in node_ids:
pt_ids[nid] = 1
point_array = vtk.vtkPoints()
point_array.Allocate(len(pt_ids))
for i in pt_ids:
vert_idx = self._vertex_idx[i]
pt = [0, 0, 0]
for j in range(dim):
pt[j] = self._vertices[vert_idx][j]
point_array.InsertPoint(i, pt)
block.SetPoints(point_array)
# this assumes all cells in the cell array are of the same type
cell_array = vtk.vtkCellArray()
for fid in face_ids:
pt_idxs = []
# this works, weirdly
edge_ids = self._graph[fid]
for eid in edge_ids:
node_ids = self._graph[eid]
if node_ids[0] not in pt_idxs:
pt_idxs.append(node_ids[0])
if node_ids[1] not in pt_idxs:
pt_idxs.append(node_ids[1])
if len(pt_idxs) == 3:
elem = vtk.vtkTriangle()
for i in range(3):
elem.GetPointIds().SetId(i, pt_idxs[i])
cell_array.InsertNextCell(elem)
type = vtk.VTK_TRIANGLE
elif len(pt_idxs) == 4:
elem = vtk.vtkQuad()
for i in range(4):
elem.GetPointIds().SetId(i, pt_idxs[i])
cell_array.InsertNextCell(elem)
type = vtk.VTK_QUAD
block.SetCells(type, cell_array)
return block
else:
return None
def _readVertexFields(self, block, vertex_fields):
point_data = block.GetPointData()
for (fname, ds) in vertex_fields.items():
if ds.attrs['vector_field_type'] == b'scalar':
arr = vtk.vtkDataArray.CreateDataArray(vtk.VTK_DOUBLE)
arr.SetName(fname)
arr.Allocate(ds.shape[0])
for val in list(ds):
arr.InsertNextTuple1(val)
point_data.AddArray(arr)
def _readCellFields(self, block, cell_fields):
cell_data = block.GetCellData()
for (fname, ds) in cell_fields.items():
if ds.attrs['vector_field_type'] == b'scalar':
arr = vtk.vtkDataArray.CreateDataArray(vtk.VTK_DOUBLE)
arr.SetName(fname)
arr.Allocate(ds.shape[0])
for val in list(ds):
arr.InsertNextTuple1(val)
cell_data.AddArray(arr)
def SetFileName(self, fname):
if fname != self._file_name:
self.Modified()
self._file_name = fname
def GetFileName(self):
return self._file_name
def GetTotalNumberOfElements(self):
return self._output.GetNumberOfCells()
def GetTotalNumberOfNodes(self):
return self._output.GetNumberOfPoints()
def getBlockInfo(self):
return self._block_info
def getSideSetInfo(self):
return self._sideset_info
def getDimensionality(self):
return self._cell_dim
class PetscHDF5Reader(Reader):
"""
PETSc HDF5 file reader
"""
def __init__(self, file_name):
super().__init__(file_name)
self._reader = None
self._block_info = dict()
self._sideset_info = dict()
self._variable_info = dict()
def isValid(self):
# TODO: check that the file was created by PETSc
return True
def load(self):
self._reader = PetscHDF5DataSetReader()
with common.lock_file(self._file_name):
self._reader.SetFileName(self._file_name)
self._reader.Update()
self._readBlockInfo()
self._readSidesetInfo()
self._readVariableInfo()
def _readBlockInfo(self):
self._block_info = self._reader.getBlockInfo()
def _readSidesetInfo(self):
self._sideset_info = self._reader.getSideSetInfo()
def _readVariableInfo(self):
# TODO
vinfo = VariableInformation(name="sln_u",
object_type=Reader.VAR_NODAL,
num_components=1)
self._variable_info["sln_u"] = vinfo
def getVtkOutputPort(self):
return self._reader.GetOutputPort(0)
def getBlocks(self):
return self._block_info.values()
def getSideSets(self):
return self._sideset_info.values()
def getNodeSets(self):
return []
def getVariableInfo(self):
return self._variable_info.values()
def getTotalNumberOfElements(self):
return self._reader.GetTotalNumberOfElements()
def getTotalNumberOfNodes(self):
return self._reader.GetTotalNumberOfNodes()
def getDimensionality(self):
return self._reader.getDimensionality() | otter/plugins/common/PetscHDF5Reader.py | import vtk
import h5py
import numpy as np
from vtk.util.vtkAlgorithm import VTKPythonAlgorithmBase
import otter.plugins.common as common
from otter.plugins.common.Reader import Reader
from otter.plugins.common.Reader import BlockInformation, VariableInformation
class PetscHDF5DataSetReader(VTKPythonAlgorithmBase):
"""
Reader for datasets produced by PETSc
"""
def __init__(self):
VTKPythonAlgorithmBase.__init__(
self,
nInputPorts=0,
nOutputPorts=1,
outputType='vtkMultiBlockDataSet')
self._file_name = ""
self._output = None
self._cell_dim = None
self._labels = {}
self._graph = {}
self._multi_idx = 0
self._cell_connectivity = None
self._block_info = None
self._sideset_info = None
def RequestData(self, request, in_info, out_info):
self._block_info = {}
self._sideset_info = {}
self._output = vtk.vtkMultiBlockDataSet.GetData(out_info)
self._readFile()
self._block_idx = 0
self._multi_idx = 0
self._buildBlocks()
self._buildFaceSets()
return 1
def _readFile(self):
f = h5py.File(self._file_name, 'r')
self._labels = {}
self._vertices = f['geometry']['vertices']
cells = np.reshape(f['topology']['cells'], -1)
cones = np.reshape(f['topology']['cones'], -1)
self._graph = {}
i = 0
j = 0
for c in cones:
lst = []
for k in range(c):
lst.append(cells[i])
i += 1
self._graph[j] = lst
j += 1
self._orientation = np.reshape(f['topology']['orientation'], -1)
labels = f['labels']
if 'celltype' in labels:
celltypes = labels['celltype']
self._cell_types = {}
self._dim_of_cell = {}
for ct in celltypes.keys():
indices = np.reshape(celltypes[ct]['indices'], -1)
for i in indices:
self._dim_of_cell[i] = ct
self._cell_types[int(ct)] = indices
self._vertex_idx = {}
for i, val in enumerate(self._cell_types[0]):
self._vertex_idx[val] = i
if 'Face Sets' in labels:
face_sets = labels['Face Sets']
self._labels['face_sets'] = {}
for fs in face_sets.keys():
indices = face_sets[fs]['indices']
self._labels['face_sets'][fs] = indices
if 'vertex_fields' in f:
self._vertex_fields = f['vertex_fields']
else:
self._vertex_fields = {}
if 'cell_fields' in f:
self._cell_fields = f['cell_fields']
else:
self._cell_fields = {}
self._cell_connectivity = f['viz']['topology']['cells']
def _buildBlocks(self):
block = vtk.vtkUnstructuredGrid()
dim = self._vertices.shape[1]
verts = self._cell_types[0]
n_points = len(verts)
point_array = vtk.vtkPoints()
point_array.Allocate(n_points)
for i in range(n_points):
pt = [0, 0, 0]
for j in range(dim):
pt[j] = self._vertices[i][j]
point_array.InsertPoint(i, pt)
block.SetPoints(point_array)
# FIXME: build this from cells and cones
n_cell_corners = self._cell_connectivity.attrs['cell_corners']
self._cell_dim = self._cell_connectivity.attrs['cell_dim']
c_conn = self._cell_connectivity
if self._cell_dim == 1:
if n_cell_corners == 2:
cell_array = self._buildCells(c_conn, "vtkLine", 2)
block.SetCells(vtk.VTK_LINE, cell_array)
elif self._cell_dim == 2:
if n_cell_corners == 3:
cell_array = self._buildCells(c_conn, "vtkTriangle", 3)
block.SetCells(vtk.VTK_TRIANGLE, cell_array)
elif n_cell_corners == 4:
cell_array = self._buildCells(c_conn, "vtkQuad", 4)
block.SetCells(vtk.VTK_QUAD, cell_array)
elif self._cell_dim == 3:
if n_cell_corners == 4:
cell_array = self._buildCells(c_conn, "vtkTetra", 4)
block.SetCells(vtk.VTK_TETRA, cell_array)
elif n_cell_corners == 6:
cell_array = self._buildCells(c_conn, "vtkWedge", 6)
block.SetCells(vtk.VTK_WEDGE, cell_array)
elif n_cell_corners == 8:
cell_array = self._buildCells(c_conn, "vtkHexahedron", 8)
block.SetCells(vtk.VTK_HEXAHEDRON, cell_array)
self._readVertexFields(block, self._vertex_fields)
self._readCellFields(block, self._cell_fields)
self._output.SetBlock(self._block_idx, block)
self._block_idx += 1
binfo = BlockInformation(object_type=0,
name="block",
number=self._multi_idx,
object_index=0,
multiblock_index=self._multi_idx)
self._block_info[0] = binfo
def _buildCells(self, cells, class_name, n_vertices):
n_cells = cells.shape[0]
cell_array = vtk.vtkCellArray()
cell_array.Allocate(n_cells)
for i in range(n_cells):
connectivity = cells[i]
ctor = getattr(vtk, class_name)
elem = ctor()
for j in range(n_vertices):
elem.GetPointIds().SetId(j, connectivity[j])
cell_array.InsertNextCell(elem)
return cell_array
def _buildFaceSets(self):
self._multi_idx += 1
j = 0
for (id, fs) in self._labels['face_sets'].items():
self._multi_idx += 1
block = self._buildFaceSet(fs)
self._output.SetBlock(self._block_idx, block)
self._block_idx += 1
binfo = BlockInformation(object_type=1,
name=str(id),
number=self._multi_idx,
object_index=j,
multiblock_index=self._multi_idx)
self._sideset_info[id] = binfo
j += 1
def _buildFaceSet(self, face_set):
dim = self._vertices.shape[1]
if dim == 2:
block = vtk.vtkUnstructuredGrid()
edge_ids = np.reshape(face_set, -1)
pt_ids = {}
for eid in edge_ids:
node_ids = self._graph[eid]
for nid in node_ids:
pt_ids[nid] = 1
point_array = vtk.vtkPoints()
point_array.Allocate(len(pt_ids))
for i in pt_ids:
vert_idx = self._vertex_idx[i]
pt = [0, 0, 0]
for j in range(dim):
pt[j] = self._vertices[vert_idx][j]
point_array.InsertPoint(i, pt)
block.SetPoints(point_array)
cell_array = vtk.vtkCellArray()
for eid in edge_ids:
node_ids = self._graph[eid]
elem = vtk.vtkLine()
elem.GetPointIds().SetId(0, node_ids[0])
elem.GetPointIds().SetId(1, node_ids[1])
cell_array.InsertNextCell(elem)
block.SetCells(vtk.VTK_LINE, cell_array)
return block
elif dim == 3:
block = vtk.vtkUnstructuredGrid()
face_ids = np.reshape(face_set, -1)
pt_ids = {}
for fid in face_ids:
edge_ids = self._graph[fid]
for eid in edge_ids:
node_ids = self._graph[eid]
for nid in node_ids:
pt_ids[nid] = 1
point_array = vtk.vtkPoints()
point_array.Allocate(len(pt_ids))
for i in pt_ids:
vert_idx = self._vertex_idx[i]
pt = [0, 0, 0]
for j in range(dim):
pt[j] = self._vertices[vert_idx][j]
point_array.InsertPoint(i, pt)
block.SetPoints(point_array)
# this assumes all cells in the cell array are of the same type
cell_array = vtk.vtkCellArray()
for fid in face_ids:
pt_idxs = []
# this works, weirdly
edge_ids = self._graph[fid]
for eid in edge_ids:
node_ids = self._graph[eid]
if node_ids[0] not in pt_idxs:
pt_idxs.append(node_ids[0])
if node_ids[1] not in pt_idxs:
pt_idxs.append(node_ids[1])
if len(pt_idxs) == 3:
elem = vtk.vtkTriangle()
for i in range(3):
elem.GetPointIds().SetId(i, pt_idxs[i])
cell_array.InsertNextCell(elem)
type = vtk.VTK_TRIANGLE
elif len(pt_idxs) == 4:
elem = vtk.vtkQuad()
for i in range(4):
elem.GetPointIds().SetId(i, pt_idxs[i])
cell_array.InsertNextCell(elem)
type = vtk.VTK_QUAD
block.SetCells(type, cell_array)
return block
else:
return None
def _readVertexFields(self, block, vertex_fields):
point_data = block.GetPointData()
for (fname, ds) in vertex_fields.items():
if ds.attrs['vector_field_type'] == b'scalar':
arr = vtk.vtkDataArray.CreateDataArray(vtk.VTK_DOUBLE)
arr.SetName(fname)
arr.Allocate(ds.shape[0])
for val in list(ds):
arr.InsertNextTuple1(val)
point_data.AddArray(arr)
def _readCellFields(self, block, cell_fields):
cell_data = block.GetCellData()
for (fname, ds) in cell_fields.items():
if ds.attrs['vector_field_type'] == b'scalar':
arr = vtk.vtkDataArray.CreateDataArray(vtk.VTK_DOUBLE)
arr.SetName(fname)
arr.Allocate(ds.shape[0])
for val in list(ds):
arr.InsertNextTuple1(val)
cell_data.AddArray(arr)
def SetFileName(self, fname):
if fname != self._file_name:
self.Modified()
self._file_name = fname
def GetFileName(self):
return self._file_name
def GetTotalNumberOfElements(self):
return self._output.GetNumberOfCells()
def GetTotalNumberOfNodes(self):
return self._output.GetNumberOfPoints()
def getBlockInfo(self):
return self._block_info
def getSideSetInfo(self):
return self._sideset_info
def getDimensionality(self):
return self._cell_dim
class PetscHDF5Reader(Reader):
"""
PETSc HDF5 file reader
"""
def __init__(self, file_name):
super().__init__(file_name)
self._reader = None
self._block_info = dict()
self._sideset_info = dict()
self._variable_info = dict()
def isValid(self):
# TODO: check that the file was created by PETSc
return True
def load(self):
self._reader = PetscHDF5DataSetReader()
with common.lock_file(self._file_name):
self._reader.SetFileName(self._file_name)
self._reader.Update()
self._readBlockInfo()
self._readSidesetInfo()
self._readVariableInfo()
def _readBlockInfo(self):
self._block_info = self._reader.getBlockInfo()
def _readSidesetInfo(self):
self._sideset_info = self._reader.getSideSetInfo()
def _readVariableInfo(self):
# TODO
vinfo = VariableInformation(name="sln_u",
object_type=Reader.VAR_NODAL,
num_components=1)
self._variable_info["sln_u"] = vinfo
def getVtkOutputPort(self):
return self._reader.GetOutputPort(0)
def getBlocks(self):
return self._block_info.values()
def getSideSets(self):
return self._sideset_info.values()
def getNodeSets(self):
return []
def getVariableInfo(self):
return self._variable_info.values()
def getTotalNumberOfElements(self):
return self._reader.GetTotalNumberOfElements()
def getTotalNumberOfNodes(self):
return self._reader.GetTotalNumberOfNodes()
def getDimensionality(self):
return self._reader.getDimensionality() | 0.338733 | 0.209288 |
from datetime import datetime
from .common import ScraperTest
class RacesTest(ScraperTest):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.meet = {
'date': datetime(2016, 2, 1),
'track': 'Kilmore',
'url': '/racing-results/victoria/Kilmore/2016-02-01/'
}
cls.expected_races = [
{
'number': 1,
'distance': 1100,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 13, 10),
'url': '/form-guide/Kilmore_69146/Wandong-Bus-and-Coach-Maiden-Plate_411192/',
'entry_conditions': [
'Three-Years-Old and Upwards',
'Maiden',
'No sex restriction',
'Set Weights'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 2,
'distance': 1200,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 13, 45),
'url': '/form-guide/Kilmore_69146/Book-now-for-Valentines-Day-14-Feb-Maiden-Plate_411193/',
'entry_conditions': [
'Three-Years-Old',
'Maiden',
'Fillies',
'Set Weights'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 3,
'distance': 1450,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 14, 20),
'url': '/form-guide/Kilmore_69146/Montmorency-RSL-Maiden-Plate_411194/',
'entry_conditions': [
'Three-Years-Old and Upwards',
'Maiden',
'No sex restriction',
'Set Weights'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 4,
'distance': 1600,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 14, 55),
'url': '/form-guide/Kilmore_69146/Sunday-Sessions-%40-Trackside-7-Feb-Maiden-Plate_411195/',
'entry_conditions': [
'Three-Years-Old and Upwards',
'Maiden',
'No sex restriction',
'Set Weights'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 5,
'distance': 1100,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 15, 32),
'url': '/form-guide/Kilmore_69146/www.kilmoreracingclub.com.au-BM64-Handicap_411196/',
'entry_conditions': [
'No age restriction',
'BenchMark 64',
'No sex restriction',
'Handicap'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 6,
'distance': 1200,
'prize_money': 16000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 16, 12),
'url': '/form-guide/Kilmore_69146/Wilson-Medic-One-Rising-Stars-0-58-Handicap_411197/',
'entry_conditions': [
'No age restriction',
'0 - 58',
'No sex restriction',
'Handicap'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 7,
'distance': 1900,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 16, 52),
'url': '/form-guide/Kilmore_69146/Sportsmans-Lunch-%40-Trackside-26-Feb-BM64-Handicap_411198/',
'entry_conditions': [
'No age restriction',
'BenchMark 64',
'No sex restriction',
'Handicap'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 8,
'distance': 1600,
'prize_money': 16000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 17, 32),
'url': '/form-guide/Kilmore_69146/Book-Now-Jet-Roofing-Kilmore-Pacing-Cup-0-58-Handicap_411199/',
'entry_conditions': [
'No age restriction',
'0 - 58',
'No sex restriction',
'Handicap'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
}
]
cls.scraped_races = cls.scraper.scrape_races(cls.meet)
def setUp(self):
self.assertIsInstance(self.scraped_races, list)
def test_expected_races(self):
"""The scrape_races method should return a list containing all expected races"""
self.check_expected_items(self.expected_races, self.scraped_races)
def test_unexpected_races(self):
"""The scrape_races method should return a list that does not contain any unexpected races"""
self.check_unexpected_items(self.expected_races, self.scraped_races) | pypunters/test/races.py | from datetime import datetime
from .common import ScraperTest
class RacesTest(ScraperTest):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.meet = {
'date': datetime(2016, 2, 1),
'track': 'Kilmore',
'url': '/racing-results/victoria/Kilmore/2016-02-01/'
}
cls.expected_races = [
{
'number': 1,
'distance': 1100,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 13, 10),
'url': '/form-guide/Kilmore_69146/Wandong-Bus-and-Coach-Maiden-Plate_411192/',
'entry_conditions': [
'Three-Years-Old and Upwards',
'Maiden',
'No sex restriction',
'Set Weights'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 2,
'distance': 1200,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 13, 45),
'url': '/form-guide/Kilmore_69146/Book-now-for-Valentines-Day-14-Feb-Maiden-Plate_411193/',
'entry_conditions': [
'Three-Years-Old',
'Maiden',
'Fillies',
'Set Weights'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 3,
'distance': 1450,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 14, 20),
'url': '/form-guide/Kilmore_69146/Montmorency-RSL-Maiden-Plate_411194/',
'entry_conditions': [
'Three-Years-Old and Upwards',
'Maiden',
'No sex restriction',
'Set Weights'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 4,
'distance': 1600,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 14, 55),
'url': '/form-guide/Kilmore_69146/Sunday-Sessions-%40-Trackside-7-Feb-Maiden-Plate_411195/',
'entry_conditions': [
'Three-Years-Old and Upwards',
'Maiden',
'No sex restriction',
'Set Weights'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 5,
'distance': 1100,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 15, 32),
'url': '/form-guide/Kilmore_69146/www.kilmoreracingclub.com.au-BM64-Handicap_411196/',
'entry_conditions': [
'No age restriction',
'BenchMark 64',
'No sex restriction',
'Handicap'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 6,
'distance': 1200,
'prize_money': 16000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 16, 12),
'url': '/form-guide/Kilmore_69146/Wilson-Medic-One-Rising-Stars-0-58-Handicap_411197/',
'entry_conditions': [
'No age restriction',
'0 - 58',
'No sex restriction',
'Handicap'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 7,
'distance': 1900,
'prize_money': 20000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 16, 52),
'url': '/form-guide/Kilmore_69146/Sportsmans-Lunch-%40-Trackside-26-Feb-BM64-Handicap_411198/',
'entry_conditions': [
'No age restriction',
'BenchMark 64',
'No sex restriction',
'Handicap'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
},
{
'number': 8,
'distance': 1600,
'prize_money': 16000.00,
'track_condition': 'Good 4',
'start_time': datetime(2016, 2, 1, 17, 32),
'url': '/form-guide/Kilmore_69146/Book-Now-Jet-Roofing-Kilmore-Pacing-Cup-0-58-Handicap_411199/',
'entry_conditions': [
'No age restriction',
'0 - 58',
'No sex restriction',
'Handicap'
],
'track_circ': 1735,
'track_straight': 320,
'track_rail': 'True Entire Circuit'
}
]
cls.scraped_races = cls.scraper.scrape_races(cls.meet)
def setUp(self):
self.assertIsInstance(self.scraped_races, list)
def test_expected_races(self):
"""The scrape_races method should return a list containing all expected races"""
self.check_expected_items(self.expected_races, self.scraped_races)
def test_unexpected_races(self):
"""The scrape_races method should return a list that does not contain any unexpected races"""
self.check_unexpected_items(self.expected_races, self.scraped_races) | 0.421552 | 0.158597 |
# Rest server
from MiniREST.RESTServer import RESTServer, responseCodes, responseTypes
class RCubicServer(RESTServer):
"""RCubicServer - creates a new RCubicServer instance.
Extends RESTServer with custom functions.
"""
def __init__(self, *args, **kwargs):
"""Create a RCubicServer. Call 'start' to start the server.
Keyword arguments:
bind -- the address to which the server binds (default '0.0.0.0')
port -- the port on which the server listens (default 8000)
"""
super(RCubicServer, self).__init__(*args, **kwargs)
self.receivedCheckIns = {}
self.registerFunction('checkInUser', self.checkInUser)
def checkInUser(self, env, start_reponse, post):
"""Responds to a 'checkInUser' request by calling set() on the waiting event.
Keyword arguments:
env -- exepects 'user' and 'checkInName' in POST.
"""
user = post['user']
checkInName = post['checkInName']
# Try an 'anyuser' room check in
vs = user.split('/')
try:
self.receivedCheckIns[checkInName][vs[0]].set()
except KeyError:
self.receivedCheckIns[checkInName][user].set()
start_reponse(responseCodes[200], responseTypes['plaintext'])
return 'OK'
def registerCheckIn(self, user, checkInName, ev):
"""Internal function which records the reference to an event to wake up
once a checkIn is recieved.
Keyword arguments:
user -- the user
checkInName -- unique string identifier
"""
if not checkInName in self.receivedCheckIns:
self.receivedCheckIns[checkInName] = {}
self.receivedCheckIns[checkInName][user] = ev
def unRegisterCheckIn(self, checkInName):
"""Internal function which deletes all events waiting for 'checkInName'.
Calls set() on all of them before returning.
Keyword arguments:
checkInName -- the checkIn events to delete
"""
try:
events = self.receivedCheckIns.pop(checkInName)
for event in events.values():
event.set()
return True
except KeyError:
return False | RCubic/RCubicServer.py |
# Rest server
from MiniREST.RESTServer import RESTServer, responseCodes, responseTypes
class RCubicServer(RESTServer):
"""RCubicServer - creates a new RCubicServer instance.
Extends RESTServer with custom functions.
"""
def __init__(self, *args, **kwargs):
"""Create a RCubicServer. Call 'start' to start the server.
Keyword arguments:
bind -- the address to which the server binds (default '0.0.0.0')
port -- the port on which the server listens (default 8000)
"""
super(RCubicServer, self).__init__(*args, **kwargs)
self.receivedCheckIns = {}
self.registerFunction('checkInUser', self.checkInUser)
def checkInUser(self, env, start_reponse, post):
"""Responds to a 'checkInUser' request by calling set() on the waiting event.
Keyword arguments:
env -- exepects 'user' and 'checkInName' in POST.
"""
user = post['user']
checkInName = post['checkInName']
# Try an 'anyuser' room check in
vs = user.split('/')
try:
self.receivedCheckIns[checkInName][vs[0]].set()
except KeyError:
self.receivedCheckIns[checkInName][user].set()
start_reponse(responseCodes[200], responseTypes['plaintext'])
return 'OK'
def registerCheckIn(self, user, checkInName, ev):
"""Internal function which records the reference to an event to wake up
once a checkIn is recieved.
Keyword arguments:
user -- the user
checkInName -- unique string identifier
"""
if not checkInName in self.receivedCheckIns:
self.receivedCheckIns[checkInName] = {}
self.receivedCheckIns[checkInName][user] = ev
def unRegisterCheckIn(self, checkInName):
"""Internal function which deletes all events waiting for 'checkInName'.
Calls set() on all of them before returning.
Keyword arguments:
checkInName -- the checkIn events to delete
"""
try:
events = self.receivedCheckIns.pop(checkInName)
for event in events.values():
event.set()
return True
except KeyError:
return False | 0.636918 | 0.339636 |
import os
from pathlib import Path
import cv2
import numpy as np
INPUT_IMAGES_DIR = 'LR6_data/train/images'
INPUT_MASKS_DIR = 'LR6_data/train/masks'
OUTPUT_IMAGES_DIR = 'LR6_data/train/train_images2'
OUTPUT_MASKS_DIR = 'LR6_data/train/train_masks2'
BACKGROUDS_DIR = 'LR6_data/train2/backgrounds'
MASK_EXTENSION = '.png'
OUTPUT_EXTENSION = '.png'
"""
# ######### GENERATE FROM CAMERA ######### #
def glue_backgroud(input_image, input_backgroud):
chroma_mask = cv2.inRange(input_image, (0, 100, 0), (80, 255, 80))
input_image = np.copy(input_image)
input_image[chroma_mask != 0] = [0, 0, 0]
input_backgroud[chroma_mask == 0] = [0, 0, 0]
output_image = input_image + input_backgroud
return output_image
file_id_counter = 0
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
kernel_filter = np.ones((7, 7), np.uint8)
kernel = np.ones((15, 15), np.uint8)
while True:
ret, img = cap.read()
if img is None:
break
if img.shape[1] != 640 and img.shape[0] != 480:
resized = cv2.resize(img, (854, 480))
img = np.zeros((480, 640, 3), np.uint8)
img[0:480, 0:640] = resized[0:480, 107:107 + 640]
original_image = img.copy()
final_image = glue_backgroud(img, cv2.imread(BACKGROUDS_DIR + '/' + str(0) + OUTPUT_EXTENSION))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (55, 0, 0), (65, 255, 255))
mask = cv2.erode(mask, kernel_filter)
mask = cv2.dilate(mask, kernel_filter)
final_mask = np.zeros((mask.shape[0], mask.shape[1], 3), np.uint8)
mask_dilated_ext = cv2.dilate(255 - mask, kernel)
mask_dilated_ext = mask_dilated_ext - (255 - mask)
mask_dilated_int = cv2.dilate(mask, kernel)
mask_dilated_int = mask_dilated_int - mask
blue = np.ones((mask.shape[0], mask.shape[1]), np.uint8) * 255
red = np.ones((mask.shape[0], mask.shape[1]), np.uint8) * 255
blue[mask == 0] = 0
blue[mask_dilated_ext == 255] = 0
red[mask == 255] = 0
red[mask_dilated_int == 255] = 0
final_mask[:, :, 0] = blue
final_mask[:, :, 1] = mask_dilated_ext + mask_dilated_int
final_mask[:, :, 2] = red
# final_mask[final_mask.shape[0] - 6:final_mask.shape[0], :, 2] = 0
cv2.imshow('original', original_image)
cv2.imshow('chroma', final_image)
cv2.imshow('mask', final_mask)
k = cv2.waitKey(30) & 0xff
if k == 13: # Enter
cv2.imwrite(BACKGROUDS_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, original_image)
print('File', file_id_counter, 'saved.')
file_id_counter += 1
elif k == 32: # Space
print('Start saving from', file_id_counter, '...')
background_id_counter = 0
entries = Path(BACKGROUDS_DIR)
for entry in entries.iterdir():
background = cv2.imread(BACKGROUDS_DIR + '/'
+ str(background_id_counter) + OUTPUT_EXTENSION)
if background is not None:
final_image = glue_backgroud(img, background)
cv2.imwrite(OUTPUT_IMAGES_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, final_image)
cv2.imwrite(OUTPUT_MASKS_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, final_mask)
file_id_counter += 1
background_id_counter += 1
print('Done', file_id_counter, '.')
elif k == 27: # ESC
break
cap.release()
# ######### GENERATE FROM FILES ######### #
"""
_, _, files = next(os.walk(INPUT_IMAGES_DIR))
file_id_counter = 0
entries = Path(INPUT_IMAGES_DIR)
kernel = np.ones((7, 7), np.uint8)
for entry in entries.iterdir():
image = cv2.imread(str(entry), 0)
mask = cv2.imread(INPUT_MASKS_DIR + '/' + os.path.splitext(entry.name)[0] + MASK_EXTENSION, 0)
if image is not None:
# image = cv2.resize(image, (256, 256), interpolation=cv2.INTER_NEAREST) # (640, 480)
# mask = cv2.resize(mask, (256, 256), interpolation=cv2.INTER_NEAREST)
object_layer = mask.copy()
object_layer[object_layer == 1] = 255
object_layer[object_layer == 2] = 0
object_layer[object_layer == 3] = 0
contout_layer = mask.copy()
contout_layer[contout_layer == 1] = 0
contout_layer[contout_layer == 2] = 0
contout_layer[contout_layer == 3] = 255
background_layer = mask.copy()
background_layer[background_layer == 1] = 0
background_layer[background_layer == 2] = 255
background_layer[background_layer == 3] = 0
mask = np.zeros((mask.shape[0], mask.shape[1]), np.uint8) # (480, 640, 3)
mask[:, :] = cv2.dilate(object_layer, kernel)
cv2.imwrite(OUTPUT_IMAGES_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, image)
cv2.imwrite(OUTPUT_MASKS_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, mask)
file_id_counter += 1
if file_id_counter % 100 == 0:
print('Collected', file_id_counter, 'out of', len(files)) | LR6/LR6_data_collector.py | import os
from pathlib import Path
import cv2
import numpy as np
INPUT_IMAGES_DIR = 'LR6_data/train/images'
INPUT_MASKS_DIR = 'LR6_data/train/masks'
OUTPUT_IMAGES_DIR = 'LR6_data/train/train_images2'
OUTPUT_MASKS_DIR = 'LR6_data/train/train_masks2'
BACKGROUDS_DIR = 'LR6_data/train2/backgrounds'
MASK_EXTENSION = '.png'
OUTPUT_EXTENSION = '.png'
"""
# ######### GENERATE FROM CAMERA ######### #
def glue_backgroud(input_image, input_backgroud):
chroma_mask = cv2.inRange(input_image, (0, 100, 0), (80, 255, 80))
input_image = np.copy(input_image)
input_image[chroma_mask != 0] = [0, 0, 0]
input_backgroud[chroma_mask == 0] = [0, 0, 0]
output_image = input_image + input_backgroud
return output_image
file_id_counter = 0
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
kernel_filter = np.ones((7, 7), np.uint8)
kernel = np.ones((15, 15), np.uint8)
while True:
ret, img = cap.read()
if img is None:
break
if img.shape[1] != 640 and img.shape[0] != 480:
resized = cv2.resize(img, (854, 480))
img = np.zeros((480, 640, 3), np.uint8)
img[0:480, 0:640] = resized[0:480, 107:107 + 640]
original_image = img.copy()
final_image = glue_backgroud(img, cv2.imread(BACKGROUDS_DIR + '/' + str(0) + OUTPUT_EXTENSION))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (55, 0, 0), (65, 255, 255))
mask = cv2.erode(mask, kernel_filter)
mask = cv2.dilate(mask, kernel_filter)
final_mask = np.zeros((mask.shape[0], mask.shape[1], 3), np.uint8)
mask_dilated_ext = cv2.dilate(255 - mask, kernel)
mask_dilated_ext = mask_dilated_ext - (255 - mask)
mask_dilated_int = cv2.dilate(mask, kernel)
mask_dilated_int = mask_dilated_int - mask
blue = np.ones((mask.shape[0], mask.shape[1]), np.uint8) * 255
red = np.ones((mask.shape[0], mask.shape[1]), np.uint8) * 255
blue[mask == 0] = 0
blue[mask_dilated_ext == 255] = 0
red[mask == 255] = 0
red[mask_dilated_int == 255] = 0
final_mask[:, :, 0] = blue
final_mask[:, :, 1] = mask_dilated_ext + mask_dilated_int
final_mask[:, :, 2] = red
# final_mask[final_mask.shape[0] - 6:final_mask.shape[0], :, 2] = 0
cv2.imshow('original', original_image)
cv2.imshow('chroma', final_image)
cv2.imshow('mask', final_mask)
k = cv2.waitKey(30) & 0xff
if k == 13: # Enter
cv2.imwrite(BACKGROUDS_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, original_image)
print('File', file_id_counter, 'saved.')
file_id_counter += 1
elif k == 32: # Space
print('Start saving from', file_id_counter, '...')
background_id_counter = 0
entries = Path(BACKGROUDS_DIR)
for entry in entries.iterdir():
background = cv2.imread(BACKGROUDS_DIR + '/'
+ str(background_id_counter) + OUTPUT_EXTENSION)
if background is not None:
final_image = glue_backgroud(img, background)
cv2.imwrite(OUTPUT_IMAGES_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, final_image)
cv2.imwrite(OUTPUT_MASKS_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, final_mask)
file_id_counter += 1
background_id_counter += 1
print('Done', file_id_counter, '.')
elif k == 27: # ESC
break
cap.release()
# ######### GENERATE FROM FILES ######### #
"""
_, _, files = next(os.walk(INPUT_IMAGES_DIR))
file_id_counter = 0
entries = Path(INPUT_IMAGES_DIR)
kernel = np.ones((7, 7), np.uint8)
for entry in entries.iterdir():
image = cv2.imread(str(entry), 0)
mask = cv2.imread(INPUT_MASKS_DIR + '/' + os.path.splitext(entry.name)[0] + MASK_EXTENSION, 0)
if image is not None:
# image = cv2.resize(image, (256, 256), interpolation=cv2.INTER_NEAREST) # (640, 480)
# mask = cv2.resize(mask, (256, 256), interpolation=cv2.INTER_NEAREST)
object_layer = mask.copy()
object_layer[object_layer == 1] = 255
object_layer[object_layer == 2] = 0
object_layer[object_layer == 3] = 0
contout_layer = mask.copy()
contout_layer[contout_layer == 1] = 0
contout_layer[contout_layer == 2] = 0
contout_layer[contout_layer == 3] = 255
background_layer = mask.copy()
background_layer[background_layer == 1] = 0
background_layer[background_layer == 2] = 255
background_layer[background_layer == 3] = 0
mask = np.zeros((mask.shape[0], mask.shape[1]), np.uint8) # (480, 640, 3)
mask[:, :] = cv2.dilate(object_layer, kernel)
cv2.imwrite(OUTPUT_IMAGES_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, image)
cv2.imwrite(OUTPUT_MASKS_DIR + '/' + str(file_id_counter) + OUTPUT_EXTENSION, mask)
file_id_counter += 1
if file_id_counter % 100 == 0:
print('Collected', file_id_counter, 'out of', len(files)) | 0.165323 | 0.117851 |
from django.db import migrations, models
import django.db.models.deletion
from utils.migrate_base_product import update_id_on_models
def link_retreat_to_base_product(apps, schema_editor):
retreat_model = apps.get_model('retirement',
'retreat')
base_product_model = apps.get_model('store',
'baseproduct')
order_line_model = apps.get_model('store',
'orderline')
updated_ids = {}
for retreat in retreat_model.objects.all():
base_product = base_product_model.objects.create(
name=retreat.name,
name_fr=retreat.name_fr,
name_en=retreat.name_en,
available=retreat.available,
price=retreat.price,
details_fr=retreat.details_fr,
details_en=retreat.details_en
)
updated_ids[retreat.old_id] = base_product.id
retreat.baseproduct_ptr = base_product
retreat.save()
for order_line in order_line_model.objects.filter(
content_type__model='retreat'):
order_line.object_id = updated_ids[order_line.object_id]
order_line.save()
def update_retreat_id_on_other_models(apps, schema_editor):
retreat_model = apps.get_model('retirement',
'retreat')
list_model_to_migrate = [
('retirement', 'picture', 'id', 'retreat', True),
('retirement', 'reservation', 'id', 'retreat', True),
('store', 'membership', 'baseproduct_ptr_id', 'retreats', False),
('store', 'coupon', 'id', 'applicable_retreats', False),
('store', 'membershipcoupon', 'id', 'applicable_retreats', False),
('retirement', 'WaitQueueNotification', 'id', 'retreat', True),
]
updated_ids = {}
for retreat in retreat_model.objects.all():
updated_ids[retreat.old_id] = retreat.baseproduct_ptr_id
update_id_on_models(apps, list_model_to_migrate,
updated_ids, retreat_model)
# Update wait queue
# Copy them, delete and recreate
waite_queue_model = apps.get_model('retirement', 'waitqueue')
list_wait_queue = list(waite_queue_model.objects.all())
waite_queue_model.objects.all().delete()
for waite_queue in list_wait_queue:
waite_queue.retreat_id = updated_ids[waite_queue.retreat_id]
waite_queue.save()
def save_old_id(apps, schema_editor):
retreat_model = apps.get_model('retirement',
'retreat')
for retreat in retreat_model.objects.all():
retreat.old_id = retreat.id
retreat.save()
class Migration(migrations.Migration):
dependencies = [
('store', '0028_auto_20190815_0328'),
('retirement', '0015_auto_20190815_0305'),
]
operations = [
migrations.AddField(
model_name='historicalretreat',
name='old_id',
field=models.IntegerField(default=1,
null=True,
verbose_name='Id before migrate to base product'),
preserve_default=False,
),
migrations.AddField(
model_name='retreat',
name='old_id',
field=models.IntegerField(default=1,
null=True,
verbose_name='Id before migrate to base product'),
preserve_default=False,
),
migrations.RunPython(save_old_id),
migrations.AddField(
model_name='historicalretreat',
name='baseproduct_ptr',
field=models.ForeignKey(auto_created=True, blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
parent_link=True, related_name='+',
to='store.BaseProduct'),
),
migrations.AddField(
model_name='retreat',
name='baseproduct_ptr',
field=models.OneToOneField(auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True, null=True, blank=True,
serialize=False,
to='store.BaseProduct'),
preserve_default=False,
),
migrations.RunPython(link_retreat_to_base_product),
migrations.RemoveField(
model_name='retreat',
name='id',
),
migrations.AlterField(
model_name='retreat',
name='baseproduct_ptr',
field=models.OneToOneField(auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True, primary_key=True,
serialize=False,
to='store.BaseProduct'),
preserve_default=False,
),
migrations.RemoveField(
model_name='retreat',
name='available',
),
migrations.RemoveField(
model_name='retreat',
name='details',
),
migrations.RemoveField(
model_name='retreat',
name='details_en',
),
migrations.RemoveField(
model_name='retreat',
name='details_fr',
),
migrations.RemoveField(
model_name='retreat',
name='name',
),
migrations.RemoveField(
model_name='retreat',
name='name_en',
),
migrations.RemoveField(
model_name='retreat',
name='name_fr',
),
migrations.RemoveField(
model_name='retreat',
name='price',
),
migrations.RunPython(update_retreat_id_on_other_models),
] | retirement/migrations/0016_auto_20190815_0328.py |
from django.db import migrations, models
import django.db.models.deletion
from utils.migrate_base_product import update_id_on_models
def link_retreat_to_base_product(apps, schema_editor):
retreat_model = apps.get_model('retirement',
'retreat')
base_product_model = apps.get_model('store',
'baseproduct')
order_line_model = apps.get_model('store',
'orderline')
updated_ids = {}
for retreat in retreat_model.objects.all():
base_product = base_product_model.objects.create(
name=retreat.name,
name_fr=retreat.name_fr,
name_en=retreat.name_en,
available=retreat.available,
price=retreat.price,
details_fr=retreat.details_fr,
details_en=retreat.details_en
)
updated_ids[retreat.old_id] = base_product.id
retreat.baseproduct_ptr = base_product
retreat.save()
for order_line in order_line_model.objects.filter(
content_type__model='retreat'):
order_line.object_id = updated_ids[order_line.object_id]
order_line.save()
def update_retreat_id_on_other_models(apps, schema_editor):
retreat_model = apps.get_model('retirement',
'retreat')
list_model_to_migrate = [
('retirement', 'picture', 'id', 'retreat', True),
('retirement', 'reservation', 'id', 'retreat', True),
('store', 'membership', 'baseproduct_ptr_id', 'retreats', False),
('store', 'coupon', 'id', 'applicable_retreats', False),
('store', 'membershipcoupon', 'id', 'applicable_retreats', False),
('retirement', 'WaitQueueNotification', 'id', 'retreat', True),
]
updated_ids = {}
for retreat in retreat_model.objects.all():
updated_ids[retreat.old_id] = retreat.baseproduct_ptr_id
update_id_on_models(apps, list_model_to_migrate,
updated_ids, retreat_model)
# Update wait queue
# Copy them, delete and recreate
waite_queue_model = apps.get_model('retirement', 'waitqueue')
list_wait_queue = list(waite_queue_model.objects.all())
waite_queue_model.objects.all().delete()
for waite_queue in list_wait_queue:
waite_queue.retreat_id = updated_ids[waite_queue.retreat_id]
waite_queue.save()
def save_old_id(apps, schema_editor):
retreat_model = apps.get_model('retirement',
'retreat')
for retreat in retreat_model.objects.all():
retreat.old_id = retreat.id
retreat.save()
class Migration(migrations.Migration):
dependencies = [
('store', '0028_auto_20190815_0328'),
('retirement', '0015_auto_20190815_0305'),
]
operations = [
migrations.AddField(
model_name='historicalretreat',
name='old_id',
field=models.IntegerField(default=1,
null=True,
verbose_name='Id before migrate to base product'),
preserve_default=False,
),
migrations.AddField(
model_name='retreat',
name='old_id',
field=models.IntegerField(default=1,
null=True,
verbose_name='Id before migrate to base product'),
preserve_default=False,
),
migrations.RunPython(save_old_id),
migrations.AddField(
model_name='historicalretreat',
name='baseproduct_ptr',
field=models.ForeignKey(auto_created=True, blank=True,
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
parent_link=True, related_name='+',
to='store.BaseProduct'),
),
migrations.AddField(
model_name='retreat',
name='baseproduct_ptr',
field=models.OneToOneField(auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True, null=True, blank=True,
serialize=False,
to='store.BaseProduct'),
preserve_default=False,
),
migrations.RunPython(link_retreat_to_base_product),
migrations.RemoveField(
model_name='retreat',
name='id',
),
migrations.AlterField(
model_name='retreat',
name='baseproduct_ptr',
field=models.OneToOneField(auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True, primary_key=True,
serialize=False,
to='store.BaseProduct'),
preserve_default=False,
),
migrations.RemoveField(
model_name='retreat',
name='available',
),
migrations.RemoveField(
model_name='retreat',
name='details',
),
migrations.RemoveField(
model_name='retreat',
name='details_en',
),
migrations.RemoveField(
model_name='retreat',
name='details_fr',
),
migrations.RemoveField(
model_name='retreat',
name='name',
),
migrations.RemoveField(
model_name='retreat',
name='name_en',
),
migrations.RemoveField(
model_name='retreat',
name='name_fr',
),
migrations.RemoveField(
model_name='retreat',
name='price',
),
migrations.RunPython(update_retreat_id_on_other_models),
] | 0.333829 | 0.067424 |
import tvm
import json
from functools import reduce
from .. import _ffi_api
from ..target import TENET
class TenetContext(object):
def __init__(self, level):
self.level = level
self.space_time_loops = [[[], []] for i in range(level)] # outer --> inner
self.memory_scopes = [None for i in range(level)]
def set_space_loop(self, level, loop):
assert isinstance(loop, list)
self.space_time_loops[level][0] = loop
def update_space_loop(self, level, loop, push_front=True):
assert isinstance(loop, list)
if push_front:
self.space_time_loops[level][0] = loop + self.space_time_loops[level][0]
else:
self.space_time_loops[level][0] = self.space_time_loops[level][0] + loop
def set_time_loop(self, level, loop):
assert isinstance(loop, list)
self.space_time_loops[level][1] = loop
def update_time_loop(self, level, loop, push_front=True):
assert isinstance(loop, list)
if push_front:
self.space_time_loops[level][1] = loop + self.space_time_loops[level][1]
else:
self.space_time_loops[level][1] = self.space_time_loops[level][1] + loop
def set_space_time_loops(self, level, space, time):
assert isinstance(space, list)
assert isinstance(time, list)
self.space_time_loops[level] = [space, time]
def update_space_time_loops(self, level, space, time, push_front=True):
assert isinstance(space, list)
assert isinstance(time, list)
if push_front:
self.space_time_loops[level][0] = space + self.space_time_loops[level][0]
self.space_time_loops[level][1] = time + self.space_time_loops[level][1]
else:
self.space_time_loops[level][0] = self.space_time_loops[level][0] + space
self.space_time_loops[level][1] = self.space_time_loops[level][1] + time
def set_memory_scope(self, level, scope):
assert isinstance(scope, str)
self.memory_scopes[level] = scope
def __repr__(self):
levels = "\n".join(
[
f"level_{i}:"
+ str(
{
"space": self.space_time_loops[i][0],
"time": self.space_time_loops[i][1],
"memory": self.memory_scopes[i],
}
)
for i in range(self.level)
]
)
return str(levels)
def __str__(self):
return self.__repr__()
class TenetFunc(object):
def __init__(self, memory_size, space_time_loops, target):
self.memory_size = memory_size
self.space_time_loops = space_time_loops
self.target = target
def save(self, filename):
obj = {
"memory_size": self.memory_size,
"space_time_loops": self.space_time_loops,
"target": self.target,
}
with open(filename, "w") as fout:
fout.write(json.dumps(obj))
def get_buffer_size(scope, stmt):
"""
scope: str
stmt: Stmt
"""
return _ffi_api.get_buffer_size(scope, stmt)
def build(sch, args, ctx, target="tenet gemm", target_host="llvm", name="main"):
ir_module = tvm.lower(sch, args, simple_mode=True)
# print(ir_module)
from tvm.te import schedule
sch = sch.normalize()
bounds = schedule.InferBound(sch)
# calculate memory size
memory_size = []
for scope in ctx.memory_scopes:
sum_val = 0
for _, f in ir_module.functions.items():
for k, v in get_buffer_size(scope, f.body).items():
sum_val += v.value
memory_size.append([scope, sum_val])
# calculate space time loops
space_time_loops = []
for l, [s, t] in enumerate(ctx.space_time_loops):
ss = [bounds[x].extent.value for x in s]
tt = [bounds[x].extent.value for x in t]
space_time_loops.append([ss, tt])
# print(space_time_loops)
return TenetFunc(memory_size, space_time_loops, target)
def load_func(filename):
with open(filename, "r") as fin:
string = fin.readline().strip()
obj = json.loads(string)
return TenetFunc(obj["memory_size"], obj["space_time_loops"], obj["target"])
def evaluate_tenet_accelerator(target):
if str(target).startswith("tenet"):
_, arch = target.split(" ")
else:
arch = target
t = TENET(arch=arch)
return t.compute_latency()
def get_memory_bandwidth(target, memory_scope):
if str(target).startswith("tenet"):
_, arch = target.split(" ")
else:
arch = target
t = TENET(arch=arch)
return t.memory_bandwidth(memory_scope)
def get_maximum_parallelism(target, level):
if str(target).startswith("tenet"):
_, arch = target.split(" ")
else:
arch = target
t = TENET(arch=arch)
return t.parallelism(level)
def get_maximum_memory(target, memory_scope):
if str(target).startswith("tenet"):
_, arch = target.split(" ")
else:
arch = target
t = TENET(arch=arch)
return t.memory_size(memory_scope)
def evaluate_func(func, verbose=0):
memory_latency_vector = []
compute_latency_vector = []
for l, ([s, t], [scope, m]) in enumerate(
reversed(list(zip(func.space_time_loops, func.memory_size)))
):
bandwidth = get_memory_bandwidth(func.target, scope)
parallelism = get_maximum_parallelism(func.target, l)
capacity = get_maximum_memory(func.target, scope)
if m > capacity:
raise RuntimeError(
f"Memory exceed limit {scope}: need({m/(2**10)}K), given({capacity/(2**10)}K)"
)
memory_latency_vector.append(m / bandwidth)
space_iterations = reduce(lambda x, y: x * y, s, 1)
time_iterations = reduce(lambda x, y: x * y, t, 1)
real_time_iterations = time_iterations * (space_iterations + parallelism - 1) // parallelism
if l == 0:
compute_latency_vector.append(
real_time_iterations * evaluate_tenet_accelerator(func.target)
)
else:
compute_latency_vector.append(
(real_time_iterations - 1)
* max(memory_latency_vector[l - 1], compute_latency_vector[l - 1])
+ (memory_latency_vector[l - 1] + compute_latency_vector[l - 1])
)
if verbose >= 2:
print("\nShow details:", flush=True)
print("context:", flush=True)
print("space_time_loops:", func.space_time_loops, flush=True)
print("memory_size:", func.memory_size, flush=True)
for l, (c, m) in enumerate(zip(compute_latency_vector, memory_latency_vector)):
print(f"Level {l}: compute {c/1e9} (G)cycles, memory {m/1e9} (G)cycles", flush=True)
return (compute_latency_vector[-1] / 1e9,) # G cycle | python/tvm/auto_tensorize/backend/tenet_integrate.py | import tvm
import json
from functools import reduce
from .. import _ffi_api
from ..target import TENET
class TenetContext(object):
def __init__(self, level):
self.level = level
self.space_time_loops = [[[], []] for i in range(level)] # outer --> inner
self.memory_scopes = [None for i in range(level)]
def set_space_loop(self, level, loop):
assert isinstance(loop, list)
self.space_time_loops[level][0] = loop
def update_space_loop(self, level, loop, push_front=True):
assert isinstance(loop, list)
if push_front:
self.space_time_loops[level][0] = loop + self.space_time_loops[level][0]
else:
self.space_time_loops[level][0] = self.space_time_loops[level][0] + loop
def set_time_loop(self, level, loop):
assert isinstance(loop, list)
self.space_time_loops[level][1] = loop
def update_time_loop(self, level, loop, push_front=True):
assert isinstance(loop, list)
if push_front:
self.space_time_loops[level][1] = loop + self.space_time_loops[level][1]
else:
self.space_time_loops[level][1] = self.space_time_loops[level][1] + loop
def set_space_time_loops(self, level, space, time):
assert isinstance(space, list)
assert isinstance(time, list)
self.space_time_loops[level] = [space, time]
def update_space_time_loops(self, level, space, time, push_front=True):
assert isinstance(space, list)
assert isinstance(time, list)
if push_front:
self.space_time_loops[level][0] = space + self.space_time_loops[level][0]
self.space_time_loops[level][1] = time + self.space_time_loops[level][1]
else:
self.space_time_loops[level][0] = self.space_time_loops[level][0] + space
self.space_time_loops[level][1] = self.space_time_loops[level][1] + time
def set_memory_scope(self, level, scope):
assert isinstance(scope, str)
self.memory_scopes[level] = scope
def __repr__(self):
levels = "\n".join(
[
f"level_{i}:"
+ str(
{
"space": self.space_time_loops[i][0],
"time": self.space_time_loops[i][1],
"memory": self.memory_scopes[i],
}
)
for i in range(self.level)
]
)
return str(levels)
def __str__(self):
return self.__repr__()
class TenetFunc(object):
def __init__(self, memory_size, space_time_loops, target):
self.memory_size = memory_size
self.space_time_loops = space_time_loops
self.target = target
def save(self, filename):
obj = {
"memory_size": self.memory_size,
"space_time_loops": self.space_time_loops,
"target": self.target,
}
with open(filename, "w") as fout:
fout.write(json.dumps(obj))
def get_buffer_size(scope, stmt):
"""
scope: str
stmt: Stmt
"""
return _ffi_api.get_buffer_size(scope, stmt)
def build(sch, args, ctx, target="tenet gemm", target_host="llvm", name="main"):
ir_module = tvm.lower(sch, args, simple_mode=True)
# print(ir_module)
from tvm.te import schedule
sch = sch.normalize()
bounds = schedule.InferBound(sch)
# calculate memory size
memory_size = []
for scope in ctx.memory_scopes:
sum_val = 0
for _, f in ir_module.functions.items():
for k, v in get_buffer_size(scope, f.body).items():
sum_val += v.value
memory_size.append([scope, sum_val])
# calculate space time loops
space_time_loops = []
for l, [s, t] in enumerate(ctx.space_time_loops):
ss = [bounds[x].extent.value for x in s]
tt = [bounds[x].extent.value for x in t]
space_time_loops.append([ss, tt])
# print(space_time_loops)
return TenetFunc(memory_size, space_time_loops, target)
def load_func(filename):
with open(filename, "r") as fin:
string = fin.readline().strip()
obj = json.loads(string)
return TenetFunc(obj["memory_size"], obj["space_time_loops"], obj["target"])
def evaluate_tenet_accelerator(target):
if str(target).startswith("tenet"):
_, arch = target.split(" ")
else:
arch = target
t = TENET(arch=arch)
return t.compute_latency()
def get_memory_bandwidth(target, memory_scope):
if str(target).startswith("tenet"):
_, arch = target.split(" ")
else:
arch = target
t = TENET(arch=arch)
return t.memory_bandwidth(memory_scope)
def get_maximum_parallelism(target, level):
if str(target).startswith("tenet"):
_, arch = target.split(" ")
else:
arch = target
t = TENET(arch=arch)
return t.parallelism(level)
def get_maximum_memory(target, memory_scope):
if str(target).startswith("tenet"):
_, arch = target.split(" ")
else:
arch = target
t = TENET(arch=arch)
return t.memory_size(memory_scope)
def evaluate_func(func, verbose=0):
memory_latency_vector = []
compute_latency_vector = []
for l, ([s, t], [scope, m]) in enumerate(
reversed(list(zip(func.space_time_loops, func.memory_size)))
):
bandwidth = get_memory_bandwidth(func.target, scope)
parallelism = get_maximum_parallelism(func.target, l)
capacity = get_maximum_memory(func.target, scope)
if m > capacity:
raise RuntimeError(
f"Memory exceed limit {scope}: need({m/(2**10)}K), given({capacity/(2**10)}K)"
)
memory_latency_vector.append(m / bandwidth)
space_iterations = reduce(lambda x, y: x * y, s, 1)
time_iterations = reduce(lambda x, y: x * y, t, 1)
real_time_iterations = time_iterations * (space_iterations + parallelism - 1) // parallelism
if l == 0:
compute_latency_vector.append(
real_time_iterations * evaluate_tenet_accelerator(func.target)
)
else:
compute_latency_vector.append(
(real_time_iterations - 1)
* max(memory_latency_vector[l - 1], compute_latency_vector[l - 1])
+ (memory_latency_vector[l - 1] + compute_latency_vector[l - 1])
)
if verbose >= 2:
print("\nShow details:", flush=True)
print("context:", flush=True)
print("space_time_loops:", func.space_time_loops, flush=True)
print("memory_size:", func.memory_size, flush=True)
for l, (c, m) in enumerate(zip(compute_latency_vector, memory_latency_vector)):
print(f"Level {l}: compute {c/1e9} (G)cycles, memory {m/1e9} (G)cycles", flush=True)
return (compute_latency_vector[-1] / 1e9,) # G cycle | 0.399812 | 0.345547 |
import os
import tempfile
import zipfile
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template, send_file, after_this_request, send_from_directory
from PIL import Image
import pillow_heif
pillow_heif.register_heif_opener() # Give PIL access to HEIF
ALLOWED_EXTENSIONS = set(['heic', 'heif'])
app = Flask(__name__)
def is_allowed_file(filename: str) -> bool:
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def convert_all_files(working_dir):
"""Converts all files in working_dir to pngs, assumes all files are of the proper type
Args:
working_dir (str, path): The working directory
"""
for file in os.listdir(working_dir):
original_name, _ = os.path.splitext(file)
image = Image.open(os.path.join(working_dir, file))
image.save(os.path.join(working_dir, original_name + ".png"))
del image
def zip_all_files(work_dir):
"""Zips all png files in work_dir into an archive called output.zip
Args:
work_dir (str, path): The working directory
"""
with zipfile.ZipFile(os.path.join(work_dir, "output.zip"), "w") as zip:
for file in os.listdir(work_dir):
_, ext = os.path.splitext(file)
if ext.lower() == ".png":
file_path = os.path.join(work_dir, file)
zip.write(file_path, file)
@app.route("/", methods=["GET", "POST"])
def home():
work_dir = tempfile.TemporaryDirectory()
output_file_path = os.path.join(work_dir.name, "output.zip")
if request.method == "POST":
if 'file' not in request.files: # No files given in the POST at all
return "No image provided"
files = request.files.getlist('file') # Get all of the files, contains one entry with no filename if no files were given
if files[0].filename == "": # Check if the first one is empty
return "No image provided"
for file in files:
if file and is_allowed_file(file.filename):
output_name = os.path.join(work_dir.name, file.filename)
file.save(output_name) # Save the file to the temp dir
if request.method == "GET":
return render_template("index.html")
convert_all_files(work_dir.name)
zip_all_files(work_dir.name)
@after_this_request
def cleanup(response):
work_dir.cleanup()
return response
return send_file(output_file_path, mimetype="application/zip")
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico')
if __name__ == "__main__":
http_server = WSGIServer(('0.0.0.0', int(os.environ.get("PORT", 8080))), app)
http_server.serve_forever() | heicconverter.py | import os
import tempfile
import zipfile
from gevent.pywsgi import WSGIServer
from flask import Flask, request, render_template, send_file, after_this_request, send_from_directory
from PIL import Image
import pillow_heif
pillow_heif.register_heif_opener() # Give PIL access to HEIF
ALLOWED_EXTENSIONS = set(['heic', 'heif'])
app = Flask(__name__)
def is_allowed_file(filename: str) -> bool:
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def convert_all_files(working_dir):
"""Converts all files in working_dir to pngs, assumes all files are of the proper type
Args:
working_dir (str, path): The working directory
"""
for file in os.listdir(working_dir):
original_name, _ = os.path.splitext(file)
image = Image.open(os.path.join(working_dir, file))
image.save(os.path.join(working_dir, original_name + ".png"))
del image
def zip_all_files(work_dir):
"""Zips all png files in work_dir into an archive called output.zip
Args:
work_dir (str, path): The working directory
"""
with zipfile.ZipFile(os.path.join(work_dir, "output.zip"), "w") as zip:
for file in os.listdir(work_dir):
_, ext = os.path.splitext(file)
if ext.lower() == ".png":
file_path = os.path.join(work_dir, file)
zip.write(file_path, file)
@app.route("/", methods=["GET", "POST"])
def home():
work_dir = tempfile.TemporaryDirectory()
output_file_path = os.path.join(work_dir.name, "output.zip")
if request.method == "POST":
if 'file' not in request.files: # No files given in the POST at all
return "No image provided"
files = request.files.getlist('file') # Get all of the files, contains one entry with no filename if no files were given
if files[0].filename == "": # Check if the first one is empty
return "No image provided"
for file in files:
if file and is_allowed_file(file.filename):
output_name = os.path.join(work_dir.name, file.filename)
file.save(output_name) # Save the file to the temp dir
if request.method == "GET":
return render_template("index.html")
convert_all_files(work_dir.name)
zip_all_files(work_dir.name)
@after_this_request
def cleanup(response):
work_dir.cleanup()
return response
return send_file(output_file_path, mimetype="application/zip")
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico')
if __name__ == "__main__":
http_server = WSGIServer(('0.0.0.0', int(os.environ.get("PORT", 8080))), app)
http_server.serve_forever() | 0.363421 | 0.090534 |
import os
import random
import argparse
import numpy as np
import cv2
import torch
import torch.nn as nn
import decord
from decord import VideoReader
from model import *
from data.data_utils import *
from data.test_video_clip_dataset import BasicTransform
def detect_initial_slide_transition_candidates_resnet2d(net, videofile, base, roi, load_size_roi, out_dir, opt):
# load video file
vr = VideoReader(videofile, width=load_size_roi[1], height=load_size_roi[0])
#determine number of frames
N_frames = len(vr)
anchor_frame = None
anchor_frame_idx = -1
video_frame_idx = None
prev_video_frame_idx = None
slide_id = -1
slide_ids = []
frame_ids_1 = []
frame_ids_2 = []
if opt.in_gray:
data_shape = "2_channel"
opt.input_nc = 2
else:
data_shape = "6_channel"
opt.input_nc = 6
my_transform = BasicTransform(data_shape = data_shape) #, blur = opt.blur)
activation = nn.Sigmoid()
for i in range(N_frames):
frame = vr[i]
imgs = torch.zeros((2,opt.patch_size,opt.patch_size,int(opt.input_nc/2)))
if opt.in_gray: #opencv rgb2gray for torch
frame = 0.299*frame[...,0]+0.587*frame[...,1]+0.114*frame[...,2]
frame = frame.unsqueeze(2)
# crop to bounding box region
frame = crop_frame(frame,roi[0],roi[1],roi[2],roi[3])
#scale to max size (in case patch size changed)
img_max_size = max(frame.shape[0], frame.shape[1])
scaling_factor = opt.patch_size / img_max_size
if scaling_factor != 1:
frame = cv2.resize(frame, (round(frame.shape[1] * scaling_factor), round(frame.shape[0] * scaling_factor)), interpolation = cv2.INTER_NEAREST)
H,W,C = frame.shape
imgs[1,:H,:W,:C] = frame
else:
H,W,C = frame.shape
imgs[1,:H,:W,:C] = frame
#set anchor
if anchor_frame == None:
imgs[0,:H,:W,:C] = frame
anchor_frame_idx = i
anchor_frame = frame
else:
imgs[0,:H,:W,:C] = anchor_frame
imgs = my_transform(imgs)
with torch.no_grad():
imgs = imgs.cuda()
pred = net(imgs.unsqueeze(0))
pred = pred.squeeze(1)
pred = activation(pred)
#print(pred)
if pred<0.5: #transition (class 0)
if (i - anchor_frame_idx) > opt.slide_thresh: #static frame
if video_frame_idx is not None:
if (video_frame_idx - prev_video_frame_idx) > opt.video_thresh:
print("video frame {} at {} to {}".format(-1,prev_video_frame_idx+1, video_frame_idx+1))
slide_ids.append(-1)
frame_ids_1.append(prev_video_frame_idx+1)
frame_ids_2.append(video_frame_idx+1)
video_frame_idx = None
prev_video_frame_idx = None
slide_id += 1
print("static slide {} at {} to {}".format(slide_id,anchor_frame_idx+1, i))
slide_ids.append(slide_id)
frame_ids_1.append(anchor_frame_idx+1)
frame_ids_2.append(i)
else:
#video frame or grad transition
video_frame_idx = anchor_frame_idx
if prev_video_frame_idx is None:
prev_video_frame_idx = anchor_frame_idx
#update anchor
anchor_frame_idx = i
anchor_frame = frame
print(len(frame_ids_1))
frame_ids_1 = np.array(frame_ids_1)
frame_ids_2 = np.array(frame_ids_2)
#write to file
logfile_path = os.path.join(out_dir, base + "_results.txt")
f = open(logfile_path, "w")
f.write('Slide No, FrameID0, FrameID1\n')
f.close()
for slide_id,frame_id_1,frame_id_2 in zip(slide_ids,frame_ids_1,frame_ids_2):
f = open(logfile_path, "a")
f.write("{}, {}, {}\n".format(slide_id,frame_id_1,frame_id_2))
f.close()
def test_resnet2d(opt):
torch.manual_seed(0)
random.seed(0)
if os.path.exists(opt.out_dir)==False:
os.makedirs(opt.out_dir)
####### Create model
# ---------------------------------------------------------------
net = define_resnet2d(opt)
net = net.cuda()
net = loadNetwork(net, opt.model_path, checkpoint=opt.load_checkpoint, prefix='')
net.eval()
#### Create dataloader
# ---------------------------------------------------------------
video_dir = opt.dataset_dir + "/videos/" + opt.phase
videoFilenames = []
videoFilenames.extend(os.path.join(video_dir, x)
for x in sorted(os.listdir(video_dir)) if is_video_file(x))
roi_path = os.path.join(opt.dataset_dir,"videos", opt.phase+'_bounding_box_list.txt')
rois = read_labels(roi_path)
decord.bridge.set_bridge('torch')
for k,videofile in enumerate(videoFilenames):
print("Processing video No. {}: {}".format(k+1, videofile))
base, roi, load_size_roi = determine_load_size_roi(videofile, rois, opt.patch_size)
detect_initial_slide_transition_candidates_resnet2d(net, videofile, base, roi, load_size_roi, opt.out_dir, opt)
if __name__ == '__main__':
parser = argparse.ArgumentParser('slide_detection')
parser.add_argument('--dataset_dir', help='path to dataset dir',type=str, default='C:/Users/Sindel/Project/Data/datasets/LectureVideos')
parser.add_argument('--out_dir', help='path to dataset dir',type=str, default='C:/Users/Sindel/Project/Code/SliTraNet/results/test/resnet18_gray')
parser.add_argument('--backbone_2D', help='name of backbone (resnet18 or resnet50)',type=str, default='resnet18')
parser.add_argument('--model_path', help='path of weights',type=str, default='C:/Users/Sindel/Project/Code/SliTraNet/weights/Frame_similarity_ResNet18_gray.pth')
parser.add_argument('--load_checkpoint', type=bool, default=False, help='model_path is path to checkpoint (True) or path to state dict (False)')
parser.add_argument('--slide_thresh', type=int, default=8, help='threshold for minimum static slide length')
parser.add_argument('--video_thresh', type=int, default=13, help='threshold for minimum video length to distinguish from gradual transition')
parser.add_argument('--patch_size', type=int, default=256, help='network input patch size')
parser.add_argument('--n_class', type=int, default=1, help='number of classes')
parser.add_argument('--input_nc', type=int, default=2, help='number of input channels for ResNet: gray:2, RGB:6')
parser.add_argument('--in_gray', type=bool, default=True, help='run network with grayscale input, else RGB')
parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')
opt = parser.parse_args()
test_resnet2d(opt) | test_slide_detection_2d.py | import os
import random
import argparse
import numpy as np
import cv2
import torch
import torch.nn as nn
import decord
from decord import VideoReader
from model import *
from data.data_utils import *
from data.test_video_clip_dataset import BasicTransform
def detect_initial_slide_transition_candidates_resnet2d(net, videofile, base, roi, load_size_roi, out_dir, opt):
# load video file
vr = VideoReader(videofile, width=load_size_roi[1], height=load_size_roi[0])
#determine number of frames
N_frames = len(vr)
anchor_frame = None
anchor_frame_idx = -1
video_frame_idx = None
prev_video_frame_idx = None
slide_id = -1
slide_ids = []
frame_ids_1 = []
frame_ids_2 = []
if opt.in_gray:
data_shape = "2_channel"
opt.input_nc = 2
else:
data_shape = "6_channel"
opt.input_nc = 6
my_transform = BasicTransform(data_shape = data_shape) #, blur = opt.blur)
activation = nn.Sigmoid()
for i in range(N_frames):
frame = vr[i]
imgs = torch.zeros((2,opt.patch_size,opt.patch_size,int(opt.input_nc/2)))
if opt.in_gray: #opencv rgb2gray for torch
frame = 0.299*frame[...,0]+0.587*frame[...,1]+0.114*frame[...,2]
frame = frame.unsqueeze(2)
# crop to bounding box region
frame = crop_frame(frame,roi[0],roi[1],roi[2],roi[3])
#scale to max size (in case patch size changed)
img_max_size = max(frame.shape[0], frame.shape[1])
scaling_factor = opt.patch_size / img_max_size
if scaling_factor != 1:
frame = cv2.resize(frame, (round(frame.shape[1] * scaling_factor), round(frame.shape[0] * scaling_factor)), interpolation = cv2.INTER_NEAREST)
H,W,C = frame.shape
imgs[1,:H,:W,:C] = frame
else:
H,W,C = frame.shape
imgs[1,:H,:W,:C] = frame
#set anchor
if anchor_frame == None:
imgs[0,:H,:W,:C] = frame
anchor_frame_idx = i
anchor_frame = frame
else:
imgs[0,:H,:W,:C] = anchor_frame
imgs = my_transform(imgs)
with torch.no_grad():
imgs = imgs.cuda()
pred = net(imgs.unsqueeze(0))
pred = pred.squeeze(1)
pred = activation(pred)
#print(pred)
if pred<0.5: #transition (class 0)
if (i - anchor_frame_idx) > opt.slide_thresh: #static frame
if video_frame_idx is not None:
if (video_frame_idx - prev_video_frame_idx) > opt.video_thresh:
print("video frame {} at {} to {}".format(-1,prev_video_frame_idx+1, video_frame_idx+1))
slide_ids.append(-1)
frame_ids_1.append(prev_video_frame_idx+1)
frame_ids_2.append(video_frame_idx+1)
video_frame_idx = None
prev_video_frame_idx = None
slide_id += 1
print("static slide {} at {} to {}".format(slide_id,anchor_frame_idx+1, i))
slide_ids.append(slide_id)
frame_ids_1.append(anchor_frame_idx+1)
frame_ids_2.append(i)
else:
#video frame or grad transition
video_frame_idx = anchor_frame_idx
if prev_video_frame_idx is None:
prev_video_frame_idx = anchor_frame_idx
#update anchor
anchor_frame_idx = i
anchor_frame = frame
print(len(frame_ids_1))
frame_ids_1 = np.array(frame_ids_1)
frame_ids_2 = np.array(frame_ids_2)
#write to file
logfile_path = os.path.join(out_dir, base + "_results.txt")
f = open(logfile_path, "w")
f.write('Slide No, FrameID0, FrameID1\n')
f.close()
for slide_id,frame_id_1,frame_id_2 in zip(slide_ids,frame_ids_1,frame_ids_2):
f = open(logfile_path, "a")
f.write("{}, {}, {}\n".format(slide_id,frame_id_1,frame_id_2))
f.close()
def test_resnet2d(opt):
torch.manual_seed(0)
random.seed(0)
if os.path.exists(opt.out_dir)==False:
os.makedirs(opt.out_dir)
####### Create model
# ---------------------------------------------------------------
net = define_resnet2d(opt)
net = net.cuda()
net = loadNetwork(net, opt.model_path, checkpoint=opt.load_checkpoint, prefix='')
net.eval()
#### Create dataloader
# ---------------------------------------------------------------
video_dir = opt.dataset_dir + "/videos/" + opt.phase
videoFilenames = []
videoFilenames.extend(os.path.join(video_dir, x)
for x in sorted(os.listdir(video_dir)) if is_video_file(x))
roi_path = os.path.join(opt.dataset_dir,"videos", opt.phase+'_bounding_box_list.txt')
rois = read_labels(roi_path)
decord.bridge.set_bridge('torch')
for k,videofile in enumerate(videoFilenames):
print("Processing video No. {}: {}".format(k+1, videofile))
base, roi, load_size_roi = determine_load_size_roi(videofile, rois, opt.patch_size)
detect_initial_slide_transition_candidates_resnet2d(net, videofile, base, roi, load_size_roi, opt.out_dir, opt)
if __name__ == '__main__':
parser = argparse.ArgumentParser('slide_detection')
parser.add_argument('--dataset_dir', help='path to dataset dir',type=str, default='C:/Users/Sindel/Project/Data/datasets/LectureVideos')
parser.add_argument('--out_dir', help='path to dataset dir',type=str, default='C:/Users/Sindel/Project/Code/SliTraNet/results/test/resnet18_gray')
parser.add_argument('--backbone_2D', help='name of backbone (resnet18 or resnet50)',type=str, default='resnet18')
parser.add_argument('--model_path', help='path of weights',type=str, default='C:/Users/Sindel/Project/Code/SliTraNet/weights/Frame_similarity_ResNet18_gray.pth')
parser.add_argument('--load_checkpoint', type=bool, default=False, help='model_path is path to checkpoint (True) or path to state dict (False)')
parser.add_argument('--slide_thresh', type=int, default=8, help='threshold for minimum static slide length')
parser.add_argument('--video_thresh', type=int, default=13, help='threshold for minimum video length to distinguish from gradual transition')
parser.add_argument('--patch_size', type=int, default=256, help='network input patch size')
parser.add_argument('--n_class', type=int, default=1, help='number of classes')
parser.add_argument('--input_nc', type=int, default=2, help='number of input channels for ResNet: gray:2, RGB:6')
parser.add_argument('--in_gray', type=bool, default=True, help='run network with grayscale input, else RGB')
parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')
opt = parser.parse_args()
test_resnet2d(opt) | 0.224906 | 0.179531 |
# Standard imports
from datetime import datetime, timedelta
class TimeActivity(object):
"""Class that will handle the logic of the processes."""
def __init__(self):
"""Constructor. (place holder for now)."""
self.__todayDate = datetime.today()
def getCurrentTimePerProcess(self, session):
"""Calculate the time per process base on the current session.
A session look like:
{
Pid:
{
<str date>:
[
{
'startTime': 1538355688.982312,
'name': 'chrome'
}
]
}
:param session: The session of the current processes.
:type session: dict
:return timePerProcess: A dictionary with the name of the process and the total time in seconds.
:rtype timePerProcess: dict
"""
timePerProcess = {}
for pid, processes in session.items():
for procDate, processesData in processes.items():
for processData in processesData:
if 'endTime' not in processData:
continue
processName = processData['name']
startTime = processData['startTime']
endTime = processData['endTime']
if processName not in timePerProcess:
timePerProcess[processName] = (endTime - startTime)
else:
timePerProcess[processName] += (endTime - startTime)
return timePerProcess
def getProcessesByTime(self, savedSession, days=7):
"""Get the time per process over the specified days.
By default the days specified are a week ago.
:param savedSession: The sessions saved.
:type savedSession: dict
"""
processes = {}
datesWeek = [(self.__todayDate - timedelta(days=day)).strftime('%Y-%m-%d') for day in range(days)]
for day in datesWeek:
daysession = savedSession.get(day, None)
if not daysession:
continue
for app, time in daysession.items():
if app not in processes:
processes[app] = time
else:
processes[app] += time
return processes | Modules/Chronos/TimeActivity.py | # Standard imports
from datetime import datetime, timedelta
class TimeActivity(object):
"""Class that will handle the logic of the processes."""
def __init__(self):
"""Constructor. (place holder for now)."""
self.__todayDate = datetime.today()
def getCurrentTimePerProcess(self, session):
"""Calculate the time per process base on the current session.
A session look like:
{
Pid:
{
<str date>:
[
{
'startTime': 1538355688.982312,
'name': 'chrome'
}
]
}
:param session: The session of the current processes.
:type session: dict
:return timePerProcess: A dictionary with the name of the process and the total time in seconds.
:rtype timePerProcess: dict
"""
timePerProcess = {}
for pid, processes in session.items():
for procDate, processesData in processes.items():
for processData in processesData:
if 'endTime' not in processData:
continue
processName = processData['name']
startTime = processData['startTime']
endTime = processData['endTime']
if processName not in timePerProcess:
timePerProcess[processName] = (endTime - startTime)
else:
timePerProcess[processName] += (endTime - startTime)
return timePerProcess
def getProcessesByTime(self, savedSession, days=7):
"""Get the time per process over the specified days.
By default the days specified are a week ago.
:param savedSession: The sessions saved.
:type savedSession: dict
"""
processes = {}
datesWeek = [(self.__todayDate - timedelta(days=day)).strftime('%Y-%m-%d') for day in range(days)]
for day in datesWeek:
daysession = savedSession.get(day, None)
if not daysession:
continue
for app, time in daysession.items():
if app not in processes:
processes[app] = time
else:
processes[app] += time
return processes | 0.736021 | 0.294862 |
import tensorflow as tf
from mamltf2.model import Model
class Reptile(Model):
def __init__(self, *args, nInnerSteps = 5, **kwargs):
super().__init__(*args, **kwargs)
self.nInnerSteps = nInnerSteps
self.interpolationRateInitial = self.outerLearningRate
self.sgd = tf.keras.optimizers.SGD(self.innerLearningRate)
self.modelCopy = tf.keras.models.clone_model(self.model)
@tf.function
def interpolate(self, source, target):
"""Linearly interpolate between source and target.
"""
return target + (source - target) * self.interpolationRate
@tf.function
def copyWeightsApply(self, source, target, fn=lambda s, t: s):
"""Assign weights from source to target. Apply a transform fn to source and target weights first.
"""
for j in range(len(source.trainable_weights)):
target.trainable_weights[j].assign(
fn(source.trainable_weights[j], target.trainable_weights[j]))
@tf.function
def updateInterpolationRate(self):
self.interpolationRate = self.interpolationRateInitial * (1 - self.nIteration / self.nIterations)
self.nIteration += 1
@tf.function
def taskLoss(self, batch):
"""Computes the loss for one task given one batch of inputs and correspondings labels
"""
y, x = batch
self.copyWeightsApply(self.model, self.modelCopy)
self.updateInterpolationRate()
for _ in range(self.nInnerSteps):
with tf.GradientTape() as taskTape:
loss = self.lossfn(y, self.modelCopy(tf.reshape(x, (-1, 1))))
self.sgd.minimize(
loss, self.modelCopy.trainable_variables, tape=taskTape)
self.copyWeightsApply(self.modelCopy, self.model, self.interpolate)
return loss
@tf.function
def update(self, batch):
"""Implements the meta-update step for a bunch of tasks.
@batch: Tuple of training and test data for the update step. Can be directly passed through to
the task updates.
"""
return tf.reduce_sum(
tf.map_fn(self.taskLoss, elems=batch, fn_output_signature=tf.float32))
def trainBatch(self, nSamples, nTasks, nBatch):
self.nIterations = nBatch
self.nIteration = 0
self.innerLearningRate = self.interpolationRateInitial
return super().trainBatch(nSamples, nTasks, nBatch, alsoSampleTest=False) | mamltf2/methods/reptile.py | import tensorflow as tf
from mamltf2.model import Model
class Reptile(Model):
def __init__(self, *args, nInnerSteps = 5, **kwargs):
super().__init__(*args, **kwargs)
self.nInnerSteps = nInnerSteps
self.interpolationRateInitial = self.outerLearningRate
self.sgd = tf.keras.optimizers.SGD(self.innerLearningRate)
self.modelCopy = tf.keras.models.clone_model(self.model)
@tf.function
def interpolate(self, source, target):
"""Linearly interpolate between source and target.
"""
return target + (source - target) * self.interpolationRate
@tf.function
def copyWeightsApply(self, source, target, fn=lambda s, t: s):
"""Assign weights from source to target. Apply a transform fn to source and target weights first.
"""
for j in range(len(source.trainable_weights)):
target.trainable_weights[j].assign(
fn(source.trainable_weights[j], target.trainable_weights[j]))
@tf.function
def updateInterpolationRate(self):
self.interpolationRate = self.interpolationRateInitial * (1 - self.nIteration / self.nIterations)
self.nIteration += 1
@tf.function
def taskLoss(self, batch):
"""Computes the loss for one task given one batch of inputs and correspondings labels
"""
y, x = batch
self.copyWeightsApply(self.model, self.modelCopy)
self.updateInterpolationRate()
for _ in range(self.nInnerSteps):
with tf.GradientTape() as taskTape:
loss = self.lossfn(y, self.modelCopy(tf.reshape(x, (-1, 1))))
self.sgd.minimize(
loss, self.modelCopy.trainable_variables, tape=taskTape)
self.copyWeightsApply(self.modelCopy, self.model, self.interpolate)
return loss
@tf.function
def update(self, batch):
"""Implements the meta-update step for a bunch of tasks.
@batch: Tuple of training and test data for the update step. Can be directly passed through to
the task updates.
"""
return tf.reduce_sum(
tf.map_fn(self.taskLoss, elems=batch, fn_output_signature=tf.float32))
def trainBatch(self, nSamples, nTasks, nBatch):
self.nIterations = nBatch
self.nIteration = 0
self.innerLearningRate = self.interpolationRateInitial
return super().trainBatch(nSamples, nTasks, nBatch, alsoSampleTest=False) | 0.806853 | 0.331945 |
from __future__ import absolute_import
from dohq_teamcity.custom.base_model import TeamCityObject
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from dohq_teamcity.models.group import Group # noqa: F401,E501
from dohq_teamcity.models.groups import Groups # noqa: F401,E501
from dohq_teamcity.models.properties import Properties # noqa: F401,E501
from dohq_teamcity.models.role import Role # noqa: F401,E501
from dohq_teamcity.models.roles import Roles # noqa: F401,E501
class GroupApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
base_name = 'Group'
def __init__(self, api_client=None):
self.api_client = api_client
def add_group(self, **kwargs): # noqa: E501
"""add_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_group(async_req=True)
>>> result = thread.get()
:param async_req: bool
:param Group body:
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__add_group_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.__add_group_with_http_info(**kwargs) # noqa: E501
return data
def add_role(self, group_locator, **kwargs): # noqa: E501
"""add_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_role(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param Role body:
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__add_role_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__add_role_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def add_role_simple(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""add_role_simple # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_role_simple(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__add_role_simple_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
else:
(data) = self.__add_role_simple_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
return data
def delete_group(self, group_locator, **kwargs): # noqa: E501
"""delete_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_group(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__delete_group_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__delete_group_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def delete_role(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""delete_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_role(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__delete_role_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
else:
(data) = self.__delete_role_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
return data
def get_parent_groups(self, group_locator, **kwargs): # noqa: E501
"""get_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_parent_groups(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__get_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__get_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def get_permissions(self, group_locator, **kwargs): # noqa: E501
"""get_permissions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_permissions(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__get_permissions_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__get_permissions_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def get_properties(self, group_locator, **kwargs): # noqa: E501
"""get_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_properties(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str fields:
:return: Properties
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__get_properties_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__get_properties_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def list_role(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""list_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_role(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__list_role_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
else:
(data) = self.__list_role_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
return data
def list_roles(self, group_locator, **kwargs): # noqa: E501
"""list_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_roles(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__list_roles_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__list_roles_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def put_user_property(self, group_locator, name, **kwargs): # noqa: E501
"""put_user_property # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.put_user_property(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str name: (required)
:param str body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__put_user_property_with_http_info(group_locator, name, **kwargs) # noqa: E501
else:
(data) = self.__put_user_property_with_http_info(group_locator, name, **kwargs) # noqa: E501
return data
def remove_user_property(self, group_locator, name, **kwargs): # noqa: E501
"""remove_user_property # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_user_property(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str name: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__remove_user_property_with_http_info(group_locator, name, **kwargs) # noqa: E501
else:
(data) = self.__remove_user_property_with_http_info(group_locator, name, **kwargs) # noqa: E501
return data
def serve_group(self, group_locator, **kwargs): # noqa: E501
"""serve_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.serve_group(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__serve_group_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__serve_group_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def serve_groups(self, **kwargs): # noqa: E501
"""serve_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.serve_groups(async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__serve_groups_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.__serve_groups_with_http_info(**kwargs) # noqa: E501
return data
def serve_user_properties(self, group_locator, name, **kwargs): # noqa: E501
"""serve_user_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.serve_user_properties(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str name: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__serve_user_properties_with_http_info(group_locator, name, **kwargs) # noqa: E501
else:
(data) = self.__serve_user_properties_with_http_info(group_locator, name, **kwargs) # noqa: E501
return data
def set_parent_groups(self, group_locator, **kwargs): # noqa: E501
"""set_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set_parent_groups(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param Groups body:
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__set_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__set_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def set_roles(self, group_locator, **kwargs): # noqa: E501
"""set_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set_roles(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param Roles body:
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__set_roles_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__set_roles_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def __add_group_with_http_info(self, **kwargs): # noqa: E501
"""add_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_group_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param Group body:
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_group" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Group', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __add_role_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""add_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_role_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param Role body:
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `add_role`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Role', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __add_role_simple_with_http_info(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""add_role_simple # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_role_simple_with_http_info(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'role_id', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_role_simple" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `add_role_simple`") # noqa: E501
# verify the required parameter 'role_id' is set
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `add_role_simple`") # noqa: E501
# verify the required parameter 'scope' is set
if ('scope' not in params or
params['scope'] is None):
raise ValueError("Missing the required parameter `scope` when calling `add_role_simple`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'role_id' in params:
if isinstance(params['role_id'], TeamCityObject):
path_params['roleId'] = params['role_id'].locator_id
else:
path_params['roleId'] = params['role_id'] # noqa: E501
if 'scope' in params:
if isinstance(params['scope'], TeamCityObject):
path_params['scope'] = params['scope'].locator_id
else:
path_params['scope'] = params['scope'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Role', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __delete_group_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""delete_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__delete_group_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `delete_group`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __delete_role_with_http_info(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""delete_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__delete_role_with_http_info(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'role_id', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `delete_role`") # noqa: E501
# verify the required parameter 'role_id' is set
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `delete_role`") # noqa: E501
# verify the required parameter 'scope' is set
if ('scope' not in params or
params['scope'] is None):
raise ValueError("Missing the required parameter `scope` when calling `delete_role`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'role_id' in params:
if isinstance(params['role_id'], TeamCityObject):
path_params['roleId'] = params['role_id'].locator_id
else:
path_params['roleId'] = params['role_id'] # noqa: E501
if 'scope' in params:
if isinstance(params['scope'], TeamCityObject):
path_params['scope'] = params['scope'].locator_id
else:
path_params['scope'] = params['scope'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __get_parent_groups_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""get_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__get_parent_groups_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_parent_groups" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `get_parent_groups`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/parent-groups', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Groups', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __get_permissions_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""get_permissions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__get_permissions_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_permissions" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `get_permissions`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/debug/permissions', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __get_properties_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""get_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__get_properties_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str fields:
:return: Properties
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_properties" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `get_properties`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/properties', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Properties', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __list_role_with_http_info(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""list_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__list_role_with_http_info(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'role_id', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `list_role`") # noqa: E501
# verify the required parameter 'role_id' is set
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `list_role`") # noqa: E501
# verify the required parameter 'scope' is set
if ('scope' not in params or
params['scope'] is None):
raise ValueError("Missing the required parameter `scope` when calling `list_role`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'role_id' in params:
if isinstance(params['role_id'], TeamCityObject):
path_params['roleId'] = params['role_id'].locator_id
else:
path_params['roleId'] = params['role_id'] # noqa: E501
if 'scope' in params:
if isinstance(params['scope'], TeamCityObject):
path_params['scope'] = params['scope'].locator_id
else:
path_params['scope'] = params['scope'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Role', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __list_roles_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""list_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__list_roles_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_roles" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `list_roles`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Roles', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __put_user_property_with_http_info(self, group_locator, name, **kwargs): # noqa: E501
"""put_user_property # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__put_user_property_with_http_info(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str name: (required)
:param str body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'name', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method put_user_property" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `put_user_property`") # noqa: E501
# verify the required parameter 'name' is set
if ('name' not in params or
params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `put_user_property`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'name' in params:
if isinstance(params['name'], TeamCityObject):
path_params['name'] = params['name'].locator_id
else:
path_params['name'] = params['name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/properties/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __remove_user_property_with_http_info(self, group_locator, name, **kwargs): # noqa: E501
"""remove_user_property # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__remove_user_property_with_http_info(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str name: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_user_property" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `remove_user_property`") # noqa: E501
# verify the required parameter 'name' is set
if ('name' not in params or
params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `remove_user_property`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'name' in params:
if isinstance(params['name'], TeamCityObject):
path_params['name'] = params['name'].locator_id
else:
path_params['name'] = params['name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/properties/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __serve_group_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""serve_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__serve_group_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method serve_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `serve_group`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Group', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __serve_groups_with_http_info(self, **kwargs): # noqa: E501
"""serve_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__serve_groups_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method serve_groups" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Groups', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __serve_user_properties_with_http_info(self, group_locator, name, **kwargs): # noqa: E501
"""serve_user_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__serve_user_properties_with_http_info(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str name: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method serve_user_properties" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `serve_user_properties`") # noqa: E501
# verify the required parameter 'name' is set
if ('name' not in params or
params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `serve_user_properties`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'name' in params:
if isinstance(params['name'], TeamCityObject):
path_params['name'] = params['name'].locator_id
else:
path_params['name'] = params['name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/properties/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __set_parent_groups_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""set_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__set_parent_groups_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param Groups body:
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'body', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method set_parent_groups" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `set_parent_groups`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/parent-groups', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Groups', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __set_roles_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""set_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__set_roles_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param Roles body:
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method set_roles" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `set_roles`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Roles', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats) | dohq_teamcity/api/group_api.py | from __future__ import absolute_import
from dohq_teamcity.custom.base_model import TeamCityObject
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from dohq_teamcity.models.group import Group # noqa: F401,E501
from dohq_teamcity.models.groups import Groups # noqa: F401,E501
from dohq_teamcity.models.properties import Properties # noqa: F401,E501
from dohq_teamcity.models.role import Role # noqa: F401,E501
from dohq_teamcity.models.roles import Roles # noqa: F401,E501
class GroupApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
base_name = 'Group'
def __init__(self, api_client=None):
self.api_client = api_client
def add_group(self, **kwargs): # noqa: E501
"""add_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_group(async_req=True)
>>> result = thread.get()
:param async_req: bool
:param Group body:
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__add_group_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.__add_group_with_http_info(**kwargs) # noqa: E501
return data
def add_role(self, group_locator, **kwargs): # noqa: E501
"""add_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_role(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param Role body:
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__add_role_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__add_role_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def add_role_simple(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""add_role_simple # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_role_simple(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__add_role_simple_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
else:
(data) = self.__add_role_simple_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
return data
def delete_group(self, group_locator, **kwargs): # noqa: E501
"""delete_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_group(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__delete_group_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__delete_group_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def delete_role(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""delete_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_role(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__delete_role_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
else:
(data) = self.__delete_role_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
return data
def get_parent_groups(self, group_locator, **kwargs): # noqa: E501
"""get_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_parent_groups(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__get_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__get_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def get_permissions(self, group_locator, **kwargs): # noqa: E501
"""get_permissions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_permissions(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__get_permissions_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__get_permissions_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def get_properties(self, group_locator, **kwargs): # noqa: E501
"""get_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_properties(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str fields:
:return: Properties
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__get_properties_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__get_properties_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def list_role(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""list_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_role(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__list_role_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
else:
(data) = self.__list_role_with_http_info(group_locator, role_id, scope, **kwargs) # noqa: E501
return data
def list_roles(self, group_locator, **kwargs): # noqa: E501
"""list_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_roles(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__list_roles_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__list_roles_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def put_user_property(self, group_locator, name, **kwargs): # noqa: E501
"""put_user_property # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.put_user_property(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str name: (required)
:param str body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__put_user_property_with_http_info(group_locator, name, **kwargs) # noqa: E501
else:
(data) = self.__put_user_property_with_http_info(group_locator, name, **kwargs) # noqa: E501
return data
def remove_user_property(self, group_locator, name, **kwargs): # noqa: E501
"""remove_user_property # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_user_property(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str name: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__remove_user_property_with_http_info(group_locator, name, **kwargs) # noqa: E501
else:
(data) = self.__remove_user_property_with_http_info(group_locator, name, **kwargs) # noqa: E501
return data
def serve_group(self, group_locator, **kwargs): # noqa: E501
"""serve_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.serve_group(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__serve_group_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__serve_group_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def serve_groups(self, **kwargs): # noqa: E501
"""serve_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.serve_groups(async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__serve_groups_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.__serve_groups_with_http_info(**kwargs) # noqa: E501
return data
def serve_user_properties(self, group_locator, name, **kwargs): # noqa: E501
"""serve_user_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.serve_user_properties(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str name: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__serve_user_properties_with_http_info(group_locator, name, **kwargs) # noqa: E501
else:
(data) = self.__serve_user_properties_with_http_info(group_locator, name, **kwargs) # noqa: E501
return data
def set_parent_groups(self, group_locator, **kwargs): # noqa: E501
"""set_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set_parent_groups(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param Groups body:
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__set_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__set_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def set_roles(self, group_locator, **kwargs): # noqa: E501
"""set_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set_roles(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param Roles body:
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__set_roles_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__set_roles_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def __add_group_with_http_info(self, **kwargs): # noqa: E501
"""add_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_group_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param Group body:
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_group" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Group', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __add_role_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""add_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_role_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param Role body:
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `add_role`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Role', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __add_role_simple_with_http_info(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""add_role_simple # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_role_simple_with_http_info(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'role_id', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_role_simple" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `add_role_simple`") # noqa: E501
# verify the required parameter 'role_id' is set
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `add_role_simple`") # noqa: E501
# verify the required parameter 'scope' is set
if ('scope' not in params or
params['scope'] is None):
raise ValueError("Missing the required parameter `scope` when calling `add_role_simple`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'role_id' in params:
if isinstance(params['role_id'], TeamCityObject):
path_params['roleId'] = params['role_id'].locator_id
else:
path_params['roleId'] = params['role_id'] # noqa: E501
if 'scope' in params:
if isinstance(params['scope'], TeamCityObject):
path_params['scope'] = params['scope'].locator_id
else:
path_params['scope'] = params['scope'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Role', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __delete_group_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""delete_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__delete_group_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `delete_group`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __delete_role_with_http_info(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""delete_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__delete_role_with_http_info(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'role_id', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `delete_role`") # noqa: E501
# verify the required parameter 'role_id' is set
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `delete_role`") # noqa: E501
# verify the required parameter 'scope' is set
if ('scope' not in params or
params['scope'] is None):
raise ValueError("Missing the required parameter `scope` when calling `delete_role`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'role_id' in params:
if isinstance(params['role_id'], TeamCityObject):
path_params['roleId'] = params['role_id'].locator_id
else:
path_params['roleId'] = params['role_id'] # noqa: E501
if 'scope' in params:
if isinstance(params['scope'], TeamCityObject):
path_params['scope'] = params['scope'].locator_id
else:
path_params['scope'] = params['scope'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __get_parent_groups_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""get_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__get_parent_groups_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_parent_groups" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `get_parent_groups`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/parent-groups', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Groups', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __get_permissions_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""get_permissions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__get_permissions_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_permissions" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `get_permissions`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/debug/permissions', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __get_properties_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""get_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__get_properties_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str fields:
:return: Properties
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_properties" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `get_properties`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/properties', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Properties', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __list_role_with_http_info(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""list_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__list_role_with_http_info(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'role_id', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `list_role`") # noqa: E501
# verify the required parameter 'role_id' is set
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `list_role`") # noqa: E501
# verify the required parameter 'scope' is set
if ('scope' not in params or
params['scope'] is None):
raise ValueError("Missing the required parameter `scope` when calling `list_role`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'role_id' in params:
if isinstance(params['role_id'], TeamCityObject):
path_params['roleId'] = params['role_id'].locator_id
else:
path_params['roleId'] = params['role_id'] # noqa: E501
if 'scope' in params:
if isinstance(params['scope'], TeamCityObject):
path_params['scope'] = params['scope'].locator_id
else:
path_params['scope'] = params['scope'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Role', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __list_roles_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""list_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__list_roles_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_roles" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `list_roles`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Roles', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __put_user_property_with_http_info(self, group_locator, name, **kwargs): # noqa: E501
"""put_user_property # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__put_user_property_with_http_info(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str name: (required)
:param str body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'name', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method put_user_property" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `put_user_property`") # noqa: E501
# verify the required parameter 'name' is set
if ('name' not in params or
params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `put_user_property`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'name' in params:
if isinstance(params['name'], TeamCityObject):
path_params['name'] = params['name'].locator_id
else:
path_params['name'] = params['name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/properties/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __remove_user_property_with_http_info(self, group_locator, name, **kwargs): # noqa: E501
"""remove_user_property # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__remove_user_property_with_http_info(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str name: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_user_property" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `remove_user_property`") # noqa: E501
# verify the required parameter 'name' is set
if ('name' not in params or
params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `remove_user_property`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'name' in params:
if isinstance(params['name'], TeamCityObject):
path_params['name'] = params['name'].locator_id
else:
path_params['name'] = params['name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/properties/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __serve_group_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""serve_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__serve_group_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method serve_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `serve_group`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Group', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __serve_groups_with_http_info(self, **kwargs): # noqa: E501
"""serve_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__serve_groups_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method serve_groups" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Groups', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __serve_user_properties_with_http_info(self, group_locator, name, **kwargs): # noqa: E501
"""serve_user_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__serve_user_properties_with_http_info(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str name: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method serve_user_properties" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `serve_user_properties`") # noqa: E501
# verify the required parameter 'name' is set
if ('name' not in params or
params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `serve_user_properties`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'name' in params:
if isinstance(params['name'], TeamCityObject):
path_params['name'] = params['name'].locator_id
else:
path_params['name'] = params['name'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/properties/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __set_parent_groups_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""set_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__set_parent_groups_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param Groups body:
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'body', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method set_parent_groups" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `set_parent_groups`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/parent-groups', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Groups', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __set_roles_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""set_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__set_roles_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param Roles body:
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method set_roles" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `set_roles`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Roles', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats) | 0.764012 | 0.058885 |
import argparse
import fileinput
from fairseq.models.transformer import TransformerModel
from tqdm import tqdm
import numpy as np
def main():
parser = argparse.ArgumentParser(
description=(
"Extract back-translations from the stdout of _fairseq-generate. "
"If there are multiply hypotheses for a source sentence, we cat all of them with tab. "
)
)
parser.add_argument("--output", required=True, help="output prefix")
parser.add_argument("--lm_path", required=True, help="the mono language model checkpoint file path")
parser.add_argument("--cp_file", help='the checkpoint file to load, none for best')
parser.add_argument("--lm_data_path", required=True, help="the databin where the mono language model is trained")
parser.add_argument("--bpe_file", required=False, help="the bpe code file")
parser.add_argument("--batch_size", type=int,
default=32, help="the batch size for mono language model scoring")
parser.add_argument("--silent_mode", default=True)
parser.add_argument("--max_positions", default=512,
help="the maximum number of positions, skip the sequences that are longer than this value.")
parser.add_argument("files", nargs="*", help="input files")
args = parser.parse_args()
mono_model = TransformerModel.from_pretrained(
args.lm_path,
checkpoint_file=args.cp_file or 'checkpoint_best.pt',
data_name_or_path=args.lm_data_path,
bpe='fastbpe',
bpe_codes=args.bpe_file or args.lm_data_path + '/code')
mono_model.eval() # disable dropout
# Move model to GPU
mono_model.cuda()
with open(args.output + ".mono_lprob", "w", encoding='utf-8') as mono_lprob_h:
n_batch = 0
for line in tqdm(fileinput.input(args.files, openhook=fileinput.hook_encoded('utf-8')),
disable=args.silent_mode):
line_src = line.split('\t')
if n_batch == 0:
n_batch = len(line_src) // args.batch_size
if len(line_src) % args.batch_size != 0:
n_batch += 1
line_mono_lprob = []
for i in range(n_batch):
batch_samples = line_src[i * args.batch_size:(i + 1) * args.batch_size]
batch_samples = skip_invalid_samples(batch_samples, args.max_positions)
batch_mono_lprob = []
for x in mono_model.score(batch_samples):
lprob=x["positional_scores"].sum().cpu().numpy()
batch_mono_lprob.append(str(lprob))
line_mono_lprob += batch_mono_lprob
print("\t".join(line_mono_lprob), file=mono_lprob_h)
def skip_invalid_samples(batch_samples, max_position):
output_batch = [x[:max_position] for x in batch_samples]
return output_batch
if __name__ == "__main__":
main() | examples/backtranslation/gen_mono_lprob.py | import argparse
import fileinput
from fairseq.models.transformer import TransformerModel
from tqdm import tqdm
import numpy as np
def main():
parser = argparse.ArgumentParser(
description=(
"Extract back-translations from the stdout of _fairseq-generate. "
"If there are multiply hypotheses for a source sentence, we cat all of them with tab. "
)
)
parser.add_argument("--output", required=True, help="output prefix")
parser.add_argument("--lm_path", required=True, help="the mono language model checkpoint file path")
parser.add_argument("--cp_file", help='the checkpoint file to load, none for best')
parser.add_argument("--lm_data_path", required=True, help="the databin where the mono language model is trained")
parser.add_argument("--bpe_file", required=False, help="the bpe code file")
parser.add_argument("--batch_size", type=int,
default=32, help="the batch size for mono language model scoring")
parser.add_argument("--silent_mode", default=True)
parser.add_argument("--max_positions", default=512,
help="the maximum number of positions, skip the sequences that are longer than this value.")
parser.add_argument("files", nargs="*", help="input files")
args = parser.parse_args()
mono_model = TransformerModel.from_pretrained(
args.lm_path,
checkpoint_file=args.cp_file or 'checkpoint_best.pt',
data_name_or_path=args.lm_data_path,
bpe='fastbpe',
bpe_codes=args.bpe_file or args.lm_data_path + '/code')
mono_model.eval() # disable dropout
# Move model to GPU
mono_model.cuda()
with open(args.output + ".mono_lprob", "w", encoding='utf-8') as mono_lprob_h:
n_batch = 0
for line in tqdm(fileinput.input(args.files, openhook=fileinput.hook_encoded('utf-8')),
disable=args.silent_mode):
line_src = line.split('\t')
if n_batch == 0:
n_batch = len(line_src) // args.batch_size
if len(line_src) % args.batch_size != 0:
n_batch += 1
line_mono_lprob = []
for i in range(n_batch):
batch_samples = line_src[i * args.batch_size:(i + 1) * args.batch_size]
batch_samples = skip_invalid_samples(batch_samples, args.max_positions)
batch_mono_lprob = []
for x in mono_model.score(batch_samples):
lprob=x["positional_scores"].sum().cpu().numpy()
batch_mono_lprob.append(str(lprob))
line_mono_lprob += batch_mono_lprob
print("\t".join(line_mono_lprob), file=mono_lprob_h)
def skip_invalid_samples(batch_samples, max_position):
output_batch = [x[:max_position] for x in batch_samples]
return output_batch
if __name__ == "__main__":
main() | 0.432782 | 0.089893 |
import os
from landolfio.settings.base import * # noqa
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["landolfio.vofdoesburg.nl"]
SESSION_COOKIE_SECURE = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"HOST": os.environ.get("POSTGRES_HOST"),
"PORT": int(os.environ.get("POSTGRES_PORT", 5432)),
"NAME": os.environ.get("POSTGRES_NAME"),
"USER": os.environ.get("POSTGRES_USER"),
"PASSWORD": os.environ.get("POSTGRES_PASSWORD"),
}
}
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "%(asctime)s %(name)s %(levelname)s %(message)s"
},
"brief": {
"format": "%(name)s %(levelname)s %(message)s"
},
},
"handlers": {
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "brief",
},
"file": {
"level": os.environ.get("DJANGO_LOG_LEVEL", "INFO"),
"class": "logging.FileHandler",
"formatter": "verbose",
"filename": "/landolfio/log/django.log",
},
},
"loggers": {
"django": {"handlers": ["file"], "level": "INFO", "propagate": True,}, # noqa
"moneybird": {"handlers": ["file"], "level": "INFO", "propagate": True,}, # noqa
}, # noqa
}
if os.environ.get("DJANGO_EMAIL_HOST"):
EMAIL_HOST = os.environ["DJANGO_EMAIL_HOST"]
EMAIL_PORT = os.environ["DJANGO_EMAIL_PORT"]
EMAIL_HOST_USER = os.environ.get("DJANGO_EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.environ.get("DJANGO_EMAIL_HOST_PASSWORD")
EMAIL_USE_TLS = os.environ.get("DJANGO_EMAIL_USE_TLS", False) == "True"
EMAIL_USE_SSL = os.environ.get("DJANGO_EMAIL_USE_SSL", False) == "True"
MONEYBIRD_API_TOKEN = os.environ["MONEYBIRD_API_TOKEN"]
MONEYBIRD_ADMINISTRATION_ID = os.environ["MONEYBIRD_ADMINISTRATION_ID"]
NINOX_API_TOKEN = os.environ["NINOX_API_TOKEN"]
NINOX_TEAM_ID = os.environ["NINOX_TEAM_ID"]
NINOX_DATABASE_ID = os.environ["NINOX_DATABASE_ID"] | website/landolfio/settings/production.py | import os
from landolfio.settings.base import * # noqa
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["landolfio.vofdoesburg.nl"]
SESSION_COOKIE_SECURE = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"HOST": os.environ.get("POSTGRES_HOST"),
"PORT": int(os.environ.get("POSTGRES_PORT", 5432)),
"NAME": os.environ.get("POSTGRES_NAME"),
"USER": os.environ.get("POSTGRES_USER"),
"PASSWORD": os.environ.get("POSTGRES_PASSWORD"),
}
}
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "%(asctime)s %(name)s %(levelname)s %(message)s"
},
"brief": {
"format": "%(name)s %(levelname)s %(message)s"
},
},
"handlers": {
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "brief",
},
"file": {
"level": os.environ.get("DJANGO_LOG_LEVEL", "INFO"),
"class": "logging.FileHandler",
"formatter": "verbose",
"filename": "/landolfio/log/django.log",
},
},
"loggers": {
"django": {"handlers": ["file"], "level": "INFO", "propagate": True,}, # noqa
"moneybird": {"handlers": ["file"], "level": "INFO", "propagate": True,}, # noqa
}, # noqa
}
if os.environ.get("DJANGO_EMAIL_HOST"):
EMAIL_HOST = os.environ["DJANGO_EMAIL_HOST"]
EMAIL_PORT = os.environ["DJANGO_EMAIL_PORT"]
EMAIL_HOST_USER = os.environ.get("DJANGO_EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.environ.get("DJANGO_EMAIL_HOST_PASSWORD")
EMAIL_USE_TLS = os.environ.get("DJANGO_EMAIL_USE_TLS", False) == "True"
EMAIL_USE_SSL = os.environ.get("DJANGO_EMAIL_USE_SSL", False) == "True"
MONEYBIRD_API_TOKEN = os.environ["MONEYBIRD_API_TOKEN"]
MONEYBIRD_ADMINISTRATION_ID = os.environ["MONEYBIRD_ADMINISTRATION_ID"]
NINOX_API_TOKEN = os.environ["NINOX_API_TOKEN"]
NINOX_TEAM_ID = os.environ["NINOX_TEAM_ID"]
NINOX_DATABASE_ID = os.environ["NINOX_DATABASE_ID"] | 0.136263 | 0.090133 |
try:
import unittest2 as unittest
except ImportError:
import unittest
from mock import patch
import app_config
app_config.DATABASE_NAME = 'carebot_test.db'
from plugins.npr.start_tracking import NPRStartTracking
from util.models import Story
from tests.test_util.db import clear_stories
class TestSpreadsheet(unittest.TestCase):
@patch('util.slack.SlackTools.get_channel_name')
def test_start_tracking(self, mock_get_channel_name):
"""
Test if we can start tracking a new story given only a NPR URL and a
graphic slug
"""
mock_get_channel_name.return_value = 'default-channel'
clear_stories()
tracker = NPRStartTracking()
class FakeMessage(object):
body = {
'text': '@carebot track slug-a-b-c on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong',
'channel': 'default-channel'
}
expected = "Ok, I've started tracking `slug-a-b-c` on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong"
message = tracker.respond(FakeMessage)
print message
assert expected in message['text']
results = Story.select()
self.assertEqual(len(results), 1)
self.assertEqual(results[0].url, 'http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong')
@patch('util.slack.SlackTools.get_channel_name')
def test_change_tracking(self, mock_get_channel_name):
"""
Check if we can start tracking a URL, then update the slugs that are
tracked on it
"""
mock_get_channel_name.return_value = 'default-channel'
clear_stories()
tracker = NPRStartTracking()
class FakeMessage(object):
body = {
'text': '@carebot track slug-a-b-c on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong',
'channel': 'default-channel'
}
expected = "Ok, I've started tracking `slug-a-b-c` on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong"
message = tracker.respond(FakeMessage)
assert expected in message['text']
# Now try to change the slug
FakeMessage.body['text'] = '@carebot track slug-a-b-c,slug-x-y-z on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong'
message = tracker.respond(FakeMessage)
results = Story.select()
self.assertEqual(len(results), 1)
self.assertEqual(results[0].url, 'http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong')
self.assertEqual(results[0].slug, 'slug-a-b-c,slug-x-y-z') | tests/test_plugin_track.py |
try:
import unittest2 as unittest
except ImportError:
import unittest
from mock import patch
import app_config
app_config.DATABASE_NAME = 'carebot_test.db'
from plugins.npr.start_tracking import NPRStartTracking
from util.models import Story
from tests.test_util.db import clear_stories
class TestSpreadsheet(unittest.TestCase):
@patch('util.slack.SlackTools.get_channel_name')
def test_start_tracking(self, mock_get_channel_name):
"""
Test if we can start tracking a new story given only a NPR URL and a
graphic slug
"""
mock_get_channel_name.return_value = 'default-channel'
clear_stories()
tracker = NPRStartTracking()
class FakeMessage(object):
body = {
'text': '@carebot track slug-a-b-c on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong',
'channel': 'default-channel'
}
expected = "Ok, I've started tracking `slug-a-b-c` on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong"
message = tracker.respond(FakeMessage)
print message
assert expected in message['text']
results = Story.select()
self.assertEqual(len(results), 1)
self.assertEqual(results[0].url, 'http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong')
@patch('util.slack.SlackTools.get_channel_name')
def test_change_tracking(self, mock_get_channel_name):
"""
Check if we can start tracking a URL, then update the slugs that are
tracked on it
"""
mock_get_channel_name.return_value = 'default-channel'
clear_stories()
tracker = NPRStartTracking()
class FakeMessage(object):
body = {
'text': '@carebot track slug-a-b-c on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong',
'channel': 'default-channel'
}
expected = "Ok, I've started tracking `slug-a-b-c` on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong"
message = tracker.respond(FakeMessage)
assert expected in message['text']
# Now try to change the slug
FakeMessage.body['text'] = '@carebot track slug-a-b-c,slug-x-y-z on http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong'
message = tracker.respond(FakeMessage)
results = Story.select()
self.assertEqual(len(results), 1)
self.assertEqual(results[0].url, 'http://www.npr.org/sections/13.7/2016/02/16/466109612/was-einstein-wrong')
self.assertEqual(results[0].slug, 'slug-a-b-c,slug-x-y-z') | 0.605799 | 0.270468 |
import math
import torch
import torch.nn as nn
from torch.nn import init
BATCHNORM_TRACK_RUNNING_STATS = False
BATCHNORM_MOVING_AVERAGE_DECAY = 0.9997
class BNorm_init(nn.BatchNorm2d):
def reset_parameters(self):
init.uniform_(self.weight, 0, 1)
init.zeros_(self.bias)
class Conv2d_init(nn.Conv2d):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=True,
padding_mode="zeros",
):
super(Conv2d_init, self).__init__(
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
groups,
bias,
padding_mode,
)
def reset_parameters(self):
init.xavier_normal_(self.weight)
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
def _conv_block(in_chanels, out_chanels, kernel_size, padding):
return nn.Sequential(
Conv2d_init(
in_channels=in_chanels,
out_channels=out_chanels,
kernel_size=kernel_size,
padding=padding,
bias=False,
),
FeatureNorm(num_features=out_chanels, eps=0.001),
nn.ReLU(),
)
class FeatureNorm(nn.Module):
def __init__(
self,
num_features,
feature_index=1,
rank=4,
reduce_dims=(2, 3),
eps=0.001,
include_bias=True,
):
super(FeatureNorm, self).__init__()
self.shape = [1] * rank
self.shape[feature_index] = num_features
self.reduce_dims = reduce_dims
self.scale = nn.Parameter(
torch.ones(self.shape, requires_grad=True, dtype=torch.float)
)
self.bias = (
nn.Parameter(torch.zeros(self.shape, requires_grad=True, dtype=torch.float))
if include_bias
else nn.Parameter(
torch.zeros(self.shape, requires_grad=False, dtype=torch.float)
)
)
self.eps = eps
def forward(self, features):
f_std = torch.std(features, dim=self.reduce_dims, keepdim=True)
f_mean = torch.mean(features, dim=self.reduce_dims, keepdim=True)
return (
self.scale * ((features - f_mean) / (f_std + self.eps).sqrt()) + self.bias
)
class SegDecNet(nn.Module):
def __init__(self, device, input_width, input_height, input_channels):
super(SegDecNet, self).__init__()
if input_width % 8 != 0 or input_height % 8 != 0:
raise Exception(
f"Input size must be divisible by 8! width={input_width}, height={input_height}"
)
self.input_width = input_width
self.input_height = input_height
self.input_channels = input_channels
self.volume = nn.Sequential(
_conv_block(self.input_channels, 32, 5, 2),
# _conv_block(32, 32, 5, 2), # Has been accidentally left out and remained the same since then
nn.MaxPool2d(2),
_conv_block(32, 64, 5, 2),
_conv_block(64, 64, 5, 2),
_conv_block(64, 64, 5, 2),
nn.MaxPool2d(2),
_conv_block(64, 64, 5, 2),
_conv_block(64, 64, 5, 2),
_conv_block(64, 64, 5, 2),
_conv_block(64, 64, 5, 2),
nn.MaxPool2d(2),
_conv_block(64, 1024, 15, 7),
)
self.seg_mask = nn.Sequential(
Conv2d_init(
in_channels=1024, out_channels=1, kernel_size=1, padding=0, bias=False
),
FeatureNorm(num_features=1, eps=0.001, include_bias=False),
)
self.extractor = nn.Sequential(
nn.MaxPool2d(kernel_size=2),
_conv_block(in_chanels=1025, out_chanels=8, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
_conv_block(in_chanels=8, out_chanels=16, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
_conv_block(in_chanels=16, out_chanels=32, kernel_size=5, padding=2),
)
self.global_max_pool_feat = nn.MaxPool2d(kernel_size=32)
self.global_avg_pool_feat = nn.AvgPool2d(kernel_size=32)
self.global_max_pool_seg = nn.MaxPool2d(
kernel_size=(self.input_height / 8, self.input_width / 8)
)
self.global_avg_pool_seg = nn.AvgPool2d(
kernel_size=(self.input_height / 8, self.input_width / 8)
)
self.fc = nn.Linear(in_features=66, out_features=1)
self.volume_lr_multiplier_layer = GradientMultiplyLayer().apply
self.glob_max_lr_multiplier_layer = GradientMultiplyLayer().apply
self.glob_avg_lr_multiplier_layer = GradientMultiplyLayer().apply
self.device = device
def set_gradient_multipliers(self, multiplier):
self.volume_lr_multiplier_mask = (torch.ones((1,)) * multiplier).to(self.device)
self.glob_max_lr_multiplier_mask = (torch.ones((1,)) * multiplier).to(
self.device
)
self.glob_avg_lr_multiplier_mask = (torch.ones((1,)) * multiplier).to(
self.device
)
def forward(self, input):
volume = self.volume(input)
seg_mask = self.seg_mask(volume)
cat = torch.cat([volume, seg_mask], dim=1)
cat = self.volume_lr_multiplier_layer(cat, self.volume_lr_multiplier_mask)
features = self.extractor(cat)
global_max_feat = torch.max(
torch.max(features, dim=-1, keepdim=True)[0], dim=-2, keepdim=True
)[0]
global_avg_feat = torch.mean(features, dim=(-1, -2), keepdim=True)
global_max_seg = torch.max(
torch.max(seg_mask, dim=-1, keepdim=True)[0], dim=-2, keepdim=True
)[0]
global_avg_seg = torch.mean(seg_mask, dim=(-1, -2), keepdim=True)
global_max_feat = global_max_feat.reshape(global_max_feat.size(0), -1)
global_avg_feat = global_avg_feat.reshape(global_avg_feat.size(0), -1)
global_max_seg = global_max_seg.reshape(global_max_seg.size(0), -1)
global_max_seg = self.glob_max_lr_multiplier_layer(
global_max_seg, self.glob_max_lr_multiplier_mask
)
global_avg_seg = global_avg_seg.reshape(global_avg_seg.size(0), -1)
global_avg_seg = self.glob_avg_lr_multiplier_layer(
global_avg_seg, self.glob_avg_lr_multiplier_mask
)
fc_in = torch.cat(
[global_max_feat, global_avg_feat, global_max_seg, global_avg_seg], dim=1
)
fc_in = fc_in.reshape(fc_in.size(0), -1)
prediction = self.fc(fc_in)
return prediction, seg_mask
class GradientMultiplyLayer(torch.autograd.Function):
@staticmethod
def forward(ctx, input, mask_bw):
ctx.save_for_backward(mask_bw)
return input
@staticmethod
def backward(ctx, grad_output):
(mask_bw,) = ctx.saved_tensors
return grad_output.mul(mask_bw), None
if __name__ == "__main__":
model = SegDecNet(torch.device("cpu"), 512, 1248, 1)
print(model) | models.py | import math
import torch
import torch.nn as nn
from torch.nn import init
BATCHNORM_TRACK_RUNNING_STATS = False
BATCHNORM_MOVING_AVERAGE_DECAY = 0.9997
class BNorm_init(nn.BatchNorm2d):
def reset_parameters(self):
init.uniform_(self.weight, 0, 1)
init.zeros_(self.bias)
class Conv2d_init(nn.Conv2d):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=True,
padding_mode="zeros",
):
super(Conv2d_init, self).__init__(
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
groups,
bias,
padding_mode,
)
def reset_parameters(self):
init.xavier_normal_(self.weight)
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
def _conv_block(in_chanels, out_chanels, kernel_size, padding):
return nn.Sequential(
Conv2d_init(
in_channels=in_chanels,
out_channels=out_chanels,
kernel_size=kernel_size,
padding=padding,
bias=False,
),
FeatureNorm(num_features=out_chanels, eps=0.001),
nn.ReLU(),
)
class FeatureNorm(nn.Module):
def __init__(
self,
num_features,
feature_index=1,
rank=4,
reduce_dims=(2, 3),
eps=0.001,
include_bias=True,
):
super(FeatureNorm, self).__init__()
self.shape = [1] * rank
self.shape[feature_index] = num_features
self.reduce_dims = reduce_dims
self.scale = nn.Parameter(
torch.ones(self.shape, requires_grad=True, dtype=torch.float)
)
self.bias = (
nn.Parameter(torch.zeros(self.shape, requires_grad=True, dtype=torch.float))
if include_bias
else nn.Parameter(
torch.zeros(self.shape, requires_grad=False, dtype=torch.float)
)
)
self.eps = eps
def forward(self, features):
f_std = torch.std(features, dim=self.reduce_dims, keepdim=True)
f_mean = torch.mean(features, dim=self.reduce_dims, keepdim=True)
return (
self.scale * ((features - f_mean) / (f_std + self.eps).sqrt()) + self.bias
)
class SegDecNet(nn.Module):
def __init__(self, device, input_width, input_height, input_channels):
super(SegDecNet, self).__init__()
if input_width % 8 != 0 or input_height % 8 != 0:
raise Exception(
f"Input size must be divisible by 8! width={input_width}, height={input_height}"
)
self.input_width = input_width
self.input_height = input_height
self.input_channels = input_channels
self.volume = nn.Sequential(
_conv_block(self.input_channels, 32, 5, 2),
# _conv_block(32, 32, 5, 2), # Has been accidentally left out and remained the same since then
nn.MaxPool2d(2),
_conv_block(32, 64, 5, 2),
_conv_block(64, 64, 5, 2),
_conv_block(64, 64, 5, 2),
nn.MaxPool2d(2),
_conv_block(64, 64, 5, 2),
_conv_block(64, 64, 5, 2),
_conv_block(64, 64, 5, 2),
_conv_block(64, 64, 5, 2),
nn.MaxPool2d(2),
_conv_block(64, 1024, 15, 7),
)
self.seg_mask = nn.Sequential(
Conv2d_init(
in_channels=1024, out_channels=1, kernel_size=1, padding=0, bias=False
),
FeatureNorm(num_features=1, eps=0.001, include_bias=False),
)
self.extractor = nn.Sequential(
nn.MaxPool2d(kernel_size=2),
_conv_block(in_chanels=1025, out_chanels=8, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
_conv_block(in_chanels=8, out_chanels=16, kernel_size=5, padding=2),
nn.MaxPool2d(kernel_size=2),
_conv_block(in_chanels=16, out_chanels=32, kernel_size=5, padding=2),
)
self.global_max_pool_feat = nn.MaxPool2d(kernel_size=32)
self.global_avg_pool_feat = nn.AvgPool2d(kernel_size=32)
self.global_max_pool_seg = nn.MaxPool2d(
kernel_size=(self.input_height / 8, self.input_width / 8)
)
self.global_avg_pool_seg = nn.AvgPool2d(
kernel_size=(self.input_height / 8, self.input_width / 8)
)
self.fc = nn.Linear(in_features=66, out_features=1)
self.volume_lr_multiplier_layer = GradientMultiplyLayer().apply
self.glob_max_lr_multiplier_layer = GradientMultiplyLayer().apply
self.glob_avg_lr_multiplier_layer = GradientMultiplyLayer().apply
self.device = device
def set_gradient_multipliers(self, multiplier):
self.volume_lr_multiplier_mask = (torch.ones((1,)) * multiplier).to(self.device)
self.glob_max_lr_multiplier_mask = (torch.ones((1,)) * multiplier).to(
self.device
)
self.glob_avg_lr_multiplier_mask = (torch.ones((1,)) * multiplier).to(
self.device
)
def forward(self, input):
volume = self.volume(input)
seg_mask = self.seg_mask(volume)
cat = torch.cat([volume, seg_mask], dim=1)
cat = self.volume_lr_multiplier_layer(cat, self.volume_lr_multiplier_mask)
features = self.extractor(cat)
global_max_feat = torch.max(
torch.max(features, dim=-1, keepdim=True)[0], dim=-2, keepdim=True
)[0]
global_avg_feat = torch.mean(features, dim=(-1, -2), keepdim=True)
global_max_seg = torch.max(
torch.max(seg_mask, dim=-1, keepdim=True)[0], dim=-2, keepdim=True
)[0]
global_avg_seg = torch.mean(seg_mask, dim=(-1, -2), keepdim=True)
global_max_feat = global_max_feat.reshape(global_max_feat.size(0), -1)
global_avg_feat = global_avg_feat.reshape(global_avg_feat.size(0), -1)
global_max_seg = global_max_seg.reshape(global_max_seg.size(0), -1)
global_max_seg = self.glob_max_lr_multiplier_layer(
global_max_seg, self.glob_max_lr_multiplier_mask
)
global_avg_seg = global_avg_seg.reshape(global_avg_seg.size(0), -1)
global_avg_seg = self.glob_avg_lr_multiplier_layer(
global_avg_seg, self.glob_avg_lr_multiplier_mask
)
fc_in = torch.cat(
[global_max_feat, global_avg_feat, global_max_seg, global_avg_seg], dim=1
)
fc_in = fc_in.reshape(fc_in.size(0), -1)
prediction = self.fc(fc_in)
return prediction, seg_mask
class GradientMultiplyLayer(torch.autograd.Function):
@staticmethod
def forward(ctx, input, mask_bw):
ctx.save_for_backward(mask_bw)
return input
@staticmethod
def backward(ctx, grad_output):
(mask_bw,) = ctx.saved_tensors
return grad_output.mul(mask_bw), None
if __name__ == "__main__":
model = SegDecNet(torch.device("cpu"), 512, 1248, 1)
print(model) | 0.925281 | 0.355971 |
import tkinter as tk
import requests
import json
import os
from collections import OrderedDict
from tkinter import messagebox
from tkinter import ttk
from bs4 import BeautifulSoup, SoupStrainer
# Combobox widget
global oro_ddl
oro_ddl = None
stFont = ("calibri",12)
# Token is given to each unique IEX API registered user.
token = ""
q_url = "https://cloud.iexapis.com"
e_url = "https://earningswhispers.com"
def load_Quotes():
global oro_ddl
# Simple local storage through text file of saved quotes :^)
if os.stat("wl.txt").st_size != 0:
with open("wl.txt","r") as f:
quotes = f.read().strip().split("\n")
for i,q in enumerate(quotes):
quotes[i] = q.upper()
quoteVar = tk.StringVar()
# Global declaration of this widget so that when it updates, the program can recognise that since this widget already exist, we will just update the values
if oro_ddl == None:
oro_ddl = ttk.Combobox(state='readonly',textvariable=quoteVar,values=quotes)
oro_ddl.bind("<<ComboboxSelected>>",lambda x = i: getQuote(oro_ddl.get()))
oro_ddl.grid(row=1,column=0,sticky='nsew',padx=3,pady=3)
else:
oro_ddl.config(values=quotes)
# For these functions, you see that there is the optional argument ent, this argument is used to clear the entry widget if declared.
def add_Quote(quote,ent=0):
# I was thinking of adding a check to see if the quote entered is a valid quote (response 200), but i don't know if the additional processing is worth it :^)
data = []
if len(quote.strip())!= 0:
with open("wl.txt","r+") as f:
if quote in f.read().split("\n"):
messagebox.showerror("Error",f"{quote} is already marked!")
if ent != 0:
ent.delete(0,'end')
else:
f.write(f"{quote}\n")
messagebox.showinfo("Success",f"{quote.upper()} marked!")
if ent != 0:
ent.delete(0,'end')
# Refreshes the values in the dropdown list (or combobox in tkinter)
load_Quotes()
else:
messagebox.showerror("Error","Uh oh, its empty!")
if ent != 0:
ent.delete(0,'end')
def getEarnings(quote,ent=0):
# Kinda hacky way of getting earning dates from a website without the use of API, might break apart if website code changes :^)
if len(quote.strip()) != 0:
with requests.Session() as f:
response = f.get(f"{e_url}/stocks/{quote}",allow_redirects=False)
if response.status_code == 200:
strainer = SoupStrainer(id='datebox')
soup = BeautifulSoup(response.content,'lxml',parse_only=strainer)
result = str(soup.get_text(" ",strip=True))
messagebox.showinfo(quote,f"Earnings date for {quote.upper()}\n\n{result}")
if ent != 0:
ent.delete(0,'end')
else:
messagebox.showerror("Error",f"Couldn't find {quote}")
if ent != 0:
ent.delete(0,'end')
else:
messagebox.showerror("Error","Uh oh, its empty!")
def getQuote(quote,ent=0):
# com_lbl is the first label created once results are returned, so if this label is instantiated (not None), implies the subsequent widgets are as well.
com_lbl = None
# These list hold similar stuff, naming convention could be better :^)
# widget_list holds the widgets with the values taken from the IEX API JSON values
# fabList holds the widgets beside the values, like titles of the values??
widget_list = []
fabList = []
if len(quote.strip())!= 0:
with requests.Session() as f:
response = f.get(f"{q_url}/stable/stock/{quote}/quote?token={token}")
if response.status_code != 200:
messagebox.showerror("Error",f"Couldn't find {quote}")
if ent!= 0:
ent.delete(0,'end')
else:
info = json.loads(response.text)
o_Info = OrderedDict(info)
company_name = str(o_Info['companyName'])
price_close = float(o_Info['latestPrice'])
price_close = "${0:,.2f}".format(price_close)
prev_close = float(o_Info['previousClose'])
prev_close = "${0:,.2f}".format(prev_close)
dollar_change = float("{0:.2f}".format(o_Info['change']))
percent_change = float("{0:.2f}".format(100 * o_Info['changePercent']))
date = str(o_Info['latestTime'])
if dollar_change > 0:
color_Indi = "limegreen"
else:
color_Indi = "red"
if com_lbl == None:
lbl_tit = tk.Label(text="company:",font=stFont,anchor='w',bg='white')
lbl_tit0 = tk.Label(text="price:",font=stFont,anchor='w',bg='white')
lbl_tit2 = tk.Label(text="change:",font=stFont,anchor='w',bg='white')
lbl_tit3 = tk.Label(text="change(%):",font=stFont,anchor='w',bg='white')
lbl_tit4 = tk.Label(text="last updated:",font=stFont,anchor='w',bg='white')
com_lbl = tk.Label(text=company_name,font=stFont,anchor='w',bg='white',width=30)
pri_lbl = tk.Label(text=f"{prev_close} → {price_close}",fg=color_Indi,font=stFont,anchor='w',bg='white')
doc_lbl = tk.Label(text=f"${dollar_change}",fg=color_Indi,font=stFont,anchor='w',bg='white')
per_lbl = tk.Label(text=f"{percent_change}%",fg=color_Indi,font=stFont,anchor='w',bg='white')
date_lbl = tk.Label(text=date,font=stFont,anchor='w',bg='white')
widget_list.append(com_lbl)
widget_list.append(pri_lbl)
widget_list.append(doc_lbl)
widget_list.append(per_lbl)
widget_list.append(date_lbl)
fabList.append(lbl_tit)
fabList.append(lbl_tit0)
fabList.append(lbl_tit2)
fabList.append(lbl_tit3)
fabList.append(lbl_tit4)
for i,widget in enumerate(fabList):
widget.grid(row=i+1,column=1,sticky='nsew',padx=3,pady=3)
for i,widget in enumerate(widget_list):
widget.grid(row=i+1,column=2,sticky='nsew')
if ent != 0:
ent.delete(0,'end')
else:
com_lbl.update(text=company_name)
pri_lbl.update(text=price_close,fg=color_Indi)
doc_lbl.update(text=str(dollar_change),fg=color_Indi)
per_lbl.update(text=str(percent_change),fg=color_Indi)
date_lbl.update(text=date)
if ent != 0:
ent.delete(0,'end')
else:
messagebox.showerror("Error","Uh oh, its empty!") | stocku.py | import tkinter as tk
import requests
import json
import os
from collections import OrderedDict
from tkinter import messagebox
from tkinter import ttk
from bs4 import BeautifulSoup, SoupStrainer
# Combobox widget
global oro_ddl
oro_ddl = None
stFont = ("calibri",12)
# Token is given to each unique IEX API registered user.
token = ""
q_url = "https://cloud.iexapis.com"
e_url = "https://earningswhispers.com"
def load_Quotes():
global oro_ddl
# Simple local storage through text file of saved quotes :^)
if os.stat("wl.txt").st_size != 0:
with open("wl.txt","r") as f:
quotes = f.read().strip().split("\n")
for i,q in enumerate(quotes):
quotes[i] = q.upper()
quoteVar = tk.StringVar()
# Global declaration of this widget so that when it updates, the program can recognise that since this widget already exist, we will just update the values
if oro_ddl == None:
oro_ddl = ttk.Combobox(state='readonly',textvariable=quoteVar,values=quotes)
oro_ddl.bind("<<ComboboxSelected>>",lambda x = i: getQuote(oro_ddl.get()))
oro_ddl.grid(row=1,column=0,sticky='nsew',padx=3,pady=3)
else:
oro_ddl.config(values=quotes)
# For these functions, you see that there is the optional argument ent, this argument is used to clear the entry widget if declared.
def add_Quote(quote,ent=0):
# I was thinking of adding a check to see if the quote entered is a valid quote (response 200), but i don't know if the additional processing is worth it :^)
data = []
if len(quote.strip())!= 0:
with open("wl.txt","r+") as f:
if quote in f.read().split("\n"):
messagebox.showerror("Error",f"{quote} is already marked!")
if ent != 0:
ent.delete(0,'end')
else:
f.write(f"{quote}\n")
messagebox.showinfo("Success",f"{quote.upper()} marked!")
if ent != 0:
ent.delete(0,'end')
# Refreshes the values in the dropdown list (or combobox in tkinter)
load_Quotes()
else:
messagebox.showerror("Error","Uh oh, its empty!")
if ent != 0:
ent.delete(0,'end')
def getEarnings(quote,ent=0):
# Kinda hacky way of getting earning dates from a website without the use of API, might break apart if website code changes :^)
if len(quote.strip()) != 0:
with requests.Session() as f:
response = f.get(f"{e_url}/stocks/{quote}",allow_redirects=False)
if response.status_code == 200:
strainer = SoupStrainer(id='datebox')
soup = BeautifulSoup(response.content,'lxml',parse_only=strainer)
result = str(soup.get_text(" ",strip=True))
messagebox.showinfo(quote,f"Earnings date for {quote.upper()}\n\n{result}")
if ent != 0:
ent.delete(0,'end')
else:
messagebox.showerror("Error",f"Couldn't find {quote}")
if ent != 0:
ent.delete(0,'end')
else:
messagebox.showerror("Error","Uh oh, its empty!")
def getQuote(quote,ent=0):
# com_lbl is the first label created once results are returned, so if this label is instantiated (not None), implies the subsequent widgets are as well.
com_lbl = None
# These list hold similar stuff, naming convention could be better :^)
# widget_list holds the widgets with the values taken from the IEX API JSON values
# fabList holds the widgets beside the values, like titles of the values??
widget_list = []
fabList = []
if len(quote.strip())!= 0:
with requests.Session() as f:
response = f.get(f"{q_url}/stable/stock/{quote}/quote?token={token}")
if response.status_code != 200:
messagebox.showerror("Error",f"Couldn't find {quote}")
if ent!= 0:
ent.delete(0,'end')
else:
info = json.loads(response.text)
o_Info = OrderedDict(info)
company_name = str(o_Info['companyName'])
price_close = float(o_Info['latestPrice'])
price_close = "${0:,.2f}".format(price_close)
prev_close = float(o_Info['previousClose'])
prev_close = "${0:,.2f}".format(prev_close)
dollar_change = float("{0:.2f}".format(o_Info['change']))
percent_change = float("{0:.2f}".format(100 * o_Info['changePercent']))
date = str(o_Info['latestTime'])
if dollar_change > 0:
color_Indi = "limegreen"
else:
color_Indi = "red"
if com_lbl == None:
lbl_tit = tk.Label(text="company:",font=stFont,anchor='w',bg='white')
lbl_tit0 = tk.Label(text="price:",font=stFont,anchor='w',bg='white')
lbl_tit2 = tk.Label(text="change:",font=stFont,anchor='w',bg='white')
lbl_tit3 = tk.Label(text="change(%):",font=stFont,anchor='w',bg='white')
lbl_tit4 = tk.Label(text="last updated:",font=stFont,anchor='w',bg='white')
com_lbl = tk.Label(text=company_name,font=stFont,anchor='w',bg='white',width=30)
pri_lbl = tk.Label(text=f"{prev_close} → {price_close}",fg=color_Indi,font=stFont,anchor='w',bg='white')
doc_lbl = tk.Label(text=f"${dollar_change}",fg=color_Indi,font=stFont,anchor='w',bg='white')
per_lbl = tk.Label(text=f"{percent_change}%",fg=color_Indi,font=stFont,anchor='w',bg='white')
date_lbl = tk.Label(text=date,font=stFont,anchor='w',bg='white')
widget_list.append(com_lbl)
widget_list.append(pri_lbl)
widget_list.append(doc_lbl)
widget_list.append(per_lbl)
widget_list.append(date_lbl)
fabList.append(lbl_tit)
fabList.append(lbl_tit0)
fabList.append(lbl_tit2)
fabList.append(lbl_tit3)
fabList.append(lbl_tit4)
for i,widget in enumerate(fabList):
widget.grid(row=i+1,column=1,sticky='nsew',padx=3,pady=3)
for i,widget in enumerate(widget_list):
widget.grid(row=i+1,column=2,sticky='nsew')
if ent != 0:
ent.delete(0,'end')
else:
com_lbl.update(text=company_name)
pri_lbl.update(text=price_close,fg=color_Indi)
doc_lbl.update(text=str(dollar_change),fg=color_Indi)
per_lbl.update(text=str(percent_change),fg=color_Indi)
date_lbl.update(text=date)
if ent != 0:
ent.delete(0,'end')
else:
messagebox.showerror("Error","Uh oh, its empty!") | 0.143397 | 0.093099 |
import os
import time
import requests
import json
import base64
from datetime import datetime
from distutils.util import strtobool
from dotenv import load_dotenv
from flask import Flask, request, redirect
from flasgger import Swagger, swag_from
from pixoo.pixoo import Channel, Pixoo
from PIL import Image
from swag import definitions
from swag import passthrough
load_dotenv()
pixoo_host = os.environ.get('PIXOO_HOST', 'Pixoo64')
pixoo_debug = os.environ.get('PIXOO_DEBUG', 'false').lower() == 'true'
while True:
try:
print(f'[ {datetime.now().strftime("%Y-%m-%d (%H:%M:%S)")} ] Trying to connect to "{pixoo_host}" ... ', end='')
if requests.get(f'http://{pixoo_host}/get').status_code == 200:
print('OK.')
break
except:
print('FAILED. (Sleeping 30 seconds.)')
time.sleep(30)
pixoo = Pixoo(
pixoo_host,
int(os.environ.get('PIXOO_SCREEN_SIZE', 64)),
pixoo_debug
)
app = Flask(__name__)
app.config['SWAGGER'] = {
'title': 'Pixoo REST',
'version': '1.0.0',
'description': 'A RESTful API to easily interact with the Wi-Fi enabled {} devices.'.format(
'<a href="https://www.divoom.com/de/products/pixoo-64">Divoom Pixoo</a>'
),
'termsOfService': ''
}
swagger = Swagger(app)
definitions.create(swagger)
def _push_immediately(_request):
if strtobool(_request.form.get('push_immediately', default=True)):
pixoo.push()
@app.route('/', methods=['GET'])
def home():
return redirect('/apidocs')
@app.route('/brightness/<int:percentage>', methods=['PUT'])
@swag_from('swag/set/brightness.yml')
def brightness(percentage):
pixoo.set_brightness(percentage)
return 'OK'
@app.route('/channel/<int:number>', methods=['PUT'])
@app.route('/face/<int:number>', methods=['PUT'])
@app.route('/visualizer/<int:number>', methods=['PUT'])
@app.route('/clock/<int:number>', methods=['PUT'])
@swag_from('swag/set/generic_number.yml')
def generic_set_number(number):
if request.path.startswith('/channel'):
pixoo.set_channel(Channel(number))
elif request.path.startswith('/face'):
pixoo.set_face(number)
elif request.path.startswith('/visualizer'):
pixoo.set_visualizer(number)
elif request.path.startswith('/clock'):
pixoo.set_clock(number)
return 'OK'
@app.route('/image', methods=['POST'])
@swag_from('swag/draw/image.yml')
def image():
pixoo.draw_image_at_location(
Image.open(request.files['image'].stream),
int(request.form.get('x')),
int(request.form.get('y'))
)
_push_immediately(request)
return 'OK'
@app.route('/text', methods=['POST'])
@swag_from('swag/draw/text.yml')
def text():
pixoo.draw_text_at_location_rgb(
request.form.get('text'),
int(request.form.get('x')),
int(request.form.get('y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/fill', methods=['POST'])
@swag_from('swag/draw/fill.yml')
def fill():
pixoo.fill_rgb(
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/line', methods=['POST'])
@swag_from('swag/draw/line.yml')
def line():
pixoo.draw_line_from_start_to_stop_rgb(
int(request.form.get('start_x')),
int(request.form.get('start_y')),
int(request.form.get('stop_x')),
int(request.form.get('stop_y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/rectangle', methods=['POST'])
@swag_from('swag/draw/rectangle.yml')
def rectangle():
pixoo.draw_filled_rectangle_from_top_left_to_bottom_right_rgb(
int(request.form.get('top_left_x')),
int(request.form.get('top_left_y')),
int(request.form.get('bottom_right_x')),
int(request.form.get('bottom_right_y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/pixel', methods=['POST'])
@swag_from('swag/draw/pixel.yml')
def pixel():
pixoo.draw_pixel_at_location_rgb(
int(request.form.get('x')),
int(request.form.get('y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/character', methods=['POST'])
@swag_from('swag/draw/character.yml')
def character():
pixoo.draw_character_at_location_rgb(
request.form.get('character'),
int(request.form.get('x')),
int(request.form.get('y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/sendText', methods=['POST'])
@swag_from('swag/send/text.yml')
def send_text():
pixoo.send_text(
request.form.get('text'),
(int(request.form.get('x')), int(request.form.get('y'))),
(int(request.form.get('r')), int(request.form.get('g')), int(request.form.get('b'))),
(int(request.form.get('identifier'))),
(int(request.form.get('font'))),
(int(request.form.get('width'))),
(int(request.form.get('movement_speed'))),
(int(request.form.get('direction')))
)
return 'OK'
def _reset_gif():
return requests.post(f'http://{pixoo.address}/post', json.dumps({
"Command": "Draw/ResetHttpGifId"
})).json()
def _send_gif(num, offset, width, speed, data):
return requests.post(f'http://{pixoo.address}/post', json.dumps({
"Command": "Draw/SendHttpGif",
"PicID": 1,
"PicNum": num,
"PicOffset": offset,
"PicWidth": width,
"PicSpeed": speed,
"PicData": data
})).json()
@app.route('/sendGif', methods=['POST'])
@swag_from('swag/send/gif.yml')
def send_gif():
gif = Image.open(request.files['gif'].stream)
speed = int(request.form.get('speed'))
if gif.is_animated:
_reset_gif()
for i in range(gif.n_frames):
gif.seek(i)
if gif.size not in ((16, 16), (32, 32), (64, 64)):
gif_frame = gif.resize((pixoo.size, pixoo.size)).convert("RGB")
else:
gif_frame = gif.convert("RGB")
_send_gif(
gif.n_frames,
i,
gif_frame.width,
speed,
base64.b64encode(gif_frame.tobytes()).decode("utf-8")
)
else:
pixoo.draw_image(gif)
pixoo.push()
return 'OK'
passthrough_routes = {
# channel ...
'/passthrough/channel/setIndex': passthrough.create(*passthrough.channel_set_index),
'/passthrough/channel/setCustomPageIndex': passthrough.create(*passthrough.channel_set_custom_page_index),
'/passthrough/channel/setEqPosition': passthrough.create(*passthrough.channel_set_eq_position),
'/passthrough/channel/cloudIndex': passthrough.create(*passthrough.channel_cloud_index),
'/passthrough/channel/getIndex': passthrough.create(*passthrough.channel_get_index),
'/passthrough/channel/setBrightness': passthrough.create(*passthrough.channel_set_brightness),
'/passthrough/channel/getAllConf': passthrough.create(*passthrough.channel_get_all_conf),
'/passthrough/channel/onOffScreen': passthrough.create(*passthrough.channel_on_off_screen),
# sys ...
'/passthrough/sys/logAndLat': passthrough.create(*passthrough.sys_log_and_lat),
'/passthrough/sys/timeZone': passthrough.create(*passthrough.sys_timezone),
# device ...
'/passthrough/device/setUTC': passthrough.create(*passthrough.device_set_utc),
# tools ...
'/passthrough/tools/setTimer': passthrough.create(*passthrough.tools_set_timer),
'/passthrough/tools/setStopWatch': passthrough.create(*passthrough.tools_set_stop_watch),
'/passthrough/tools/setScoreBoard': passthrough.create(*passthrough.tools_set_score_board),
'/passthrough/tools/setNoiseStatus': passthrough.create(*passthrough.tools_set_noise_status),
# draw ...
'/passthrough/draw/sendHttpText': passthrough.create(*passthrough.draw_send_http_text),
'/passthrough/draw/clearHttpText': passthrough.create(*passthrough.draw_clear_http_text),
'/passthrough/draw/sendHttpGif': passthrough.create(*passthrough.draw_send_http_gif),
'/passthrough/draw/resetHttpGifId': passthrough.create(*passthrough.draw_reset_http_gif_id),
}
def _passthrough_request(passthrough_request):
return requests.post(f'http://{pixoo.address}/post', json.dumps(passthrough_request.json)).json()
for _route, _swag in passthrough_routes.items():
exec(f"""
@app.route('{_route}', methods=['POST'], endpoint='{_route}')
@swag_from({_swag}, endpoint='{_route}')
def passthrough_{list(passthrough_routes.keys()).index(_route)}():
return _passthrough_request(request)
""")
if __name__ == '__main__':
app.run() | app.py | import os
import time
import requests
import json
import base64
from datetime import datetime
from distutils.util import strtobool
from dotenv import load_dotenv
from flask import Flask, request, redirect
from flasgger import Swagger, swag_from
from pixoo.pixoo import Channel, Pixoo
from PIL import Image
from swag import definitions
from swag import passthrough
load_dotenv()
pixoo_host = os.environ.get('PIXOO_HOST', 'Pixoo64')
pixoo_debug = os.environ.get('PIXOO_DEBUG', 'false').lower() == 'true'
while True:
try:
print(f'[ {datetime.now().strftime("%Y-%m-%d (%H:%M:%S)")} ] Trying to connect to "{pixoo_host}" ... ', end='')
if requests.get(f'http://{pixoo_host}/get').status_code == 200:
print('OK.')
break
except:
print('FAILED. (Sleeping 30 seconds.)')
time.sleep(30)
pixoo = Pixoo(
pixoo_host,
int(os.environ.get('PIXOO_SCREEN_SIZE', 64)),
pixoo_debug
)
app = Flask(__name__)
app.config['SWAGGER'] = {
'title': 'Pixoo REST',
'version': '1.0.0',
'description': 'A RESTful API to easily interact with the Wi-Fi enabled {} devices.'.format(
'<a href="https://www.divoom.com/de/products/pixoo-64">Divoom Pixoo</a>'
),
'termsOfService': ''
}
swagger = Swagger(app)
definitions.create(swagger)
def _push_immediately(_request):
if strtobool(_request.form.get('push_immediately', default=True)):
pixoo.push()
@app.route('/', methods=['GET'])
def home():
return redirect('/apidocs')
@app.route('/brightness/<int:percentage>', methods=['PUT'])
@swag_from('swag/set/brightness.yml')
def brightness(percentage):
pixoo.set_brightness(percentage)
return 'OK'
@app.route('/channel/<int:number>', methods=['PUT'])
@app.route('/face/<int:number>', methods=['PUT'])
@app.route('/visualizer/<int:number>', methods=['PUT'])
@app.route('/clock/<int:number>', methods=['PUT'])
@swag_from('swag/set/generic_number.yml')
def generic_set_number(number):
if request.path.startswith('/channel'):
pixoo.set_channel(Channel(number))
elif request.path.startswith('/face'):
pixoo.set_face(number)
elif request.path.startswith('/visualizer'):
pixoo.set_visualizer(number)
elif request.path.startswith('/clock'):
pixoo.set_clock(number)
return 'OK'
@app.route('/image', methods=['POST'])
@swag_from('swag/draw/image.yml')
def image():
pixoo.draw_image_at_location(
Image.open(request.files['image'].stream),
int(request.form.get('x')),
int(request.form.get('y'))
)
_push_immediately(request)
return 'OK'
@app.route('/text', methods=['POST'])
@swag_from('swag/draw/text.yml')
def text():
pixoo.draw_text_at_location_rgb(
request.form.get('text'),
int(request.form.get('x')),
int(request.form.get('y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/fill', methods=['POST'])
@swag_from('swag/draw/fill.yml')
def fill():
pixoo.fill_rgb(
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/line', methods=['POST'])
@swag_from('swag/draw/line.yml')
def line():
pixoo.draw_line_from_start_to_stop_rgb(
int(request.form.get('start_x')),
int(request.form.get('start_y')),
int(request.form.get('stop_x')),
int(request.form.get('stop_y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/rectangle', methods=['POST'])
@swag_from('swag/draw/rectangle.yml')
def rectangle():
pixoo.draw_filled_rectangle_from_top_left_to_bottom_right_rgb(
int(request.form.get('top_left_x')),
int(request.form.get('top_left_y')),
int(request.form.get('bottom_right_x')),
int(request.form.get('bottom_right_y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/pixel', methods=['POST'])
@swag_from('swag/draw/pixel.yml')
def pixel():
pixoo.draw_pixel_at_location_rgb(
int(request.form.get('x')),
int(request.form.get('y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/character', methods=['POST'])
@swag_from('swag/draw/character.yml')
def character():
pixoo.draw_character_at_location_rgb(
request.form.get('character'),
int(request.form.get('x')),
int(request.form.get('y')),
int(request.form.get('r')),
int(request.form.get('g')),
int(request.form.get('b'))
)
_push_immediately(request)
return 'OK'
@app.route('/sendText', methods=['POST'])
@swag_from('swag/send/text.yml')
def send_text():
pixoo.send_text(
request.form.get('text'),
(int(request.form.get('x')), int(request.form.get('y'))),
(int(request.form.get('r')), int(request.form.get('g')), int(request.form.get('b'))),
(int(request.form.get('identifier'))),
(int(request.form.get('font'))),
(int(request.form.get('width'))),
(int(request.form.get('movement_speed'))),
(int(request.form.get('direction')))
)
return 'OK'
def _reset_gif():
return requests.post(f'http://{pixoo.address}/post', json.dumps({
"Command": "Draw/ResetHttpGifId"
})).json()
def _send_gif(num, offset, width, speed, data):
return requests.post(f'http://{pixoo.address}/post', json.dumps({
"Command": "Draw/SendHttpGif",
"PicID": 1,
"PicNum": num,
"PicOffset": offset,
"PicWidth": width,
"PicSpeed": speed,
"PicData": data
})).json()
@app.route('/sendGif', methods=['POST'])
@swag_from('swag/send/gif.yml')
def send_gif():
gif = Image.open(request.files['gif'].stream)
speed = int(request.form.get('speed'))
if gif.is_animated:
_reset_gif()
for i in range(gif.n_frames):
gif.seek(i)
if gif.size not in ((16, 16), (32, 32), (64, 64)):
gif_frame = gif.resize((pixoo.size, pixoo.size)).convert("RGB")
else:
gif_frame = gif.convert("RGB")
_send_gif(
gif.n_frames,
i,
gif_frame.width,
speed,
base64.b64encode(gif_frame.tobytes()).decode("utf-8")
)
else:
pixoo.draw_image(gif)
pixoo.push()
return 'OK'
passthrough_routes = {
# channel ...
'/passthrough/channel/setIndex': passthrough.create(*passthrough.channel_set_index),
'/passthrough/channel/setCustomPageIndex': passthrough.create(*passthrough.channel_set_custom_page_index),
'/passthrough/channel/setEqPosition': passthrough.create(*passthrough.channel_set_eq_position),
'/passthrough/channel/cloudIndex': passthrough.create(*passthrough.channel_cloud_index),
'/passthrough/channel/getIndex': passthrough.create(*passthrough.channel_get_index),
'/passthrough/channel/setBrightness': passthrough.create(*passthrough.channel_set_brightness),
'/passthrough/channel/getAllConf': passthrough.create(*passthrough.channel_get_all_conf),
'/passthrough/channel/onOffScreen': passthrough.create(*passthrough.channel_on_off_screen),
# sys ...
'/passthrough/sys/logAndLat': passthrough.create(*passthrough.sys_log_and_lat),
'/passthrough/sys/timeZone': passthrough.create(*passthrough.sys_timezone),
# device ...
'/passthrough/device/setUTC': passthrough.create(*passthrough.device_set_utc),
# tools ...
'/passthrough/tools/setTimer': passthrough.create(*passthrough.tools_set_timer),
'/passthrough/tools/setStopWatch': passthrough.create(*passthrough.tools_set_stop_watch),
'/passthrough/tools/setScoreBoard': passthrough.create(*passthrough.tools_set_score_board),
'/passthrough/tools/setNoiseStatus': passthrough.create(*passthrough.tools_set_noise_status),
# draw ...
'/passthrough/draw/sendHttpText': passthrough.create(*passthrough.draw_send_http_text),
'/passthrough/draw/clearHttpText': passthrough.create(*passthrough.draw_clear_http_text),
'/passthrough/draw/sendHttpGif': passthrough.create(*passthrough.draw_send_http_gif),
'/passthrough/draw/resetHttpGifId': passthrough.create(*passthrough.draw_reset_http_gif_id),
}
def _passthrough_request(passthrough_request):
return requests.post(f'http://{pixoo.address}/post', json.dumps(passthrough_request.json)).json()
for _route, _swag in passthrough_routes.items():
exec(f"""
@app.route('{_route}', methods=['POST'], endpoint='{_route}')
@swag_from({_swag}, endpoint='{_route}')
def passthrough_{list(passthrough_routes.keys()).index(_route)}():
return _passthrough_request(request)
""")
if __name__ == '__main__':
app.run() | 0.39946 | 0.061678 |
basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
if basedir == '': basedir = '.'
sys.path.append(basedir+'/miasmX')
from miasmX.arch.ppc_arch import ppc_mn
from miasmX.arch.ia32_arch import x86_afs
import logging
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("%(levelname)-5s: %(message)s"))
log = logging.getLogger("ppc_miasm")
log.addHandler(console_handler)
log.setLevel(logging.WARN)
from plasmasm.symbols import Line
class Instruction(Line):
__slots__ = ('section', 'offset', 'bytelen', 'miasm')
CPU = 'PPC'
def from_txt(self, txt):
''' text input, in assembly format '''
TODO
def from_bin(self, in_str, section):
''' binary input, in assembly format '''
attrib = {}
self.miasm = ppc_mn.dis(in_str, attrib)
self.section = section
self.offset = self.miasm.offset
self.bytelen = self.miasm.l
return self
def pack(self):
''' binary representation '''
TODO
def txt(self):
''' text output, to be used by an assembler '''
return str(self.miasm)
def labels(self):
''' labels that are referenced in the line '''
res = set()
for a in self.miasm.arg:
if x86_afs.symb in a:
res |= set(a[x86_afs.symb].keys())
return res
def opname(self):
return self.miasm.getname()
opname = property(opname)
# Methods for binary parser
def create_label_imm(self):
''' Replace immediate values that may be labels '''
# TODO
pass
def create_label_rel(self):
''' Replace relative addresses for call/branch '''
# TODO
pass
def apply_reloc(self, pos, reloc):
''' 'reloc' is a relocation at offset 'pos'
This function modifies the argument impacted by the relocation '''
offset = 0 # TODO: current value of the argument impacted
from plasmasm.get_symbols import analyze_reloc
label, label_dif, offset, size = analyze_reloc(self,
reloc, offset, pos, self.bytelen)
# TODO: find which arg is impacted
# by computing: pos -= self.miasm.offset
for argname in ['simm', 'li']:
if hasattr(self.miasm, argname):
break
else:
log.info("Apply reloc '%s' on '%s'", label, self)
return
setattr(self.miasm, argname, label)
def is_symb(arg):
return type(arg) == dict and x86_afs.symb in arg and arg.get(x86_afs.ad, False) == False
class InstructionCFG(Instruction):
__slots__ = ('flow', 'dst')
def _set_flow(self):
if not self.miasm.breakflow(): self.flow = None
elif self.miasm.is_subcall(): self.flow = 'sub'
elif not self.miasm.dstflow(): self.flow = 'ret'
elif not self.miasm.splitflow(): self.flow = 'jmp'
elif self.miasm.dstflow(): self.flow = 'jcc'
else: NEVER
def _set_dst(self):
if self.flow is None:
dst = []
elif self.flow == 'ret':
dst = [None]
elif self.flow in [ 'sub', 'jmp', 'jcc' ]:
dst = self.miasm.getdstflow()
else:
raise ValueError("Flow %s unknown"%self.flow)
self.dst = dst
"""
# No PPC semantic in miasm1
from miasmX.arch import ppc_sem
from miasmX.expression import expression
class InstructionRW(InstructionCFG):
__slots__ = ('rw',)
def _set_rw(self):
r, w = get_rw(ppc_sem, self)
self.rw = (r, w)
def reg_name(self, r):
if isinstance(r, expression.ExprMem):
if r.segm:
return 'MEM'
else:
return str(r)
elif isinstance(r, expression.ExprId):
return r.name
else:
return r
reg_name = classmethod(reg_name)
""" | plasmasm/arch/PPC_MIASM.py | basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
if basedir == '': basedir = '.'
sys.path.append(basedir+'/miasmX')
from miasmX.arch.ppc_arch import ppc_mn
from miasmX.arch.ia32_arch import x86_afs
import logging
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("%(levelname)-5s: %(message)s"))
log = logging.getLogger("ppc_miasm")
log.addHandler(console_handler)
log.setLevel(logging.WARN)
from plasmasm.symbols import Line
class Instruction(Line):
__slots__ = ('section', 'offset', 'bytelen', 'miasm')
CPU = 'PPC'
def from_txt(self, txt):
''' text input, in assembly format '''
TODO
def from_bin(self, in_str, section):
''' binary input, in assembly format '''
attrib = {}
self.miasm = ppc_mn.dis(in_str, attrib)
self.section = section
self.offset = self.miasm.offset
self.bytelen = self.miasm.l
return self
def pack(self):
''' binary representation '''
TODO
def txt(self):
''' text output, to be used by an assembler '''
return str(self.miasm)
def labels(self):
''' labels that are referenced in the line '''
res = set()
for a in self.miasm.arg:
if x86_afs.symb in a:
res |= set(a[x86_afs.symb].keys())
return res
def opname(self):
return self.miasm.getname()
opname = property(opname)
# Methods for binary parser
def create_label_imm(self):
''' Replace immediate values that may be labels '''
# TODO
pass
def create_label_rel(self):
''' Replace relative addresses for call/branch '''
# TODO
pass
def apply_reloc(self, pos, reloc):
''' 'reloc' is a relocation at offset 'pos'
This function modifies the argument impacted by the relocation '''
offset = 0 # TODO: current value of the argument impacted
from plasmasm.get_symbols import analyze_reloc
label, label_dif, offset, size = analyze_reloc(self,
reloc, offset, pos, self.bytelen)
# TODO: find which arg is impacted
# by computing: pos -= self.miasm.offset
for argname in ['simm', 'li']:
if hasattr(self.miasm, argname):
break
else:
log.info("Apply reloc '%s' on '%s'", label, self)
return
setattr(self.miasm, argname, label)
def is_symb(arg):
return type(arg) == dict and x86_afs.symb in arg and arg.get(x86_afs.ad, False) == False
class InstructionCFG(Instruction):
__slots__ = ('flow', 'dst')
def _set_flow(self):
if not self.miasm.breakflow(): self.flow = None
elif self.miasm.is_subcall(): self.flow = 'sub'
elif not self.miasm.dstflow(): self.flow = 'ret'
elif not self.miasm.splitflow(): self.flow = 'jmp'
elif self.miasm.dstflow(): self.flow = 'jcc'
else: NEVER
def _set_dst(self):
if self.flow is None:
dst = []
elif self.flow == 'ret':
dst = [None]
elif self.flow in [ 'sub', 'jmp', 'jcc' ]:
dst = self.miasm.getdstflow()
else:
raise ValueError("Flow %s unknown"%self.flow)
self.dst = dst
"""
# No PPC semantic in miasm1
from miasmX.arch import ppc_sem
from miasmX.expression import expression
class InstructionRW(InstructionCFG):
__slots__ = ('rw',)
def _set_rw(self):
r, w = get_rw(ppc_sem, self)
self.rw = (r, w)
def reg_name(self, r):
if isinstance(r, expression.ExprMem):
if r.segm:
return 'MEM'
else:
return str(r)
elif isinstance(r, expression.ExprId):
return r.name
else:
return r
reg_name = classmethod(reg_name)
""" | 0.196788 | 0.185855 |
from vumi.config import (
ConfigText, ConfigInt, ConfigBool, ConfigClientEndpoint, ConfigDict,
ConfigFloat, ConfigClassName, ClientEndpointFallback)
from vumi.transports.smpp.iprocessors import (
IDeliveryReportProcessor, IDeliverShortMessageProcessor,
ISubmitShortMessageProcessor)
from vumi.codecs.ivumi_codecs import IVumiCodec
from vumi.transports.base import Transport
class SmppTransportConfig(Transport.CONFIG_CLASS):
twisted_endpoint = ConfigClientEndpoint(
'The SMPP endpoint to connect to.',
required=True, static=True,
fallbacks=[ClientEndpointFallback()])
initial_reconnect_delay = ConfigInt(
'How long (in seconds) to wait between reconnecting attempts. '
'Defaults to 5 seconds.', default=5, static=True)
throttle_delay = ConfigFloat(
"Delay (in seconds) before retrying a message after receiving "
"`ESME_RTHROTTLED` or `ESME_RMSGQFUL`.", default=0.1, static=True)
deliver_sm_decoding_error = ConfigText(
'The error to respond with when we were unable to decode all parts '
'of a PDU.', default='ESME_RDELIVERYFAILURE', static=True)
submit_sm_expiry = ConfigInt(
'How long (in seconds) to wait for the SMSC to return with a '
'`submit_sm_resp`. Defaults to 24 hours.',
default=(60 * 60 * 24), static=True)
third_party_id_expiry = ConfigInt(
'How long (in seconds) to keep 3rd party message IDs around to allow '
'for matching submit_sm_resp and delivery report messages. Defaults '
'to 1 week.',
default=(60 * 60 * 24 * 7), static=True)
redis_manager = ConfigDict(
'How to connect to Redis.', default={}, static=True)
split_bind_prefix = ConfigText(
"This is the Redis prefix to use for storing things like sequence "
"numbers and message ids for delivery report handling. It defaults "
"to `<system_id>@<transport_name>`. "
"This should *ONLY* be done for TX & RX since messages sent via "
"the TX bind are handled by the RX bind and they need to share the "
"same prefix for the lookup for message ids in delivery reports to "
"work.", default='', static=True)
codec_class = ConfigClassName(
'Which class should be used to handle character encoding/decoding. '
'MUST implement `IVumiCodec`.',
default='vumi.codecs.VumiCodec',
static=True, implements=IVumiCodec)
delivery_report_processor = ConfigClassName(
'Which delivery report processor to use. '
'MUST implement `IDeliveryReportProcessor`.',
default=('vumi.transports.smpp.processors.'
'DeliveryReportProcessor'),
static=True, implements=IDeliveryReportProcessor)
delivery_report_processor_config = ConfigDict(
'The configuration for the `delivery_report_processor`.',
default={}, static=True)
deliver_short_message_processor = ConfigClassName(
'Which deliver short message processor to use. '
'MUST implement `IDeliverShortMessageProcessor`.',
default='vumi.transports.smpp.processors.DeliverShortMessageProcessor',
static=True, implements=IDeliverShortMessageProcessor)
deliver_short_message_processor_config = ConfigDict(
'The configuration for the `deliver_short_message_processor`.',
default={}, static=True)
submit_short_message_processor = ConfigClassName(
'Which submit short message processor to use. '
'Should implements `ISubmitShortMessageProcessor`.',
default='vumi.transports.smpp.processors.SubmitShortMessageProcessor',
static=True, implements=ISubmitShortMessageProcessor)
submit_short_message_processor_config = ConfigDict(
'The configuration for the `submit_short_message_processor`.',
default={}, static=True)
system_id = ConfigText(
'User id used to connect to the SMPP server.', required=True,
static=True)
password = ConfigText(
'Password for the system id.', required=True, static=True)
system_type = ConfigText(
"Additional system metadata that is passed through to the SMPP "
"server on connect.", default="", static=True)
interface_version = ConfigText(
"SMPP protocol version. Default is '34' (i.e. version 3.4).",
default="34", static=True)
service_type = ConfigText(
'The SMPP service type.', default="", static=True)
address_range = ConfigText(
"Address range to receive. (SMSC-specific format, default empty.)",
default="", static=True)
dest_addr_ton = ConfigInt(
'Destination TON (type of number).', default=0, static=True)
dest_addr_npi = ConfigInt(
'Destination NPI (number plan identifier). '
'Default 1 (ISDN/E.164/E.163).', default=1, static=True)
source_addr_ton = ConfigInt(
'Source TON (type of number).', default=0, static=True)
source_addr_npi = ConfigInt(
'Source NPI (number plan identifier).', default=0, static=True)
registered_delivery = ConfigBool(
'Whether or not to request delivery reports. Default True.',
default=True, static=True)
smpp_bind_timeout = ConfigInt(
'How long (in seconds) to wait for a succesful bind. Default 30.',
default=30, static=True)
smpp_enquire_link_interval = ConfigInt(
"How long (in seconds) to delay before reconnecting to the server "
"after being disconnected. Some WASPs, e.g. Clickatell require a 30s "
"delay before reconnecting. In these cases a 45s "
"`initial_reconnect_delay` is recommended. Default 55.",
default=55, static=True)
mt_tps = ConfigInt(
'Mobile Terminated Transactions per Second. The Maximum Vumi '
'messages per second to attempt to put on the wire. '
'Defaults to 0 which means no throttling is applied. '
'(NOTE: 1 Vumi message may result in multiple PDUs)',
default=0, static=True, required=False)
# TODO: Deprecate these fields when confmodel#5 is done.
host = ConfigText(
"*DEPRECATED* 'host' and 'port' fields may be used in place of the"
" 'twisted_endpoint' field.", static=True)
port = ConfigInt(
"*DEPRECATED* 'host' and 'port' fields may be used in place of the"
" 'twisted_endpoint' field.", static=True) | vumi/transports/smpp/config.py | from vumi.config import (
ConfigText, ConfigInt, ConfigBool, ConfigClientEndpoint, ConfigDict,
ConfigFloat, ConfigClassName, ClientEndpointFallback)
from vumi.transports.smpp.iprocessors import (
IDeliveryReportProcessor, IDeliverShortMessageProcessor,
ISubmitShortMessageProcessor)
from vumi.codecs.ivumi_codecs import IVumiCodec
from vumi.transports.base import Transport
class SmppTransportConfig(Transport.CONFIG_CLASS):
twisted_endpoint = ConfigClientEndpoint(
'The SMPP endpoint to connect to.',
required=True, static=True,
fallbacks=[ClientEndpointFallback()])
initial_reconnect_delay = ConfigInt(
'How long (in seconds) to wait between reconnecting attempts. '
'Defaults to 5 seconds.', default=5, static=True)
throttle_delay = ConfigFloat(
"Delay (in seconds) before retrying a message after receiving "
"`ESME_RTHROTTLED` or `ESME_RMSGQFUL`.", default=0.1, static=True)
deliver_sm_decoding_error = ConfigText(
'The error to respond with when we were unable to decode all parts '
'of a PDU.', default='ESME_RDELIVERYFAILURE', static=True)
submit_sm_expiry = ConfigInt(
'How long (in seconds) to wait for the SMSC to return with a '
'`submit_sm_resp`. Defaults to 24 hours.',
default=(60 * 60 * 24), static=True)
third_party_id_expiry = ConfigInt(
'How long (in seconds) to keep 3rd party message IDs around to allow '
'for matching submit_sm_resp and delivery report messages. Defaults '
'to 1 week.',
default=(60 * 60 * 24 * 7), static=True)
redis_manager = ConfigDict(
'How to connect to Redis.', default={}, static=True)
split_bind_prefix = ConfigText(
"This is the Redis prefix to use for storing things like sequence "
"numbers and message ids for delivery report handling. It defaults "
"to `<system_id>@<transport_name>`. "
"This should *ONLY* be done for TX & RX since messages sent via "
"the TX bind are handled by the RX bind and they need to share the "
"same prefix for the lookup for message ids in delivery reports to "
"work.", default='', static=True)
codec_class = ConfigClassName(
'Which class should be used to handle character encoding/decoding. '
'MUST implement `IVumiCodec`.',
default='vumi.codecs.VumiCodec',
static=True, implements=IVumiCodec)
delivery_report_processor = ConfigClassName(
'Which delivery report processor to use. '
'MUST implement `IDeliveryReportProcessor`.',
default=('vumi.transports.smpp.processors.'
'DeliveryReportProcessor'),
static=True, implements=IDeliveryReportProcessor)
delivery_report_processor_config = ConfigDict(
'The configuration for the `delivery_report_processor`.',
default={}, static=True)
deliver_short_message_processor = ConfigClassName(
'Which deliver short message processor to use. '
'MUST implement `IDeliverShortMessageProcessor`.',
default='vumi.transports.smpp.processors.DeliverShortMessageProcessor',
static=True, implements=IDeliverShortMessageProcessor)
deliver_short_message_processor_config = ConfigDict(
'The configuration for the `deliver_short_message_processor`.',
default={}, static=True)
submit_short_message_processor = ConfigClassName(
'Which submit short message processor to use. '
'Should implements `ISubmitShortMessageProcessor`.',
default='vumi.transports.smpp.processors.SubmitShortMessageProcessor',
static=True, implements=ISubmitShortMessageProcessor)
submit_short_message_processor_config = ConfigDict(
'The configuration for the `submit_short_message_processor`.',
default={}, static=True)
system_id = ConfigText(
'User id used to connect to the SMPP server.', required=True,
static=True)
password = ConfigText(
'Password for the system id.', required=True, static=True)
system_type = ConfigText(
"Additional system metadata that is passed through to the SMPP "
"server on connect.", default="", static=True)
interface_version = ConfigText(
"SMPP protocol version. Default is '34' (i.e. version 3.4).",
default="34", static=True)
service_type = ConfigText(
'The SMPP service type.', default="", static=True)
address_range = ConfigText(
"Address range to receive. (SMSC-specific format, default empty.)",
default="", static=True)
dest_addr_ton = ConfigInt(
'Destination TON (type of number).', default=0, static=True)
dest_addr_npi = ConfigInt(
'Destination NPI (number plan identifier). '
'Default 1 (ISDN/E.164/E.163).', default=1, static=True)
source_addr_ton = ConfigInt(
'Source TON (type of number).', default=0, static=True)
source_addr_npi = ConfigInt(
'Source NPI (number plan identifier).', default=0, static=True)
registered_delivery = ConfigBool(
'Whether or not to request delivery reports. Default True.',
default=True, static=True)
smpp_bind_timeout = ConfigInt(
'How long (in seconds) to wait for a succesful bind. Default 30.',
default=30, static=True)
smpp_enquire_link_interval = ConfigInt(
"How long (in seconds) to delay before reconnecting to the server "
"after being disconnected. Some WASPs, e.g. Clickatell require a 30s "
"delay before reconnecting. In these cases a 45s "
"`initial_reconnect_delay` is recommended. Default 55.",
default=55, static=True)
mt_tps = ConfigInt(
'Mobile Terminated Transactions per Second. The Maximum Vumi '
'messages per second to attempt to put on the wire. '
'Defaults to 0 which means no throttling is applied. '
'(NOTE: 1 Vumi message may result in multiple PDUs)',
default=0, static=True, required=False)
# TODO: Deprecate these fields when confmodel#5 is done.
host = ConfigText(
"*DEPRECATED* 'host' and 'port' fields may be used in place of the"
" 'twisted_endpoint' field.", static=True)
port = ConfigInt(
"*DEPRECATED* 'host' and 'port' fields may be used in place of the"
" 'twisted_endpoint' field.", static=True) | 0.578448 | 0.165661 |
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore import permissions
from Products.CMFCore.utils import getToolByName
from bika.lims.permissions import AddAttachment
def upgrade(tool):
# Hack prevent out-of-date upgrading
# Related: PR #1484
# https://github.com/bikalabs/Bika-LIMS/pull/1484
from bika.lims.upgrade import skip_pre315
if skip_pre315(aq_parent(aq_inner(tool))):
return True
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
# Add new Client role
role = "Client"
if role not in portal.acl_users.portal_role_manager.listRoleIds():
portal.acl_users.portal_role_manager.addRole(role)
portal._addRole(role)
# Add the role Client role to Clients group
portal.portal_groups.editGroup('Clients', roles=['Member',
'Authenticated',
'Client'])
# Add all Client contacts to Clients group
for client in portal.clients.values():
for contact in client.getContacts():
user = portal.portal_membership.getMemberById(contact.getUsername())
if user is not None:
portal.portal_groups.addPrincipalToGroup(user.getUserName(),
"Clients")
# Add AddAttachment permission to Clients
mp = portal.manage_permission
mp(AddAttachment, ['Manager', 'LabManager', 'Owner' 'Analyst', 'LabClerk', 'Client', 'Sampler'], 0)
# Add Analysis Services View permission to Clients
mp = portal.bika_setup.bika_analysisservices.manage_permission
mp('Access contents information', ['Authenticated', 'Analyst', 'Client'], 1)
mp(permissions.View, ['Authenticated', 'Analyst', 'Client'], 1)
portal.bika_setup.bika_analysisservices.reindexObject()
for obj in portal.bika_setup.bika_analysisservices.objectValues():
mp = obj.manage_permission
mp(permissions.View, ['Manager', 'LabManager', 'Analyst', 'Client'], 0)
mp('Access contents information', ['Manager', 'LabManager', 'Member', 'LabClerk', 'Analyst', 'Client', 'Sampler', 'Preserver', 'Owner'], 0)
obj.reindexObject()
# Grant AttachmentType view access to Clients
mp = portal.bika_setup.bika_attachmenttypes.manage_permission
mp('Access contents information', ['Authenticated', 'Analyst', 'Client'], 1)
mp(permissions.View, ['Authenticated', 'Analyst', 'Client'], 1)
portal.bika_setup.bika_attachmenttypes.reindexObject()
wf = getToolByName(portal, 'portal_workflow')
setup.runImportStepFromProfile('profile-bika.lims:default', 'workflow-csv')
wf.updateRoleMappings()
return True | bika/lims/upgrade/to3002.py | from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.CMFCore import permissions
from Products.CMFCore.utils import getToolByName
from bika.lims.permissions import AddAttachment
def upgrade(tool):
# Hack prevent out-of-date upgrading
# Related: PR #1484
# https://github.com/bikalabs/Bika-LIMS/pull/1484
from bika.lims.upgrade import skip_pre315
if skip_pre315(aq_parent(aq_inner(tool))):
return True
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
# Add new Client role
role = "Client"
if role not in portal.acl_users.portal_role_manager.listRoleIds():
portal.acl_users.portal_role_manager.addRole(role)
portal._addRole(role)
# Add the role Client role to Clients group
portal.portal_groups.editGroup('Clients', roles=['Member',
'Authenticated',
'Client'])
# Add all Client contacts to Clients group
for client in portal.clients.values():
for contact in client.getContacts():
user = portal.portal_membership.getMemberById(contact.getUsername())
if user is not None:
portal.portal_groups.addPrincipalToGroup(user.getUserName(),
"Clients")
# Add AddAttachment permission to Clients
mp = portal.manage_permission
mp(AddAttachment, ['Manager', 'LabManager', 'Owner' 'Analyst', 'LabClerk', 'Client', 'Sampler'], 0)
# Add Analysis Services View permission to Clients
mp = portal.bika_setup.bika_analysisservices.manage_permission
mp('Access contents information', ['Authenticated', 'Analyst', 'Client'], 1)
mp(permissions.View, ['Authenticated', 'Analyst', 'Client'], 1)
portal.bika_setup.bika_analysisservices.reindexObject()
for obj in portal.bika_setup.bika_analysisservices.objectValues():
mp = obj.manage_permission
mp(permissions.View, ['Manager', 'LabManager', 'Analyst', 'Client'], 0)
mp('Access contents information', ['Manager', 'LabManager', 'Member', 'LabClerk', 'Analyst', 'Client', 'Sampler', 'Preserver', 'Owner'], 0)
obj.reindexObject()
# Grant AttachmentType view access to Clients
mp = portal.bika_setup.bika_attachmenttypes.manage_permission
mp('Access contents information', ['Authenticated', 'Analyst', 'Client'], 1)
mp(permissions.View, ['Authenticated', 'Analyst', 'Client'], 1)
portal.bika_setup.bika_attachmenttypes.reindexObject()
wf = getToolByName(portal, 'portal_workflow')
setup.runImportStepFromProfile('profile-bika.lims:default', 'workflow-csv')
wf.updateRoleMappings()
return True | 0.619701 | 0.150091 |
import requests
from datetime import date
class Stoncks:
base_url = "https://www.alphavantage.co/query?"
api_key = "API_KEY"
def __init__(self, function, crypto, base_currency, analysis):
self.function = function
self.crypto = crypto
self.base_currency = base_currency
self.analysis = analysis
def send(self):
response = requests.get(f'{self.base_url}function={self.function}&symbol={self.crypto}&market={self.base_currency}&apikey={self.api_key}')
response = response.json()
dates = list(response["Time Series (Digital Currency Daily)"])
if self.analysis == 'st':
dates = dates[0:30]
dates = dates[::-1]
metrics = self.get_metrics(response, dates)
return {
"datetime": dates,
"high": metrics['high'][::-1],
"low": metrics['low'][::-1],
"open": metrics['open_values'][::-1],
"close": metrics['close'][::-1],
"volume": metrics['volume'][::-1],
"market_cap": metrics['cap'][::-1]
}
def get_metrics(self, response, dates):
metrics = {}
metrics['high'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"2a. high ({self.base_currency})"])) for date in dates]
metrics['low'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"3a. low ({self.base_currency})"])) for date in dates]
metrics['close'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"4a. close ({self.base_currency})"])) for date in dates]
metrics['open_values'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"1a. open ({self.base_currency})"])) for date in dates]
metrics['volume'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"5. volume"])) for date in dates]
metrics['cap'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"6. market cap (USD)"])) for date in dates]
return metrics | forevis/crypto/Classes/Stoncks.py | import requests
from datetime import date
class Stoncks:
base_url = "https://www.alphavantage.co/query?"
api_key = "API_KEY"
def __init__(self, function, crypto, base_currency, analysis):
self.function = function
self.crypto = crypto
self.base_currency = base_currency
self.analysis = analysis
def send(self):
response = requests.get(f'{self.base_url}function={self.function}&symbol={self.crypto}&market={self.base_currency}&apikey={self.api_key}')
response = response.json()
dates = list(response["Time Series (Digital Currency Daily)"])
if self.analysis == 'st':
dates = dates[0:30]
dates = dates[::-1]
metrics = self.get_metrics(response, dates)
return {
"datetime": dates,
"high": metrics['high'][::-1],
"low": metrics['low'][::-1],
"open": metrics['open_values'][::-1],
"close": metrics['close'][::-1],
"volume": metrics['volume'][::-1],
"market_cap": metrics['cap'][::-1]
}
def get_metrics(self, response, dates):
metrics = {}
metrics['high'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"2a. high ({self.base_currency})"])) for date in dates]
metrics['low'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"3a. low ({self.base_currency})"])) for date in dates]
metrics['close'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"4a. close ({self.base_currency})"])) for date in dates]
metrics['open_values'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"1a. open ({self.base_currency})"])) for date in dates]
metrics['volume'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"5. volume"])) for date in dates]
metrics['cap'] = [int(float(response["Time Series (Digital Currency Daily)"][date][f"6. market cap (USD)"])) for date in dates]
return metrics | 0.61451 | 0.213224 |
from __future__ import print_function
import sys
import numpy as np
#This code calculates the aproximate memory footprint of PMPIC (total and per process)
#It can thus be used to choose a value of maxparcels to maximise memory usage
#number of grid/parcel variables
n_grids=32
n_parcels=38
#number of bytes in a variable
sizeof=8
#default values (can be overridden)
ppn=24 #processes per node
mpn=64 #memory per node (GB)
#parse an input value of the form "quantity=number" to return the number
def getvalue(arg):
loc=arg.find("=")
if loc == -1:
print("Warning: Cannot parse arguent '%s'"%arg)
return None
num=arg[loc+1:]
try:
num=int(num)
return num
except:
print("Warning: cound not convert %s value '%s' to a string"%(arg[0:loc],num))
return None
def getdims(nprocs):
#first we want to factorise nprocs
n=nprocs
factors=[]
i=2
while n>=i:
if n%i==0:
factors.append(i)
n /= i
else:
i+=1
#print("Factors are", factors)
dims=[1,1]
while len(factors) > 0:
val = factors.pop()
dims.sort()
dims[0] *= val
dims.sort()
return dims
#command line arguments:
#nprocs - number of processes
nprocs=None
#ngrid - number of grid cells (nx=ny=nz=ngrid)
ngrid=None
#nx - number of cells in x
nx=None
#ny - number of cells in y
ny=None
#nz - number of cells in z
nz=None
#ppn - processes per node
#mpn - memory per node
#get the command line arguments and remove the first one (script name)
args=sys.argv
args.pop(0)
if len(args) == 0:
print('Error: no command line arguments supplied')
print("\nUsage: 'planner.py [args]'")
print("\nPossible arguments:")
print("nprocs - number of processes used (REQUIRED)")
print("ngrid - number of grid cells in each direction*")
print("nx - number of cells in x direction*")
print("ny - number of cells in y direction*")
print("nz - number of cells in z direction*")
print("ppn - number of processes per node (default=24)")
print("mpn - memory per node (default 64GB)")
print("* either n or nx, ny and nx must be specified")
print("\nExample usage: 'planner.py nprocs=4 ngrid=128'")
sys.exit()
#parse arguments:
print("\nThe following options were registered:")
for arg in args:
if "nprocs=" in arg:
print(arg)
nprocs=getvalue(arg)
args.remove(arg)
for arg in args:
if "ngrid=" in arg:
print(arg)
ngrid=getvalue(arg)
nx=ngrid
ny=ngrid
nz=ngrid
args.remove(arg)
for arg in args:
if "nx=" in arg:
print(arg)
nx=getvalue(arg)
args.remove(arg)
for arg in args:
if "ny=" in arg:
print(arg)
ny=getvalue(arg)
args.remove(arg)
for arg in args:
if "nz=" in arg:
print(arg)
nz=getvalue(arg)
args.remove(arg)
for arg in args:
if "ppn=" in arg:
print(arg)
ppn=getvalue(arg)
args.remove(arg)
for arg in args:
if "mpn=" in arg:
print(arg)
mpn=getvalue(arg)
args.remove(arg)
if len(args) > 0:
print("\nWarning: There are un-parsed arguments:")
for arg in args:
print("'%s'"%arg)
if nprocs==None:
print('Error: nprocs must defined')
sys.exit()
if ngrid == None:
if nx == None or ny==None or nz==None:
print("Error: either ngrid or nx, ny and nz must be defined")
sys.exit()
#determine nodes used:
nnodes=int(np.ceil(float(nprocs)/ppn))
#determine the decomposition of the grid between processes (should return the same result as MPI_Dims_create)
dims = getdims(nprocs)
print("\n################################################################################")
#print("01234567890123456789012345678901234567890123456789012345678901234567890123456789")
print("# Parallel Decomposition #")
print("################################################################################")
print("# #")
print("# Number of Processes = %5d #"%nprocs)
print("# Number of nodes = %4d #"%nnodes)
print("# Processes in x, y and z = %3d x %3d x %3d #"%(dims[0],dims[1],1))
#print("################################################################################")
#print("\n################################################################################")
#print("01234567890123456789012345678901234567890123456789012345678901234567890123456789")
#print("# Grids #")
#print("################################################################################")
if nx%dims[0] !=0 or ny%dims[1] !=0:
print("Error: MPI cannot divide the grids evenly between processes!")
sys.exit()
nxlocal = nx/dims[0]
nylocal = ny/dims[1]
print("# Global gridsizes (nx,ny,nz) = (%4d,%4d,%4d) #"%(nx,ny,nz))
print("# Local gridsizes = (%3d,%3d,%3d) #"%(nxlocal,nylocal,nz))
print("# Local gridsizes (inc halos) = (%3d,%3d,%3d) #"%(nxlocal+4,nylocal+4,nz+1))
print("# #")
print("################################################################################")
#print("01234567890123456789012345678901234567890123456789012345678901234567890123456789")
print("# Memory #")
print("################################################################################")
print("# #")
print("# Memory per node = %6.2f GB #"%mpn)
if nprocs<=ppn:
mperproc=mpn/float(nprocs)
else:
mperproc = mpn/float(ppn)
print("# Memory per process = %5.2f GB #"%mperproc)
print("# #")
print("# Assuming 10% of the memory is required by PMPIC and temporary variables: #")
mperproc *= 0.9
print("# Memory for parcels and grids = %5.2f GB #"%mperproc)
gridsize=(nxlocal+4)*(nylocal+4)*(nz+1)*sizeof
grids=gridsize*n_grids
print("# #")
print("# Grids: #")
print("# Number of gridded variables = %2d #"%n_grids)
print("# A single gridded variable takes up %7.2f MB #"%(gridsize/1000000.))
print("# All gridded variables take up %7.2f MB #"%(grids/1000000.))
# we now calculate OMP_Stacksize requirements
stacksize=int(np.ceil(gridsize*14./1E6))
print("# Recommended minimum OMP_STACKSIZE =%4dM #"%(stacksize))
if (grids/1E9 > mperproc) :
print('Error: insufficient memory for grids')
sys.exit()
mperproc = mperproc - grids/1E9
numparcels = mperproc*1E9/float(n_parcels)/float(sizeof)
print("# #")
print("# Parcels: #")
print("# Available memory for parcels = %5.2f GB #"%(mperproc))
print("# Number of parcel variables = %2d #"%n_parcels)
print("# Therefore a single parcel takes up %3d Bytes #"%(sizeof*n_parcels))
print("# Therefore each process can have up to %10d parcels #"%(numparcels))
print("# Maximum parcel count for simulation = %12d #"%(numparcels*nprocs))
totalparcels=numparcels*nprocs
npercell = totalparcels/nx/ny/nz
print("# Maximum mean number of parcels per cell = %5.1f (%6.2f^3) #"%(npercell,np.power(npercell,1./3.)))
print("# #")
print("################################################################################\n") | planner.py | from __future__ import print_function
import sys
import numpy as np
#This code calculates the aproximate memory footprint of PMPIC (total and per process)
#It can thus be used to choose a value of maxparcels to maximise memory usage
#number of grid/parcel variables
n_grids=32
n_parcels=38
#number of bytes in a variable
sizeof=8
#default values (can be overridden)
ppn=24 #processes per node
mpn=64 #memory per node (GB)
#parse an input value of the form "quantity=number" to return the number
def getvalue(arg):
loc=arg.find("=")
if loc == -1:
print("Warning: Cannot parse arguent '%s'"%arg)
return None
num=arg[loc+1:]
try:
num=int(num)
return num
except:
print("Warning: cound not convert %s value '%s' to a string"%(arg[0:loc],num))
return None
def getdims(nprocs):
#first we want to factorise nprocs
n=nprocs
factors=[]
i=2
while n>=i:
if n%i==0:
factors.append(i)
n /= i
else:
i+=1
#print("Factors are", factors)
dims=[1,1]
while len(factors) > 0:
val = factors.pop()
dims.sort()
dims[0] *= val
dims.sort()
return dims
#command line arguments:
#nprocs - number of processes
nprocs=None
#ngrid - number of grid cells (nx=ny=nz=ngrid)
ngrid=None
#nx - number of cells in x
nx=None
#ny - number of cells in y
ny=None
#nz - number of cells in z
nz=None
#ppn - processes per node
#mpn - memory per node
#get the command line arguments and remove the first one (script name)
args=sys.argv
args.pop(0)
if len(args) == 0:
print('Error: no command line arguments supplied')
print("\nUsage: 'planner.py [args]'")
print("\nPossible arguments:")
print("nprocs - number of processes used (REQUIRED)")
print("ngrid - number of grid cells in each direction*")
print("nx - number of cells in x direction*")
print("ny - number of cells in y direction*")
print("nz - number of cells in z direction*")
print("ppn - number of processes per node (default=24)")
print("mpn - memory per node (default 64GB)")
print("* either n or nx, ny and nx must be specified")
print("\nExample usage: 'planner.py nprocs=4 ngrid=128'")
sys.exit()
#parse arguments:
print("\nThe following options were registered:")
for arg in args:
if "nprocs=" in arg:
print(arg)
nprocs=getvalue(arg)
args.remove(arg)
for arg in args:
if "ngrid=" in arg:
print(arg)
ngrid=getvalue(arg)
nx=ngrid
ny=ngrid
nz=ngrid
args.remove(arg)
for arg in args:
if "nx=" in arg:
print(arg)
nx=getvalue(arg)
args.remove(arg)
for arg in args:
if "ny=" in arg:
print(arg)
ny=getvalue(arg)
args.remove(arg)
for arg in args:
if "nz=" in arg:
print(arg)
nz=getvalue(arg)
args.remove(arg)
for arg in args:
if "ppn=" in arg:
print(arg)
ppn=getvalue(arg)
args.remove(arg)
for arg in args:
if "mpn=" in arg:
print(arg)
mpn=getvalue(arg)
args.remove(arg)
if len(args) > 0:
print("\nWarning: There are un-parsed arguments:")
for arg in args:
print("'%s'"%arg)
if nprocs==None:
print('Error: nprocs must defined')
sys.exit()
if ngrid == None:
if nx == None or ny==None or nz==None:
print("Error: either ngrid or nx, ny and nz must be defined")
sys.exit()
#determine nodes used:
nnodes=int(np.ceil(float(nprocs)/ppn))
#determine the decomposition of the grid between processes (should return the same result as MPI_Dims_create)
dims = getdims(nprocs)
print("\n################################################################################")
#print("01234567890123456789012345678901234567890123456789012345678901234567890123456789")
print("# Parallel Decomposition #")
print("################################################################################")
print("# #")
print("# Number of Processes = %5d #"%nprocs)
print("# Number of nodes = %4d #"%nnodes)
print("# Processes in x, y and z = %3d x %3d x %3d #"%(dims[0],dims[1],1))
#print("################################################################################")
#print("\n################################################################################")
#print("01234567890123456789012345678901234567890123456789012345678901234567890123456789")
#print("# Grids #")
#print("################################################################################")
if nx%dims[0] !=0 or ny%dims[1] !=0:
print("Error: MPI cannot divide the grids evenly between processes!")
sys.exit()
nxlocal = nx/dims[0]
nylocal = ny/dims[1]
print("# Global gridsizes (nx,ny,nz) = (%4d,%4d,%4d) #"%(nx,ny,nz))
print("# Local gridsizes = (%3d,%3d,%3d) #"%(nxlocal,nylocal,nz))
print("# Local gridsizes (inc halos) = (%3d,%3d,%3d) #"%(nxlocal+4,nylocal+4,nz+1))
print("# #")
print("################################################################################")
#print("01234567890123456789012345678901234567890123456789012345678901234567890123456789")
print("# Memory #")
print("################################################################################")
print("# #")
print("# Memory per node = %6.2f GB #"%mpn)
if nprocs<=ppn:
mperproc=mpn/float(nprocs)
else:
mperproc = mpn/float(ppn)
print("# Memory per process = %5.2f GB #"%mperproc)
print("# #")
print("# Assuming 10% of the memory is required by PMPIC and temporary variables: #")
mperproc *= 0.9
print("# Memory for parcels and grids = %5.2f GB #"%mperproc)
gridsize=(nxlocal+4)*(nylocal+4)*(nz+1)*sizeof
grids=gridsize*n_grids
print("# #")
print("# Grids: #")
print("# Number of gridded variables = %2d #"%n_grids)
print("# A single gridded variable takes up %7.2f MB #"%(gridsize/1000000.))
print("# All gridded variables take up %7.2f MB #"%(grids/1000000.))
# we now calculate OMP_Stacksize requirements
stacksize=int(np.ceil(gridsize*14./1E6))
print("# Recommended minimum OMP_STACKSIZE =%4dM #"%(stacksize))
if (grids/1E9 > mperproc) :
print('Error: insufficient memory for grids')
sys.exit()
mperproc = mperproc - grids/1E9
numparcels = mperproc*1E9/float(n_parcels)/float(sizeof)
print("# #")
print("# Parcels: #")
print("# Available memory for parcels = %5.2f GB #"%(mperproc))
print("# Number of parcel variables = %2d #"%n_parcels)
print("# Therefore a single parcel takes up %3d Bytes #"%(sizeof*n_parcels))
print("# Therefore each process can have up to %10d parcels #"%(numparcels))
print("# Maximum parcel count for simulation = %12d #"%(numparcels*nprocs))
totalparcels=numparcels*nprocs
npercell = totalparcels/nx/ny/nz
print("# Maximum mean number of parcels per cell = %5.1f (%6.2f^3) #"%(npercell,np.power(npercell,1./3.)))
print("# #")
print("################################################################################\n") | 0.181662 | 0.245362 |
from graphgen import _helpers
from graphgen.analysis import edge_num_distr
import networkx as nx
import random
import numpy as np
import math
UNIFORM = -1
NORMAL = -2
def naive_random_graph(num_vertices, num_edges=UNIFORM, seed=None):
"""
Generate a random undirected graph in a naive way.
First, a random number of edges is generated from a uniform or normal distribution (see below) if this one
('num_edges') is not specified in parameter. Second, the list of all edges is generated, suffled and the 'num_edges'
first edges are selected. Third, the adjacency matrix is created thanks to these edges and then the NetworkX graph.
You can specify the number of edges ('num_edges') or choose to generate it from a uniform or normal distribution
(with graph_generators.UNIFORM and graph_generators.NORMAL). The normal distribution will give better results
because it fits with the real distribution of numbers of edges of all different graphs with 'num_vertices' vertices.
:num_vertices: The number of desired vertices.
:num_edges: The number of the desired edges. If 'num_edges' is set to graph_generators.UNIFORM, then the number of
edges will be randomly generated from a uniform distribution. If it set to graph_generators.NORMAL, then this
number will be generated from a normal distribution. The number of edges generated will be between 0 and
n * (n - 1) / 2, where n is 'num_vertices'.
:seed: The seed of the random generator for the reproducibility.
:return: A random NetworkX graph.
"""
# Set the seed.
if seed:
random.seed(seed)
# The maximum number of edges.
edge_max_num = _helpers.compute_edge_max_num(num_vertices)
if not(0 <= num_edges <= edge_max_num) and (num_edges != UNIFORM) and (num_edges != NORMAL):
raise ValueError("Error: 'num_edges' must be between -1 and n * (n - 1) / 2, where n is the number of vertices "
"('num_vertices').")
# Generate the number of edges.
if num_edges == UNIFORM:
num_edges = generate_uniform_num_edges(num_vertices, seed=seed)
elif num_edges == NORMAL:
num_edges = generate_normal_num_edges(num_vertices, seed=seed)
# The list of indexes of all edges.
edge_indexes = list(range(edge_max_num))
# Randomly select 'num_edges' edges.
random.shuffle(edge_indexes)
selected_edges = edge_indexes[:num_edges]
# Create the adjacency matrix.
adjacency_matrix = np.zeros((num_vertices, num_vertices), dtype=int)
for edge_index in selected_edges:
# 'edge_index' is an index of the upper triangle of the adjacency matrix
# Get the coordinates from this index.
# Source: https://gist.github.com/PhDP/2358809
i = int(-0.5 + 0.5 * math.sqrt(1 + 8 * edge_index)) + 1
j = int((i + 1) * (2 - i) / 2 + edge_index) - 1
adjacency_matrix[i][j] = 1
adjacency_matrix[j][i] = 1
return nx.from_numpy_matrix(adjacency_matrix)
def gnm_random_graph(num_vertices, num_edges=UNIFORM, seed=None):
"""
Call the 'gnm_random_graph' function from NetworkX, except that this function generates a random number of edges
from a uniform or normal distribution (see below) if this one ('num_edges') is not specified in parameter.
You can specify the number of edges ('num_edges') or choose to generate it from a uniform or normal distribution
(with graph_generators.UNIFORM and graph_generators.NORMAL). The normal distribution will give better results
because it fits with the real distribution of numbers of edges of all different graphs with 'num_vertices' vertices.
:num_vertices: The number of desired vertices.
:num_edges: The number of the desired edges. If 'num_edges' is set to graph_generators.UNIFORM, then the number of
edges will be randomly generated from a uniform distribution. If it set to graph_generators.NORMAL, then this
number will be generated from a normal distribution. The number of edges generated will be between 0 and
n * (n - 1) / 2, where n is 'num_vertices'.
:seed: The seed of the random generator for the reproducibility.
:return: A random NetworkX graph.
"""
# The maximum number of edges.
edge_max_num = _helpers.compute_edge_max_num(num_vertices)
if not(0 <= num_edges <= edge_max_num) and (num_edges != UNIFORM) and (num_edges != NORMAL):
raise ValueError("Error: 'num_edges' must be between -1 and n * (n - 1) / 2, where n is the number of vertices "
"('num_vertices').")
# Generate the number of edges.
if num_edges == UNIFORM:
num_edges = generate_uniform_num_edges(num_vertices, seed=seed)
elif num_edges == NORMAL:
num_edges = generate_normal_num_edges(num_vertices, seed=seed)
return nx.gnm_random_graph(num_vertices, num_edges, seed=seed)
def generate_uniform_num_edges(num_vertices, seed=None):
"""
Generate a number of edges from a uniform distribution between 0 and the maximum number of edges.
:num_vertices: The number of vertices.
:seed: The seed of the random generator for the reproducibility.
:return: The number of edges generated.
"""
# Set the seed.
if seed:
random.seed(seed)
# The maximum number of edges.
edge_max_num = _helpers.compute_edge_max_num(num_vertices)
# Generate the number of edges.
num_edges = random.randint(0, edge_max_num)
return num_edges
def generate_normal_num_edges(num_vertices, seed=None):
"""
Generate a number of edges from a normal distribution between 0 and the maximum number of edges. The mean and the
standard deviation of the normal distribution are automaticlly computed from the number of vertices (thanks to the
distribution of numbers of edges of all different graphs with 'num_vertices' vertices).
:num_vertices: The number of vertices.
:seed: The seed of the random generator for the reproducibility.
:return: The number of edges generated.
"""
# Compute the mean and standard deviation of numbers of edges of all graphs with 'num_vertices' vertices.
mean = edge_num_distr.compute_mean(num_vertices)
std = edge_num_distr.compute_std(num_vertices)
# Set the seed.
if seed:
np.random.seed(seed)
# The maximum number of edges.
edge_max_num = _helpers.compute_edge_max_num(num_vertices)
# Generate the number of edges.
num_edges = round(np.random.normal(mean, std))
if num_edges < 0:
num_edges = 0
elif num_edges > edge_max_num:
num_edges = edge_max_num
return num_edges
if __name__ == '__main__':
import matplotlib.pyplot as plt
# Parameters.
num_vertices = 4
seed = 42
# Generate a graph.
graph = naive_random_graph(num_vertices, seed=seed)
nx.draw(graph)
plt.show() | graphgen/graph_generators.py | from graphgen import _helpers
from graphgen.analysis import edge_num_distr
import networkx as nx
import random
import numpy as np
import math
UNIFORM = -1
NORMAL = -2
def naive_random_graph(num_vertices, num_edges=UNIFORM, seed=None):
"""
Generate a random undirected graph in a naive way.
First, a random number of edges is generated from a uniform or normal distribution (see below) if this one
('num_edges') is not specified in parameter. Second, the list of all edges is generated, suffled and the 'num_edges'
first edges are selected. Third, the adjacency matrix is created thanks to these edges and then the NetworkX graph.
You can specify the number of edges ('num_edges') or choose to generate it from a uniform or normal distribution
(with graph_generators.UNIFORM and graph_generators.NORMAL). The normal distribution will give better results
because it fits with the real distribution of numbers of edges of all different graphs with 'num_vertices' vertices.
:num_vertices: The number of desired vertices.
:num_edges: The number of the desired edges. If 'num_edges' is set to graph_generators.UNIFORM, then the number of
edges will be randomly generated from a uniform distribution. If it set to graph_generators.NORMAL, then this
number will be generated from a normal distribution. The number of edges generated will be between 0 and
n * (n - 1) / 2, where n is 'num_vertices'.
:seed: The seed of the random generator for the reproducibility.
:return: A random NetworkX graph.
"""
# Set the seed.
if seed:
random.seed(seed)
# The maximum number of edges.
edge_max_num = _helpers.compute_edge_max_num(num_vertices)
if not(0 <= num_edges <= edge_max_num) and (num_edges != UNIFORM) and (num_edges != NORMAL):
raise ValueError("Error: 'num_edges' must be between -1 and n * (n - 1) / 2, where n is the number of vertices "
"('num_vertices').")
# Generate the number of edges.
if num_edges == UNIFORM:
num_edges = generate_uniform_num_edges(num_vertices, seed=seed)
elif num_edges == NORMAL:
num_edges = generate_normal_num_edges(num_vertices, seed=seed)
# The list of indexes of all edges.
edge_indexes = list(range(edge_max_num))
# Randomly select 'num_edges' edges.
random.shuffle(edge_indexes)
selected_edges = edge_indexes[:num_edges]
# Create the adjacency matrix.
adjacency_matrix = np.zeros((num_vertices, num_vertices), dtype=int)
for edge_index in selected_edges:
# 'edge_index' is an index of the upper triangle of the adjacency matrix
# Get the coordinates from this index.
# Source: https://gist.github.com/PhDP/2358809
i = int(-0.5 + 0.5 * math.sqrt(1 + 8 * edge_index)) + 1
j = int((i + 1) * (2 - i) / 2 + edge_index) - 1
adjacency_matrix[i][j] = 1
adjacency_matrix[j][i] = 1
return nx.from_numpy_matrix(adjacency_matrix)
def gnm_random_graph(num_vertices, num_edges=UNIFORM, seed=None):
"""
Call the 'gnm_random_graph' function from NetworkX, except that this function generates a random number of edges
from a uniform or normal distribution (see below) if this one ('num_edges') is not specified in parameter.
You can specify the number of edges ('num_edges') or choose to generate it from a uniform or normal distribution
(with graph_generators.UNIFORM and graph_generators.NORMAL). The normal distribution will give better results
because it fits with the real distribution of numbers of edges of all different graphs with 'num_vertices' vertices.
:num_vertices: The number of desired vertices.
:num_edges: The number of the desired edges. If 'num_edges' is set to graph_generators.UNIFORM, then the number of
edges will be randomly generated from a uniform distribution. If it set to graph_generators.NORMAL, then this
number will be generated from a normal distribution. The number of edges generated will be between 0 and
n * (n - 1) / 2, where n is 'num_vertices'.
:seed: The seed of the random generator for the reproducibility.
:return: A random NetworkX graph.
"""
# The maximum number of edges.
edge_max_num = _helpers.compute_edge_max_num(num_vertices)
if not(0 <= num_edges <= edge_max_num) and (num_edges != UNIFORM) and (num_edges != NORMAL):
raise ValueError("Error: 'num_edges' must be between -1 and n * (n - 1) / 2, where n is the number of vertices "
"('num_vertices').")
# Generate the number of edges.
if num_edges == UNIFORM:
num_edges = generate_uniform_num_edges(num_vertices, seed=seed)
elif num_edges == NORMAL:
num_edges = generate_normal_num_edges(num_vertices, seed=seed)
return nx.gnm_random_graph(num_vertices, num_edges, seed=seed)
def generate_uniform_num_edges(num_vertices, seed=None):
"""
Generate a number of edges from a uniform distribution between 0 and the maximum number of edges.
:num_vertices: The number of vertices.
:seed: The seed of the random generator for the reproducibility.
:return: The number of edges generated.
"""
# Set the seed.
if seed:
random.seed(seed)
# The maximum number of edges.
edge_max_num = _helpers.compute_edge_max_num(num_vertices)
# Generate the number of edges.
num_edges = random.randint(0, edge_max_num)
return num_edges
def generate_normal_num_edges(num_vertices, seed=None):
"""
Generate a number of edges from a normal distribution between 0 and the maximum number of edges. The mean and the
standard deviation of the normal distribution are automaticlly computed from the number of vertices (thanks to the
distribution of numbers of edges of all different graphs with 'num_vertices' vertices).
:num_vertices: The number of vertices.
:seed: The seed of the random generator for the reproducibility.
:return: The number of edges generated.
"""
# Compute the mean and standard deviation of numbers of edges of all graphs with 'num_vertices' vertices.
mean = edge_num_distr.compute_mean(num_vertices)
std = edge_num_distr.compute_std(num_vertices)
# Set the seed.
if seed:
np.random.seed(seed)
# The maximum number of edges.
edge_max_num = _helpers.compute_edge_max_num(num_vertices)
# Generate the number of edges.
num_edges = round(np.random.normal(mean, std))
if num_edges < 0:
num_edges = 0
elif num_edges > edge_max_num:
num_edges = edge_max_num
return num_edges
if __name__ == '__main__':
import matplotlib.pyplot as plt
# Parameters.
num_vertices = 4
seed = 42
# Generate a graph.
graph = naive_random_graph(num_vertices, seed=seed)
nx.draw(graph)
plt.show() | 0.754192 | 0.627666 |
import os
import sys
import signal
import argparse
import subprocess
import json
parser = argparse.ArgumentParser(description = 'Create a dataproc cluster')
parser.add_argument('script')
parser.add_argument('-n','--cluster-name', type=str, required=False) #name of the cluster so you can create multiple
parser.add_argument('-m','--master-machine-type', type=str, required=False)
parser.add_argument('-w','--worker-machine-type', type=str, required=False)
parser.add_argument('-j','--num-workers', type=int, required=False)
parser.add_argument('-z','--zone', type=int, required=False)
args = parser.parse_args()
#gather cluster variables
cluster_name = 'powerwatch-analysis'
num_workers = 4
worker_machine_type = 'n1-standard-4'
master_machine_type = 'n1-standard-4'
bucket = 'powerwatch-analysis'
zone = 'us-west1-b'
if(args.zone):
zone = args.zone
if(args.num_workers):
num_workers = args.num_workers
if(args.worker_machine_type):
worker_machine_type = args.worker_machine_type
if(args.master_machine_type):
master_machine_type = args.master_machine_type
if(args.cluster_name):
cluster_name = args.cluster_name
bucket = args.cluster_name
config = None
with open('config.json') as data:
config = json.load(data)
#create the cloud storage bucket if it doesn't already exist
print("Creating storage bucket...")
try:
subprocess.check_output(['gsutil', 'mb', 'gs://' + bucket], stderr=subprocess.STDOUT)
except Exception as e:
if type(e) is subprocess.CalledProcessError and str(e.output, 'utf-8').find('409') != -1:
print("Storage bucket already exists. Proceeding...")
print()
else:
print(e.output);
raise e
#list the existing clusters
output = subprocess.check_output(['gcloud', 'dataproc', 'clusters', 'list'])
cluster_exists = str(output,'utf-8').find(cluster_name) != -1;
if(cluster_exists == False):
#create the cluster
print("Creating cluster");
subprocess.check_call(['gcloud', 'beta', 'dataproc','clusters','create',
cluster_name,
'--zone=' + zone,
'--image-version=1.4',
'--max-idle=30m',
'--num-workers=' + str(num_workers),
'--worker-machine-type=' + worker_machine_type,
'--master-machine-type=' + master_machine_type,
'--worker-boot-disk-size=250G',
'--bucket=' + bucket])
print()
else:
print("Cluster already exists. Proceeding...")
print()
#run the analysis script script with the output argument, and the driver
#first copy the postgres driver to the bucket
print("Setting up driver");
subprocess.check_call(['gsutil', 'cp', './postgres-driver/org.postgresql.jar','gs://' + bucket + '/org.postgresql.jar'])
print()
#next execute the script
result_name = args.script.split('.')[0]
folder_name = args.script.split('/')
if(len(folder_name) > 1):
folder_name = folder_name[:-1].join('/')
else:
folder_name = ""
first_line = None
#setup the handler to kill the job if you control C
def signal_handler(sig, frame):
#strip out the job number
job = first_line.split(' ')[1]
job = job[1:-1]
print()
subprocess.check_call(['gcloud', 'dataproc', 'jobs','kill',job])
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print("Starting job");
try:
child = subprocess.Popen(['gcloud', 'dataproc', 'jobs','submit','pyspark',
args.script,
'--cluster=' + cluster_name,
'--jars=gs://' + bucket + '/org.postgresql.jar',
'--properties=spark.driver.extraClassPath=gs://' + bucket + '/org.postgresql.jar',
'--',
'gs://' + bucket + '/' + result_name,
config['user'],
config['password']], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception as e:
print("Error executing analysis script")
sys.exit(1)
first_line = str(child.stderr.readline(),'utf-8')
print(first_line.rstrip())
while True:
line = child.stderr.readline()
if not line:
break
else:
print(str(line,'utf-8').rstrip())
print()
#now copy the results to the local folder
print("Job complete. Copying results");
try:
subprocess.check_call(['gsutil', 'cp', '-r', 'gs://' + bucket + '/' + result_name, './' + folder_name])
except:
print("Error retrieving results") | powerwatch/analysis/execute.py | import os
import sys
import signal
import argparse
import subprocess
import json
parser = argparse.ArgumentParser(description = 'Create a dataproc cluster')
parser.add_argument('script')
parser.add_argument('-n','--cluster-name', type=str, required=False) #name of the cluster so you can create multiple
parser.add_argument('-m','--master-machine-type', type=str, required=False)
parser.add_argument('-w','--worker-machine-type', type=str, required=False)
parser.add_argument('-j','--num-workers', type=int, required=False)
parser.add_argument('-z','--zone', type=int, required=False)
args = parser.parse_args()
#gather cluster variables
cluster_name = 'powerwatch-analysis'
num_workers = 4
worker_machine_type = 'n1-standard-4'
master_machine_type = 'n1-standard-4'
bucket = 'powerwatch-analysis'
zone = 'us-west1-b'
if(args.zone):
zone = args.zone
if(args.num_workers):
num_workers = args.num_workers
if(args.worker_machine_type):
worker_machine_type = args.worker_machine_type
if(args.master_machine_type):
master_machine_type = args.master_machine_type
if(args.cluster_name):
cluster_name = args.cluster_name
bucket = args.cluster_name
config = None
with open('config.json') as data:
config = json.load(data)
#create the cloud storage bucket if it doesn't already exist
print("Creating storage bucket...")
try:
subprocess.check_output(['gsutil', 'mb', 'gs://' + bucket], stderr=subprocess.STDOUT)
except Exception as e:
if type(e) is subprocess.CalledProcessError and str(e.output, 'utf-8').find('409') != -1:
print("Storage bucket already exists. Proceeding...")
print()
else:
print(e.output);
raise e
#list the existing clusters
output = subprocess.check_output(['gcloud', 'dataproc', 'clusters', 'list'])
cluster_exists = str(output,'utf-8').find(cluster_name) != -1;
if(cluster_exists == False):
#create the cluster
print("Creating cluster");
subprocess.check_call(['gcloud', 'beta', 'dataproc','clusters','create',
cluster_name,
'--zone=' + zone,
'--image-version=1.4',
'--max-idle=30m',
'--num-workers=' + str(num_workers),
'--worker-machine-type=' + worker_machine_type,
'--master-machine-type=' + master_machine_type,
'--worker-boot-disk-size=250G',
'--bucket=' + bucket])
print()
else:
print("Cluster already exists. Proceeding...")
print()
#run the analysis script script with the output argument, and the driver
#first copy the postgres driver to the bucket
print("Setting up driver");
subprocess.check_call(['gsutil', 'cp', './postgres-driver/org.postgresql.jar','gs://' + bucket + '/org.postgresql.jar'])
print()
#next execute the script
result_name = args.script.split('.')[0]
folder_name = args.script.split('/')
if(len(folder_name) > 1):
folder_name = folder_name[:-1].join('/')
else:
folder_name = ""
first_line = None
#setup the handler to kill the job if you control C
def signal_handler(sig, frame):
#strip out the job number
job = first_line.split(' ')[1]
job = job[1:-1]
print()
subprocess.check_call(['gcloud', 'dataproc', 'jobs','kill',job])
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print("Starting job");
try:
child = subprocess.Popen(['gcloud', 'dataproc', 'jobs','submit','pyspark',
args.script,
'--cluster=' + cluster_name,
'--jars=gs://' + bucket + '/org.postgresql.jar',
'--properties=spark.driver.extraClassPath=gs://' + bucket + '/org.postgresql.jar',
'--',
'gs://' + bucket + '/' + result_name,
config['user'],
config['password']], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception as e:
print("Error executing analysis script")
sys.exit(1)
first_line = str(child.stderr.readline(),'utf-8')
print(first_line.rstrip())
while True:
line = child.stderr.readline()
if not line:
break
else:
print(str(line,'utf-8').rstrip())
print()
#now copy the results to the local folder
print("Job complete. Copying results");
try:
subprocess.check_call(['gsutil', 'cp', '-r', 'gs://' + bucket + '/' + result_name, './' + folder_name])
except:
print("Error retrieving results") | 0.124226 | 0.079282 |
import torch
import math
import random
import numbers
import numpy as np
from . import functional as F
from torch.nn.modules.utils import _ntuple
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, x):
for t in self.transforms:
x = t(x)
return x
class CenterCrop(object):
"""Crops a give tensor at the center.
Args:
size (sequence or int): Desired output size of the crop.
dim : selected dims to perform cropping
"""
def __init__(self, size, dim=(1,2)):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
self.dim = dim
def __call__(self, x):
"""
Args:
x (2d or 3d tensor): tensor to be cropped.
Returns:
tensor: Cropped tensor
"""
return F._CenterCrop(x, self.size, self.dim)
class RandomCrop(object):
"""Crop the tensor at a random location
Args:
size (sequence or int): Desired output size of the crop.
dim : selected dims to perform cropping
"""
def __init__(self, size, dim=(1,2)):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
self.dim = dim
def __call__(self, x):
"""
Args:
x (2d or 3d tensor): tensor to be cropped.
Returns:
tensor: Cropped tensor
"""
return F._RandomCrop(x, self.size, self.dim)
class Scale(object):
"""Scale the tensor
Args:
scale: scale parameter
"""
def __init__(self, scale=None):
self.scale = scale
def __call__(self, x):
if self.scale is not None:
return F._Scale(x, self.scale)
else:
scale = x.abs().max()
return F._Scale(x, scale)
class ToTensor(object):
def __init__(self, div=1.):
self.division = div
def __call__(self, x):
return torch.from_numpy(x).float()/self.division
class Normalize(object):
"""Normalize the tensor to [0, 1]
Args:
dim: expected dimention indexes on which
normalization performs
"""
def __init__(self, dim=None):
self.dim = dim
def __call__(self, x):
ndim = x.dim()
if self.dim is None:
minValue = x.min()
maxValue = x.max()
return (x - minValue) / (maxValue - minValue + 1e-30)
else:
y = x
dims = _ntuple(ndim)(self.dim)
for dim in range(ndim):
if dim in dims:
maxValue, _ = x.abs().max(dim=dim, keepdim=True)
y = y.div(maxValue.expand_as(y))
minValue = y.min()
maxValue = y.max()
return (y - minValue)/(maxValue - minValue + 1e-30) | utils/mytransform.py | import torch
import math
import random
import numbers
import numpy as np
from . import functional as F
from torch.nn.modules.utils import _ntuple
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, x):
for t in self.transforms:
x = t(x)
return x
class CenterCrop(object):
"""Crops a give tensor at the center.
Args:
size (sequence or int): Desired output size of the crop.
dim : selected dims to perform cropping
"""
def __init__(self, size, dim=(1,2)):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
self.dim = dim
def __call__(self, x):
"""
Args:
x (2d or 3d tensor): tensor to be cropped.
Returns:
tensor: Cropped tensor
"""
return F._CenterCrop(x, self.size, self.dim)
class RandomCrop(object):
"""Crop the tensor at a random location
Args:
size (sequence or int): Desired output size of the crop.
dim : selected dims to perform cropping
"""
def __init__(self, size, dim=(1,2)):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
self.dim = dim
def __call__(self, x):
"""
Args:
x (2d or 3d tensor): tensor to be cropped.
Returns:
tensor: Cropped tensor
"""
return F._RandomCrop(x, self.size, self.dim)
class Scale(object):
"""Scale the tensor
Args:
scale: scale parameter
"""
def __init__(self, scale=None):
self.scale = scale
def __call__(self, x):
if self.scale is not None:
return F._Scale(x, self.scale)
else:
scale = x.abs().max()
return F._Scale(x, scale)
class ToTensor(object):
def __init__(self, div=1.):
self.division = div
def __call__(self, x):
return torch.from_numpy(x).float()/self.division
class Normalize(object):
"""Normalize the tensor to [0, 1]
Args:
dim: expected dimention indexes on which
normalization performs
"""
def __init__(self, dim=None):
self.dim = dim
def __call__(self, x):
ndim = x.dim()
if self.dim is None:
minValue = x.min()
maxValue = x.max()
return (x - minValue) / (maxValue - minValue + 1e-30)
else:
y = x
dims = _ntuple(ndim)(self.dim)
for dim in range(ndim):
if dim in dims:
maxValue, _ = x.abs().max(dim=dim, keepdim=True)
y = y.div(maxValue.expand_as(y))
minValue = y.min()
maxValue = y.max()
return (y - minValue)/(maxValue - minValue + 1e-30) | 0.737631 | 0.352313 |
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _snap.SWIG_PyInstanceMethod_New(func)
else:
from new import instancemethod as new_instancemethod
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_snap', [dirname(__file__)])
except ImportError:
import _snap
return _snap
if fp is not None:
try:
_mod = imp.load_module('_snap', fp, pathname, description)
finally:
fp.close()
return _mod
_snap = swig_import_helper()
del swig_import_helper
else:
import _snap
del version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
def _swig_setattr_nondynamic_method(set):
def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
def CalcEffDiam(*args):
"""
CalcEffDiam(TIntFltKdV const & DistNbrsCdfV, double const & Percentile=0.9) -> double
Parameters:
DistNbrsCdfV: TIntFltKdV const &
Percentile: double const &
CalcEffDiam(TIntFltKdV const & DistNbrsCdfV) -> double
Parameters:
DistNbrsCdfV: TIntFltKdV const &
CalcEffDiam(TFltPrV const & DistNbrsCdfV, double const & Percentile=0.9) -> double
Parameters:
DistNbrsCdfV: TFltPrV const &
Percentile: double const &
CalcEffDiam(TFltPrV const & DistNbrsCdfV) -> double
Parameters:
DistNbrsCdfV: TFltPrV const &
"""
return _snap.CalcEffDiam(*args)
def CalcEffDiamPdf(*args):
"""
CalcEffDiamPdf(TIntFltKdV const & DistNbrsPdfV, double const & Percentile=0.9) -> double
Parameters:
DistNbrsPdfV: TIntFltKdV const &
Percentile: double const &
CalcEffDiamPdf(TIntFltKdV const & DistNbrsPdfV) -> double
Parameters:
DistNbrsPdfV: TIntFltKdV const &
CalcEffDiamPdf(TFltPrV const & DistNbrsPdfV, double const & Percentile=0.9) -> double
Parameters:
DistNbrsPdfV: TFltPrV const &
Percentile: double const &
CalcEffDiamPdf(TFltPrV const & DistNbrsPdfV) -> double
Parameters:
DistNbrsPdfV: TFltPrV const &
"""
return _snap.CalcEffDiamPdf(*args)
def CalcAvgDiamPdf(*args):
"""
CalcAvgDiamPdf(TIntFltKdV const & DistNbrsPdfV) -> double
Parameters:
DistNbrsPdfV: TIntFltKdV const &
CalcAvgDiamPdf(TFltPrV const & DistNbrsPdfV) -> double
Parameters:
DistNbrsPdfV: TFltPrV const &
"""
return _snap.CalcAvgDiamPdf(*args)
lUndef = _snap.lUndef
lUs = _snap.lUs
lSi = _snap.lSi
def WrNotify(*args):
"""
WrNotify(char const * CaptionCStr, char const * NotifyCStr)
Parameters:
CaptionCStr: char const *
NotifyCStr: char const *
"""
return _snap.WrNotify(*args)
def SaveToErrLog(*args):
"""
SaveToErrLog(char const * MsgCStr)
Parameters:
MsgCStr: char const *
"""
return _snap.SaveToErrLog(*args)
def InfoNotify(*args):
"""
InfoNotify(char const * NotifyCStr)
Parameters:
NotifyCStr: char const *
"""
return _snap.InfoNotify(*args)
def WarnNotify(*args):
"""
WarnNotify(char const * NotifyCStr)
Parameters:
NotifyCStr: char const *
"""
return _snap.WarnNotify(*args)
def ErrNotify(*args):
"""
ErrNotify(char const * NotifyCStr)
Parameters:
NotifyCStr: char const *
"""
return _snap.ErrNotify(*args)
def StatNotify(*args):
"""
StatNotify(char const * NotifyCStr)
Parameters:
NotifyCStr: char const *
"""
return _snap.StatNotify(*args)
def ExeStop(*args):
"""
ExeStop(char const * MsgStr, char const * ReasonStr, char const * CondStr, char const * FNm,
int const & LnN)
Parameters:
MsgStr: char const *
ReasonStr: char const *
CondStr: char const *
FNm: char const *
LnN: int const &
"""
return _snap.ExeStop(*args)
loUndef = _snap.loUndef
loNot = _snap.loNot
loAnd = _snap.loAnd
loOr = _snap.loOr
roUndef = _snap.roUndef
roLs = _snap.roLs
roLEq = _snap.roLEq
roEq = _snap.roEq
roNEq = _snap.roNEq
roGEq = _snap.roGEq
roGt = _snap.roGt
class TCRef(object):
"""Proxy of C++ TCRef class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self):
"""__init__(TCRef self) -> TCRef"""
_snap.TCRef_swiginit(self,_snap.new_TCRef())
__swig_destroy__ = _snap.delete_TCRef
def MkRef(self):
"""
MkRef(TCRef self)
Parameters:
self: TCRef *
"""
return _snap.TCRef_MkRef(self)
def UnRef(self):
"""
UnRef(TCRef self)
Parameters:
self: TCRef *
"""
return _snap.TCRef_UnRef(self)
def NoRef(self):
"""
NoRef(TCRef self) -> bool
Parameters:
self: TCRef const *
"""
return _snap.TCRef_NoRef(self)
def GetRefs(self):
"""
GetRefs(TCRef self) -> int
Parameters:
self: TCRef const *
"""
return _snap.TCRef_GetRefs(self)
TCRef.MkRef = new_instancemethod(_snap.TCRef_MkRef,None,TCRef)
TCRef.UnRef = new_instancemethod(_snap.TCRef_UnRef,None,TCRef)
TCRef.NoRef = new_instancemethod(_snap.TCRef_NoRef,None,TCRef)
TCRef.GetRefs = new_instancemethod(_snap.TCRef_GetRefs,None,TCRef)
TCRef_swigregister = _snap.TCRef_swigregister
TCRef_swigregister(TCRef)
class TSStr(object):
"""Proxy of C++ TSStr class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TSStr self) -> TSStr
__init__(TSStr self, TSStr SStr) -> TSStr
Parameters:
SStr: TSStr const &
__init__(TSStr self, char const * _Bf) -> TSStr
Parameters:
_Bf: char const *
"""
_snap.TSStr_swiginit(self,_snap.new_TSStr(*args))
__swig_destroy__ = _snap.delete_TSStr
def CStr(self, *args):
"""
CStr(TSStr self) -> char
CStr(TSStr self) -> char const *
Parameters:
self: TSStr const *
"""
return _snap.TSStr_CStr(self, *args)
def Empty(self):
"""
Empty(TSStr self) -> bool
Parameters:
self: TSStr const *
"""
return _snap.TSStr_Empty(self)
def Len(self):
"""
Len(TSStr self) -> int
Parameters:
self: TSStr const *
"""
return _snap.TSStr_Len(self)
TSStr.CStr = new_instancemethod(_snap.TSStr_CStr,None,TSStr)
TSStr.Empty = new_instancemethod(_snap.TSStr_Empty,None,TSStr)
TSStr.Len = new_instancemethod(_snap.TSStr_Len,None,TSStr)
TSStr_swigregister = _snap.TSStr_swigregister
TSStr_swigregister(TSStr)
class TConv_Pt64Ints32(object):
"""Proxy of C++ TConv_Pt64Ints32 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TConv_Pt64Ints32 self) -> TConv_Pt64Ints32
__init__(TConv_Pt64Ints32 self, void * Pt) -> TConv_Pt64Ints32
Parameters:
Pt: void *
__init__(TConv_Pt64Ints32 self, uint const & Ms, uint const & Ls) -> TConv_Pt64Ints32
Parameters:
Ms: uint const &
Ls: uint const &
"""
_snap.TConv_Pt64Ints32_swiginit(self,_snap.new_TConv_Pt64Ints32(*args))
def PutPt(self, *args):
"""
PutPt(TConv_Pt64Ints32 self, void * Pt)
Parameters:
Pt: void *
"""
return _snap.TConv_Pt64Ints32_PutPt(self, *args)
def GetPt(self):
"""
GetPt(TConv_Pt64Ints32 self) -> void *
Parameters:
self: TConv_Pt64Ints32 const *
"""
return _snap.TConv_Pt64Ints32_GetPt(self)
def PutUInt64(self, *args):
"""
PutUInt64(TConv_Pt64Ints32 self, uint64 const & _UInt64)
Parameters:
_UInt64: uint64 const &
"""
return _snap.TConv_Pt64Ints32_PutUInt64(self, *args)
def GetUInt64(self):
"""
GetUInt64(TConv_Pt64Ints32 self) -> uint64
Parameters:
self: TConv_Pt64Ints32 const *
"""
return _snap.TConv_Pt64Ints32_GetUInt64(self)
def PutMsUInt32(self, *args):
"""
PutMsUInt32(TConv_Pt64Ints32 self, uint const & Ms)
Parameters:
Ms: uint const &
"""
return _snap.TConv_Pt64Ints32_PutMsUInt32(self, *args)
def GetMsUInt32(self):
"""
GetMsUInt32(TConv_Pt64Ints32 self) -> uint
Parameters:
self: TConv_Pt64Ints32 const *
"""
return _snap.TConv_Pt64Ints32_GetMsUInt32(self)
def PutLsUInt32(self, *args):
"""
PutLsUInt32(TConv_Pt64Ints32 self, uint const & Ls)
Parameters:
Ls: uint const &
"""
return _snap.TConv_Pt64Ints32_PutLsUInt32(self, *args)
def GetLsUInt32(self):
"""
GetLsUInt32(TConv_Pt64Ints32 self) -> uint
Parameters:
self: TConv_Pt64Ints32 const *
"""
return _snap.TConv_Pt64Ints32_GetLsUInt32(self)
__swig_destroy__ = _snap.delete_TConv_Pt64Ints32
TConv_Pt64Ints32.PutPt = new_instancemethod(_snap.TConv_Pt64Ints32_PutPt,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.GetPt = new_instancemethod(_snap.TConv_Pt64Ints32_GetPt,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.PutUInt64 = new_instancemethod(_snap.TConv_Pt64Ints32_PutUInt64,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.GetUInt64 = new_instancemethod(_snap.TConv_Pt64Ints32_GetUInt64,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.PutMsUInt32 = new_instancemethod(_snap.TConv_Pt64Ints32_PutMsUInt32,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.GetMsUInt32 = new_instancemethod(_snap.TConv_Pt64Ints32_GetMsUInt32,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.PutLsUInt32 = new_instancemethod(_snap.TConv_Pt64Ints32_PutLsUInt32,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.GetLsUInt32 = new_instancemethod(_snap.TConv_Pt64Ints32_GetLsUInt32,None,TConv_Pt64Ints32)
TConv_Pt64Ints32_swigregister = _snap.TConv_Pt64Ints32_swigregister
TConv_Pt64Ints32_swigregister(TConv_Pt64Ints32)
class TPairHashImpl1(object):
"""Proxy of C++ TPairHashImpl1 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetHashCd(*args):
"""
GetHashCd(int const hc1, int const hc2) -> int
Parameters:
hc1: int const
hc2: int const
"""
return _snap.TPairHashImpl1_GetHashCd(*args)
GetHashCd = staticmethod(GetHashCd)
def __init__(self):
"""__init__(TPairHashImpl1 self) -> TPairHashImpl1"""
_snap.TPairHashImpl1_swiginit(self,_snap.new_TPairHashImpl1())
__swig_destroy__ = _snap.delete_TPairHashImpl1
TPairHashImpl1_swigregister = _snap.TPairHashImpl1_swigregister
TPairHashImpl1_swigregister(TPairHashImpl1)
def TPairHashImpl1_GetHashCd(*args):
"""
TPairHashImpl1_GetHashCd(int const hc1, int const hc2) -> int
Parameters:
hc1: int const
hc2: int const
"""
return _snap.TPairHashImpl1_GetHashCd(*args)
class TPairHashImpl2(object):
"""Proxy of C++ TPairHashImpl2 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetHashCd(*args):
"""
GetHashCd(int const hc1, int const hc2) -> int
Parameters:
hc1: int const
hc2: int const
"""
return _snap.TPairHashImpl2_GetHashCd(*args)
GetHashCd = staticmethod(GetHashCd)
def __init__(self):
"""__init__(TPairHashImpl2 self) -> TPairHashImpl2"""
_snap.TPairHashImpl2_swiginit(self,_snap.new_TPairHashImpl2())
__swig_destroy__ = _snap.delete_TPairHashImpl2
TPairHashImpl2_swigregister = _snap.TPairHashImpl2_swigregister
TPairHashImpl2_swigregister(TPairHashImpl2)
def TPairHashImpl2_GetHashCd(*args):
"""
TPairHashImpl2_GetHashCd(int const hc1, int const hc2) -> int
Parameters:
hc1: int const
hc2: int const
"""
return _snap.TPairHashImpl2_GetHashCd(*args)
def GetDegreeCentr(*args):
"""
GetDegreeCentr(PUNGraph const & Graph, int const & NId) -> double
Parameters:
Graph: PUNGraph const &
NId: int const &
"""
return _snap.GetDegreeCentr(*args)
def GetFarnessCentr(*args):
"""
GetFarnessCentr(PUNGraph const & Graph, int const & NId) -> double
Parameters:
Graph: PUNGraph const &
NId: int const &
"""
return _snap.GetFarnessCentr(*args)
def GetClosenessCentr(*args):
"""
GetClosenessCentr(PUNGraph const & Graph, int const & NId) -> double
Parameters:
Graph: PUNGraph const &
NId: int const &
"""
return _snap.GetClosenessCentr(*args)
def GetBetweennessCentr(*args):
"""
GetBetweennessCentr(PUNGraph const & Graph, TIntFltH & NIdBtwH, double const & NodeFrac=1.0)
Parameters:
Graph: PUNGraph const &
NIdBtwH: TIntFltH &
NodeFrac: double const &
GetBetweennessCentr(PUNGraph const & Graph, TIntFltH & NIdBtwH)
Parameters:
Graph: PUNGraph const &
NIdBtwH: TIntFltH &
GetBetweennessCentr(PUNGraph const & Graph, TIntPrFltH & EdgeBtwH, double const & NodeFrac=1.0)
Parameters:
Graph: PUNGraph const &
EdgeBtwH: TIntPrFltH &
NodeFrac: double const &
GetBetweennessCentr(PUNGraph const & Graph, TIntPrFltH & EdgeBtwH)
Parameters:
Graph: PUNGraph const &
EdgeBtwH: TIntPrFltH &
GetBetweennessCentr(PUNGraph const & Graph, TIntFltH & NIdBtwH, TIntPrFltH & EdgeBtwH, double const & NodeFrac=1.0)
Parameters:
Graph: PUNGraph const &
NIdBtwH: TIntFltH &
EdgeBtwH: TIntPrFltH &
NodeFrac: double const &
GetBetweennessCentr(PUNGraph const & Graph, TIntFltH & NIdBtwH, TIntPrFltH & EdgeBtwH)
Parameters:
Graph: PUNGraph const &
NIdBtwH: TIntFltH &
EdgeBtwH: TIntPrFltH &
GetBetweennessCentr(PUNGraph const & Graph, TIntV BtwNIdV, TIntFltH & NodeBtwH, bool const & DoNodeCent,
TIntPrFltH & EdgeBtwH, bool const & DoEdgeCent)
Parameters:
Graph: PUNGraph const &
BtwNIdV: TIntV const &
NodeBtwH: TIntFltH &
DoNodeCent: bool const &
EdgeBtwH: TIntPrFltH &
DoEdgeCent: bool const &
"""
return _snap.GetBetweennessCentr(*args)
def GetEigenVectorCentr(*args):
"""
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4, int const & MaxIter=100)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
MaxIter: int const &
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
"""
return _snap.GetEigenVectorCentr(*args)
def CommunityGirvanNewman(*args):
"""
CommunityGirvanNewman(PUNGraph & Graph, TCnComV & CmtyV) -> double
Parameters:
Graph: PUNGraph &
CmtyV: TCnComV &
"""
return _snap.CommunityGirvanNewman(*args)
def CommunityCNM(*args):
"""
CommunityCNM(PUNGraph const & Graph, TCnComV & CmtyV) -> double
Parameters:
Graph: PUNGraph const &
CmtyV: TCnComV &
"""
return _snap.CommunityCNM(*args)
def CmtyGirvanNewmanStep(*args):
"""
CmtyGirvanNewmanStep(PUNGraph & Graph, TIntV Cmty1, TIntV Cmty2)
Parameters:
Graph: PUNGraph &
Cmty1: TIntV &
Cmty2: TIntV &
"""
return _snap.CmtyGirvanNewmanStep(*args)
def GetBiConSzCnt(*args):
"""
GetBiConSzCnt(PUNGraph const & Graph, TIntPrV & SzCntV)
Parameters:
Graph: PUNGraph const &
SzCntV: TIntPrV &
"""
return _snap.GetBiConSzCnt(*args)
def GetBiCon(*args):
"""
GetBiCon(PUNGraph const & Graph, TCnComV & BiCnComV)
Parameters:
Graph: PUNGraph const &
BiCnComV: TCnComV &
"""
return _snap.GetBiCon(*args)
def GetArtPoints(*args):
"""
GetArtPoints(PUNGraph const & Graph, TIntV ArtNIdV)
Parameters:
Graph: PUNGraph const &
ArtNIdV: TIntV &
"""
return _snap.GetArtPoints(*args)
def GetEdgeBridges(*args):
"""
GetEdgeBridges(PUNGraph const & Graph, TIntPrV & EdgeV)
Parameters:
Graph: PUNGraph const &
EdgeV: TIntPrV &
"""
return _snap.GetEdgeBridges(*args)
def Get1CnComSzCnt(*args):
"""
Get1CnComSzCnt(PUNGraph const & Graph, TIntPrV & SzCntV)
Parameters:
Graph: PUNGraph const &
SzCntV: TIntPrV &
"""
return _snap.Get1CnComSzCnt(*args)
def Get1CnCom(*args):
"""
Get1CnCom(PUNGraph const & Graph, TCnComV & Cn1ComV)
Parameters:
Graph: PUNGraph const &
Cn1ComV: TCnComV &
"""
return _snap.Get1CnCom(*args)
class TCnCom(object):
"""Proxy of C++ TCnCom class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
NIdV = _swig_property(_snap.TCnCom_NIdV_get, _snap.TCnCom_NIdV_set)
def __init__(self, *args):
"""
__init__(TCnCom self) -> TCnCom
__init__(TCnCom self, TIntV NodeIdV) -> TCnCom
Parameters:
NodeIdV: TIntV const &
__init__(TCnCom self, TCnCom CC) -> TCnCom
Parameters:
CC: TCnCom const &
__init__(TCnCom self, TSIn SIn) -> TCnCom
Parameters:
SIn: TSIn &
"""
_snap.TCnCom_swiginit(self,_snap.new_TCnCom(*args))
def Save(self, *args):
"""
Save(TCnCom self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TCnCom_Save(self, *args)
def __eq__(self, *args):
"""
__eq__(TCnCom self, TCnCom CC) -> bool
Parameters:
CC: TCnCom const &
"""
return _snap.TCnCom___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TCnCom self, TCnCom CC) -> bool
Parameters:
CC: TCnCom const &
"""
return _snap.TCnCom___lt__(self, *args)
def Len(self):
"""
Len(TCnCom self) -> int
Parameters:
self: TCnCom const *
"""
return _snap.TCnCom_Len(self)
def Empty(self):
"""
Empty(TCnCom self) -> bool
Parameters:
self: TCnCom const *
"""
return _snap.TCnCom_Empty(self)
def Clr(self):
"""
Clr(TCnCom self)
Parameters:
self: TCnCom *
"""
return _snap.TCnCom_Clr(self)
def Add(self, *args):
"""
Add(TCnCom self, int const & NodeId)
Parameters:
NodeId: int const &
"""
return _snap.TCnCom_Add(self, *args)
def __call__(self, *args):
"""
__call__(TCnCom self) -> TIntV
__call__(TCnCom self) -> TIntV
Parameters:
self: TCnCom *
"""
return _snap.TCnCom___call__(self, *args)
def Sort(self, Asc=True):
"""
Sort(TCnCom self, bool const & Asc=True)
Parameters:
Asc: bool const &
Sort(TCnCom self)
Parameters:
self: TCnCom *
"""
return _snap.TCnCom_Sort(self, Asc)
def IsNIdIn(self, *args):
"""
IsNIdIn(TCnCom self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TCnCom_IsNIdIn(self, *args)
def GetRndNId(self):
"""
GetRndNId(TCnCom self) -> TInt
Parameters:
self: TCnCom const *
"""
return _snap.TCnCom_GetRndNId(self)
def Dump(*args):
"""
Dump(TCnComV const & CnComV, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
Desc: TStr const &
Dump(TCnComV const & CnComV)
Parameters:
CnComV: TCnComV const &
"""
return _snap.TCnCom_Dump(*args)
Dump = staticmethod(Dump)
def SaveTxt(*args):
"""
SaveTxt(TCnComV const & CnComV, TStr FNm, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
FNm: TStr const &
Desc: TStr const &
SaveTxt(TCnComV const & CnComV, TStr FNm)
Parameters:
CnComV: TCnComV const &
FNm: TStr const &
"""
return _snap.TCnCom_SaveTxt(*args)
SaveTxt = staticmethod(SaveTxt)
__swig_destroy__ = _snap.delete_TCnCom
TCnCom.Save = new_instancemethod(_snap.TCnCom_Save,None,TCnCom)
TCnCom.__eq__ = new_instancemethod(_snap.TCnCom___eq__,None,TCnCom)
TCnCom.__lt__ = new_instancemethod(_snap.TCnCom___lt__,None,TCnCom)
TCnCom.Len = new_instancemethod(_snap.TCnCom_Len,None,TCnCom)
TCnCom.Empty = new_instancemethod(_snap.TCnCom_Empty,None,TCnCom)
TCnCom.Clr = new_instancemethod(_snap.TCnCom_Clr,None,TCnCom)
TCnCom.Add = new_instancemethod(_snap.TCnCom_Add,None,TCnCom)
TCnCom.__call__ = new_instancemethod(_snap.TCnCom___call__,None,TCnCom)
TCnCom.Sort = new_instancemethod(_snap.TCnCom_Sort,None,TCnCom)
TCnCom.IsNIdIn = new_instancemethod(_snap.TCnCom_IsNIdIn,None,TCnCom)
TCnCom.GetRndNId = new_instancemethod(_snap.TCnCom_GetRndNId,None,TCnCom)
TCnCom_swigregister = _snap.TCnCom_swigregister
TCnCom_swigregister(TCnCom)
def TCnCom_Dump(*args):
"""
Dump(TCnComV const & CnComV, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
Desc: TStr const &
TCnCom_Dump(TCnComV const & CnComV)
Parameters:
CnComV: TCnComV const &
"""
return _snap.TCnCom_Dump(*args)
def TCnCom_SaveTxt(*args):
"""
SaveTxt(TCnComV const & CnComV, TStr FNm, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
FNm: TStr const &
Desc: TStr const &
TCnCom_SaveTxt(TCnComV const & CnComV, TStr FNm)
Parameters:
CnComV: TCnComV const &
FNm: TStr const &
"""
return _snap.TCnCom_SaveTxt(*args)
class TArtPointVisitor(object):
"""Proxy of C++ TArtPointVisitor class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
VnLowH = _swig_property(_snap.TArtPointVisitor_VnLowH_get, _snap.TArtPointVisitor_VnLowH_set)
ParentH = _swig_property(_snap.TArtPointVisitor_ParentH_get, _snap.TArtPointVisitor_ParentH_set)
ArtSet = _swig_property(_snap.TArtPointVisitor_ArtSet_get, _snap.TArtPointVisitor_ArtSet_set)
Time = _swig_property(_snap.TArtPointVisitor_Time_get, _snap.TArtPointVisitor_Time_set)
def __init__(self, *args):
"""
__init__(TArtPointVisitor self) -> TArtPointVisitor
__init__(TArtPointVisitor self, int const & Nodes) -> TArtPointVisitor
Parameters:
Nodes: int const &
"""
_snap.TArtPointVisitor_swiginit(self,_snap.new_TArtPointVisitor(*args))
def DiscoverNode(self, *args):
"""
DiscoverNode(TArtPointVisitor self, int NId)
Parameters:
NId: int
"""
return _snap.TArtPointVisitor_DiscoverNode(self, *args)
def FinishNode(self, *args):
"""
FinishNode(TArtPointVisitor self, int const & NId)
Parameters:
NId: int const &
"""
return _snap.TArtPointVisitor_FinishNode(self, *args)
def ExamineEdge(self, *args):
"""
ExamineEdge(TArtPointVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TArtPointVisitor_ExamineEdge(self, *args)
def TreeEdge(self, *args):
"""
TreeEdge(TArtPointVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TArtPointVisitor_TreeEdge(self, *args)
def BackEdge(self, *args):
"""
BackEdge(TArtPointVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TArtPointVisitor_BackEdge(self, *args)
def FwdEdge(self, *args):
"""
FwdEdge(TArtPointVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TArtPointVisitor_FwdEdge(self, *args)
__swig_destroy__ = _snap.delete_TArtPointVisitor
TArtPointVisitor.DiscoverNode = new_instancemethod(_snap.TArtPointVisitor_DiscoverNode,None,TArtPointVisitor)
TArtPointVisitor.FinishNode = new_instancemethod(_snap.TArtPointVisitor_FinishNode,None,TArtPointVisitor)
TArtPointVisitor.ExamineEdge = new_instancemethod(_snap.TArtPointVisitor_ExamineEdge,None,TArtPointVisitor)
TArtPointVisitor.TreeEdge = new_instancemethod(_snap.TArtPointVisitor_TreeEdge,None,TArtPointVisitor)
TArtPointVisitor.BackEdge = new_instancemethod(_snap.TArtPointVisitor_BackEdge,None,TArtPointVisitor)
TArtPointVisitor.FwdEdge = new_instancemethod(_snap.TArtPointVisitor_FwdEdge,None,TArtPointVisitor)
TArtPointVisitor_swigregister = _snap.TArtPointVisitor_swigregister
TArtPointVisitor_swigregister(TArtPointVisitor)
class TBiConVisitor(object):
"""Proxy of C++ TBiConVisitor class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
VnLowH = _swig_property(_snap.TBiConVisitor_VnLowH_get, _snap.TBiConVisitor_VnLowH_set)
ParentH = _swig_property(_snap.TBiConVisitor_ParentH_get, _snap.TBiConVisitor_ParentH_set)
Stack = _swig_property(_snap.TBiConVisitor_Stack_get, _snap.TBiConVisitor_Stack_set)
CnComV = _swig_property(_snap.TBiConVisitor_CnComV_get, _snap.TBiConVisitor_CnComV_set)
NSet = _swig_property(_snap.TBiConVisitor_NSet_get, _snap.TBiConVisitor_NSet_set)
Time = _swig_property(_snap.TBiConVisitor_Time_get, _snap.TBiConVisitor_Time_set)
def __init__(self, *args):
"""
__init__(TBiConVisitor self) -> TBiConVisitor
__init__(TBiConVisitor self, int const & Nodes) -> TBiConVisitor
Parameters:
Nodes: int const &
"""
_snap.TBiConVisitor_swiginit(self,_snap.new_TBiConVisitor(*args))
def DiscoverNode(self, *args):
"""
DiscoverNode(TBiConVisitor self, int NId)
Parameters:
NId: int
"""
return _snap.TBiConVisitor_DiscoverNode(self, *args)
def FinishNode(self, *args):
"""
FinishNode(TBiConVisitor self, int const & NId)
Parameters:
NId: int const &
"""
return _snap.TBiConVisitor_FinishNode(self, *args)
def ExamineEdge(self, *args):
"""
ExamineEdge(TBiConVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TBiConVisitor_ExamineEdge(self, *args)
def TreeEdge(self, *args):
"""
TreeEdge(TBiConVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TBiConVisitor_TreeEdge(self, *args)
def BackEdge(self, *args):
"""
BackEdge(TBiConVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TBiConVisitor_BackEdge(self, *args)
def FwdEdge(self, *args):
"""
FwdEdge(TBiConVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TBiConVisitor_FwdEdge(self, *args)
__swig_destroy__ = _snap.delete_TBiConVisitor
TBiConVisitor.DiscoverNode = new_instancemethod(_snap.TBiConVisitor_DiscoverNode,None,TBiConVisitor)
TBiConVisitor.FinishNode = new_instancemethod(_snap.TBiConVisitor_FinishNode,None,TBiConVisitor)
TBiConVisitor.ExamineEdge = new_instancemethod(_snap.TBiConVisitor_ExamineEdge,None,TBiConVisitor)
TBiConVisitor.TreeEdge = new_instancemethod(_snap.TBiConVisitor_TreeEdge,None,TBiConVisitor)
TBiConVisitor.BackEdge = new_instancemethod(_snap.TBiConVisitor_BackEdge,None,TBiConVisitor)
TBiConVisitor.FwdEdge = new_instancemethod(_snap.TBiConVisitor_FwdEdge,None,TBiConVisitor)
TBiConVisitor_swigregister = _snap.TBiConVisitor_swigregister
TBiConVisitor_swigregister(TBiConVisitor)
class TForestFire(object):
"""Proxy of C++ TForestFire class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TForestFire self) -> TForestFire
__init__(TForestFire self, PNGraph const & GraphPt, double const & ForwBurnProb, double const & BackBurnProb,
double const & DecayProb=1.0, int const & RndSeed=1) -> TForestFire
Parameters:
GraphPt: PNGraph const &
ForwBurnProb: double const &
BackBurnProb: double const &
DecayProb: double const &
RndSeed: int const &
__init__(TForestFire self, PNGraph const & GraphPt, double const & ForwBurnProb, double const & BackBurnProb,
double const & DecayProb=1.0) -> TForestFire
Parameters:
GraphPt: PNGraph const &
ForwBurnProb: double const &
BackBurnProb: double const &
DecayProb: double const &
__init__(TForestFire self, PNGraph const & GraphPt, double const & ForwBurnProb, double const & BackBurnProb) -> TForestFire
Parameters:
GraphPt: PNGraph const &
ForwBurnProb: double const &
BackBurnProb: double const &
"""
_snap.TForestFire_swiginit(self,_snap.new_TForestFire(*args))
def SetGraph(self, *args):
"""
SetGraph(TForestFire self, PNGraph const & GraphPt)
Parameters:
GraphPt: PNGraph const &
"""
return _snap.TForestFire_SetGraph(self, *args)
def GetGraph(self):
"""
GetGraph(TForestFire self) -> PNGraph
Parameters:
self: TForestFire const *
"""
return _snap.TForestFire_GetGraph(self)
def SetBurnProb(self, *args):
"""
SetBurnProb(TForestFire self, double const & ForwBurnProb, double const & BackBurnProb)
Parameters:
ForwBurnProb: double const &
BackBurnProb: double const &
"""
return _snap.TForestFire_SetBurnProb(self, *args)
def SetProbDecay(self, *args):
"""
SetProbDecay(TForestFire self, double const & DecayProb)
Parameters:
DecayProb: double const &
"""
return _snap.TForestFire_SetProbDecay(self, *args)
def Infect(self, *args):
"""
Infect(TForestFire self, int const & NodeId)
Parameters:
NodeId: int const &
Infect(TForestFire self, TIntV InfectedNIdV)
Parameters:
InfectedNIdV: TIntV const &
"""
return _snap.TForestFire_Infect(self, *args)
def InfectAll(self):
"""
InfectAll(TForestFire self)
Parameters:
self: TForestFire *
"""
return _snap.TForestFire_InfectAll(self)
def InfectRnd(self, *args):
"""
InfectRnd(TForestFire self, int const & NInfect)
Parameters:
NInfect: int const &
"""
return _snap.TForestFire_InfectRnd(self, *args)
def BurnExpFire(self):
"""
BurnExpFire(TForestFire self)
Parameters:
self: TForestFire *
"""
return _snap.TForestFire_BurnExpFire(self)
def BurnGeoFire(self):
"""
BurnGeoFire(TForestFire self)
Parameters:
self: TForestFire *
"""
return _snap.TForestFire_BurnGeoFire(self)
def GetFireTm(self):
"""
GetFireTm(TForestFire self) -> int
Parameters:
self: TForestFire const *
"""
return _snap.TForestFire_GetFireTm(self)
def GetBurned(self):
"""
GetBurned(TForestFire self) -> int
Parameters:
self: TForestFire const *
"""
return _snap.TForestFire_GetBurned(self)
def GetBurnedNId(self, *args):
"""
GetBurnedNId(TForestFire self, int const & NIdN) -> int
Parameters:
NIdN: int const &
"""
return _snap.TForestFire_GetBurnedNId(self, *args)
def GetBurnedNIdV(self, *args):
"""
GetBurnedNIdV(TForestFire self) -> TIntV
GetBurnedNIdV(TForestFire self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TForestFire_GetBurnedNIdV(self, *args)
def PlotFire(self, *args):
"""
PlotFire(TForestFire self, TStr FNmPref, TStr Desc, bool const & PlotAllBurned=False)
Parameters:
FNmPref: TStr const &
Desc: TStr const &
PlotAllBurned: bool const &
PlotFire(TForestFire self, TStr FNmPref, TStr Desc)
Parameters:
FNmPref: TStr const &
Desc: TStr const &
"""
return _snap.TForestFire_PlotFire(self, *args)
def GenGraph(*args):
"""
GenGraph(int const & Nodes, double const & FwdProb, double const & BckProb) -> PNGraph
Parameters:
Nodes: int const &
FwdProb: double const &
BckProb: double const &
"""
return _snap.TForestFire_GenGraph(*args)
GenGraph = staticmethod(GenGraph)
__swig_destroy__ = _snap.delete_TForestFire
TForestFire.SetGraph = new_instancemethod(_snap.TForestFire_SetGraph,None,TForestFire)
TForestFire.GetGraph = new_instancemethod(_snap.TForestFire_GetGraph,None,TForestFire)
TForestFire.SetBurnProb = new_instancemethod(_snap.TForestFire_SetBurnProb,None,TForestFire)
TForestFire.SetProbDecay = new_instancemethod(_snap.TForestFire_SetProbDecay,None,TForestFire)
TForestFire.Infect = new_instancemethod(_snap.TForestFire_Infect,None,TForestFire)
TForestFire.InfectAll = new_instancemethod(_snap.TForestFire_InfectAll,None,TForestFire)
TForestFire.InfectRnd = new_instancemethod(_snap.TForestFire_InfectRnd,None,TForestFire)
TForestFire.BurnExpFire = new_instancemethod(_snap.TForestFire_BurnExpFire,None,TForestFire)
TForestFire.BurnGeoFire = new_instancemethod(_snap.TForestFire_BurnGeoFire,None,TForestFire)
TForestFire.GetFireTm = new_instancemethod(_snap.TForestFire_GetFireTm,None,TForestFire)
TForestFire.GetBurned = new_instancemethod(_snap.TForestFire_GetBurned,None,TForestFire)
TForestFire.GetBurnedNId = new_instancemethod(_snap.TForestFire_GetBurnedNId,None,TForestFire)
TForestFire.GetBurnedNIdV = new_instancemethod(_snap.TForestFire_GetBurnedNIdV,None,TForestFire)
TForestFire.PlotFire = new_instancemethod(_snap.TForestFire_PlotFire,None,TForestFire)
TForestFire_swigregister = _snap.TForestFire_swigregister
TForestFire_swigregister(TForestFire)
def TForestFire_GenGraph(*args):
"""
TForestFire_GenGraph(int const & Nodes, double const & FwdProb, double const & BckProb) -> PNGraph
Parameters:
Nodes: int const &
FwdProb: double const &
BckProb: double const &
"""
return _snap.TForestFire_GenGraph(*args)
class TFfGGen(object):
"""Proxy of C++ TFfGGen class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
srUndef = _snap.TFfGGen_srUndef
srOk = _snap.TFfGGen_srOk
srFlood = _snap.TFfGGen_srFlood
srTimeLimit = _snap.TFfGGen_srTimeLimit
TimeLimitSec = _swig_property(_snap.TFfGGen_TimeLimitSec_get, _snap.TFfGGen_TimeLimitSec_set)
def __init__(self, *args):
"""
__init__(TFfGGen self, bool const & BurnExpFireP, int const & StartNNodes, double const & ForwBurnProb,
double const & BackBurnProb, double const & DecayProb, double const & Take2AmbasPrb,
double const & OrphanPrb) -> TFfGGen
Parameters:
BurnExpFireP: bool const &
StartNNodes: int const &
ForwBurnProb: double const &
BackBurnProb: double const &
DecayProb: double const &
Take2AmbasPrb: double const &
OrphanPrb: double const &
"""
_snap.TFfGGen_swiginit(self,_snap.new_TFfGGen(*args))
def GetGraph(self):
"""
GetGraph(TFfGGen self) -> PNGraph
Parameters:
self: TFfGGen const *
"""
return _snap.TFfGGen_GetGraph(self)
def SetGraph(self, *args):
"""
SetGraph(TFfGGen self, PNGraph const & NGraph)
Parameters:
NGraph: PNGraph const &
"""
return _snap.TFfGGen_SetGraph(self, *args)
def Clr(self):
"""
Clr(TFfGGen self)
Parameters:
self: TFfGGen *
"""
return _snap.TFfGGen_Clr(self)
def GetParamStr(self):
"""
GetParamStr(TFfGGen self) -> TStr
Parameters:
self: TFfGGen const *
"""
return _snap.TFfGGen_GetParamStr(self)
def AddNodes(self, *args):
"""
AddNodes(TFfGGen self, int const & GraphNodes, bool const & FloodStop=True) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
FloodStop: bool const &
AddNodes(TFfGGen self, int const & GraphNodes) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
"""
return _snap.TFfGGen_AddNodes(self, *args)
def GenGraph(self, *args):
"""
GenGraph(TFfGGen self, int const & GraphNodes, bool const & FloodStop=True) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
FloodStop: bool const &
GenGraph(TFfGGen self, int const & GraphNodes) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
GenGraph(TFfGGen self, int const & GraphNodes, PGStatVec & EvolStat, bool const & FloodStop=True) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
EvolStat: PGStatVec &
FloodStop: bool const &
GenGraph(TFfGGen self, int const & GraphNodes, PGStatVec & EvolStat) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
EvolStat: PGStatVec &
"""
return _snap.TFfGGen_GenGraph(self, *args)
def PlotFireSize(self, *args):
"""
PlotFireSize(TFfGGen self, TStr FNmPref, TStr DescStr)
Parameters:
FNmPref: TStr const &
DescStr: TStr const &
"""
return _snap.TFfGGen_PlotFireSize(self, *args)
def GenFFGraphs(*args):
"""
GenFFGraphs(double const & FProb, double const & BProb, TStr FNm)
Parameters:
FProb: double const &
BProb: double const &
FNm: TStr const &
"""
return _snap.TFfGGen_GenFFGraphs(*args)
GenFFGraphs = staticmethod(GenFFGraphs)
__swig_destroy__ = _snap.delete_TFfGGen
TFfGGen.GetGraph = new_instancemethod(_snap.TFfGGen_GetGraph,None,TFfGGen)
TFfGGen.SetGraph = new_instancemethod(_snap.TFfGGen_SetGraph,None,TFfGGen)
TFfGGen.Clr = new_instancemethod(_snap.TFfGGen_Clr,None,TFfGGen)
TFfGGen.GetParamStr = new_instancemethod(_snap.TFfGGen_GetParamStr,None,TFfGGen)
TFfGGen.AddNodes = new_instancemethod(_snap.TFfGGen_AddNodes,None,TFfGGen)
TFfGGen.GenGraph = new_instancemethod(_snap.TFfGGen_GenGraph,None,TFfGGen)
TFfGGen.PlotFireSize = new_instancemethod(_snap.TFfGGen_PlotFireSize,None,TFfGGen)
TFfGGen_swigregister = _snap.TFfGGen_swigregister
TFfGGen_swigregister(TFfGGen)
cvar = _snap.cvar
def TFfGGen_GenFFGraphs(*args):
"""
TFfGGen_GenFFGraphs(double const & FProb, double const & BProb, TStr FNm)
Parameters:
FProb: double const &
BProb: double const &
FNm: TStr const &
"""
return _snap.TFfGGen_GenFFGraphs(*args)
class TUndirFFire(object):
"""Proxy of C++ TUndirFFire class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, _BurnProb=0.3):
"""
__init__(TUndirFFire self, double const & _BurnProb=0.3) -> TUndirFFire
Parameters:
_BurnProb: double const &
__init__(TUndirFFire self) -> TUndirFFire
"""
_snap.TUndirFFire_swiginit(self,_snap.new_TUndirFFire(_BurnProb))
def SetGraph(self, *args):
"""
SetGraph(TUndirFFire self, PUNGraph const & GraphPt)
Parameters:
GraphPt: PUNGraph const &
"""
return _snap.TUndirFFire_SetGraph(self, *args)
def GetGraph(self):
"""
GetGraph(TUndirFFire self) -> PUNGraph
Parameters:
self: TUndirFFire const *
"""
return _snap.TUndirFFire_GetGraph(self)
def GetNBurned(self):
"""
GetNBurned(TUndirFFire self) -> int
Parameters:
self: TUndirFFire const *
"""
return _snap.TUndirFFire_GetNBurned(self)
def GetBurnedNId(self, *args):
"""
GetBurnedNId(TUndirFFire self, int const & n) -> int
Parameters:
n: int const &
"""
return _snap.TUndirFFire_GetBurnedNId(self, *args)
def BurnGeoFire(self, *args):
"""
BurnGeoFire(TUndirFFire self, int const & StartNId) -> int
Parameters:
StartNId: int const &
"""
return _snap.TUndirFFire_BurnGeoFire(self, *args)
def AddNodes(self, *args):
"""
AddNodes(TUndirFFire self, int const & GraphNodes, bool const & FloodStop=True) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
FloodStop: bool const &
AddNodes(TUndirFFire self, int const & GraphNodes) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
"""
return _snap.TUndirFFire_AddNodes(self, *args)
__swig_destroy__ = _snap.delete_TUndirFFire
TUndirFFire.SetGraph = new_instancemethod(_snap.TUndirFFire_SetGraph,None,TUndirFFire)
TUndirFFire.GetGraph = new_instancemethod(_snap.TUndirFFire_GetGraph,None,TUndirFFire)
TUndirFFire.GetNBurned = new_instancemethod(_snap.TUndirFFire_GetNBurned,None,TUndirFFire)
TUndirFFire.GetBurnedNId = new_instancemethod(_snap.TUndirFFire_GetBurnedNId,None,TUndirFFire)
TUndirFFire.BurnGeoFire = new_instancemethod(_snap.TUndirFFire_BurnGeoFire,None,TUndirFFire)
TUndirFFire.AddNodes = new_instancemethod(_snap.TUndirFFire_AddNodes,None,TUndirFFire)
TUndirFFire_swigregister = _snap.TUndirFFire_swigregister
TUndirFFire_swigregister(TUndirFFire)
class TCs(object):
"""Proxy of C++ TCs class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TCs self) -> TCs
__init__(TCs self, TCs Cs) -> TCs
Parameters:
Cs: TCs const &
__init__(TCs self, int const & Int) -> TCs
Parameters:
Int: int const &
"""
_snap.TCs_swiginit(self,_snap.new_TCs(*args))
def __eq__(self, *args):
"""
__eq__(TCs self, TCs Cs) -> bool
Parameters:
Cs: TCs const &
"""
return _snap.TCs___eq__(self, *args)
def __iadd__(self, *args):
"""
__iadd__(TCs self, TCs Cs) -> TCs
Parameters:
Cs: TCs const &
__iadd__(TCs self, char const & Ch) -> TCs
Parameters:
Ch: char const &
__iadd__(TCs self, int const & Int) -> TCs
Parameters:
Int: int const &
"""
return _snap.TCs___iadd__(self, *args)
def Get(self):
"""
Get(TCs self) -> int
Parameters:
self: TCs const *
"""
return _snap.TCs_Get(self)
def GetCsFromBf(*args):
"""
GetCsFromBf(char * Bf, int const & BfL) -> TCs
Parameters:
Bf: char *
BfL: int const &
"""
return _snap.TCs_GetCsFromBf(*args)
GetCsFromBf = staticmethod(GetCsFromBf)
__swig_destroy__ = _snap.delete_TCs
TCs.__eq__ = new_instancemethod(_snap.TCs___eq__,None,TCs)
TCs.__iadd__ = new_instancemethod(_snap.TCs___iadd__,None,TCs)
TCs.Get = new_instancemethod(_snap.TCs_Get,None,TCs)
TCs_swigregister = _snap.TCs_swigregister
TCs_swigregister(TCs)
def TCs_GetCsFromBf(*args):
"""
TCs_GetCsFromBf(char * Bf, int const & BfL) -> TCs
Parameters:
Bf: char *
BfL: int const &
"""
return _snap.TCs_GetCsFromBf(*args)
class TSOutMnp(object):
"""Proxy of C++ TSOutMnp class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
def __call__(self, *args):
"""
__call__(TSOutMnp self, TSOut SOut) -> TSOut
Parameters:
SOut: TSOut &
"""
return _snap.TSOutMnp___call__(self, *args)
__swig_destroy__ = _snap.delete_TSOutMnp
TSOutMnp.__call__ = new_instancemethod(_snap.TSOutMnp___call__,None,TSOutMnp)
TSOutMnp_swigregister = _snap.TSOutMnp_swigregister
TSOutMnp_swigregister(TSOutMnp)
class TSBase(object):
"""Proxy of C++ TSBase class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TSBase self, TSStr Nm) -> TSBase
Parameters:
Nm: TSStr const &
"""
_snap.TSBase_swiginit(self,_snap.new_TSBase(*args))
__swig_destroy__ = _snap.delete_TSBase
def GetSNm(self):
"""
GetSNm(TSBase self) -> TStr
Parameters:
self: TSBase const *
"""
return _snap.TSBase_GetSNm(self)
TSBase.GetSNm = new_instancemethod(_snap.TSBase_GetSNm,None,TSBase)
TSBase_swigregister = _snap.TSBase_swigregister
TSBase_swigregister(TSBase)
class TSIn(TSBase):
"""Proxy of C++ TSIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TSIn
def Eof(self):
"""
Eof(TSIn self) -> bool
Parameters:
self: TSIn *
"""
return _snap.TSIn_Eof(self)
def Len(self):
"""
Len(TSIn self) -> int
Parameters:
self: TSIn const *
"""
return _snap.TSIn_Len(self)
def GetCh(self):
"""
GetCh(TSIn self) -> char
Parameters:
self: TSIn *
"""
return _snap.TSIn_GetCh(self)
def PeekCh(self):
"""
PeekCh(TSIn self) -> char
Parameters:
self: TSIn *
"""
return _snap.TSIn_PeekCh(self)
def GetBf(self, *args):
"""
GetBf(TSIn self, void const * Bf, TSize const & BfL) -> int
Parameters:
Bf: void const *
BfL: TSize const &
"""
return _snap.TSIn_GetBf(self, *args)
def GetNextLnBf(self, *args):
"""
GetNextLnBf(TSIn self, TChA LnChA) -> bool
Parameters:
LnChA: TChA &
"""
return _snap.TSIn_GetNextLnBf(self, *args)
def Reset(self):
"""
Reset(TSIn self)
Parameters:
self: TSIn *
"""
return _snap.TSIn_Reset(self)
def IsFastMode(self):
"""
IsFastMode(TSIn self) -> bool
Parameters:
self: TSIn const *
"""
return _snap.TSIn_IsFastMode(self)
def SetFastMode(self, *args):
"""
SetFastMode(TSIn self, bool const & _FastMode)
Parameters:
_FastMode: bool const &
"""
return _snap.TSIn_SetFastMode(self, *args)
def LoadCs(self):
"""
LoadCs(TSIn self)
Parameters:
self: TSIn *
"""
return _snap.TSIn_LoadCs(self)
def LoadBf(self, *args):
"""
LoadBf(TSIn self, void const * Bf, TSize const & BfL)
Parameters:
Bf: void const *
BfL: TSize const &
"""
return _snap.TSIn_LoadBf(self, *args)
def LoadNewBf(self, *args):
"""
LoadNewBf(TSIn self, int const & BfL) -> void *
Parameters:
BfL: int const &
"""
return _snap.TSIn_LoadNewBf(self, *args)
def Load(self, *args):
"""
Load(TSIn self, bool & Bool)
Parameters:
Bool: bool &
Load(TSIn self, uchar & UCh)
Parameters:
UCh: uchar &
Load(TSIn self, char & Ch)
Parameters:
Ch: char &
Load(TSIn self, short & Short)
Parameters:
Short: short &
Load(TSIn self, ushort & UShort)
Parameters:
UShort: ushort &
Load(TSIn self, int & Int)
Parameters:
Int: int &
Load(TSIn self, uint & UInt)
Parameters:
UInt: uint &
Load(TSIn self, int64 & Int)
Parameters:
Int: int64 &
Load(TSIn self, uint64 & UInt)
Parameters:
UInt: uint64 &
Load(TSIn self, double & Flt)
Parameters:
Flt: double &
Load(TSIn self, sdouble & SFlt)
Parameters:
SFlt: sdouble &
Load(TSIn self, ldouble & LFlt)
Parameters:
LFlt: ldouble &
Load(TSIn self, char *& CStr, int const & MxCStrLen, int const & CStrLen)
Parameters:
CStr: char *&
MxCStrLen: int const &
CStrLen: int const &
Load(TSIn self, char *& CStr)
Parameters:
CStr: char *&
"""
return _snap.TSIn_Load(self, *args)
def __rshift__(self, *args):
"""
__rshift__(TSIn self, bool & Bool) -> TSIn
Parameters:
Bool: bool &
__rshift__(TSIn self, uchar & UCh) -> TSIn
Parameters:
UCh: uchar &
__rshift__(TSIn self, char & Ch) -> TSIn
Parameters:
Ch: char &
__rshift__(TSIn self, short & Sh) -> TSIn
Parameters:
Sh: short &
__rshift__(TSIn self, ushort & USh) -> TSIn
Parameters:
USh: ushort &
__rshift__(TSIn self, int & Int) -> TSIn
Parameters:
Int: int &
__rshift__(TSIn self, uint & UInt) -> TSIn
Parameters:
UInt: uint &
__rshift__(TSIn self, int64 & Int) -> TSIn
Parameters:
Int: int64 &
__rshift__(TSIn self, uint64 & UInt) -> TSIn
Parameters:
UInt: uint64 &
__rshift__(TSIn self, float & Flt) -> TSIn
Parameters:
Flt: float &
__rshift__(TSIn self, double & Double) -> TSIn
Parameters:
Double: double &
__rshift__(TSIn self, long double & LDouble) -> TSIn
Parameters:
LDouble: long double &
"""
return _snap.TSIn___rshift__(self, *args)
def GetNextLn(self, *args):
"""
GetNextLn(TSIn self, TStr LnStr) -> bool
Parameters:
LnStr: TStr &
GetNextLn(TSIn self, TChA LnChA) -> bool
Parameters:
LnChA: TChA &
"""
return _snap.TSIn_GetNextLn(self, *args)
TSIn.Eof = new_instancemethod(_snap.TSIn_Eof,None,TSIn)
TSIn.Len = new_instancemethod(_snap.TSIn_Len,None,TSIn)
TSIn.GetCh = new_instancemethod(_snap.TSIn_GetCh,None,TSIn)
TSIn.PeekCh = new_instancemethod(_snap.TSIn_PeekCh,None,TSIn)
TSIn.GetBf = new_instancemethod(_snap.TSIn_GetBf,None,TSIn)
TSIn.GetNextLnBf = new_instancemethod(_snap.TSIn_GetNextLnBf,None,TSIn)
TSIn.Reset = new_instancemethod(_snap.TSIn_Reset,None,TSIn)
TSIn.IsFastMode = new_instancemethod(_snap.TSIn_IsFastMode,None,TSIn)
TSIn.SetFastMode = new_instancemethod(_snap.TSIn_SetFastMode,None,TSIn)
TSIn.LoadCs = new_instancemethod(_snap.TSIn_LoadCs,None,TSIn)
TSIn.LoadBf = new_instancemethod(_snap.TSIn_LoadBf,None,TSIn)
TSIn.LoadNewBf = new_instancemethod(_snap.TSIn_LoadNewBf,None,TSIn)
TSIn.Load = new_instancemethod(_snap.TSIn_Load,None,TSIn)
TSIn.__rshift__ = new_instancemethod(_snap.TSIn___rshift__,None,TSIn)
TSIn.GetNextLn = new_instancemethod(_snap.TSIn_GetNextLn,None,TSIn)
TSIn_swigregister = _snap.TSIn_swigregister
TSIn_swigregister(TSIn)
TSIn.StdIn = _snap.cvar.TSIn_StdIn
class TSOut(TSBase):
"""Proxy of C++ TSOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TSOut
def EnableLnTrunc(self, *args):
"""
EnableLnTrunc(TSOut self, int const & _MxLnLen)
Parameters:
_MxLnLen: int const &
"""
return _snap.TSOut_EnableLnTrunc(self, *args)
def DisableLnTrunc(self):
"""
DisableLnTrunc(TSOut self)
Parameters:
self: TSOut *
"""
return _snap.TSOut_DisableLnTrunc(self)
def PutBf(self, *args):
"""
PutBf(TSOut self, void const * LBf, TSize const & LBfL) -> int
Parameters:
LBf: void const *
LBfL: TSize const &
"""
return _snap.TSOut_PutBf(self, *args)
def Flush(self):
"""
Flush(TSOut self)
Parameters:
self: TSOut *
"""
return _snap.TSOut_Flush(self)
def GetFileId(self):
"""
GetFileId(TSOut self) -> TFileId
Parameters:
self: TSOut const *
"""
return _snap.TSOut_GetFileId(self)
def PutMem(self, *args):
"""
PutMem(TSOut self, TMem Mem) -> int
Parameters:
Mem: TMem const &
"""
return _snap.TSOut_PutMem(self, *args)
def PutCh(self, *args):
"""
PutCh(TSOut self, char const & Ch) -> int
Parameters:
Ch: char const &
PutCh(TSOut self, char const & Ch, int const & Chs) -> int
Parameters:
Ch: char const &
Chs: int const &
"""
return _snap.TSOut_PutCh(self, *args)
def PutBool(self, *args):
"""
PutBool(TSOut self, bool const & Bool) -> int
Parameters:
Bool: bool const &
"""
return _snap.TSOut_PutBool(self, *args)
def PutInt(self, *args):
"""
PutInt(TSOut self, int const & Int) -> int
Parameters:
Int: int const &
PutInt(TSOut self, int const & Int, char const * FmtStr) -> int
Parameters:
Int: int const &
FmtStr: char const *
"""
return _snap.TSOut_PutInt(self, *args)
def PutUInt(self, *args):
"""
PutUInt(TSOut self, uint const & Int) -> int
Parameters:
Int: uint const &
PutUInt(TSOut self, uint const & Int, char const * FmtStr) -> int
Parameters:
Int: uint const &
FmtStr: char const *
"""
return _snap.TSOut_PutUInt(self, *args)
def PutFlt(self, *args):
"""
PutFlt(TSOut self, double const & Flt) -> int
Parameters:
Flt: double const &
PutFlt(TSOut self, double const & Flt, char const * FmtStr) -> int
Parameters:
Flt: double const &
FmtStr: char const *
"""
return _snap.TSOut_PutFlt(self, *args)
def PutStr(self, *args):
"""
PutStr(TSOut self, char const * CStr) -> int
Parameters:
CStr: char const *
PutStr(TSOut self, TChA ChA) -> int
Parameters:
ChA: TChA const &
PutStr(TSOut self, TStr Str, char const * FmtStr) -> int
Parameters:
Str: TStr const &
FmtStr: char const *
PutStr(TSOut self, TStr Str, bool const & ForceInLn=False) -> int
Parameters:
Str: TStr const &
ForceInLn: bool const &
PutStr(TSOut self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TSOut_PutStr(self, *args)
def PutStrLn(self, *args):
"""
PutStrLn(TSOut self, TStr Str, bool const & ForceInLn=False) -> int
Parameters:
Str: TStr const &
ForceInLn: bool const &
PutStrLn(TSOut self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TSOut_PutStrLn(self, *args)
def PutStrFmt(self, *args):
"""
PutStrFmt(TSOut self, char const * FmtStr) -> int
Parameters:
FmtStr: char const *
"""
return _snap.TSOut_PutStrFmt(self, *args)
def PutStrFmtLn(self, *args):
"""
PutStrFmtLn(TSOut self, char const * FmtStr) -> int
Parameters:
FmtStr: char const *
"""
return _snap.TSOut_PutStrFmtLn(self, *args)
def PutIndent(self, IndentLev=1):
"""
PutIndent(TSOut self, int const & IndentLev=1) -> int
Parameters:
IndentLev: int const &
PutIndent(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutIndent(self, IndentLev)
def PutLn(self, Lns=1):
"""
PutLn(TSOut self, int const & Lns=1) -> int
Parameters:
Lns: int const &
PutLn(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutLn(self, Lns)
def PutDosLn(self, Lns=1):
"""
PutDosLn(TSOut self, int const & Lns=1) -> int
Parameters:
Lns: int const &
PutDosLn(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutDosLn(self, Lns)
def PutSep(self, NextStrLen=0):
"""
PutSep(TSOut self, int const & NextStrLen=0) -> int
Parameters:
NextStrLen: int const &
PutSep(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutSep(self, NextStrLen)
def PutSepLn(self, Lns=0):
"""
PutSepLn(TSOut self, int const & Lns=0) -> int
Parameters:
Lns: int const &
PutSepLn(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutSepLn(self, Lns)
def SaveCs(self):
"""
SaveCs(TSOut self)
Parameters:
self: TSOut *
"""
return _snap.TSOut_SaveCs(self)
def SaveBf(self, *args):
"""
SaveBf(TSOut self, void const * Bf, TSize const & BfL)
Parameters:
Bf: void const *
BfL: TSize const &
"""
return _snap.TSOut_SaveBf(self, *args)
def Save(self, *args):
"""
Save(TSOut self, bool const & Bool)
Parameters:
Bool: bool const &
Save(TSOut self, char const & Ch)
Parameters:
Ch: char const &
Save(TSOut self, uchar const & UCh)
Parameters:
UCh: uchar const &
Save(TSOut self, short const & Short)
Parameters:
Short: short const &
Save(TSOut self, ushort const & UShort)
Parameters:
UShort: ushort const &
Save(TSOut self, int const & Int)
Parameters:
Int: int const &
Save(TSOut self, uint const & UInt)
Parameters:
UInt: uint const &
Save(TSOut self, int64 const & Int)
Parameters:
Int: int64 const &
Save(TSOut self, uint64 const & UInt)
Parameters:
UInt: uint64 const &
Save(TSOut self, double const & Flt)
Parameters:
Flt: double const &
Save(TSOut self, sdouble const & SFlt)
Parameters:
SFlt: sdouble const &
Save(TSOut self, ldouble const & LFlt)
Parameters:
LFlt: ldouble const &
Save(TSOut self, char const * CStr, TSize const & CStrLen)
Parameters:
CStr: char const *
CStrLen: TSize const &
Save(TSOut self, char const * CStr)
Parameters:
CStr: char const *
Save(TSOut self, TSIn SIn, TSize const & BfL=-1)
Parameters:
SIn: TSIn &
BfL: TSize const &
Save(TSOut self, TSIn SIn)
Parameters:
SIn: TSIn &
Save(TSOut self, PSIn const & SIn, TSize const & BfL=-1)
Parameters:
SIn: PSIn const &
BfL: TSize const &
Save(TSOut self, PSIn const & SIn)
Parameters:
SIn: PSIn const &
Save(TSOut self, void const * Bf, TSize const & BfL)
Parameters:
Bf: void const *
BfL: TSize const &
"""
return _snap.TSOut_Save(self, *args)
def __lshift__(self, *args):
"""
__lshift__(TSOut self, bool const & Bool) -> TSOut
Parameters:
Bool: bool const &
__lshift__(TSOut self, uchar const & UCh) -> TSOut
Parameters:
UCh: uchar const &
__lshift__(TSOut self, char const & Ch) -> TSOut
Parameters:
Ch: char const &
__lshift__(TSOut self, short const & Sh) -> TSOut
Parameters:
Sh: short const &
__lshift__(TSOut self, ushort const & USh) -> TSOut
Parameters:
USh: ushort const &
__lshift__(TSOut self, int const & Int) -> TSOut
Parameters:
Int: int const &
__lshift__(TSOut self, uint const & Int) -> TSOut
Parameters:
Int: uint const &
__lshift__(TSOut self, int64 const & Int) -> TSOut
Parameters:
Int: int64 const &
__lshift__(TSOut self, uint64 const & UInt) -> TSOut
Parameters:
UInt: uint64 const &
__lshift__(TSOut self, float const & Flt) -> TSOut
Parameters:
Flt: float const &
__lshift__(TSOut self, double const & Double) -> TSOut
Parameters:
Double: double const &
__lshift__(TSOut self, long double const & LDouble) -> TSOut
Parameters:
LDouble: long double const &
__lshift__(TSOut self, TSOutMnp Mnp) -> TSOut
Parameters:
Mnp: TSOutMnp const &
__lshift__(TSOut self, TSOut &(*)(TSOut &) FuncPt) -> TSOut
Parameters:
FuncPt: TSOut &(*)(TSOut &)
__lshift__(TSOut self, TSIn SIn) -> TSOut
Parameters:
SIn: TSIn &
__lshift__(TSOut self, PSIn & SIn) -> TSOut
Parameters:
SIn: PSIn &
"""
return _snap.TSOut___lshift__(self, *args)
TSOut.EnableLnTrunc = new_instancemethod(_snap.TSOut_EnableLnTrunc,None,TSOut)
TSOut.DisableLnTrunc = new_instancemethod(_snap.TSOut_DisableLnTrunc,None,TSOut)
TSOut.PutBf = new_instancemethod(_snap.TSOut_PutBf,None,TSOut)
TSOut.Flush = new_instancemethod(_snap.TSOut_Flush,None,TSOut)
TSOut.GetFileId = new_instancemethod(_snap.TSOut_GetFileId,None,TSOut)
TSOut.PutMem = new_instancemethod(_snap.TSOut_PutMem,None,TSOut)
TSOut.PutCh = new_instancemethod(_snap.TSOut_PutCh,None,TSOut)
TSOut.PutBool = new_instancemethod(_snap.TSOut_PutBool,None,TSOut)
TSOut.PutInt = new_instancemethod(_snap.TSOut_PutInt,None,TSOut)
TSOut.PutUInt = new_instancemethod(_snap.TSOut_PutUInt,None,TSOut)
TSOut.PutFlt = new_instancemethod(_snap.TSOut_PutFlt,None,TSOut)
TSOut.PutStr = new_instancemethod(_snap.TSOut_PutStr,None,TSOut)
TSOut.PutStrLn = new_instancemethod(_snap.TSOut_PutStrLn,None,TSOut)
TSOut.PutStrFmt = new_instancemethod(_snap.TSOut_PutStrFmt,None,TSOut)
TSOut.PutStrFmtLn = new_instancemethod(_snap.TSOut_PutStrFmtLn,None,TSOut)
TSOut.PutIndent = new_instancemethod(_snap.TSOut_PutIndent,None,TSOut)
TSOut.PutLn = new_instancemethod(_snap.TSOut_PutLn,None,TSOut)
TSOut.PutDosLn = new_instancemethod(_snap.TSOut_PutDosLn,None,TSOut)
TSOut.PutSep = new_instancemethod(_snap.TSOut_PutSep,None,TSOut)
TSOut.PutSepLn = new_instancemethod(_snap.TSOut_PutSepLn,None,TSOut)
TSOut.SaveCs = new_instancemethod(_snap.TSOut_SaveCs,None,TSOut)
TSOut.SaveBf = new_instancemethod(_snap.TSOut_SaveBf,None,TSOut)
TSOut.Save = new_instancemethod(_snap.TSOut_Save,None,TSOut)
TSOut.__lshift__ = new_instancemethod(_snap.TSOut___lshift__,None,TSOut)
TSOut_swigregister = _snap.TSOut_swigregister
TSOut_swigregister(TSOut)
TSOut.StdOut = _snap.cvar.TSOut_StdOut
class TSInOut(TSIn,TSOut):
"""Proxy of C++ TSInOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TSInOut
def SetPos(self, *args):
"""
SetPos(TSInOut self, int const & Pos)
Parameters:
Pos: int const &
"""
return _snap.TSInOut_SetPos(self, *args)
def MovePos(self, *args):
"""
MovePos(TSInOut self, int const & DPos)
Parameters:
DPos: int const &
"""
return _snap.TSInOut_MovePos(self, *args)
def GetPos(self):
"""
GetPos(TSInOut self) -> int
Parameters:
self: TSInOut const *
"""
return _snap.TSInOut_GetPos(self)
def GetSize(self):
"""
GetSize(TSInOut self) -> int
Parameters:
self: TSInOut const *
"""
return _snap.TSInOut_GetSize(self)
def Clr(self):
"""
Clr(TSInOut self)
Parameters:
self: TSInOut *
"""
return _snap.TSInOut_Clr(self)
TSInOut.SetPos = new_instancemethod(_snap.TSInOut_SetPos,None,TSInOut)
TSInOut.MovePos = new_instancemethod(_snap.TSInOut_MovePos,None,TSInOut)
TSInOut.GetPos = new_instancemethod(_snap.TSInOut_GetPos,None,TSInOut)
TSInOut.GetSize = new_instancemethod(_snap.TSInOut_GetSize,None,TSInOut)
TSInOut.Clr = new_instancemethod(_snap.TSInOut_Clr,None,TSInOut)
TSInOut_swigregister = _snap.TSInOut_swigregister
TSInOut_swigregister(TSInOut)
class TStdIn(TSIn):
"""Proxy of C++ TStdIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self):
"""__init__(TStdIn self) -> TStdIn"""
_snap.TStdIn_swiginit(self,_snap.new_TStdIn())
def New():
"""New() -> TPt< TSIn >"""
return _snap.TStdIn_New()
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TStdIn
TStdIn_swigregister = _snap.TStdIn_swigregister
TStdIn_swigregister(TStdIn)
def TStdIn_New():
"""TStdIn_New() -> TPt< TSIn >"""
return _snap.TStdIn_New()
class TStdOut(TSOut):
"""Proxy of C++ TStdOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self):
"""__init__(TStdOut self) -> TStdOut"""
_snap.TStdOut_swiginit(self,_snap.new_TStdOut())
def New():
"""New() -> TPt< TSOut >"""
return _snap.TStdOut_New()
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TStdOut
TStdOut_swigregister = _snap.TStdOut_swigregister
TStdOut_swigregister(TStdOut)
def TStdOut_New():
"""TStdOut_New() -> TPt< TSOut >"""
return _snap.TStdOut_New()
class TFIn(TSIn):
"""Proxy of C++ TFIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TFIn self, TStr FNm) -> TFIn
Parameters:
FNm: TStr const &
__init__(TFIn self, TStr FNm, bool & OpenedP) -> TFIn
Parameters:
FNm: TStr const &
OpenedP: bool &
"""
_snap.TFIn_swiginit(self,_snap.new_TFIn(*args))
def New(*args):
"""
New(TStr FNm) -> PSIn
Parameters:
FNm: TStr const &
New(TStr FNm, bool & OpenedP) -> PSIn
Parameters:
FNm: TStr const &
OpenedP: bool &
"""
return _snap.TFIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TFIn
TFIn_swigregister = _snap.TFIn_swigregister
TFIn_swigregister(TFIn)
def TFIn_New(*args):
"""
New(TStr FNm) -> PSIn
Parameters:
FNm: TStr const &
TFIn_New(TStr FNm, bool & OpenedP) -> PSIn
Parameters:
FNm: TStr const &
OpenedP: bool &
"""
return _snap.TFIn_New(*args)
class TFOut(TSOut):
"""Proxy of C++ TFOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TFOut self, TStr _FNm, bool const & Append=False) -> TFOut
Parameters:
_FNm: TStr const &
Append: bool const &
__init__(TFOut self, TStr _FNm) -> TFOut
Parameters:
_FNm: TStr const &
__init__(TFOut self, TStr _FNm, bool const & Append, bool & OpenedP) -> TFOut
Parameters:
_FNm: TStr const &
Append: bool const &
OpenedP: bool &
"""
_snap.TFOut_swiginit(self,_snap.new_TFOut(*args))
def New(*args):
"""
New(TStr FNm, bool const & Append=False) -> PSOut
Parameters:
FNm: TStr const &
Append: bool const &
New(TStr FNm) -> PSOut
Parameters:
FNm: TStr const &
New(TStr FNm, bool const & Append, bool & OpenedP) -> PSOut
Parameters:
FNm: TStr const &
Append: bool const &
OpenedP: bool &
"""
return _snap.TFOut_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TFOut
TFOut_swigregister = _snap.TFOut_swigregister
TFOut_swigregister(TFOut)
def TFOut_New(*args):
"""
New(TStr FNm, bool const & Append=False) -> PSOut
Parameters:
FNm: TStr const &
Append: bool const &
New(TStr FNm) -> PSOut
Parameters:
FNm: TStr const &
TFOut_New(TStr FNm, bool const & Append, bool & OpenedP) -> PSOut
Parameters:
FNm: TStr const &
Append: bool const &
OpenedP: bool &
"""
return _snap.TFOut_New(*args)
faUndef = _snap.faUndef
faCreate = _snap.faCreate
faUpdate = _snap.faUpdate
faAppend = _snap.faAppend
faRdOnly = _snap.faRdOnly
faRestore = _snap.faRestore
class TMIn(TSIn):
"""Proxy of C++ TMIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TMIn self, void const * _Bf, int const & _BfL, bool const & TakeBf=False) -> TMIn
Parameters:
_Bf: void const *
_BfL: int const &
TakeBf: bool const &
__init__(TMIn self, void const * _Bf, int const & _BfL) -> TMIn
Parameters:
_Bf: void const *
_BfL: int const &
__init__(TMIn self, TSIn SIn) -> TMIn
Parameters:
SIn: TSIn &
__init__(TMIn self, char const * CStr) -> TMIn
Parameters:
CStr: char const *
__init__(TMIn self, TStr Str) -> TMIn
Parameters:
Str: TStr const &
__init__(TMIn self, TChA ChA) -> TMIn
Parameters:
ChA: TChA const &
"""
_snap.TMIn_swiginit(self,_snap.new_TMIn(*args))
def New(*args):
"""
New(void const * _Bf, int const & _BfL, bool const & TakeBf=False) -> PSIn
Parameters:
_Bf: void const *
_BfL: int const &
TakeBf: bool const &
New(void const * _Bf, int const & _BfL) -> PSIn
Parameters:
_Bf: void const *
_BfL: int const &
New(char const * CStr) -> PSIn
Parameters:
CStr: char const *
New(TStr Str) -> PSIn
Parameters:
Str: TStr const &
New(TChA ChA) -> PSIn
Parameters:
ChA: TChA const &
"""
return _snap.TMIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TMIn
def GetBfAddr(self):
"""
GetBfAddr(TMIn self) -> char *
Parameters:
self: TMIn *
"""
return _snap.TMIn_GetBfAddr(self)
TMIn.GetBfAddr = new_instancemethod(_snap.TMIn_GetBfAddr,None,TMIn)
TMIn_swigregister = _snap.TMIn_swigregister
TMIn_swigregister(TMIn)
def TMIn_New(*args):
"""
New(void const * _Bf, int const & _BfL, bool const & TakeBf=False) -> PSIn
Parameters:
_Bf: void const *
_BfL: int const &
TakeBf: bool const &
New(void const * _Bf, int const & _BfL) -> PSIn
Parameters:
_Bf: void const *
_BfL: int const &
New(char const * CStr) -> PSIn
Parameters:
CStr: char const *
New(TStr Str) -> PSIn
Parameters:
Str: TStr const &
TMIn_New(TChA ChA) -> PSIn
Parameters:
ChA: TChA const &
"""
return _snap.TMIn_New(*args)
class TMOut(TSOut):
"""Proxy of C++ TMOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def New(MxBfL=1024):
"""
New(int const & MxBfL=1024) -> PSOut
Parameters:
MxBfL: int const &
New() -> PSOut
"""
return _snap.TMOut_New(MxBfL)
New = staticmethod(New)
def __init__(self, *args):
"""
__init__(TMOut self, int const & _MxBfL=1024) -> TMOut
Parameters:
_MxBfL: int const &
__init__(TMOut self) -> TMOut
__init__(TMOut self, char * _Bf, int const & _MxBfL) -> TMOut
Parameters:
_Bf: char *
_MxBfL: int const &
"""
_snap.TMOut_swiginit(self,_snap.new_TMOut(*args))
__swig_destroy__ = _snap.delete_TMOut
def AppendBf(self, *args):
"""
AppendBf(TMOut self, void const * LBf, TSize const & LBfL)
Parameters:
LBf: void const *
LBfL: TSize const &
"""
return _snap.TMOut_AppendBf(self, *args)
def Len(self):
"""
Len(TMOut self) -> int
Parameters:
self: TMOut const *
"""
return _snap.TMOut_Len(self)
def Clr(self):
"""
Clr(TMOut self)
Parameters:
self: TMOut *
"""
return _snap.TMOut_Clr(self)
def GetCh(self, *args):
"""
GetCh(TMOut self, int const & ChN) -> char
Parameters:
ChN: int const &
"""
return _snap.TMOut_GetCh(self, *args)
def GetAsStr(self):
"""
GetAsStr(TMOut self) -> TStr
Parameters:
self: TMOut const *
"""
return _snap.TMOut_GetAsStr(self)
def CutBf(self, *args):
"""
CutBf(TMOut self, int const & CutBfL)
Parameters:
CutBfL: int const &
"""
return _snap.TMOut_CutBf(self, *args)
def GetSIn(self, *args):
"""
GetSIn(TMOut self, bool const & IsCut=True, int const & CutBfL=-1) -> PSIn
Parameters:
IsCut: bool const &
CutBfL: int const &
GetSIn(TMOut self, bool const & IsCut=True) -> PSIn
Parameters:
IsCut: bool const &
GetSIn(TMOut self) -> PSIn
Parameters:
self: TMOut *
"""
return _snap.TMOut_GetSIn(self, *args)
def GetBfAddr(self):
"""
GetBfAddr(TMOut self) -> char *
Parameters:
self: TMOut const *
"""
return _snap.TMOut_GetBfAddr(self)
def IsCrLfLn(self):
"""
IsCrLfLn(TMOut self) -> bool
Parameters:
self: TMOut const *
"""
return _snap.TMOut_IsCrLfLn(self)
def GetCrLfLn(self):
"""
GetCrLfLn(TMOut self) -> TStr
Parameters:
self: TMOut *
"""
return _snap.TMOut_GetCrLfLn(self)
def IsEolnLn(self):
"""
IsEolnLn(TMOut self) -> bool
Parameters:
self: TMOut const *
"""
return _snap.TMOut_IsEolnLn(self)
def GetEolnLn(self, *args):
"""
GetEolnLn(TMOut self, bool const & DoAddEoln, bool const & DoCutBf) -> TStr
Parameters:
DoAddEoln: bool const &
DoCutBf: bool const &
"""
return _snap.TMOut_GetEolnLn(self, *args)
def MkEolnLn(self):
"""
MkEolnLn(TMOut self)
Parameters:
self: TMOut *
"""
return _snap.TMOut_MkEolnLn(self)
TMOut.AppendBf = new_instancemethod(_snap.TMOut_AppendBf,None,TMOut)
TMOut.Len = new_instancemethod(_snap.TMOut_Len,None,TMOut)
TMOut.Clr = new_instancemethod(_snap.TMOut_Clr,None,TMOut)
TMOut.GetCh = new_instancemethod(_snap.TMOut_GetCh,None,TMOut)
TMOut.GetAsStr = new_instancemethod(_snap.TMOut_GetAsStr,None,TMOut)
TMOut.CutBf = new_instancemethod(_snap.TMOut_CutBf,None,TMOut)
TMOut.GetSIn = new_instancemethod(_snap.TMOut_GetSIn,None,TMOut)
TMOut.GetBfAddr = new_instancemethod(_snap.TMOut_GetBfAddr,None,TMOut)
TMOut.IsCrLfLn = new_instancemethod(_snap.TMOut_IsCrLfLn,None,TMOut)
TMOut.GetCrLfLn = new_instancemethod(_snap.TMOut_GetCrLfLn,None,TMOut)
TMOut.IsEolnLn = new_instancemethod(_snap.TMOut_IsEolnLn,None,TMOut)
TMOut.GetEolnLn = new_instancemethod(_snap.TMOut_GetEolnLn,None,TMOut)
TMOut.MkEolnLn = new_instancemethod(_snap.TMOut_MkEolnLn,None,TMOut)
TMOut_swigregister = _snap.TMOut_swigregister
TMOut_swigregister(TMOut)
def TMOut_New(MxBfL=1024):
"""
New(int const & MxBfL=1024) -> PSOut
Parameters:
MxBfL: int const &
TMOut_New() -> PSOut
"""
return _snap.TMOut_New(MxBfL)
class TChRet(object):
"""Proxy of C++ TChRet class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TChRet self, PSIn const & _SIn, char const & _EofCh=0) -> TChRet
Parameters:
_SIn: PSIn const &
_EofCh: char const &
__init__(TChRet self, PSIn const & _SIn) -> TChRet
Parameters:
_SIn: PSIn const &
"""
_snap.TChRet_swiginit(self,_snap.new_TChRet(*args))
def Eof(self):
"""
Eof(TChRet self) -> bool
Parameters:
self: TChRet const *
"""
return _snap.TChRet_Eof(self)
def GetCh(self):
"""
GetCh(TChRet self) -> char
Parameters:
self: TChRet *
"""
return _snap.TChRet_GetCh(self)
def __call__(self):
"""
__call__(TChRet self) -> char
Parameters:
self: TChRet *
"""
return _snap.TChRet___call__(self)
__swig_destroy__ = _snap.delete_TChRet
TChRet.Eof = new_instancemethod(_snap.TChRet_Eof,None,TChRet)
TChRet.GetCh = new_instancemethod(_snap.TChRet_GetCh,None,TChRet)
TChRet.__call__ = new_instancemethod(_snap.TChRet___call__,None,TChRet)
TChRet_swigregister = _snap.TChRet_swigregister
TChRet_swigregister(TChRet)
class TLnRet(object):
"""Proxy of C++ TLnRet class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TLnRet self, PSIn const & _SIn) -> TLnRet
Parameters:
_SIn: PSIn const &
"""
_snap.TLnRet_swiginit(self,_snap.new_TLnRet(*args))
def NextLn(self, *args):
"""
NextLn(TLnRet self, TStr LnStr) -> bool
Parameters:
LnStr: TStr &
"""
return _snap.TLnRet_NextLn(self, *args)
__swig_destroy__ = _snap.delete_TLnRet
TLnRet.NextLn = new_instancemethod(_snap.TLnRet_NextLn,None,TLnRet)
TLnRet_swigregister = _snap.TLnRet_swigregister
TLnRet_swigregister(TLnRet)
class TFile(object):
"""Proxy of C++ TFile class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def Exists(*args):
"""
Exists(TStr FNm) -> bool
Parameters:
FNm: TStr const &
"""
return _snap.TFile_Exists(*args)
Exists = staticmethod(Exists)
def Del(*args):
"""
Del(TStr FNm, bool const & ThrowExceptP=True)
Parameters:
FNm: TStr const &
ThrowExceptP: bool const &
Del(TStr FNm)
Parameters:
FNm: TStr const &
"""
return _snap.TFile_Del(*args)
Del = staticmethod(Del)
def DelWc(*args):
"""
DelWc(TStr WcStr, bool const & RecurseDirP=False)
Parameters:
WcStr: TStr const &
RecurseDirP: bool const &
DelWc(TStr WcStr)
Parameters:
WcStr: TStr const &
"""
return _snap.TFile_DelWc(*args)
DelWc = staticmethod(DelWc)
def Rename(*args):
"""
Rename(TStr SrcFNm, TStr DstFNm)
Parameters:
SrcFNm: TStr const &
DstFNm: TStr const &
"""
return _snap.TFile_Rename(*args)
Rename = staticmethod(Rename)
def GetUniqueFNm(*args):
"""
GetUniqueFNm(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TFile_GetUniqueFNm(*args)
GetUniqueFNm = staticmethod(GetUniqueFNm)
def __init__(self):
"""__init__(TFile self) -> TFile"""
_snap.TFile_swiginit(self,_snap.new_TFile())
__swig_destroy__ = _snap.delete_TFile
TFile_swigregister = _snap.TFile_swigregister
TFile_swigregister(TFile)
TFile.TxtFExt = _snap.cvar.TFile_TxtFExt
TFile.HtmlFExt = _snap.cvar.TFile_HtmlFExt
TFile.HtmFExt = _snap.cvar.TFile_HtmFExt
TFile.GifFExt = _snap.cvar.TFile_GifFExt
TFile.JarFExt = _snap.cvar.TFile_JarFExt
def TFile_Exists(*args):
"""
TFile_Exists(TStr FNm) -> bool
Parameters:
FNm: TStr const &
"""
return _snap.TFile_Exists(*args)
def TFile_Del(*args):
"""
Del(TStr FNm, bool const & ThrowExceptP=True)
Parameters:
FNm: TStr const &
ThrowExceptP: bool const &
TFile_Del(TStr FNm)
Parameters:
FNm: TStr const &
"""
return _snap.TFile_Del(*args)
def TFile_DelWc(*args):
"""
DelWc(TStr WcStr, bool const & RecurseDirP=False)
Parameters:
WcStr: TStr const &
RecurseDirP: bool const &
TFile_DelWc(TStr WcStr)
Parameters:
WcStr: TStr const &
"""
return _snap.TFile_DelWc(*args)
def TFile_Rename(*args):
"""
TFile_Rename(TStr SrcFNm, TStr DstFNm)
Parameters:
SrcFNm: TStr const &
DstFNm: TStr const &
"""
return _snap.TFile_Rename(*args)
def TFile_GetUniqueFNm(*args):
"""
TFile_GetUniqueFNm(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TFile_GetUniqueFNm(*args)
class TUNGraph(object):
"""Proxy of C++ TUNGraph class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TUNGraph self) -> TUNGraph
__init__(TUNGraph self, int const & Nodes, int const & Edges) -> TUNGraph
Parameters:
Nodes: int const &
Edges: int const &
__init__(TUNGraph self, TUNGraph Graph) -> TUNGraph
Parameters:
Graph: TUNGraph const &
__init__(TUNGraph self, TSIn SIn) -> TUNGraph
Parameters:
SIn: TSIn &
"""
_snap.TUNGraph_swiginit(self,_snap.new_TUNGraph(*args))
def Save(self, *args):
"""
Save(TUNGraph self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TUNGraph_Save(self, *args)
def New(*args):
"""
New() -> PUNGraph
New(int const & Nodes, int const & Edges) -> PUNGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TUNGraph_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PUNGraph
Parameters:
SIn: TSIn &
"""
return _snap.TUNGraph_Load(*args)
Load = staticmethod(Load)
def HasFlag(self, *args):
"""
HasFlag(TUNGraph self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.TUNGraph_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(TUNGraph self) -> int
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(TUNGraph self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TUNGraph self) -> int
AddNode(TUNGraph self, TUNGraph::TNodeI const & NodeI) -> int
Parameters:
NodeI: TUNGraph::TNodeI const &
AddNode(TUNGraph self, int const & NId, TIntV NbrNIdV) -> int
Parameters:
NId: int const &
NbrNIdV: TIntV const &
AddNode(TUNGraph self, int const & NId, TVecPool< TInt > const & Pool, int const & NIdVId) -> int
Parameters:
NId: int const &
Pool: TVecPool< TInt > const &
NIdVId: int const &
"""
return _snap.TUNGraph_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TUNGraph self, int const & NId)
Parameters:
NId: int const &
DelNode(TUNGraph self, TUNGraph::TNode const & NodeI)
Parameters:
NodeI: TUNGraph::TNode const &
"""
return _snap.TUNGraph_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TUNGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraph_IsNode(self, *args)
def BegNI(self):
"""
BegNI(TUNGraph self) -> TUNGraph::TNodeI
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_BegNI(self)
def EndNI(self):
"""
EndNI(TUNGraph self) -> TUNGraph::TNodeI
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_EndNI(self)
def GetNI(self, *args):
"""
GetNI(TUNGraph self, int const & NId) -> TUNGraph::TNodeI
Parameters:
NId: int const &
"""
return _snap.TUNGraph_GetNI(self, *args)
def GetMxNId(self):
"""
GetMxNId(TUNGraph self) -> int
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(TUNGraph self) -> int
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TUNGraph self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(TUNGraph self, TUNGraph::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TUNGraph::TEdgeI const &
"""
return _snap.TUNGraph_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TUNGraph self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TUNGraph_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TUNGraph self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TUNGraph_IsEdge(self, *args)
def BegEI(self):
"""
BegEI(TUNGraph self) -> TUNGraph::TEdgeI
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_BegEI(self)
def EndEI(self):
"""
EndEI(TUNGraph self) -> TUNGraph::TEdgeI
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TUNGraph self, int const & SrcNId, int const & DstNId) -> TUNGraph::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TUNGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TUNGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TUNGraph self) -> int
Parameters:
self: TUNGraph *
"""
return _snap.TUNGraph_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TUNGraph self, TRnd Rnd=Rnd) -> TUNGraph::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TUNGraph self) -> TUNGraph::TNodeI
Parameters:
self: TUNGraph *
"""
return _snap.TUNGraph_GetRndNI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TUNGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TUNGraph_GetNIdV(self, *args)
def Empty(self):
"""
Empty(TUNGraph self) -> bool
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_Empty(self)
def Clr(self):
"""
Clr(TUNGraph self)
Parameters:
self: TUNGraph *
"""
return _snap.TUNGraph_Clr(self)
def Reserve(self, *args):
"""
Reserve(TUNGraph self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TUNGraph_Reserve(self, *args)
def ReserveNIdDeg(self, *args):
"""
ReserveNIdDeg(TUNGraph self, int const & NId, int const & Deg)
Parameters:
NId: int const &
Deg: int const &
"""
return _snap.TUNGraph_ReserveNIdDeg(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TUNGraph self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TUNGraph self)
Parameters:
self: TUNGraph *
"""
return _snap.TUNGraph_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TUNGraph self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TUNGraph self) -> bool
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TUNGraph self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TUNGraph self)
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_Dump(self, *args)
def GetSmallGraph():
"""GetSmallGraph() -> PUNGraph"""
return _snap.TUNGraph_GetSmallGraph()
GetSmallGraph = staticmethod(GetSmallGraph)
__swig_destroy__ = _snap.delete_TUNGraph
TUNGraph.Save = new_instancemethod(_snap.TUNGraph_Save,None,TUNGraph)
TUNGraph.HasFlag = new_instancemethod(_snap.TUNGraph_HasFlag,None,TUNGraph)
TUNGraph.GetNodes = new_instancemethod(_snap.TUNGraph_GetNodes,None,TUNGraph)
TUNGraph.AddNode = new_instancemethod(_snap.TUNGraph_AddNode,None,TUNGraph)
TUNGraph.DelNode = new_instancemethod(_snap.TUNGraph_DelNode,None,TUNGraph)
TUNGraph.IsNode = new_instancemethod(_snap.TUNGraph_IsNode,None,TUNGraph)
TUNGraph.BegNI = new_instancemethod(_snap.TUNGraph_BegNI,None,TUNGraph)
TUNGraph.EndNI = new_instancemethod(_snap.TUNGraph_EndNI,None,TUNGraph)
TUNGraph.GetNI = new_instancemethod(_snap.TUNGraph_GetNI,None,TUNGraph)
TUNGraph.GetMxNId = new_instancemethod(_snap.TUNGraph_GetMxNId,None,TUNGraph)
TUNGraph.GetEdges = new_instancemethod(_snap.TUNGraph_GetEdges,None,TUNGraph)
TUNGraph.AddEdge = new_instancemethod(_snap.TUNGraph_AddEdge,None,TUNGraph)
TUNGraph.DelEdge = new_instancemethod(_snap.TUNGraph_DelEdge,None,TUNGraph)
TUNGraph.IsEdge = new_instancemethod(_snap.TUNGraph_IsEdge,None,TUNGraph)
TUNGraph.BegEI = new_instancemethod(_snap.TUNGraph_BegEI,None,TUNGraph)
TUNGraph.EndEI = new_instancemethod(_snap.TUNGraph_EndEI,None,TUNGraph)
TUNGraph.GetEI = new_instancemethod(_snap.TUNGraph_GetEI,None,TUNGraph)
TUNGraph.GetRndNId = new_instancemethod(_snap.TUNGraph_GetRndNId,None,TUNGraph)
TUNGraph.GetRndNI = new_instancemethod(_snap.TUNGraph_GetRndNI,None,TUNGraph)
TUNGraph.GetNIdV = new_instancemethod(_snap.TUNGraph_GetNIdV,None,TUNGraph)
TUNGraph.Empty = new_instancemethod(_snap.TUNGraph_Empty,None,TUNGraph)
TUNGraph.Clr = new_instancemethod(_snap.TUNGraph_Clr,None,TUNGraph)
TUNGraph.Reserve = new_instancemethod(_snap.TUNGraph_Reserve,None,TUNGraph)
TUNGraph.ReserveNIdDeg = new_instancemethod(_snap.TUNGraph_ReserveNIdDeg,None,TUNGraph)
TUNGraph.Defrag = new_instancemethod(_snap.TUNGraph_Defrag,None,TUNGraph)
TUNGraph.IsOk = new_instancemethod(_snap.TUNGraph_IsOk,None,TUNGraph)
TUNGraph.Dump = new_instancemethod(_snap.TUNGraph_Dump,None,TUNGraph)
TUNGraph_swigregister = _snap.TUNGraph_swigregister
TUNGraph_swigregister(TUNGraph)
def TUNGraph_New(*args):
"""
New() -> PUNGraph
TUNGraph_New(int const & Nodes, int const & Edges) -> PUNGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TUNGraph_New(*args)
def TUNGraph_Load(*args):
"""
TUNGraph_Load(TSIn SIn) -> PUNGraph
Parameters:
SIn: TSIn &
"""
return _snap.TUNGraph_Load(*args)
def TUNGraph_GetSmallGraph():
"""TUNGraph_GetSmallGraph() -> PUNGraph"""
return _snap.TUNGraph_GetSmallGraph()
class TNGraph(object):
"""Proxy of C++ TNGraph class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNGraph self) -> TNGraph
__init__(TNGraph self, int const & Nodes, int const & Edges) -> TNGraph
Parameters:
Nodes: int const &
Edges: int const &
__init__(TNGraph self, TNGraph Graph) -> TNGraph
Parameters:
Graph: TNGraph const &
__init__(TNGraph self, TSIn SIn) -> TNGraph
Parameters:
SIn: TSIn &
"""
_snap.TNGraph_swiginit(self,_snap.new_TNGraph(*args))
def Save(self, *args):
"""
Save(TNGraph self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TNGraph_Save(self, *args)
def New(*args):
"""
New() -> PNGraph
New(int const & Nodes, int const & Edges) -> PNGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNGraph_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PNGraph
Parameters:
SIn: TSIn &
"""
return _snap.TNGraph_Load(*args)
Load = staticmethod(Load)
def HasFlag(self, *args):
"""
HasFlag(TNGraph self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.TNGraph_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(TNGraph self) -> int
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(TNGraph self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TNGraph self) -> int
AddNode(TNGraph self, TNGraph::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNGraph::TNodeI const &
AddNode(TNGraph self, int const & NId, TIntV InNIdV, TIntV OutNIdV) -> int
Parameters:
NId: int const &
InNIdV: TIntV const &
OutNIdV: TIntV const &
AddNode(TNGraph self, int const & NId, TVecPool< TInt > const & Pool, int const & SrcVId, int const & DstVId) -> int
Parameters:
NId: int const &
Pool: TVecPool< TInt > const &
SrcVId: int const &
DstVId: int const &
"""
return _snap.TNGraph_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TNGraph self, int const & NId)
Parameters:
NId: int const &
DelNode(TNGraph self, TNGraph::TNode const & NodeI)
Parameters:
NodeI: TNGraph::TNode const &
"""
return _snap.TNGraph_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TNGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNGraph_IsNode(self, *args)
def BegNI(self):
"""
BegNI(TNGraph self) -> TNGraph::TNodeI
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_BegNI(self)
def EndNI(self):
"""
EndNI(TNGraph self) -> TNGraph::TNodeI
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_EndNI(self)
def GetNI(self, *args):
"""
GetNI(TNGraph self, int const & NId) -> TNGraph::TNodeI
Parameters:
NId: int const &
"""
return _snap.TNGraph_GetNI(self, *args)
def GetMxNId(self):
"""
GetMxNId(TNGraph self) -> int
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(TNGraph self) -> int
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TNGraph self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(TNGraph self, TNGraph::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TNGraph::TEdgeI const &
"""
return _snap.TNGraph_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TNGraph self, int const & SrcNId, int const & DstNId, bool const & IsDir=True)
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
DelEdge(TNGraph self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNGraph_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TNGraph self, int const & SrcNId, int const & DstNId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
IsEdge(TNGraph self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNGraph_IsEdge(self, *args)
def BegEI(self):
"""
BegEI(TNGraph self) -> TNGraph::TEdgeI
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_BegEI(self)
def EndEI(self):
"""
EndEI(TNGraph self) -> TNGraph::TEdgeI
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TNGraph self, int const & SrcNId, int const & DstNId) -> TNGraph::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TNGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TNGraph self) -> int
Parameters:
self: TNGraph *
"""
return _snap.TNGraph_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TNGraph self, TRnd Rnd=Rnd) -> TNGraph::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TNGraph self) -> TNGraph::TNodeI
Parameters:
self: TNGraph *
"""
return _snap.TNGraph_GetRndNI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TNGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TNGraph_GetNIdV(self, *args)
def Empty(self):
"""
Empty(TNGraph self) -> bool
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_Empty(self)
def Clr(self):
"""
Clr(TNGraph self)
Parameters:
self: TNGraph *
"""
return _snap.TNGraph_Clr(self)
def Reserve(self, *args):
"""
Reserve(TNGraph self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNGraph_Reserve(self, *args)
def ReserveNIdInDeg(self, *args):
"""
ReserveNIdInDeg(TNGraph self, int const & NId, int const & InDeg)
Parameters:
NId: int const &
InDeg: int const &
"""
return _snap.TNGraph_ReserveNIdInDeg(self, *args)
def ReserveNIdOutDeg(self, *args):
"""
ReserveNIdOutDeg(TNGraph self, int const & NId, int const & OutDeg)
Parameters:
NId: int const &
OutDeg: int const &
"""
return _snap.TNGraph_ReserveNIdOutDeg(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TNGraph self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TNGraph self)
Parameters:
self: TNGraph *
"""
return _snap.TNGraph_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TNGraph self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TNGraph self) -> bool
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TNGraph self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TNGraph self)
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_Dump(self, *args)
def GetSmallGraph():
"""GetSmallGraph() -> PNGraph"""
return _snap.TNGraph_GetSmallGraph()
GetSmallGraph = staticmethod(GetSmallGraph)
__swig_destroy__ = _snap.delete_TNGraph
TNGraph.Save = new_instancemethod(_snap.TNGraph_Save,None,TNGraph)
TNGraph.HasFlag = new_instancemethod(_snap.TNGraph_HasFlag,None,TNGraph)
TNGraph.GetNodes = new_instancemethod(_snap.TNGraph_GetNodes,None,TNGraph)
TNGraph.AddNode = new_instancemethod(_snap.TNGraph_AddNode,None,TNGraph)
TNGraph.DelNode = new_instancemethod(_snap.TNGraph_DelNode,None,TNGraph)
TNGraph.IsNode = new_instancemethod(_snap.TNGraph_IsNode,None,TNGraph)
TNGraph.BegNI = new_instancemethod(_snap.TNGraph_BegNI,None,TNGraph)
TNGraph.EndNI = new_instancemethod(_snap.TNGraph_EndNI,None,TNGraph)
TNGraph.GetNI = new_instancemethod(_snap.TNGraph_GetNI,None,TNGraph)
TNGraph.GetMxNId = new_instancemethod(_snap.TNGraph_GetMxNId,None,TNGraph)
TNGraph.GetEdges = new_instancemethod(_snap.TNGraph_GetEdges,None,TNGraph)
TNGraph.AddEdge = new_instancemethod(_snap.TNGraph_AddEdge,None,TNGraph)
TNGraph.DelEdge = new_instancemethod(_snap.TNGraph_DelEdge,None,TNGraph)
TNGraph.IsEdge = new_instancemethod(_snap.TNGraph_IsEdge,None,TNGraph)
TNGraph.BegEI = new_instancemethod(_snap.TNGraph_BegEI,None,TNGraph)
TNGraph.EndEI = new_instancemethod(_snap.TNGraph_EndEI,None,TNGraph)
TNGraph.GetEI = new_instancemethod(_snap.TNGraph_GetEI,None,TNGraph)
TNGraph.GetRndNId = new_instancemethod(_snap.TNGraph_GetRndNId,None,TNGraph)
TNGraph.GetRndNI = new_instancemethod(_snap.TNGraph_GetRndNI,None,TNGraph)
TNGraph.GetNIdV = new_instancemethod(_snap.TNGraph_GetNIdV,None,TNGraph)
TNGraph.Empty = new_instancemethod(_snap.TNGraph_Empty,None,TNGraph)
TNGraph.Clr = new_instancemethod(_snap.TNGraph_Clr,None,TNGraph)
TNGraph.Reserve = new_instancemethod(_snap.TNGraph_Reserve,None,TNGraph)
TNGraph.ReserveNIdInDeg = new_instancemethod(_snap.TNGraph_ReserveNIdInDeg,None,TNGraph)
TNGraph.ReserveNIdOutDeg = new_instancemethod(_snap.TNGraph_ReserveNIdOutDeg,None,TNGraph)
TNGraph.Defrag = new_instancemethod(_snap.TNGraph_Defrag,None,TNGraph)
TNGraph.IsOk = new_instancemethod(_snap.TNGraph_IsOk,None,TNGraph)
TNGraph.Dump = new_instancemethod(_snap.TNGraph_Dump,None,TNGraph)
TNGraph_swigregister = _snap.TNGraph_swigregister
TNGraph_swigregister(TNGraph)
def TNGraph_New(*args):
"""
New() -> PNGraph
TNGraph_New(int const & Nodes, int const & Edges) -> PNGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNGraph_New(*args)
def TNGraph_Load(*args):
"""
TNGraph_Load(TSIn SIn) -> PNGraph
Parameters:
SIn: TSIn &
"""
return _snap.TNGraph_Load(*args)
def TNGraph_GetSmallGraph():
"""TNGraph_GetSmallGraph() -> PNGraph"""
return _snap.TNGraph_GetSmallGraph()
class TNEGraph(object):
"""Proxy of C++ TNEGraph class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEGraph self) -> TNEGraph
__init__(TNEGraph self, int const & Nodes, int const & Edges) -> TNEGraph
Parameters:
Nodes: int const &
Edges: int const &
__init__(TNEGraph self, TNEGraph Graph) -> TNEGraph
Parameters:
Graph: TNEGraph const &
__init__(TNEGraph self, TSIn SIn) -> TNEGraph
Parameters:
SIn: TSIn &
"""
_snap.TNEGraph_swiginit(self,_snap.new_TNEGraph(*args))
def Save(self, *args):
"""
Save(TNEGraph self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TNEGraph_Save(self, *args)
def New(*args):
"""
New() -> PNEGraph
New(int const & Nodes, int const & Edges) -> PNEGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEGraph_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PNEGraph
Parameters:
SIn: TSIn &
"""
return _snap.TNEGraph_Load(*args)
Load = staticmethod(Load)
def HasFlag(self, *args):
"""
HasFlag(TNEGraph self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.TNEGraph_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(TNEGraph self) -> int
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(TNEGraph self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TNEGraph self) -> int
AddNode(TNEGraph self, TNEGraph::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNEGraph::TNodeI const &
"""
return _snap.TNEGraph_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TNEGraph self, int const & NId)
Parameters:
NId: int const &
DelNode(TNEGraph self, TNEGraph::TNode const & NodeI)
Parameters:
NodeI: TNEGraph::TNode const &
"""
return _snap.TNEGraph_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TNEGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEGraph_IsNode(self, *args)
def BegNI(self):
"""
BegNI(TNEGraph self) -> TNEGraph::TNodeI
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_BegNI(self)
def EndNI(self):
"""
EndNI(TNEGraph self) -> TNEGraph::TNodeI
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_EndNI(self)
def GetNI(self, *args):
"""
GetNI(TNEGraph self, int const & NId) -> TNEGraph::TNodeI
Parameters:
NId: int const &
"""
return _snap.TNEGraph_GetNI(self, *args)
def GetMxNId(self):
"""
GetMxNId(TNEGraph self) -> int
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(TNEGraph self) -> int
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TNEGraph self, int const & SrcNId, int const & DstNId, int EId=-1) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int
AddEdge(TNEGraph self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(TNEGraph self, TNEGraph::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TNEGraph::TEdgeI const &
"""
return _snap.TNEGraph_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TNEGraph self, int const & EId)
Parameters:
EId: int const &
DelEdge(TNEGraph self, int const & SrcNId, int const & DstNId, bool const & IsDir=True)
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
DelEdge(TNEGraph self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEGraph_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TNEGraph self, int const & EId) -> bool
Parameters:
EId: int const &
IsEdge(TNEGraph self, int const & SrcNId, int const & DstNId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
IsEdge(TNEGraph self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsEdge(TNEGraph self, int const & SrcNId, int const & DstNId, int & EId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
IsDir: bool const &
IsEdge(TNEGraph self, int const & SrcNId, int const & DstNId, int & EId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
"""
return _snap.TNEGraph_IsEdge(self, *args)
def GetEId(self, *args):
"""
GetEId(TNEGraph self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEGraph_GetEId(self, *args)
def BegEI(self):
"""
BegEI(TNEGraph self) -> TNEGraph::TEdgeI
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_BegEI(self)
def EndEI(self):
"""
EndEI(TNEGraph self) -> TNEGraph::TEdgeI
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TNEGraph self, int const & EId) -> TNEGraph::TEdgeI
Parameters:
EId: int const &
GetEI(TNEGraph self, int const & SrcNId, int const & DstNId) -> TNEGraph::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TNEGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TNEGraph self) -> int
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TNEGraph self, TRnd Rnd=Rnd) -> TNEGraph::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TNEGraph self) -> TNEGraph::TNodeI
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_GetRndNI(self, *args)
def GetRndEId(self, *args):
"""
GetRndEId(TNEGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndEId(TNEGraph self) -> int
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_GetRndEId(self, *args)
def GetRndEI(self, *args):
"""
GetRndEI(TNEGraph self, TRnd Rnd=Rnd) -> TNEGraph::TEdgeI
Parameters:
Rnd: TRnd &
GetRndEI(TNEGraph self) -> TNEGraph::TEdgeI
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_GetRndEI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TNEGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TNEGraph_GetNIdV(self, *args)
def GetEIdV(self, *args):
"""
GetEIdV(TNEGraph self, TIntV EIdV)
Parameters:
EIdV: TIntV &
"""
return _snap.TNEGraph_GetEIdV(self, *args)
def Empty(self):
"""
Empty(TNEGraph self) -> bool
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_Empty(self)
def Clr(self):
"""
Clr(TNEGraph self)
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_Clr(self)
def Reserve(self, *args):
"""
Reserve(TNEGraph self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEGraph_Reserve(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TNEGraph self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TNEGraph self)
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TNEGraph self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TNEGraph self) -> bool
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TNEGraph self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TNEGraph self)
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_Dump(self, *args)
__swig_destroy__ = _snap.delete_TNEGraph
TNEGraph.Save = new_instancemethod(_snap.TNEGraph_Save,None,TNEGraph)
TNEGraph.HasFlag = new_instancemethod(_snap.TNEGraph_HasFlag,None,TNEGraph)
TNEGraph.GetNodes = new_instancemethod(_snap.TNEGraph_GetNodes,None,TNEGraph)
TNEGraph.AddNode = new_instancemethod(_snap.TNEGraph_AddNode,None,TNEGraph)
TNEGraph.DelNode = new_instancemethod(_snap.TNEGraph_DelNode,None,TNEGraph)
TNEGraph.IsNode = new_instancemethod(_snap.TNEGraph_IsNode,None,TNEGraph)
TNEGraph.BegNI = new_instancemethod(_snap.TNEGraph_BegNI,None,TNEGraph)
TNEGraph.EndNI = new_instancemethod(_snap.TNEGraph_EndNI,None,TNEGraph)
TNEGraph.GetNI = new_instancemethod(_snap.TNEGraph_GetNI,None,TNEGraph)
TNEGraph.GetMxNId = new_instancemethod(_snap.TNEGraph_GetMxNId,None,TNEGraph)
TNEGraph.GetEdges = new_instancemethod(_snap.TNEGraph_GetEdges,None,TNEGraph)
TNEGraph.AddEdge = new_instancemethod(_snap.TNEGraph_AddEdge,None,TNEGraph)
TNEGraph.DelEdge = new_instancemethod(_snap.TNEGraph_DelEdge,None,TNEGraph)
TNEGraph.IsEdge = new_instancemethod(_snap.TNEGraph_IsEdge,None,TNEGraph)
TNEGraph.GetEId = new_instancemethod(_snap.TNEGraph_GetEId,None,TNEGraph)
TNEGraph.BegEI = new_instancemethod(_snap.TNEGraph_BegEI,None,TNEGraph)
TNEGraph.EndEI = new_instancemethod(_snap.TNEGraph_EndEI,None,TNEGraph)
TNEGraph.GetEI = new_instancemethod(_snap.TNEGraph_GetEI,None,TNEGraph)
TNEGraph.GetRndNId = new_instancemethod(_snap.TNEGraph_GetRndNId,None,TNEGraph)
TNEGraph.GetRndNI = new_instancemethod(_snap.TNEGraph_GetRndNI,None,TNEGraph)
TNEGraph.GetRndEId = new_instancemethod(_snap.TNEGraph_GetRndEId,None,TNEGraph)
TNEGraph.GetRndEI = new_instancemethod(_snap.TNEGraph_GetRndEI,None,TNEGraph)
TNEGraph.GetNIdV = new_instancemethod(_snap.TNEGraph_GetNIdV,None,TNEGraph)
TNEGraph.GetEIdV = new_instancemethod(_snap.TNEGraph_GetEIdV,None,TNEGraph)
TNEGraph.Empty = new_instancemethod(_snap.TNEGraph_Empty,None,TNEGraph)
TNEGraph.Clr = new_instancemethod(_snap.TNEGraph_Clr,None,TNEGraph)
TNEGraph.Reserve = new_instancemethod(_snap.TNEGraph_Reserve,None,TNEGraph)
TNEGraph.Defrag = new_instancemethod(_snap.TNEGraph_Defrag,None,TNEGraph)
TNEGraph.IsOk = new_instancemethod(_snap.TNEGraph_IsOk,None,TNEGraph)
TNEGraph.Dump = new_instancemethod(_snap.TNEGraph_Dump,None,TNEGraph)
TNEGraph_swigregister = _snap.TNEGraph_swigregister
TNEGraph_swigregister(TNEGraph)
def TNEGraph_New(*args):
"""
New() -> PNEGraph
TNEGraph_New(int const & Nodes, int const & Edges) -> PNEGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEGraph_New(*args)
def TNEGraph_Load(*args):
"""
TNEGraph_Load(TSIn SIn) -> PNEGraph
Parameters:
SIn: TSIn &
"""
return _snap.TNEGraph_Load(*args)
class TBPGraph(object):
"""Proxy of C++ TBPGraph class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
bgsUndef = _snap.TBPGraph_bgsUndef
bgsLeft = _snap.TBPGraph_bgsLeft
bgsRight = _snap.TBPGraph_bgsRight
bgsBoth = _snap.TBPGraph_bgsBoth
def __init__(self, *args):
"""
__init__(TBPGraph self) -> TBPGraph
__init__(TBPGraph self, int const & Nodes, int const & Edges) -> TBPGraph
Parameters:
Nodes: int const &
Edges: int const &
__init__(TBPGraph self, TBPGraph BPGraph) -> TBPGraph
Parameters:
BPGraph: TBPGraph const &
__init__(TBPGraph self, TSIn SIn) -> TBPGraph
Parameters:
SIn: TSIn &
"""
_snap.TBPGraph_swiginit(self,_snap.new_TBPGraph(*args))
def Save(self, *args):
"""
Save(TBPGraph self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TBPGraph_Save(self, *args)
def New(*args):
"""
New() -> PBPGraph
New(int const & Nodes, int const & Edges) -> PBPGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TBPGraph_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PBPGraph
Parameters:
SIn: TSIn &
"""
return _snap.TBPGraph_Load(*args)
Load = staticmethod(Load)
def GetNodes(self):
"""
GetNodes(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetNodes(self)
def GetLNodes(self):
"""
GetLNodes(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetLNodes(self)
def GetRNodes(self):
"""
GetRNodes(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetRNodes(self)
def AddNode(self, *args):
"""
AddNode(TBPGraph self, int NId=-1, bool const & LeftNode=True) -> int
Parameters:
NId: int
LeftNode: bool const &
AddNode(TBPGraph self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TBPGraph self) -> int
AddNode(TBPGraph self, TBPGraph::TNodeI const & NodeI) -> int
Parameters:
NodeI: TBPGraph::TNodeI const &
"""
return _snap.TBPGraph_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TBPGraph self, int const & NId)
Parameters:
NId: int const &
DelNode(TBPGraph self, TBPGraph::TNode const & NodeI)
Parameters:
NodeI: TBPGraph::TNode const &
"""
return _snap.TBPGraph_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TBPGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TBPGraph_IsNode(self, *args)
def IsLNode(self, *args):
"""
IsLNode(TBPGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TBPGraph_IsLNode(self, *args)
def IsRNode(self, *args):
"""
IsRNode(TBPGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TBPGraph_IsRNode(self, *args)
def GetMxNId(self):
"""
GetMxNId(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetMxNId(self)
def BegNI(self):
"""
BegNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_BegNI(self)
def EndNI(self):
"""
EndNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_EndNI(self)
def GetNI(self, *args):
"""
GetNI(TBPGraph self, int const & NId) -> TBPGraph::TNodeI
Parameters:
NId: int const &
"""
return _snap.TBPGraph_GetNI(self, *args)
def BegLNI(self):
"""
BegLNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_BegLNI(self)
def EndLNI(self):
"""
EndLNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_EndLNI(self)
def BegRNI(self):
"""
BegRNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_BegRNI(self)
def EndRNI(self):
"""
EndRNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_EndRNI(self)
def GetEdges(self):
"""
GetEdges(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TBPGraph self, int const & LeftNId, int const & RightNId) -> int
Parameters:
LeftNId: int const &
RightNId: int const &
AddEdge(TBPGraph self, TBPGraph::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TBPGraph::TEdgeI const &
"""
return _snap.TBPGraph_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TBPGraph self, int const & LeftNId, int const & RightNId)
Parameters:
LeftNId: int const &
RightNId: int const &
"""
return _snap.TBPGraph_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TBPGraph self, int const & LeftNId, int const & RightNId) -> bool
Parameters:
LeftNId: int const &
RightNId: int const &
"""
return _snap.TBPGraph_IsEdge(self, *args)
def BegEI(self):
"""
BegEI(TBPGraph self) -> TBPGraph::TEdgeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_BegEI(self)
def EndEI(self):
"""
EndEI(TBPGraph self) -> TBPGraph::TEdgeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TBPGraph self, int const & LeftNId, int const & RightNId) -> TBPGraph::TEdgeI
Parameters:
LeftNId: int const &
RightNId: int const &
"""
return _snap.TBPGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TBPGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TBPGraph self) -> int
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_GetRndNId(self, *args)
def GetRndLNId(self, *args):
"""
GetRndLNId(TBPGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndLNId(TBPGraph self) -> int
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_GetRndLNId(self, *args)
def GetRndRNId(self, *args):
"""
GetRndRNId(TBPGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndRNId(TBPGraph self) -> int
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_GetRndRNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TBPGraph self, TRnd Rnd=Rnd) -> TBPGraph::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_GetRndNI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TBPGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TBPGraph_GetNIdV(self, *args)
def GetLNIdV(self, *args):
"""
GetLNIdV(TBPGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TBPGraph_GetLNIdV(self, *args)
def GetRNIdV(self, *args):
"""
GetRNIdV(TBPGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TBPGraph_GetRNIdV(self, *args)
def Empty(self):
"""
Empty(TBPGraph self) -> bool
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_Empty(self)
def Clr(self):
"""
Clr(TBPGraph self)
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_Clr(self)
def Reserve(self, *args):
"""
Reserve(TBPGraph self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TBPGraph_Reserve(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TBPGraph self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TBPGraph self)
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TBPGraph self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TBPGraph self) -> bool
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TBPGraph self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TBPGraph self)
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_Dump(self, *args)
def GetSmallGraph():
"""GetSmallGraph() -> PBPGraph"""
return _snap.TBPGraph_GetSmallGraph()
GetSmallGraph = staticmethod(GetSmallGraph)
__swig_destroy__ = _snap.delete_TBPGraph
TBPGraph.Save = new_instancemethod(_snap.TBPGraph_Save,None,TBPGraph)
TBPGraph.GetNodes = new_instancemethod(_snap.TBPGraph_GetNodes,None,TBPGraph)
TBPGraph.GetLNodes = new_instancemethod(_snap.TBPGraph_GetLNodes,None,TBPGraph)
TBPGraph.GetRNodes = new_instancemethod(_snap.TBPGraph_GetRNodes,None,TBPGraph)
TBPGraph.AddNode = new_instancemethod(_snap.TBPGraph_AddNode,None,TBPGraph)
TBPGraph.DelNode = new_instancemethod(_snap.TBPGraph_DelNode,None,TBPGraph)
TBPGraph.IsNode = new_instancemethod(_snap.TBPGraph_IsNode,None,TBPGraph)
TBPGraph.IsLNode = new_instancemethod(_snap.TBPGraph_IsLNode,None,TBPGraph)
TBPGraph.IsRNode = new_instancemethod(_snap.TBPGraph_IsRNode,None,TBPGraph)
TBPGraph.GetMxNId = new_instancemethod(_snap.TBPGraph_GetMxNId,None,TBPGraph)
TBPGraph.BegNI = new_instancemethod(_snap.TBPGraph_BegNI,None,TBPGraph)
TBPGraph.EndNI = new_instancemethod(_snap.TBPGraph_EndNI,None,TBPGraph)
TBPGraph.GetNI = new_instancemethod(_snap.TBPGraph_GetNI,None,TBPGraph)
TBPGraph.BegLNI = new_instancemethod(_snap.TBPGraph_BegLNI,None,TBPGraph)
TBPGraph.EndLNI = new_instancemethod(_snap.TBPGraph_EndLNI,None,TBPGraph)
TBPGraph.BegRNI = new_instancemethod(_snap.TBPGraph_BegRNI,None,TBPGraph)
TBPGraph.EndRNI = new_instancemethod(_snap.TBPGraph_EndRNI,None,TBPGraph)
TBPGraph.GetEdges = new_instancemethod(_snap.TBPGraph_GetEdges,None,TBPGraph)
TBPGraph.AddEdge = new_instancemethod(_snap.TBPGraph_AddEdge,None,TBPGraph)
TBPGraph.DelEdge = new_instancemethod(_snap.TBPGraph_DelEdge,None,TBPGraph)
TBPGraph.IsEdge = new_instancemethod(_snap.TBPGraph_IsEdge,None,TBPGraph)
TBPGraph.BegEI = new_instancemethod(_snap.TBPGraph_BegEI,None,TBPGraph)
TBPGraph.EndEI = new_instancemethod(_snap.TBPGraph_EndEI,None,TBPGraph)
TBPGraph.GetEI = new_instancemethod(_snap.TBPGraph_GetEI,None,TBPGraph)
TBPGraph.GetRndNId = new_instancemethod(_snap.TBPGraph_GetRndNId,None,TBPGraph)
TBPGraph.GetRndLNId = new_instancemethod(_snap.TBPGraph_GetRndLNId,None,TBPGraph)
TBPGraph.GetRndRNId = new_instancemethod(_snap.TBPGraph_GetRndRNId,None,TBPGraph)
TBPGraph.GetRndNI = new_instancemethod(_snap.TBPGraph_GetRndNI,None,TBPGraph)
TBPGraph.GetNIdV = new_instancemethod(_snap.TBPGraph_GetNIdV,None,TBPGraph)
TBPGraph.GetLNIdV = new_instancemethod(_snap.TBPGraph_GetLNIdV,None,TBPGraph)
TBPGraph.GetRNIdV = new_instancemethod(_snap.TBPGraph_GetRNIdV,None,TBPGraph)
TBPGraph.Empty = new_instancemethod(_snap.TBPGraph_Empty,None,TBPGraph)
TBPGraph.Clr = new_instancemethod(_snap.TBPGraph_Clr,None,TBPGraph)
TBPGraph.Reserve = new_instancemethod(_snap.TBPGraph_Reserve,None,TBPGraph)
TBPGraph.Defrag = new_instancemethod(_snap.TBPGraph_Defrag,None,TBPGraph)
TBPGraph.IsOk = new_instancemethod(_snap.TBPGraph_IsOk,None,TBPGraph)
TBPGraph.Dump = new_instancemethod(_snap.TBPGraph_Dump,None,TBPGraph)
TBPGraph_swigregister = _snap.TBPGraph_swigregister
TBPGraph_swigregister(TBPGraph)
def TBPGraph_New(*args):
"""
New() -> PBPGraph
TBPGraph_New(int const & Nodes, int const & Edges) -> PBPGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TBPGraph_New(*args)
def TBPGraph_Load(*args):
"""
TBPGraph_Load(TSIn SIn) -> PBPGraph
Parameters:
SIn: TSIn &
"""
return _snap.TBPGraph_Load(*args)
def TBPGraph_GetSmallGraph():
"""TBPGraph_GetSmallGraph() -> PBPGraph"""
return _snap.TBPGraph_GetSmallGraph()
class TNGraphMtx(object):
"""Proxy of C++ TNGraphMtx class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNGraphMtx self, PNGraph const & GraphPt) -> TNGraphMtx
Parameters:
GraphPt: PNGraph const &
__init__(TNGraphMtx self, TNGraphMtx GraphMtx) -> TNGraphMtx
Parameters:
GraphMtx: TNGraphMtx const &
"""
_snap.TNGraphMtx_swiginit(self,_snap.new_TNGraphMtx(*args))
def PGetRows(self):
"""
PGetRows(TNGraphMtx self) -> int
Parameters:
self: TNGraphMtx const *
"""
return _snap.TNGraphMtx_PGetRows(self)
def PGetCols(self):
"""
PGetCols(TNGraphMtx self) -> int
Parameters:
self: TNGraphMtx const *
"""
return _snap.TNGraphMtx_PGetCols(self)
def PMultiply(self, *args):
"""
PMultiply(TNGraphMtx self, TFltVV const & B, int ColId, TFltV & Result)
Parameters:
B: TFltVV const &
ColId: int
Result: TFltV &
PMultiply(TNGraphMtx self, TFltV const & Vec, TFltV & Result)
Parameters:
Vec: TFltV const &
Result: TFltV &
"""
return _snap.TNGraphMtx_PMultiply(self, *args)
def PMultiplyT(self, *args):
"""
PMultiplyT(TNGraphMtx self, TFltVV const & B, int ColId, TFltV & Result)
Parameters:
B: TFltVV const &
ColId: int
Result: TFltV &
PMultiplyT(TNGraphMtx self, TFltV const & Vec, TFltV & Result)
Parameters:
Vec: TFltV const &
Result: TFltV &
"""
return _snap.TNGraphMtx_PMultiplyT(self, *args)
__swig_destroy__ = _snap.delete_TNGraphMtx
TNGraphMtx.PGetRows = new_instancemethod(_snap.TNGraphMtx_PGetRows,None,TNGraphMtx)
TNGraphMtx.PGetCols = new_instancemethod(_snap.TNGraphMtx_PGetCols,None,TNGraphMtx)
TNGraphMtx.PMultiply = new_instancemethod(_snap.TNGraphMtx_PMultiply,None,TNGraphMtx)
TNGraphMtx.PMultiplyT = new_instancemethod(_snap.TNGraphMtx_PMultiplyT,None,TNGraphMtx)
TNGraphMtx_swigregister = _snap.TNGraphMtx_swigregister
TNGraphMtx_swigregister(TNGraphMtx)
class TUNGraphMtx(object):
"""Proxy of C++ TUNGraphMtx class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TUNGraphMtx self, PUNGraph const & GraphPt) -> TUNGraphMtx
Parameters:
GraphPt: PUNGraph const &
__init__(TUNGraphMtx self, TUNGraphMtx GraphMtx) -> TUNGraphMtx
Parameters:
GraphMtx: TUNGraphMtx const &
"""
_snap.TUNGraphMtx_swiginit(self,_snap.new_TUNGraphMtx(*args))
def PGetRows(self):
"""
PGetRows(TUNGraphMtx self) -> int
Parameters:
self: TUNGraphMtx const *
"""
return _snap.TUNGraphMtx_PGetRows(self)
def PGetCols(self):
"""
PGetCols(TUNGraphMtx self) -> int
Parameters:
self: TUNGraphMtx const *
"""
return _snap.TUNGraphMtx_PGetCols(self)
def PMultiply(self, *args):
"""
PMultiply(TUNGraphMtx self, TFltVV const & B, int ColId, TFltV & Result)
Parameters:
B: TFltVV const &
ColId: int
Result: TFltV &
PMultiply(TUNGraphMtx self, TFltV const & Vec, TFltV & Result)
Parameters:
Vec: TFltV const &
Result: TFltV &
"""
return _snap.TUNGraphMtx_PMultiply(self, *args)
def PMultiplyT(self, *args):
"""
PMultiplyT(TUNGraphMtx self, TFltVV const & B, int ColId, TFltV & Result)
Parameters:
B: TFltVV const &
ColId: int
Result: TFltV &
PMultiplyT(TUNGraphMtx self, TFltV const & Vec, TFltV & Result)
Parameters:
Vec: TFltV const &
Result: TFltV &
"""
return _snap.TUNGraphMtx_PMultiplyT(self, *args)
__swig_destroy__ = _snap.delete_TUNGraphMtx
TUNGraphMtx.PGetRows = new_instancemethod(_snap.TUNGraphMtx_PGetRows,None,TUNGraphMtx)
TUNGraphMtx.PGetCols = new_instancemethod(_snap.TUNGraphMtx_PGetCols,None,TUNGraphMtx)
TUNGraphMtx.PMultiply = new_instancemethod(_snap.TUNGraphMtx_PMultiply,None,TUNGraphMtx)
TUNGraphMtx.PMultiplyT = new_instancemethod(_snap.TUNGraphMtx_PMultiplyT,None,TUNGraphMtx)
TUNGraphMtx_swigregister = _snap.TUNGraphMtx_swigregister
TUNGraphMtx_swigregister(TUNGraphMtx)
def GetSngVals(*args):
"""
GetSngVals(PNGraph const & Graph, int const & SngVals, TFltV & SngValV)
Parameters:
Graph: PNGraph const &
SngVals: int const &
SngValV: TFltV &
"""
return _snap.GetSngVals(*args)
def GetSngVec(*args):
"""
GetSngVec(PNGraph const & Graph, TFltV & LeftSV, TFltV & RightSV)
Parameters:
Graph: PNGraph const &
LeftSV: TFltV &
RightSV: TFltV &
GetSngVec(PNGraph const & Graph, int const & SngVecs, TFltV & SngValV, TVec< TFltV > & LeftSV,
TVec< TFltV > & RightSV)
Parameters:
Graph: PNGraph const &
SngVecs: int const &
SngValV: TFltV &
LeftSV: TVec< TFltV > &
RightSV: TVec< TFltV > &
"""
return _snap.GetSngVec(*args)
def GetEigVals(*args):
"""
GetEigVals(PUNGraph const & Graph, int const & EigVals, TFltV & EigValV)
Parameters:
Graph: PUNGraph const &
EigVals: int const &
EigValV: TFltV &
"""
return _snap.GetEigVals(*args)
def GetEigVec(*args):
"""
GetEigVec(PUNGraph const & Graph, TFltV & EigVecV)
Parameters:
Graph: PUNGraph const &
EigVecV: TFltV &
GetEigVec(PUNGraph const & Graph, int const & EigVecs, TFltV & EigValV, TVec< TFltV > & EigVecV)
Parameters:
Graph: PUNGraph const &
EigVecs: int const &
EigValV: TFltV &
EigVecV: TVec< TFltV > &
"""
return _snap.GetEigVec(*args)
def GetInvParticipRat(*args):
"""
GetInvParticipRat(PUNGraph const & Graph, int MaxEigVecs, int TimeLimit, TFltPrV & EigValIprV)
Parameters:
Graph: PUNGraph const &
MaxEigVecs: int
TimeLimit: int
EigValIprV: TFltPrV &
"""
return _snap.GetInvParticipRat(*args)
def GetInvParticipRatEig(*args):
"""
GetInvParticipRatEig(TFltV const & EigVec) -> double
Parameters:
EigVec: TFltV const &
"""
return _snap.GetInvParticipRatEig(*args)
def LoadDyNet(*args):
"""
LoadDyNet(TStr FNm) -> PNGraph
Parameters:
FNm: TStr const &
"""
return _snap.LoadDyNet(*args)
def LoadDyNetGraphV(*args):
"""
LoadDyNetGraphV(TStr FNm) -> TVec< PNGraph >
Parameters:
FNm: TStr const &
"""
return _snap.LoadDyNetGraphV(*args)
gvlDot = _snap.gvlDot
gvlNeato = _snap.gvlNeato
gvlTwopi = _snap.gvlTwopi
gvlCirco = _snap.gvlCirco
def GVizDoLayout(*args):
"""
GVizDoLayout(TStr GraphInFNm, TStr OutFNm, TGVizLayout const & Layout)
Parameters:
GraphInFNm: TStr const &
OutFNm: TStr
Layout: TGVizLayout const &
"""
return _snap.GVizDoLayout(*args)
def GVizGetLayoutStr(*args):
"""
GVizGetLayoutStr(TGVizLayout const & Layout) -> TStr
Parameters:
Layout: TGVizLayout const &
"""
return _snap.GVizGetLayoutStr(*args)
class TBigStrPool(object):
"""Proxy of C++ TBigStrPool class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TBigStrPool self, TSize MxBfLen=0, uint _GrowBy=16*1024*1024) -> TBigStrPool
Parameters:
MxBfLen: TSize
_GrowBy: uint
__init__(TBigStrPool self, TSize MxBfLen=0) -> TBigStrPool
Parameters:
MxBfLen: TSize
__init__(TBigStrPool self) -> TBigStrPool
__init__(TBigStrPool self, TSIn SIn, bool LoadCompact=True) -> TBigStrPool
Parameters:
SIn: TSIn &
LoadCompact: bool
__init__(TBigStrPool self, TSIn SIn) -> TBigStrPool
Parameters:
SIn: TSIn &
__init__(TBigStrPool self, TBigStrPool Pool) -> TBigStrPool
Parameters:
Pool: TBigStrPool const &
"""
_snap.TBigStrPool_swiginit(self,_snap.new_TBigStrPool(*args))
__swig_destroy__ = _snap.delete_TBigStrPool
def New(*args):
"""
New(TSize _MxBfLen=0, uint _GrowBy=16*1024*1024) -> PBigStrPool
Parameters:
_MxBfLen: TSize
_GrowBy: uint
New(TSize _MxBfLen=0) -> PBigStrPool
Parameters:
_MxBfLen: TSize
New() -> PBigStrPool
New(TSIn SIn) -> PBigStrPool
Parameters:
SIn: TSIn &
New(TStr fileName) -> PBigStrPool
Parameters:
fileName: TStr const &
"""
return _snap.TBigStrPool_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn, bool LoadCompacted=True) -> PBigStrPool
Parameters:
SIn: TSIn &
LoadCompacted: bool
Load(TSIn SIn) -> PBigStrPool
Parameters:
SIn: TSIn &
"""
return _snap.TBigStrPool_Load(*args)
Load = staticmethod(Load)
def Save(self, *args):
"""
Save(TBigStrPool self, TSOut SOut)
Parameters:
SOut: TSOut &
Save(TBigStrPool self, TStr fileName)
Parameters:
fileName: TStr const &
"""
return _snap.TBigStrPool_Save(self, *args)
def GetStrs(self):
"""
GetStrs(TBigStrPool self) -> int
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool_GetStrs(self)
def Len(self):
"""
Len(TBigStrPool self) -> TSize
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool_Len(self)
def Size(self):
"""
Size(TBigStrPool self) -> TSize
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool_Size(self)
def Empty(self):
"""
Empty(TBigStrPool self) -> bool
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool_Empty(self)
def __call__(self):
"""
__call__(TBigStrPool self) -> char *
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool___call__(self)
def AddStr(self, *args):
"""
AddStr(TBigStrPool self, char const * Str, uint Len) -> int
Parameters:
Str: char const *
Len: uint
AddStr(TBigStrPool self, char const * Str) -> int
Parameters:
Str: char const *
AddStr(TBigStrPool self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TBigStrPool_AddStr(self, *args)
def GetCStr(self, *args):
"""
GetCStr(TBigStrPool self, int const & StrId) -> char const *
Parameters:
StrId: int const &
"""
return _snap.TBigStrPool_GetCStr(self, *args)
def GetStrFromOffset(self, *args):
"""
GetStrFromOffset(TBigStrPool self, TSize const & Offset) -> TStr
Parameters:
Offset: TSize const &
"""
return _snap.TBigStrPool_GetStrFromOffset(self, *args)
def GetCStrFromOffset(self, *args):
"""
GetCStrFromOffset(TBigStrPool self, TSize const & Offset) -> char const *
Parameters:
Offset: TSize const &
"""
return _snap.TBigStrPool_GetCStrFromOffset(self, *args)
def Clr(self, DoDel=False):
"""
Clr(TBigStrPool self, bool DoDel=False)
Parameters:
DoDel: bool
Clr(TBigStrPool self)
Parameters:
self: TBigStrPool *
"""
return _snap.TBigStrPool_Clr(self, DoDel)
def Cmp(self, *args):
"""
Cmp(TBigStrPool self, int const & StrId, char const * Str) -> int
Parameters:
StrId: int const &
Str: char const *
"""
return _snap.TBigStrPool_Cmp(self, *args)
def GetPrimHashCd(self, *args):
"""
GetPrimHashCd(TBigStrPool self, char const * CStr) -> int
Parameters:
CStr: char const *
GetPrimHashCd(TBigStrPool self, int const & StrId) -> int
Parameters:
StrId: int const &
"""
return _snap.TBigStrPool_GetPrimHashCd(self, *args)
def GetSecHashCd(self, *args):
"""
GetSecHashCd(TBigStrPool self, char const * CStr) -> int
Parameters:
CStr: char const *
GetSecHashCd(TBigStrPool self, int const & StrId) -> int
Parameters:
StrId: int const &
"""
return _snap.TBigStrPool_GetSecHashCd(self, *args)
TBigStrPool.Save = new_instancemethod(_snap.TBigStrPool_Save,None,TBigStrPool)
TBigStrPool.GetStrs = new_instancemethod(_snap.TBigStrPool_GetStrs,None,TBigStrPool)
TBigStrPool.Len = new_instancemethod(_snap.TBigStrPool_Len,None,TBigStrPool)
TBigStrPool.Size = new_instancemethod(_snap.TBigStrPool_Size,None,TBigStrPool)
TBigStrPool.Empty = new_instancemethod(_snap.TBigStrPool_Empty,None,TBigStrPool)
TBigStrPool.__call__ = new_instancemethod(_snap.TBigStrPool___call__,None,TBigStrPool)
TBigStrPool.AddStr = new_instancemethod(_snap.TBigStrPool_AddStr,None,TBigStrPool)
TBigStrPool.GetCStr = new_instancemethod(_snap.TBigStrPool_GetCStr,None,TBigStrPool)
TBigStrPool.GetStrFromOffset = new_instancemethod(_snap.TBigStrPool_GetStrFromOffset,None,TBigStrPool)
TBigStrPool.GetCStrFromOffset = new_instancemethod(_snap.TBigStrPool_GetCStrFromOffset,None,TBigStrPool)
TBigStrPool.Clr = new_instancemethod(_snap.TBigStrPool_Clr,None,TBigStrPool)
TBigStrPool.Cmp = new_instancemethod(_snap.TBigStrPool_Cmp,None,TBigStrPool)
TBigStrPool.GetPrimHashCd = new_instancemethod(_snap.TBigStrPool_GetPrimHashCd,None,TBigStrPool)
TBigStrPool.GetSecHashCd = new_instancemethod(_snap.TBigStrPool_GetSecHashCd,None,TBigStrPool)
TBigStrPool_swigregister = _snap.TBigStrPool_swigregister
TBigStrPool_swigregister(TBigStrPool)
def TBigStrPool_New(*args):
"""
New(TSize _MxBfLen=0, uint _GrowBy=16*1024*1024) -> PBigStrPool
Parameters:
_MxBfLen: TSize
_GrowBy: uint
New(TSize _MxBfLen=0) -> PBigStrPool
Parameters:
_MxBfLen: TSize
New() -> PBigStrPool
New(TSIn SIn) -> PBigStrPool
Parameters:
SIn: TSIn &
TBigStrPool_New(TStr fileName) -> PBigStrPool
Parameters:
fileName: TStr const &
"""
return _snap.TBigStrPool_New(*args)
def TBigStrPool_Load(*args):
"""
Load(TSIn SIn, bool LoadCompacted=True) -> PBigStrPool
Parameters:
SIn: TSIn &
LoadCompacted: bool
TBigStrPool_Load(TSIn SIn) -> PBigStrPool
Parameters:
SIn: TSIn &
"""
return _snap.TBigStrPool_Load(*args)
class TStrHashF_OldGLib(object):
"""Proxy of C++ TStrHashF_OldGLib class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetPrimHashCd(*args)
GetPrimHashCd = staticmethod(GetPrimHashCd)
def GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetSecHashCd(*args)
GetSecHashCd = staticmethod(GetSecHashCd)
def __init__(self):
"""__init__(TStrHashF_OldGLib self) -> TStrHashF_OldGLib"""
_snap.TStrHashF_OldGLib_swiginit(self,_snap.new_TStrHashF_OldGLib())
__swig_destroy__ = _snap.delete_TStrHashF_OldGLib
TStrHashF_OldGLib_swigregister = _snap.TStrHashF_OldGLib_swigregister
TStrHashF_OldGLib_swigregister(TStrHashF_OldGLib)
def TStrHashF_OldGLib_GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_OldGLib_GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetPrimHashCd(*args)
def TStrHashF_OldGLib_GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_OldGLib_GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetSecHashCd(*args)
class TStrHashF_Md5(object):
"""Proxy of C++ TStrHashF_Md5 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_Md5_GetPrimHashCd(*args)
GetPrimHashCd = staticmethod(GetPrimHashCd)
def GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_Md5_GetSecHashCd(*args)
GetSecHashCd = staticmethod(GetSecHashCd)
def __init__(self):
"""__init__(TStrHashF_Md5 self) -> TStrHashF_Md5"""
_snap.TStrHashF_Md5_swiginit(self,_snap.new_TStrHashF_Md5())
__swig_destroy__ = _snap.delete_TStrHashF_Md5
TStrHashF_Md5_swigregister = _snap.TStrHashF_Md5_swigregister
TStrHashF_Md5_swigregister(TStrHashF_Md5)
def TStrHashF_Md5_GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_Md5_GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_Md5_GetPrimHashCd(*args)
def TStrHashF_Md5_GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_Md5_GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_Md5_GetSecHashCd(*args)
class TStrHashF_DJB(object):
"""Proxy of C++ TStrHashF_DJB class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_DJB_GetPrimHashCd(*args)
GetPrimHashCd = staticmethod(GetPrimHashCd)
def GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_DJB_GetSecHashCd(*args)
GetSecHashCd = staticmethod(GetSecHashCd)
def __init__(self):
"""__init__(TStrHashF_DJB self) -> TStrHashF_DJB"""
_snap.TStrHashF_DJB_swiginit(self,_snap.new_TStrHashF_DJB())
__swig_destroy__ = _snap.delete_TStrHashF_DJB
TStrHashF_DJB_swigregister = _snap.TStrHashF_DJB_swigregister
TStrHashF_DJB_swigregister(TStrHashF_DJB)
def TStrHashF_DJB_GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_DJB_GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_DJB_GetPrimHashCd(*args)
def TStrHashF_DJB_GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_DJB_GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_DJB_GetSecHashCd(*args)
def GenRndBipart(*args):
"""
GenRndBipart(int const & LeftNodes, int const & RightNodes, int const & Edges, TRnd Rnd=Rnd) -> PBPGraph
Parameters:
LeftNodes: int const &
RightNodes: int const &
Edges: int const &
Rnd: TRnd &
GenRndBipart(int const & LeftNodes, int const & RightNodes, int const & Edges) -> PBPGraph
Parameters:
LeftNodes: int const &
RightNodes: int const &
Edges: int const &
"""
return _snap.GenRndBipart(*args)
def GenRndDegK(*args):
"""
GenRndDegK(int const & Nodes, int const & NodeDeg, int const & NSwitch=100, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
NodeDeg: int const &
NSwitch: int const &
Rnd: TRnd &
GenRndDegK(int const & Nodes, int const & NodeDeg, int const & NSwitch=100) -> PUNGraph
Parameters:
Nodes: int const &
NodeDeg: int const &
NSwitch: int const &
GenRndDegK(int const & Nodes, int const & NodeDeg) -> PUNGraph
Parameters:
Nodes: int const &
NodeDeg: int const &
"""
return _snap.GenRndDegK(*args)
def GenRndPowerLaw(*args):
"""
GenRndPowerLaw(int const & Nodes, double const & PowerExp, bool const & ConfModel=True, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
PowerExp: double const &
ConfModel: bool const &
Rnd: TRnd &
GenRndPowerLaw(int const & Nodes, double const & PowerExp, bool const & ConfModel=True) -> PUNGraph
Parameters:
Nodes: int const &
PowerExp: double const &
ConfModel: bool const &
GenRndPowerLaw(int const & Nodes, double const & PowerExp) -> PUNGraph
Parameters:
Nodes: int const &
PowerExp: double const &
"""
return _snap.GenRndPowerLaw(*args)
def GenDegSeq(*args):
"""
GenDegSeq(TIntV DegSeqV, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
DegSeqV: TIntV const &
Rnd: TRnd &
GenDegSeq(TIntV DegSeqV) -> PUNGraph
Parameters:
DegSeqV: TIntV const &
"""
return _snap.GenDegSeq(*args)
def GenPrefAttach(*args):
"""
GenPrefAttach(int const & Nodes, int const & NodeOutDeg, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
NodeOutDeg: int const &
Rnd: TRnd &
GenPrefAttach(int const & Nodes, int const & NodeOutDeg) -> PUNGraph
Parameters:
Nodes: int const &
NodeOutDeg: int const &
"""
return _snap.GenPrefAttach(*args)
def GenGeoPrefAttach(*args):
"""
GenGeoPrefAttach(int const & Nodes, int const & OutDeg, double const & Beta, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
OutDeg: int const &
Beta: double const &
Rnd: TRnd &
GenGeoPrefAttach(int const & Nodes, int const & OutDeg, double const & Beta) -> PUNGraph
Parameters:
Nodes: int const &
OutDeg: int const &
Beta: double const &
"""
return _snap.GenGeoPrefAttach(*args)
def GenSmallWorld(*args):
"""
GenSmallWorld(int const & Nodes, int const & NodeOutDeg, double const & RewireProb, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
NodeOutDeg: int const &
RewireProb: double const &
Rnd: TRnd &
GenSmallWorld(int const & Nodes, int const & NodeOutDeg, double const & RewireProb) -> PUNGraph
Parameters:
Nodes: int const &
NodeOutDeg: int const &
RewireProb: double const &
"""
return _snap.GenSmallWorld(*args)
def GenForestFire(*args):
"""
GenForestFire(int const & Nodes, double const & FwdProb, double const & BckProb) -> PNGraph
Parameters:
Nodes: int const &
FwdProb: double const &
BckProb: double const &
"""
return _snap.GenForestFire(*args)
def GenCopyModel(*args):
"""
GenCopyModel(int const & Nodes, double const & Beta, TRnd Rnd=Rnd) -> PNGraph
Parameters:
Nodes: int const &
Beta: double const &
Rnd: TRnd &
GenCopyModel(int const & Nodes, double const & Beta) -> PNGraph
Parameters:
Nodes: int const &
Beta: double const &
"""
return _snap.GenCopyModel(*args)
def GenRMat(*args):
"""
GenRMat(int const & Nodes, int const & Edges, double const & A, double const & B, double const & C,
TRnd Rnd=Rnd) -> PNGraph
Parameters:
Nodes: int const &
Edges: int const &
A: double const &
B: double const &
C: double const &
Rnd: TRnd &
GenRMat(int const & Nodes, int const & Edges, double const & A, double const & B, double const & C) -> PNGraph
Parameters:
Nodes: int const &
Edges: int const &
A: double const &
B: double const &
C: double const &
"""
return _snap.GenRMat(*args)
def GenRMatEpinions():
"""GenRMatEpinions() -> PNGraph"""
return _snap.GenRMatEpinions()
def GenRewire(*args):
"""
GenRewire(PUNGraph const & Graph, int const & NSwitch=100, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Graph: PUNGraph const &
NSwitch: int const &
Rnd: TRnd &
GenRewire(PUNGraph const & Graph, int const & NSwitch=100) -> PUNGraph
Parameters:
Graph: PUNGraph const &
NSwitch: int const &
GenRewire(PUNGraph const & Graph) -> PUNGraph
Parameters:
Graph: PUNGraph const &
GenRewire(PNGraph const & Graph, int const & NSwitch=100, TRnd Rnd=Rnd) -> PNGraph
Parameters:
Graph: PNGraph const &
NSwitch: int const &
Rnd: TRnd &
GenRewire(PNGraph const & Graph, int const & NSwitch=100) -> PNGraph
Parameters:
Graph: PNGraph const &
NSwitch: int const &
GenRewire(PNGraph const & Graph) -> PNGraph
Parameters:
Graph: PNGraph const &
GenRewire(PBPGraph const & Graph, int const & NSwitch=100, TRnd Rnd=Rnd) -> PBPGraph
Parameters:
Graph: PBPGraph const &
NSwitch: int const &
Rnd: TRnd &
GenRewire(PBPGraph const & Graph, int const & NSwitch=100) -> PBPGraph
Parameters:
Graph: PBPGraph const &
NSwitch: int const &
GenRewire(PBPGraph const & Graph) -> PBPGraph
Parameters:
Graph: PBPGraph const &
"""
return _snap.GenRewire(*args)
def GenConfModel(*args):
"""
GenConfModel(TIntV DegSeqV, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
DegSeqV: TIntV const &
Rnd: TRnd &
GenConfModel(TIntV DegSeqV) -> PUNGraph
Parameters:
DegSeqV: TIntV const &
GenConfModel(PUNGraph const & G) -> PUNGraph
Parameters:
G: PUNGraph const &
"""
return _snap.GenConfModel(*args)
def GetSubGraph(*args):
"""
GetSubGraph(PUNGraph const & Graph, TIntV NIdV, bool const & RenumberNodes=False) -> PUNGraph
Parameters:
Graph: PUNGraph const &
NIdV: TIntV const &
RenumberNodes: bool const &
GetSubGraph(PUNGraph const & Graph, TIntV NIdV) -> PUNGraph
Parameters:
Graph: PUNGraph const &
NIdV: TIntV const &
GetSubGraph(PNGraph const & Graph, TIntV NIdV, bool const & RenumberNodes=False) -> PNGraph
Parameters:
Graph: PNGraph const &
NIdV: TIntV const &
RenumberNodes: bool const &
GetSubGraph(PNGraph const & Graph, TIntV NIdV) -> PNGraph
Parameters:
Graph: PNGraph const &
NIdV: TIntV const &
"""
return _snap.GetSubGraph(*args)
class TGUtil(object):
"""Proxy of C++ TGUtil class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetCdf(*args):
"""
GetCdf(TIntPrV const & PdfV, TIntPrV & CdfV)
Parameters:
PdfV: TIntPrV const &
CdfV: TIntPrV &
GetCdf(TFltPrV const & PdfV, TFltPrV & CdfV)
Parameters:
PdfV: TFltPrV const &
CdfV: TFltPrV &
GetCdf(TIntFltKdV const & PdfV, TIntFltKdV & CdfV)
Parameters:
PdfV: TIntFltKdV const &
CdfV: TIntFltKdV &
GetCdf(TIntPrV const & PdfV) -> TIntPrV
Parameters:
PdfV: TIntPrV const &
GetCdf(TFltPrV const & PdfV) -> TFltPrV
Parameters:
PdfV: TFltPrV const &
"""
return _snap.TGUtil_GetCdf(*args)
GetCdf = staticmethod(GetCdf)
def GetCCdf(*args):
"""
GetCCdf(TIntPrV const & PdfV, TIntPrV & CCdfV)
Parameters:
PdfV: TIntPrV const &
CCdfV: TIntPrV &
GetCCdf(TFltPrV const & PdfV, TFltPrV & CCdfV)
Parameters:
PdfV: TFltPrV const &
CCdfV: TFltPrV &
GetCCdf(TIntFltKdV const & PdfV, TIntFltKdV & CCdfV)
Parameters:
PdfV: TIntFltKdV const &
CCdfV: TIntFltKdV &
GetCCdf(TIntPrV const & PdfV) -> TIntPrV
Parameters:
PdfV: TIntPrV const &
GetCCdf(TFltPrV const & PdfV) -> TFltPrV
Parameters:
PdfV: TFltPrV const &
"""
return _snap.TGUtil_GetCCdf(*args)
GetCCdf = staticmethod(GetCCdf)
def GetPdf(*args):
"""
GetPdf(TIntPrV const & CdfV, TIntPrV & PdfV)
Parameters:
CdfV: TIntPrV const &
PdfV: TIntPrV &
GetPdf(TFltPrV const & CdfV, TFltPrV & PdfV)
Parameters:
CdfV: TFltPrV const &
PdfV: TFltPrV &
GetPdf(TIntFltKdV const & CdfV, TIntFltKdV & PdfV)
Parameters:
CdfV: TIntFltKdV const &
PdfV: TIntFltKdV &
"""
return _snap.TGUtil_GetPdf(*args)
GetPdf = staticmethod(GetPdf)
def Normalize(*args):
"""
Normalize(TFltPrV & PdfV)
Parameters:
PdfV: TFltPrV &
Normalize(TIntFltKdV & PdfV)
Parameters:
PdfV: TIntFltKdV &
"""
return _snap.TGUtil_Normalize(*args)
Normalize = staticmethod(Normalize)
def MakeExpBins(*args):
"""
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV, double const & BinFactor=2, double const & MinYVal=1)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
BinFactor: double const &
MinYVal: double const &
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV, double const & BinFactor=2)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
BinFactor: double const &
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV, double const & BinFactor=2, double const & MinYVal=1)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
BinFactor: double const &
MinYVal: double const &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV, double const & BinFactor=2)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
BinFactor: double const &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
MakeExpBins(TFltV const & YValV, TFltV & ExpYValV, double const & BinFactor=1.01)
Parameters:
YValV: TFltV const &
ExpYValV: TFltV &
BinFactor: double const &
MakeExpBins(TFltV const & YValV, TFltV & ExpYValV)
Parameters:
YValV: TFltV const &
ExpYValV: TFltV &
MakeExpBins(TIntV YValV, TIntV ExpYValV, double const & BinFactor=1.01)
Parameters:
YValV: TIntV const &
ExpYValV: TIntV &
BinFactor: double const &
MakeExpBins(TIntV YValV, TIntV ExpYValV)
Parameters:
YValV: TIntV const &
ExpYValV: TIntV &
"""
return _snap.TGUtil_MakeExpBins(*args)
MakeExpBins = staticmethod(MakeExpBins)
def __init__(self):
"""__init__(TGUtil self) -> TGUtil"""
_snap.TGUtil_swiginit(self,_snap.new_TGUtil())
__swig_destroy__ = _snap.delete_TGUtil
TGUtil_swigregister = _snap.TGUtil_swigregister
TGUtil_swigregister(TGUtil)
def TGUtil_GetCdf(*args):
"""
GetCdf(TIntPrV const & PdfV, TIntPrV & CdfV)
Parameters:
PdfV: TIntPrV const &
CdfV: TIntPrV &
GetCdf(TFltPrV const & PdfV, TFltPrV & CdfV)
Parameters:
PdfV: TFltPrV const &
CdfV: TFltPrV &
GetCdf(TIntFltKdV const & PdfV, TIntFltKdV & CdfV)
Parameters:
PdfV: TIntFltKdV const &
CdfV: TIntFltKdV &
GetCdf(TIntPrV const & PdfV) -> TIntPrV
Parameters:
PdfV: TIntPrV const &
TGUtil_GetCdf(TFltPrV const & PdfV) -> TFltPrV
Parameters:
PdfV: TFltPrV const &
"""
return _snap.TGUtil_GetCdf(*args)
def TGUtil_GetCCdf(*args):
"""
GetCCdf(TIntPrV const & PdfV, TIntPrV & CCdfV)
Parameters:
PdfV: TIntPrV const &
CCdfV: TIntPrV &
GetCCdf(TFltPrV const & PdfV, TFltPrV & CCdfV)
Parameters:
PdfV: TFltPrV const &
CCdfV: TFltPrV &
GetCCdf(TIntFltKdV const & PdfV, TIntFltKdV & CCdfV)
Parameters:
PdfV: TIntFltKdV const &
CCdfV: TIntFltKdV &
GetCCdf(TIntPrV const & PdfV) -> TIntPrV
Parameters:
PdfV: TIntPrV const &
TGUtil_GetCCdf(TFltPrV const & PdfV) -> TFltPrV
Parameters:
PdfV: TFltPrV const &
"""
return _snap.TGUtil_GetCCdf(*args)
def TGUtil_GetPdf(*args):
"""
GetPdf(TIntPrV const & CdfV, TIntPrV & PdfV)
Parameters:
CdfV: TIntPrV const &
PdfV: TIntPrV &
GetPdf(TFltPrV const & CdfV, TFltPrV & PdfV)
Parameters:
CdfV: TFltPrV const &
PdfV: TFltPrV &
TGUtil_GetPdf(TIntFltKdV const & CdfV, TIntFltKdV & PdfV)
Parameters:
CdfV: TIntFltKdV const &
PdfV: TIntFltKdV &
"""
return _snap.TGUtil_GetPdf(*args)
def TGUtil_Normalize(*args):
"""
Normalize(TFltPrV & PdfV)
Parameters:
PdfV: TFltPrV &
TGUtil_Normalize(TIntFltKdV & PdfV)
Parameters:
PdfV: TIntFltKdV &
"""
return _snap.TGUtil_Normalize(*args)
def TGUtil_MakeExpBins(*args):
"""
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV, double const & BinFactor=2, double const & MinYVal=1)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
BinFactor: double const &
MinYVal: double const &
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV, double const & BinFactor=2)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
BinFactor: double const &
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV, double const & BinFactor=2, double const & MinYVal=1)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
BinFactor: double const &
MinYVal: double const &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV, double const & BinFactor=2)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
BinFactor: double const &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
MakeExpBins(TFltV const & YValV, TFltV & ExpYValV, double const & BinFactor=1.01)
Parameters:
YValV: TFltV const &
ExpYValV: TFltV &
BinFactor: double const &
MakeExpBins(TFltV const & YValV, TFltV & ExpYValV)
Parameters:
YValV: TFltV const &
ExpYValV: TFltV &
MakeExpBins(TIntV YValV, TIntV ExpYValV, double const & BinFactor=1.01)
Parameters:
YValV: TIntV const &
ExpYValV: TIntV &
BinFactor: double const &
TGUtil_MakeExpBins(TIntV YValV, TIntV ExpYValV)
Parameters:
YValV: TIntV const &
ExpYValV: TIntV &
"""
return _snap.TGUtil_MakeExpBins(*args)
class TStrUtil(object):
"""Proxy of C++ TStrUtil class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetXmlTagVal(*args):
"""
GetXmlTagVal(TXmlLx & XmlLx, TChA TagNm) -> TChA
Parameters:
XmlLx: TXmlLx &
TagNm: TChA const &
"""
return _snap.TStrUtil_GetXmlTagVal(*args)
GetXmlTagVal = staticmethod(GetXmlTagVal)
def GetXmlTagNmVal(*args):
"""
GetXmlTagNmVal(TXmlLx & XmlLx, TChA TagNm, TChA TagVal)
Parameters:
XmlLx: TXmlLx &
TagNm: TChA &
TagVal: TChA &
"""
return _snap.TStrUtil_GetXmlTagNmVal(*args)
GetXmlTagNmVal = staticmethod(GetXmlTagNmVal)
def GetXmlTagNmVal2(*args):
"""
GetXmlTagNmVal2(TXmlLx & XmlLx, TChA TagNm, TChA TagVal, bool const & TakeTagNms) -> bool
Parameters:
XmlLx: TXmlLx &
TagNm: TChA &
TagVal: TChA &
TakeTagNms: bool const &
"""
return _snap.TStrUtil_GetXmlTagNmVal2(*args)
GetXmlTagNmVal2 = staticmethod(GetXmlTagNmVal2)
def GetDomNm(*args):
"""
GetDomNm(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetDomNm(*args)
GetDomNm = staticmethod(GetDomNm)
def GetDomNm2(*args):
"""
GetDomNm2(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetDomNm2(*args)
GetDomNm2 = staticmethod(GetDomNm2)
def GetWebsiteNm(*args):
"""
GetWebsiteNm(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetWebsiteNm(*args)
GetWebsiteNm = staticmethod(GetWebsiteNm)
def GetNormalizedUrl(*args):
"""
GetNormalizedUrl(TChA UrlIn, TChA BaseUrl, TChA UrlOut) -> bool
Parameters:
UrlIn: TChA const &
BaseUrl: TChA const &
UrlOut: TChA &
"""
return _snap.TStrUtil_GetNormalizedUrl(*args)
GetNormalizedUrl = staticmethod(GetNormalizedUrl)
def StripEnd(*args):
"""
StripEnd(TChA Str, TChA SearchStr, TChA NewStr) -> bool
Parameters:
Str: TChA const &
SearchStr: TChA const &
NewStr: TChA &
"""
return _snap.TStrUtil_StripEnd(*args)
StripEnd = staticmethod(StripEnd)
def GetShorStr(*args):
"""
GetShorStr(TChA LongStr, int const MaxLen=50) -> TChA
Parameters:
LongStr: TChA const &
MaxLen: int const
GetShorStr(TChA LongStr) -> TChA
Parameters:
LongStr: TChA const &
"""
return _snap.TStrUtil_GetShorStr(*args)
GetShorStr = staticmethod(GetShorStr)
def GetCleanStr(*args):
"""
GetCleanStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanStr(*args)
GetCleanStr = staticmethod(GetCleanStr)
def GetCleanWrdStr(*args):
"""
GetCleanWrdStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanWrdStr(*args)
GetCleanWrdStr = staticmethod(GetCleanWrdStr)
def CountWords(*args):
"""
CountWords(char const * CStr) -> int
Parameters:
CStr: char const *
CountWords(TChA ChA) -> int
Parameters:
ChA: TChA const &
CountWords(TChA ChA, TStrHash< TInt > const & StopWordH) -> int
Parameters:
ChA: TChA const &
StopWordH: TStrHash< TInt > const &
"""
return _snap.TStrUtil_CountWords(*args)
CountWords = staticmethod(CountWords)
def SplitWords(*args):
"""
SplitWords(TChA ChA, TVec< char * > & WrdV, bool const & SplitOnWs=True) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
SplitOnWs: bool const &
SplitWords(TChA ChA, TVec< char * > & WrdV) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
"""
return _snap.TStrUtil_SplitWords(*args)
SplitWords = staticmethod(SplitWords)
def SplitOnCh(*args):
"""
SplitOnCh(TChA ChA, TVec< char * > & WrdV, char const & Ch, bool const & SkipEmpty=False) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
Ch: char const &
SkipEmpty: bool const &
SplitOnCh(TChA ChA, TVec< char * > & WrdV, char const & Ch) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
Ch: char const &
"""
return _snap.TStrUtil_SplitOnCh(*args)
SplitOnCh = staticmethod(SplitOnCh)
def SplitLines(*args):
"""
SplitLines(TChA ChA, TVec< char * > & LineV, bool const & SkipEmpty=False) -> int
Parameters:
ChA: TChA &
LineV: TVec< char * > &
SkipEmpty: bool const &
SplitLines(TChA ChA, TVec< char * > & LineV) -> int
Parameters:
ChA: TChA &
LineV: TVec< char * > &
"""
return _snap.TStrUtil_SplitLines(*args)
SplitLines = staticmethod(SplitLines)
def SplitSentences(*args):
"""
SplitSentences(TChA ChA, TVec< char * > & SentenceV) -> int
Parameters:
ChA: TChA &
SentenceV: TVec< char * > &
"""
return _snap.TStrUtil_SplitSentences(*args)
SplitSentences = staticmethod(SplitSentences)
def RemoveHtmlTags(*args):
"""
RemoveHtmlTags(TChA HtmlStr, TChA TextStr)
Parameters:
HtmlStr: TChA const &
TextStr: TChA &
"""
return _snap.TStrUtil_RemoveHtmlTags(*args)
RemoveHtmlTags = staticmethod(RemoveHtmlTags)
def IsLatinStr(*args):
"""
IsLatinStr(TChA Str, double const & MinAlFrac) -> bool
Parameters:
Str: TChA const &
MinAlFrac: double const &
"""
return _snap.TStrUtil_IsLatinStr(*args)
IsLatinStr = staticmethod(IsLatinStr)
def GetWIdV(*args):
"""
GetWIdV(TStrHash< TInt > const & StrH, char const * CStr, TIntV WIdV)
Parameters:
StrH: TStrHash< TInt > const &
CStr: char const *
WIdV: TIntV &
"""
return _snap.TStrUtil_GetWIdV(*args)
GetWIdV = staticmethod(GetWIdV)
def GetAddWIdV(*args):
"""
GetAddWIdV(TStrHash< TInt > & StrH, char const * CStr, TIntV WIdV)
Parameters:
StrH: TStrHash< TInt > &
CStr: char const *
WIdV: TIntV &
"""
return _snap.TStrUtil_GetAddWIdV(*args)
GetAddWIdV = staticmethod(GetAddWIdV)
def GetTmFromStr(*args):
"""
GetTmFromStr(char const * TmStr, TSecTm & Tm) -> bool
Parameters:
TmStr: char const *
Tm: TSecTm &
"""
return _snap.TStrUtil_GetTmFromStr(*args)
GetTmFromStr = staticmethod(GetTmFromStr)
def GetStdName(*args):
"""
GetStdName(TStr AuthorName) -> TStr
Parameters:
AuthorName: TStr
"""
return _snap.TStrUtil_GetStdName(*args)
GetStdName = staticmethod(GetStdName)
def GetStdNameV(*args):
"""
GetStdNameV(TStr AuthorNames, TStrV StdNameV)
Parameters:
AuthorNames: TStr
StdNameV: TStrV &
"""
return _snap.TStrUtil_GetStdNameV(*args)
GetStdNameV = staticmethod(GetStdNameV)
def __init__(self):
"""__init__(TStrUtil self) -> TStrUtil"""
_snap.TStrUtil_swiginit(self,_snap.new_TStrUtil())
__swig_destroy__ = _snap.delete_TStrUtil
TStrUtil_swigregister = _snap.TStrUtil_swigregister
TStrUtil_swigregister(TStrUtil)
def TStrUtil_GetXmlTagVal(*args):
"""
TStrUtil_GetXmlTagVal(TXmlLx & XmlLx, TChA TagNm) -> TChA
Parameters:
XmlLx: TXmlLx &
TagNm: TChA const &
"""
return _snap.TStrUtil_GetXmlTagVal(*args)
def TStrUtil_GetXmlTagNmVal(*args):
"""
TStrUtil_GetXmlTagNmVal(TXmlLx & XmlLx, TChA TagNm, TChA TagVal)
Parameters:
XmlLx: TXmlLx &
TagNm: TChA &
TagVal: TChA &
"""
return _snap.TStrUtil_GetXmlTagNmVal(*args)
def TStrUtil_GetXmlTagNmVal2(*args):
"""
TStrUtil_GetXmlTagNmVal2(TXmlLx & XmlLx, TChA TagNm, TChA TagVal, bool const & TakeTagNms) -> bool
Parameters:
XmlLx: TXmlLx &
TagNm: TChA &
TagVal: TChA &
TakeTagNms: bool const &
"""
return _snap.TStrUtil_GetXmlTagNmVal2(*args)
def TStrUtil_GetDomNm(*args):
"""
TStrUtil_GetDomNm(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetDomNm(*args)
def TStrUtil_GetDomNm2(*args):
"""
TStrUtil_GetDomNm2(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetDomNm2(*args)
def TStrUtil_GetWebsiteNm(*args):
"""
TStrUtil_GetWebsiteNm(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetWebsiteNm(*args)
def TStrUtil_GetNormalizedUrl(*args):
"""
TStrUtil_GetNormalizedUrl(TChA UrlIn, TChA BaseUrl, TChA UrlOut) -> bool
Parameters:
UrlIn: TChA const &
BaseUrl: TChA const &
UrlOut: TChA &
"""
return _snap.TStrUtil_GetNormalizedUrl(*args)
def TStrUtil_StripEnd(*args):
"""
TStrUtil_StripEnd(TChA Str, TChA SearchStr, TChA NewStr) -> bool
Parameters:
Str: TChA const &
SearchStr: TChA const &
NewStr: TChA &
"""
return _snap.TStrUtil_StripEnd(*args)
def TStrUtil_GetShorStr(*args):
"""
GetShorStr(TChA LongStr, int const MaxLen=50) -> TChA
Parameters:
LongStr: TChA const &
MaxLen: int const
TStrUtil_GetShorStr(TChA LongStr) -> TChA
Parameters:
LongStr: TChA const &
"""
return _snap.TStrUtil_GetShorStr(*args)
def TStrUtil_GetCleanStr(*args):
"""
TStrUtil_GetCleanStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanStr(*args)
def TStrUtil_GetCleanWrdStr(*args):
"""
TStrUtil_GetCleanWrdStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanWrdStr(*args)
def TStrUtil_CountWords(*args):
"""
CountWords(char const * CStr) -> int
Parameters:
CStr: char const *
CountWords(TChA ChA) -> int
Parameters:
ChA: TChA const &
TStrUtil_CountWords(TChA ChA, TStrHash< TInt > const & StopWordH) -> int
Parameters:
ChA: TChA const &
StopWordH: TStrHash< TInt > const &
"""
return _snap.TStrUtil_CountWords(*args)
def TStrUtil_SplitWords(*args):
"""
SplitWords(TChA ChA, TVec< char * > & WrdV, bool const & SplitOnWs=True) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
SplitOnWs: bool const &
TStrUtil_SplitWords(TChA ChA, TVec< char * > & WrdV) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
"""
return _snap.TStrUtil_SplitWords(*args)
def TStrUtil_SplitOnCh(*args):
"""
SplitOnCh(TChA ChA, TVec< char * > & WrdV, char const & Ch, bool const & SkipEmpty=False) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
Ch: char const &
SkipEmpty: bool const &
TStrUtil_SplitOnCh(TChA ChA, TVec< char * > & WrdV, char const & Ch) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
Ch: char const &
"""
return _snap.TStrUtil_SplitOnCh(*args)
def TStrUtil_SplitLines(*args):
"""
SplitLines(TChA ChA, TVec< char * > & LineV, bool const & SkipEmpty=False) -> int
Parameters:
ChA: TChA &
LineV: TVec< char * > &
SkipEmpty: bool const &
TStrUtil_SplitLines(TChA ChA, TVec< char * > & LineV) -> int
Parameters:
ChA: TChA &
LineV: TVec< char * > &
"""
return _snap.TStrUtil_SplitLines(*args)
def TStrUtil_SplitSentences(*args):
"""
TStrUtil_SplitSentences(TChA ChA, TVec< char * > & SentenceV) -> int
Parameters:
ChA: TChA &
SentenceV: TVec< char * > &
"""
return _snap.TStrUtil_SplitSentences(*args)
def TStrUtil_RemoveHtmlTags(*args):
"""
TStrUtil_RemoveHtmlTags(TChA HtmlStr, TChA TextStr)
Parameters:
HtmlStr: TChA const &
TextStr: TChA &
"""
return _snap.TStrUtil_RemoveHtmlTags(*args)
def TStrUtil_IsLatinStr(*args):
"""
TStrUtil_IsLatinStr(TChA Str, double const & MinAlFrac) -> bool
Parameters:
Str: TChA const &
MinAlFrac: double const &
"""
return _snap.TStrUtil_IsLatinStr(*args)
def TStrUtil_GetWIdV(*args):
"""
TStrUtil_GetWIdV(TStrHash< TInt > const & StrH, char const * CStr, TIntV WIdV)
Parameters:
StrH: TStrHash< TInt > const &
CStr: char const *
WIdV: TIntV &
"""
return _snap.TStrUtil_GetWIdV(*args)
def TStrUtil_GetAddWIdV(*args):
"""
TStrUtil_GetAddWIdV(TStrHash< TInt > & StrH, char const * CStr, TIntV WIdV)
Parameters:
StrH: TStrHash< TInt > &
CStr: char const *
WIdV: TIntV &
"""
return _snap.TStrUtil_GetAddWIdV(*args)
def TStrUtil_GetTmFromStr(*args):
"""
TStrUtil_GetTmFromStr(char const * TmStr, TSecTm & Tm) -> bool
Parameters:
TmStr: char const *
Tm: TSecTm &
"""
return _snap.TStrUtil_GetTmFromStr(*args)
def TStrUtil_GetStdName(*args):
"""
TStrUtil_GetStdName(TStr AuthorName) -> TStr
Parameters:
AuthorName: TStr
"""
return _snap.TStrUtil_GetStdName(*args)
def TStrUtil_GetStdNameV(*args):
"""
TStrUtil_GetStdNameV(TStr AuthorNames, TStrV StdNameV)
Parameters:
AuthorNames: TStr
StdNameV: TStrV &
"""
return _snap.TStrUtil_GetStdNameV(*args)
class TRnd(object):
"""Proxy of C++ TRnd class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TRnd self, int const & _Seed=1, int const & Steps=0) -> TRnd
Parameters:
_Seed: int const &
Steps: int const &
__init__(TRnd self, int const & _Seed=1) -> TRnd
Parameters:
_Seed: int const &
__init__(TRnd self) -> TRnd
__init__(TRnd self, TSIn SIn) -> TRnd
Parameters:
SIn: TSIn &
"""
_snap.TRnd_swiginit(self,_snap.new_TRnd(*args))
def Save(self, *args):
"""
Save(TRnd self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TRnd_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TRnd self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TRnd_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TRnd self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TRnd_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TRnd self, TRnd arg2) -> bool
Parameters:
arg2: TRnd const &
"""
return _snap.TRnd___eq__(self, *args)
def GetUniDev(self):
"""
GetUniDev(TRnd self) -> double
Parameters:
self: TRnd *
"""
return _snap.TRnd_GetUniDev(self)
def GetUniDevInt(self, *args):
"""
GetUniDevInt(TRnd self, int const & Range=0) -> int
Parameters:
Range: int const &
GetUniDevInt(TRnd self) -> int
GetUniDevInt(TRnd self, int const & MnVal, int const & MxVal) -> int
Parameters:
MnVal: int const &
MxVal: int const &
"""
return _snap.TRnd_GetUniDevInt(self, *args)
def GetUniDevUInt(self, Range=0):
"""
GetUniDevUInt(TRnd self, uint const & Range=0) -> uint
Parameters:
Range: uint const &
GetUniDevUInt(TRnd self) -> uint
Parameters:
self: TRnd *
"""
return _snap.TRnd_GetUniDevUInt(self, Range)
def GetUniDevInt64(self, Range=0):
"""
GetUniDevInt64(TRnd self, int64 const & Range=0) -> int64
Parameters:
Range: int64 const &
GetUniDevInt64(TRnd self) -> int64
Parameters:
self: TRnd *
"""
return _snap.TRnd_GetUniDevInt64(self, Range)
def GetUniDevUInt64(self, Range=0):
"""
GetUniDevUInt64(TRnd self, uint64 const & Range=0) -> uint64
Parameters:
Range: uint64 const &
GetUniDevUInt64(TRnd self) -> uint64
Parameters:
self: TRnd *
"""
return _snap.TRnd_GetUniDevUInt64(self, Range)
def GetNrmDev(self, *args):
"""
GetNrmDev(TRnd self) -> double
GetNrmDev(TRnd self, double const & Mean, double const & SDev, double const & Mn, double const & Mx) -> double
Parameters:
Mean: double const &
SDev: double const &
Mn: double const &
Mx: double const &
"""
return _snap.TRnd_GetNrmDev(self, *args)
def GetExpDev(self, *args):
"""
GetExpDev(TRnd self) -> double
GetExpDev(TRnd self, double const & Lambda) -> double
Parameters:
Lambda: double const &
"""
return _snap.TRnd_GetExpDev(self, *args)
def GetGammaDev(self, *args):
"""
GetGammaDev(TRnd self, int const & Order) -> double
Parameters:
Order: int const &
"""
return _snap.TRnd_GetGammaDev(self, *args)
def GetPoissonDev(self, *args):
"""
GetPoissonDev(TRnd self, double const & Mean) -> double
Parameters:
Mean: double const &
"""
return _snap.TRnd_GetPoissonDev(self, *args)
def GetBinomialDev(self, *args):
"""
GetBinomialDev(TRnd self, double const & Prb, int const & Trials) -> double
Parameters:
Prb: double const &
Trials: int const &
"""
return _snap.TRnd_GetBinomialDev(self, *args)
def GetGeoDev(self, *args):
"""
GetGeoDev(TRnd self, double const & Prb) -> int
Parameters:
Prb: double const &
"""
return _snap.TRnd_GetGeoDev(self, *args)
def GetPowerDev(self, *args):
"""
GetPowerDev(TRnd self, double const & AlphaSlope) -> double
Parameters:
AlphaSlope: double const &
"""
return _snap.TRnd_GetPowerDev(self, *args)
def GetRayleigh(self, *args):
"""
GetRayleigh(TRnd self, double const & Sigma) -> double
Parameters:
Sigma: double const &
"""
return _snap.TRnd_GetRayleigh(self, *args)
def GetWeibull(self, *args):
"""
GetWeibull(TRnd self, double const & K, double const & Lambda) -> double
Parameters:
K: double const &
Lambda: double const &
"""
return _snap.TRnd_GetWeibull(self, *args)
def PutSeed(self, *args):
"""
PutSeed(TRnd self, int const & _Seed)
Parameters:
_Seed: int const &
"""
return _snap.TRnd_PutSeed(self, *args)
def GetSeed(self):
"""
GetSeed(TRnd self) -> int
Parameters:
self: TRnd const *
"""
return _snap.TRnd_GetSeed(self)
def Randomize(self):
"""
Randomize(TRnd self)
Parameters:
self: TRnd *
"""
return _snap.TRnd_Randomize(self)
def Move(self, *args):
"""
Move(TRnd self, int const & Steps)
Parameters:
Steps: int const &
"""
return _snap.TRnd_Move(self, *args)
def Check(self):
"""
Check(TRnd self) -> bool
Parameters:
self: TRnd *
"""
return _snap.TRnd_Check(self)
def GetUniDevStep(*args):
"""
GetUniDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetUniDevStep(*args)
GetUniDevStep = staticmethod(GetUniDevStep)
def GetNrmDevStep(*args):
"""
GetNrmDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetNrmDevStep(*args)
GetNrmDevStep = staticmethod(GetNrmDevStep)
def GetExpDevStep(*args):
"""
GetExpDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetExpDevStep(*args)
GetExpDevStep = staticmethod(GetExpDevStep)
def LoadTxt(*args):
"""
LoadTxt(TILx & Lx) -> TRnd
Parameters:
Lx: TILx &
"""
return _snap.TRnd_LoadTxt(*args)
LoadTxt = staticmethod(LoadTxt)
def SaveTxt(self, *args):
"""
SaveTxt(TRnd self, TOLx & Lx)
Parameters:
Lx: TOLx &
"""
return _snap.TRnd_SaveTxt(self, *args)
__swig_destroy__ = _snap.delete_TRnd
TRnd.Save = new_instancemethod(_snap.TRnd_Save,None,TRnd)
TRnd.LoadXml = new_instancemethod(_snap.TRnd_LoadXml,None,TRnd)
TRnd.SaveXml = new_instancemethod(_snap.TRnd_SaveXml,None,TRnd)
TRnd.__eq__ = new_instancemethod(_snap.TRnd___eq__,None,TRnd)
TRnd.GetUniDev = new_instancemethod(_snap.TRnd_GetUniDev,None,TRnd)
TRnd.GetUniDevInt = new_instancemethod(_snap.TRnd_GetUniDevInt,None,TRnd)
TRnd.GetUniDevUInt = new_instancemethod(_snap.TRnd_GetUniDevUInt,None,TRnd)
TRnd.GetUniDevInt64 = new_instancemethod(_snap.TRnd_GetUniDevInt64,None,TRnd)
TRnd.GetUniDevUInt64 = new_instancemethod(_snap.TRnd_GetUniDevUInt64,None,TRnd)
TRnd.GetNrmDev = new_instancemethod(_snap.TRnd_GetNrmDev,None,TRnd)
TRnd.GetExpDev = new_instancemethod(_snap.TRnd_GetExpDev,None,TRnd)
TRnd.GetGammaDev = new_instancemethod(_snap.TRnd_GetGammaDev,None,TRnd)
TRnd.GetPoissonDev = new_instancemethod(_snap.TRnd_GetPoissonDev,None,TRnd)
TRnd.GetBinomialDev = new_instancemethod(_snap.TRnd_GetBinomialDev,None,TRnd)
TRnd.GetGeoDev = new_instancemethod(_snap.TRnd_GetGeoDev,None,TRnd)
TRnd.GetPowerDev = new_instancemethod(_snap.TRnd_GetPowerDev,None,TRnd)
TRnd.GetRayleigh = new_instancemethod(_snap.TRnd_GetRayleigh,None,TRnd)
TRnd.GetWeibull = new_instancemethod(_snap.TRnd_GetWeibull,None,TRnd)
TRnd.PutSeed = new_instancemethod(_snap.TRnd_PutSeed,None,TRnd)
TRnd.GetSeed = new_instancemethod(_snap.TRnd_GetSeed,None,TRnd)
TRnd.Randomize = new_instancemethod(_snap.TRnd_Randomize,None,TRnd)
TRnd.Move = new_instancemethod(_snap.TRnd_Move,None,TRnd)
TRnd.Check = new_instancemethod(_snap.TRnd_Check,None,TRnd)
TRnd.SaveTxt = new_instancemethod(_snap.TRnd_SaveTxt,None,TRnd)
TRnd_swigregister = _snap.TRnd_swigregister
TRnd_swigregister(TRnd)
TRnd.RndSeed = _snap.cvar.TRnd_RndSeed
def TRnd_GetUniDevStep(*args):
"""
TRnd_GetUniDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetUniDevStep(*args)
def TRnd_GetNrmDevStep(*args):
"""
TRnd_GetNrmDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetNrmDevStep(*args)
def TRnd_GetExpDevStep(*args):
"""
TRnd_GetExpDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetExpDevStep(*args)
def TRnd_LoadTxt(*args):
"""
TRnd_LoadTxt(TILx & Lx) -> TRnd
Parameters:
Lx: TILx &
"""
return _snap.TRnd_LoadTxt(*args)
class TMem(object):
"""Proxy of C++ TMem class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def New(*args):
"""
New(int const & MxBfL=0) -> PMem
Parameters:
MxBfL: int const &
New() -> PMem
New(void const * Bf, int const & BfL) -> PMem
Parameters:
Bf: void const *
BfL: int const &
New(TMem Mem) -> PMem
Parameters:
Mem: TMem const &
New(PMem const & Mem) -> PMem
Parameters:
Mem: PMem const &
New(TStr Str) -> PMem
Parameters:
Str: TStr const &
"""
return _snap.TMem_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TMem
def __init__(self, *args):
"""
__init__(TMem self, int const & _MxBfL=0) -> TMem
Parameters:
_MxBfL: int const &
__init__(TMem self) -> TMem
__init__(TMem self, void const * _Bf, int const & _BfL) -> TMem
Parameters:
_Bf: void const *
_BfL: int const &
__init__(TMem self, TMem Mem) -> TMem
Parameters:
Mem: TMem const &
__init__(TMem self, TStr Str) -> TMem
Parameters:
Str: TStr const &
__init__(TMem self, TSIn SIn) -> TMem
Parameters:
SIn: TSIn &
"""
_snap.TMem_swiginit(self,_snap.new_TMem(*args))
def Save(self, *args):
"""
Save(TMem self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TMem_Save(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TMem self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TMem_SaveXml(self, *args)
def __call__(self):
"""
__call__(TMem self) -> char *
Parameters:
self: TMem const *
"""
return _snap.TMem___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TMem self, char const & Ch) -> TMem
Parameters:
Ch: char const &
__iadd__(TMem self, TMem Mem) -> TMem
Parameters:
Mem: TMem const &
__iadd__(TMem self, TStr Str) -> TMem
Parameters:
Str: TStr const &
__iadd__(TMem self, PSIn const & SIn) -> TMem
Parameters:
SIn: PSIn const &
"""
return _snap.TMem___iadd__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TMem self) -> int
Parameters:
self: TMem const *
"""
return _snap.TMem_GetMemUsed(self)
def Gen(self, *args):
"""
Gen(TMem self, int const & _BfL)
Parameters:
_BfL: int const &
"""
return _snap.TMem_Gen(self, *args)
def GenZeros(self, *args):
"""
GenZeros(TMem self, int const & _BfL)
Parameters:
_BfL: int const &
"""
return _snap.TMem_GenZeros(self, *args)
def Reserve(self, *args):
"""
Reserve(TMem self, int const & _MxBfL, bool const & DoClr=True)
Parameters:
_MxBfL: int const &
DoClr: bool const &
Reserve(TMem self, int const & _MxBfL)
Parameters:
_MxBfL: int const &
"""
return _snap.TMem_Reserve(self, *args)
def Del(self, *args):
"""
Del(TMem self, int const & BChN, int const & EChN)
Parameters:
BChN: int const &
EChN: int const &
"""
return _snap.TMem_Del(self, *args)
def Clr(self, DoDel=True):
"""
Clr(TMem self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TMem self)
Parameters:
self: TMem *
"""
return _snap.TMem_Clr(self, DoDel)
def Len(self):
"""
Len(TMem self) -> int
Parameters:
self: TMem const *
"""
return _snap.TMem_Len(self)
def Empty(self):
"""
Empty(TMem self) -> bool
Parameters:
self: TMem const *
"""
return _snap.TMem_Empty(self)
def Trunc(self, *args):
"""
Trunc(TMem self, int const & _BfL)
Parameters:
_BfL: int const &
"""
return _snap.TMem_Trunc(self, *args)
def Push(self, *args):
"""
Push(TMem self, char const & Ch)
Parameters:
Ch: char const &
"""
return _snap.TMem_Push(self, *args)
def Pop(self):
"""
Pop(TMem self) -> char
Parameters:
self: TMem *
"""
return _snap.TMem_Pop(self)
def DoFitStr(self, *args):
"""
DoFitStr(TMem self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TMem_DoFitStr(self, *args)
def AddBf(self, *args):
"""
AddBf(TMem self, void const * Bf, int const & BfL)
Parameters:
Bf: void const *
BfL: int const &
"""
return _snap.TMem_AddBf(self, *args)
def GetBf(self):
"""
GetBf(TMem self) -> char *
Parameters:
self: TMem const *
"""
return _snap.TMem_GetBf(self)
def GetAsStr(self, NewNullCh='\0'):
"""
GetAsStr(TMem self, char const & NewNullCh='\0') -> TStr
Parameters:
NewNullCh: char const &
GetAsStr(TMem self) -> TStr
Parameters:
self: TMem const *
"""
return _snap.TMem_GetAsStr(self, NewNullCh)
def GetSIn(self):
"""
GetSIn(TMem self) -> PSIn
Parameters:
self: TMem const *
"""
return _snap.TMem_GetSIn(self)
def LoadMem(*args):
"""
LoadMem(PSIn const & SIn, TMem Mem)
Parameters:
SIn: PSIn const &
Mem: TMem &
LoadMem(PSIn const & SIn, PMem const & Mem)
Parameters:
SIn: PSIn const &
Mem: PMem const &
"""
return _snap.TMem_LoadMem(*args)
LoadMem = staticmethod(LoadMem)
def SaveMem(self, *args):
"""
SaveMem(TMem self, PSOut const & SOut)
Parameters:
SOut: PSOut const &
"""
return _snap.TMem_SaveMem(self, *args)
TMem.Save = new_instancemethod(_snap.TMem_Save,None,TMem)
TMem.SaveXml = new_instancemethod(_snap.TMem_SaveXml,None,TMem)
TMem.__call__ = new_instancemethod(_snap.TMem___call__,None,TMem)
TMem.__iadd__ = new_instancemethod(_snap.TMem___iadd__,None,TMem)
TMem.GetMemUsed = new_instancemethod(_snap.TMem_GetMemUsed,None,TMem)
TMem.Gen = new_instancemethod(_snap.TMem_Gen,None,TMem)
TMem.GenZeros = new_instancemethod(_snap.TMem_GenZeros,None,TMem)
TMem.Reserve = new_instancemethod(_snap.TMem_Reserve,None,TMem)
TMem.Del = new_instancemethod(_snap.TMem_Del,None,TMem)
TMem.Clr = new_instancemethod(_snap.TMem_Clr,None,TMem)
TMem.Len = new_instancemethod(_snap.TMem_Len,None,TMem)
TMem.Empty = new_instancemethod(_snap.TMem_Empty,None,TMem)
TMem.Trunc = new_instancemethod(_snap.TMem_Trunc,None,TMem)
TMem.Push = new_instancemethod(_snap.TMem_Push,None,TMem)
TMem.Pop = new_instancemethod(_snap.TMem_Pop,None,TMem)
TMem.DoFitStr = new_instancemethod(_snap.TMem_DoFitStr,None,TMem)
TMem.AddBf = new_instancemethod(_snap.TMem_AddBf,None,TMem)
TMem.GetBf = new_instancemethod(_snap.TMem_GetBf,None,TMem)
TMem.GetAsStr = new_instancemethod(_snap.TMem_GetAsStr,None,TMem)
TMem.GetSIn = new_instancemethod(_snap.TMem_GetSIn,None,TMem)
TMem.SaveMem = new_instancemethod(_snap.TMem_SaveMem,None,TMem)
TMem_swigregister = _snap.TMem_swigregister
TMem_swigregister(TMem)
def TMem_New(*args):
"""
New(int const & MxBfL=0) -> PMem
Parameters:
MxBfL: int const &
New() -> PMem
New(void const * Bf, int const & BfL) -> PMem
Parameters:
Bf: void const *
BfL: int const &
New(TMem Mem) -> PMem
Parameters:
Mem: TMem const &
New(PMem const & Mem) -> PMem
Parameters:
Mem: PMem const &
TMem_New(TStr Str) -> PMem
Parameters:
Str: TStr const &
"""
return _snap.TMem_New(*args)
def TMem_LoadMem(*args):
"""
LoadMem(PSIn const & SIn, TMem Mem)
Parameters:
SIn: PSIn const &
Mem: TMem &
TMem_LoadMem(PSIn const & SIn, PMem const & Mem)
Parameters:
SIn: PSIn const &
Mem: PMem const &
"""
return _snap.TMem_LoadMem(*args)
class TMemIn(TSIn):
"""Proxy of C++ TMemIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TMemIn self, TMem _Mem, int const & _BfC=0) -> TMemIn
Parameters:
_Mem: TMem const &
_BfC: int const &
__init__(TMemIn self, TMem _Mem) -> TMemIn
Parameters:
_Mem: TMem const &
"""
_snap.TMemIn_swiginit(self,_snap.new_TMemIn(*args))
def New(*args):
"""
New(TMem Mem) -> PSIn
Parameters:
Mem: TMem const &
New(PMem const & Mem) -> PSIn
Parameters:
Mem: PMem const &
"""
return _snap.TMemIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TMemIn
TMemIn_swigregister = _snap.TMemIn_swigregister
TMemIn_swigregister(TMemIn)
def TMemIn_New(*args):
"""
New(TMem Mem) -> PSIn
Parameters:
Mem: TMem const &
TMemIn_New(PMem const & Mem) -> PSIn
Parameters:
Mem: PMem const &
"""
return _snap.TMemIn_New(*args)
class TMemOut(TSOut):
"""Proxy of C++ TMemOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TMemOut self, PMem const & _Mem) -> TMemOut
Parameters:
_Mem: PMem const &
"""
_snap.TMemOut_swiginit(self,_snap.new_TMemOut(*args))
def New(*args):
"""
New(PMem const & Mem) -> PSOut
Parameters:
Mem: PMem const &
"""
return _snap.TMemOut_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TMemOut
TMemOut_swigregister = _snap.TMemOut_swigregister
TMemOut_swigregister(TMemOut)
def TMemOut_New(*args):
"""
TMemOut_New(PMem const & Mem) -> PSOut
Parameters:
Mem: PMem const &
"""
return _snap.TMemOut_New(*args)
class TChA(object):
"""Proxy of C++ TChA class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TChA
def __init__(self, *args):
"""
__init__(TChA self, int const & _MxBfL=256) -> TChA
Parameters:
_MxBfL: int const &
__init__(TChA self) -> TChA
__init__(TChA self, char const * CStr) -> TChA
Parameters:
CStr: char const *
__init__(TChA self, char const * CStr, int const & StrLen) -> TChA
Parameters:
CStr: char const *
StrLen: int const &
__init__(TChA self, TChA ChA) -> TChA
Parameters:
ChA: TChA const &
__init__(TChA self, TStr Str) -> TChA
Parameters:
Str: TStr const &
__init__(TChA self, TMem Mem) -> TChA
Parameters:
Mem: TMem const &
__init__(TChA self, TSIn SIn) -> TChA
Parameters:
SIn: TSIn &
"""
_snap.TChA_swiginit(self,_snap.new_TChA(*args))
def Load(self, *args):
"""
Load(TChA self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TChA_Load(self, *args)
def Save(self, *args):
"""
Save(TChA self, TSOut SOut, bool const & SaveCompact=True)
Parameters:
SOut: TSOut &
SaveCompact: bool const &
Save(TChA self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TChA_Save(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TChA self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TChA_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TChA self, TChA ChA) -> bool
Parameters:
ChA: TChA const &
__eq__(TChA self, char const * _CStr) -> bool
Parameters:
_CStr: char const *
__eq__(TChA self, char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TChA___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TChA self, TChA ChA) -> bool
Parameters:
ChA: TChA const &
__ne__(TChA self, char const * _CStr) -> bool
Parameters:
_CStr: char const *
__ne__(TChA self, char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TChA___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TChA self, TChA ChA) -> bool
Parameters:
ChA: TChA const &
"""
return _snap.TChA___lt__(self, *args)
def __iadd__(self, *args):
"""
__iadd__(TChA self, TMem Mem) -> TChA
Parameters:
Mem: TMem const &
__iadd__(TChA self, TChA ChA) -> TChA
Parameters:
ChA: TChA const &
__iadd__(TChA self, TStr Str) -> TChA
Parameters:
Str: TStr const &
__iadd__(TChA self, char const * CStr) -> TChA
Parameters:
CStr: char const *
__iadd__(TChA self, char const & Ch) -> TChA
Parameters:
Ch: char const &
"""
return _snap.TChA___iadd__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TChA self) -> int
Parameters:
self: TChA const *
"""
return _snap.TChA_GetMemUsed(self)
def __call__(self, *args):
"""
__call__(TChA self) -> char
__call__(TChA self) -> char const *
Parameters:
self: TChA const *
"""
return _snap.TChA___call__(self, *args)
def CStr(self, *args):
"""
CStr(TChA self) -> char
CStr(TChA self) -> char const *
Parameters:
self: TChA const *
"""
return _snap.TChA_CStr(self, *args)
def Clr(self):
"""
Clr(TChA self)
Parameters:
self: TChA *
"""
return _snap.TChA_Clr(self)
def Len(self):
"""
Len(TChA self) -> int
Parameters:
self: TChA const *
"""
return _snap.TChA_Len(self)
def Empty(self):
"""
Empty(TChA self) -> bool
Parameters:
self: TChA const *
"""
return _snap.TChA_Empty(self)
def Ins(self, *args):
"""
Ins(TChA self, int const & BChN, char const * CStr)
Parameters:
BChN: int const &
CStr: char const *
"""
return _snap.TChA_Ins(self, *args)
def Del(self, *args):
"""
Del(TChA self, int const & ChN)
Parameters:
ChN: int const &
"""
return _snap.TChA_Del(self, *args)
def DelLastCh(self):
"""
DelLastCh(TChA self)
Parameters:
self: TChA *
"""
return _snap.TChA_DelLastCh(self)
def Push(self, *args):
"""
Push(TChA self, char const & Ch)
Parameters:
Ch: char const &
"""
return _snap.TChA_Push(self, *args)
def Pop(self):
"""
Pop(TChA self) -> char
Parameters:
self: TChA *
"""
return _snap.TChA_Pop(self)
def Trunc(self, *args):
"""
Trunc(TChA self)
Trunc(TChA self, int const & _BfL)
Parameters:
_BfL: int const &
"""
return _snap.TChA_Trunc(self, *args)
def Reverse(self):
"""
Reverse(TChA self)
Parameters:
self: TChA *
"""
return _snap.TChA_Reverse(self)
def AddCh(self, *args):
"""
AddCh(TChA self, char const & Ch, int const & MxLen=-1)
Parameters:
Ch: char const &
MxLen: int const &
AddCh(TChA self, char const & Ch)
Parameters:
Ch: char const &
"""
return _snap.TChA_AddCh(self, *args)
def AddChTo(self, *args):
"""
AddChTo(TChA self, char const & Ch, int const & ToChN)
Parameters:
Ch: char const &
ToChN: int const &
"""
return _snap.TChA_AddChTo(self, *args)
def AddBf(self, *args):
"""
AddBf(TChA self, char * NewBf, int const & BfS)
Parameters:
NewBf: char *
BfS: int const &
"""
return _snap.TChA_AddBf(self, *args)
def PutCh(self, *args):
"""
PutCh(TChA self, int const & ChN, char const & Ch)
Parameters:
ChN: int const &
Ch: char const &
"""
return _snap.TChA_PutCh(self, *args)
def GetCh(self, *args):
"""
GetCh(TChA self, int const & ChN) -> char
Parameters:
ChN: int const &
"""
return _snap.TChA_GetCh(self, *args)
def LastCh(self):
"""
LastCh(TChA self) -> char
Parameters:
self: TChA const *
"""
return _snap.TChA_LastCh(self)
def LastLastCh(self):
"""
LastLastCh(TChA self) -> char
Parameters:
self: TChA const *
"""
return _snap.TChA_LastLastCh(self)
def GetSubStr(self, *args):
"""
GetSubStr(TChA self, int const & BChN, int const & EChN) -> TChA
Parameters:
BChN: int const &
EChN: int const &
"""
return _snap.TChA_GetSubStr(self, *args)
def CountCh(self, *args):
"""
CountCh(TChA self, char const & Ch, int const & BChN=0) -> int
Parameters:
Ch: char const &
BChN: int const &
CountCh(TChA self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TChA_CountCh(self, *args)
def SearchCh(self, *args):
"""
SearchCh(TChA self, char const & Ch, int const & BChN=0) -> int
Parameters:
Ch: char const &
BChN: int const &
SearchCh(TChA self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TChA_SearchCh(self, *args)
def SearchChBack(self, *args):
"""
SearchChBack(TChA self, char const & Ch, int BChN=-1) -> int
Parameters:
Ch: char const &
BChN: int
SearchChBack(TChA self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TChA_SearchChBack(self, *args)
def SearchStr(self, *args):
"""
SearchStr(TChA self, TChA Str, int const & BChN=0) -> int
Parameters:
Str: TChA const &
BChN: int const &
SearchStr(TChA self, TChA Str) -> int
Parameters:
Str: TChA const &
SearchStr(TChA self, TStr Str, int const & BChN=0) -> int
Parameters:
Str: TStr const &
BChN: int const &
SearchStr(TChA self, TStr Str) -> int
Parameters:
Str: TStr const &
SearchStr(TChA self, char const * CStr, int const & BChN=0) -> int
Parameters:
CStr: char const *
BChN: int const &
SearchStr(TChA self, char const * CStr) -> int
Parameters:
CStr: char const *
"""
return _snap.TChA_SearchStr(self, *args)
def IsStrIn(self, *args):
"""
IsStrIn(TChA self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TChA_IsStrIn(self, *args)
def IsPrefix(self, *args):
"""
IsPrefix(TChA self, char const * CStr, int const & BChN=0) -> bool
Parameters:
CStr: char const *
BChN: int const &
IsPrefix(TChA self, char const * CStr) -> bool
Parameters:
CStr: char const *
IsPrefix(TChA self, TStr Str) -> bool
Parameters:
Str: TStr const &
IsPrefix(TChA self, TChA Str) -> bool
Parameters:
Str: TChA const &
"""
return _snap.TChA_IsPrefix(self, *args)
def IsSuffix(self, *args):
"""
IsSuffix(TChA self, char const * CStr) -> bool
Parameters:
CStr: char const *
IsSuffix(TChA self, TStr Str) -> bool
Parameters:
Str: TStr const &
IsSuffix(TChA self, TChA Str) -> bool
Parameters:
Str: TChA const &
"""
return _snap.TChA_IsSuffix(self, *args)
def IsChIn(self, *args):
"""
IsChIn(TChA self, char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TChA_IsChIn(self, *args)
def ChangeCh(self, *args):
"""
ChangeCh(TChA self, char const & SrcCh, char const & DstCh)
Parameters:
SrcCh: char const &
DstCh: char const &
"""
return _snap.TChA_ChangeCh(self, *args)
def ToUc(self):
"""
ToUc(TChA self) -> TChA
Parameters:
self: TChA *
"""
return _snap.TChA_ToUc(self)
def ToLc(self):
"""
ToLc(TChA self) -> TChA
Parameters:
self: TChA *
"""
return _snap.TChA_ToLc(self)
def ToTrunc(self):
"""
ToTrunc(TChA self) -> TChA
Parameters:
self: TChA *
"""
return _snap.TChA_ToTrunc(self)
def CompressWs(self):
"""
CompressWs(TChA self)
Parameters:
self: TChA *
"""
return _snap.TChA_CompressWs(self)
def Swap(self, *args):
"""
Swap(TChA self, int const & ChN1, int const & ChN2)
Parameters:
ChN1: int const &
ChN2: int const &
Swap(TChA self, TChA ChA)
Parameters:
ChA: TChA &
"""
return _snap.TChA_Swap(self, *args)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TChA self) -> int
Parameters:
self: TChA const *
"""
return _snap.TChA_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TChA self) -> int
Parameters:
self: TChA const *
"""
return _snap.TChA_GetSecHashCd(self)
def LoadTxt(*args):
"""
LoadTxt(PSIn const & SIn, TChA ChA)
Parameters:
SIn: PSIn const &
ChA: TChA &
"""
return _snap.TChA_LoadTxt(*args)
LoadTxt = staticmethod(LoadTxt)
def SaveTxt(self, *args):
"""
SaveTxt(TChA self, PSOut const & SOut)
Parameters:
SOut: PSOut const &
"""
return _snap.TChA_SaveTxt(self, *args)
TChA.Load = new_instancemethod(_snap.TChA_Load,None,TChA)
TChA.Save = new_instancemethod(_snap.TChA_Save,None,TChA)
TChA.SaveXml = new_instancemethod(_snap.TChA_SaveXml,None,TChA)
TChA.__eq__ = new_instancemethod(_snap.TChA___eq__,None,TChA)
TChA.__ne__ = new_instancemethod(_snap.TChA___ne__,None,TChA)
TChA.__lt__ = new_instancemethod(_snap.TChA___lt__,None,TChA)
TChA.__iadd__ = new_instancemethod(_snap.TChA___iadd__,None,TChA)
TChA.GetMemUsed = new_instancemethod(_snap.TChA_GetMemUsed,None,TChA)
TChA.__call__ = new_instancemethod(_snap.TChA___call__,None,TChA)
TChA.CStr = new_instancemethod(_snap.TChA_CStr,None,TChA)
TChA.Clr = new_instancemethod(_snap.TChA_Clr,None,TChA)
TChA.Len = new_instancemethod(_snap.TChA_Len,None,TChA)
TChA.Empty = new_instancemethod(_snap.TChA_Empty,None,TChA)
TChA.Ins = new_instancemethod(_snap.TChA_Ins,None,TChA)
TChA.Del = new_instancemethod(_snap.TChA_Del,None,TChA)
TChA.DelLastCh = new_instancemethod(_snap.TChA_DelLastCh,None,TChA)
TChA.Push = new_instancemethod(_snap.TChA_Push,None,TChA)
TChA.Pop = new_instancemethod(_snap.TChA_Pop,None,TChA)
TChA.Trunc = new_instancemethod(_snap.TChA_Trunc,None,TChA)
TChA.Reverse = new_instancemethod(_snap.TChA_Reverse,None,TChA)
TChA.AddCh = new_instancemethod(_snap.TChA_AddCh,None,TChA)
TChA.AddChTo = new_instancemethod(_snap.TChA_AddChTo,None,TChA)
TChA.AddBf = new_instancemethod(_snap.TChA_AddBf,None,TChA)
TChA.PutCh = new_instancemethod(_snap.TChA_PutCh,None,TChA)
TChA.GetCh = new_instancemethod(_snap.TChA_GetCh,None,TChA)
TChA.LastCh = new_instancemethod(_snap.TChA_LastCh,None,TChA)
TChA.LastLastCh = new_instancemethod(_snap.TChA_LastLastCh,None,TChA)
TChA.GetSubStr = new_instancemethod(_snap.TChA_GetSubStr,None,TChA)
TChA.CountCh = new_instancemethod(_snap.TChA_CountCh,None,TChA)
TChA.SearchCh = new_instancemethod(_snap.TChA_SearchCh,None,TChA)
TChA.SearchChBack = new_instancemethod(_snap.TChA_SearchChBack,None,TChA)
TChA.SearchStr = new_instancemethod(_snap.TChA_SearchStr,None,TChA)
TChA.IsStrIn = new_instancemethod(_snap.TChA_IsStrIn,None,TChA)
TChA.IsPrefix = new_instancemethod(_snap.TChA_IsPrefix,None,TChA)
TChA.IsSuffix = new_instancemethod(_snap.TChA_IsSuffix,None,TChA)
TChA.IsChIn = new_instancemethod(_snap.TChA_IsChIn,None,TChA)
TChA.ChangeCh = new_instancemethod(_snap.TChA_ChangeCh,None,TChA)
TChA.ToUc = new_instancemethod(_snap.TChA_ToUc,None,TChA)
TChA.ToLc = new_instancemethod(_snap.TChA_ToLc,None,TChA)
TChA.ToTrunc = new_instancemethod(_snap.TChA_ToTrunc,None,TChA)
TChA.CompressWs = new_instancemethod(_snap.TChA_CompressWs,None,TChA)
TChA.Swap = new_instancemethod(_snap.TChA_Swap,None,TChA)
TChA.GetPrimHashCd = new_instancemethod(_snap.TChA_GetPrimHashCd,None,TChA)
TChA.GetSecHashCd = new_instancemethod(_snap.TChA_GetSecHashCd,None,TChA)
TChA.SaveTxt = new_instancemethod(_snap.TChA_SaveTxt,None,TChA)
TChA_swigregister = _snap.TChA_swigregister
TChA_swigregister(TChA)
def TChA_LoadTxt(*args):
"""
TChA_LoadTxt(PSIn const & SIn, TChA ChA)
Parameters:
SIn: PSIn const &
ChA: TChA &
"""
return _snap.TChA_LoadTxt(*args)
class TChAIn(TSIn):
"""Proxy of C++ TChAIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TChAIn self, TChA ChA, int const & _BfC=0) -> TChAIn
Parameters:
ChA: TChA const &
_BfC: int const &
__init__(TChAIn self, TChA ChA) -> TChAIn
Parameters:
ChA: TChA const &
"""
_snap.TChAIn_swiginit(self,_snap.new_TChAIn(*args))
def New(*args):
"""
New(TChA ChA) -> PSIn
Parameters:
ChA: TChA const &
"""
return _snap.TChAIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TChAIn
TChAIn_swigregister = _snap.TChAIn_swigregister
TChAIn_swigregister(TChAIn)
def TChAIn_New(*args):
"""
TChAIn_New(TChA ChA) -> PSIn
Parameters:
ChA: TChA const &
"""
return _snap.TChAIn_New(*args)
class TRStr(object):
"""Proxy of C++ TRStr class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Bf = _swig_property(_snap.TRStr_Bf_get, _snap.TRStr_Bf_set)
Refs = _swig_property(_snap.TRStr_Refs_get, _snap.TRStr_Refs_set)
__swig_destroy__ = _snap.delete_TRStr
def __init__(self, *args):
"""
__init__(TRStr self) -> TRStr
__init__(TRStr self, int const & Len) -> TRStr
Parameters:
Len: int const &
__init__(TRStr self, char const * CStr) -> TRStr
Parameters:
CStr: char const *
__init__(TRStr self, char const * CStr, int const & MxLen) -> TRStr
Parameters:
CStr: char const *
MxLen: int const &
__init__(TRStr self, char const * CStr1, char const * CStr2) -> TRStr
Parameters:
CStr1: char const *
CStr2: char const *
__init__(TRStr self, char const & Ch) -> TRStr
Parameters:
Ch: char const &
__init__(TRStr self, char const & Ch1, char const & Ch2) -> TRStr
Parameters:
Ch1: char const &
Ch2: char const &
__init__(TRStr self, TSIn SIn, bool const & IsSmall) -> TRStr
Parameters:
SIn: TSIn &
IsSmall: bool const &
"""
_snap.TRStr_swiginit(self,_snap.new_TRStr(*args))
def Save(self, *args):
"""
Save(TRStr self, TSOut SOut, bool const & IsSmall)
Parameters:
SOut: TSOut &
IsSmall: bool const &
"""
return _snap.TRStr_Save(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TRStr self) -> int
Parameters:
self: TRStr const *
"""
return _snap.TRStr_GetMemUsed(self)
def MkRef(self):
"""
MkRef(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_MkRef(self)
def UnRef(self):
"""
UnRef(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_UnRef(self)
def CStr(self, *args):
"""
CStr(TRStr self) -> char const
CStr(TRStr self) -> char *
Parameters:
self: TRStr *
"""
return _snap.TRStr_CStr(self, *args)
def Empty(self):
"""
Empty(TRStr self) -> bool
Parameters:
self: TRStr const *
"""
return _snap.TRStr_Empty(self)
def Len(self):
"""
Len(TRStr self) -> int
Parameters:
self: TRStr const *
"""
return _snap.TRStr_Len(self)
def PutCh(self, *args):
"""
PutCh(TRStr self, int const & ChN, char const & Ch)
Parameters:
ChN: int const &
Ch: char const &
"""
return _snap.TRStr_PutCh(self, *args)
def GetCh(self, *args):
"""
GetCh(TRStr self, int const & ChN) -> char
Parameters:
ChN: int const &
"""
return _snap.TRStr_GetCh(self, *args)
def IsUc(self):
"""
IsUc(TRStr self) -> bool
Parameters:
self: TRStr const *
"""
return _snap.TRStr_IsUc(self)
def ToUc(self):
"""
ToUc(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_ToUc(self)
def IsLc(self):
"""
IsLc(TRStr self) -> bool
Parameters:
self: TRStr const *
"""
return _snap.TRStr_IsLc(self)
def ToLc(self):
"""
ToLc(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_ToLc(self)
def ToCap(self):
"""
ToCap(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_ToCap(self)
def ConvUsFromYuAscii(self):
"""
ConvUsFromYuAscii(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_ConvUsFromYuAscii(self)
def CmpI(*args):
"""
CmpI(char const * CStr1, char const * CStr2) -> int
Parameters:
CStr1: char const *
CStr2: char const *
"""
return _snap.TRStr_CmpI(*args)
CmpI = staticmethod(CmpI)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TRStr self) -> int
Parameters:
self: TRStr const *
"""
return _snap.TRStr_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TRStr self) -> int
Parameters:
self: TRStr const *
"""
return _snap.TRStr_GetSecHashCd(self)
def GetNullRStr():
"""GetNullRStr() -> TRStr"""
return _snap.TRStr_GetNullRStr()
GetNullRStr = staticmethod(GetNullRStr)
TRStr.Save = new_instancemethod(_snap.TRStr_Save,None,TRStr)
TRStr.GetMemUsed = new_instancemethod(_snap.TRStr_GetMemUsed,None,TRStr)
TRStr.MkRef = new_instancemethod(_snap.TRStr_MkRef,None,TRStr)
TRStr.UnRef = new_instancemethod(_snap.TRStr_UnRef,None,TRStr)
TRStr.CStr = new_instancemethod(_snap.TRStr_CStr,None,TRStr)
TRStr.Empty = new_instancemethod(_snap.TRStr_Empty,None,TRStr)
TRStr.Len = new_instancemethod(_snap.TRStr_Len,None,TRStr)
TRStr.PutCh = new_instancemethod(_snap.TRStr_PutCh,None,TRStr)
TRStr.GetCh = new_instancemethod(_snap.TRStr_GetCh,None,TRStr)
TRStr.IsUc = new_instancemethod(_snap.TRStr_IsUc,None,TRStr)
TRStr.ToUc = new_instancemethod(_snap.TRStr_ToUc,None,TRStr)
TRStr.IsLc = new_instancemethod(_snap.TRStr_IsLc,None,TRStr)
TRStr.ToLc = new_instancemethod(_snap.TRStr_ToLc,None,TRStr)
TRStr.ToCap = new_instancemethod(_snap.TRStr_ToCap,None,TRStr)
TRStr.ConvUsFromYuAscii = new_instancemethod(_snap.TRStr_ConvUsFromYuAscii,None,TRStr)
TRStr.GetPrimHashCd = new_instancemethod(_snap.TRStr_GetPrimHashCd,None,TRStr)
TRStr.GetSecHashCd = new_instancemethod(_snap.TRStr_GetSecHashCd,None,TRStr)
TRStr_swigregister = _snap.TRStr_swigregister
TRStr_swigregister(TRStr)
def TRStr_CmpI(*args):
"""
TRStr_CmpI(char const * CStr1, char const * CStr2) -> int
Parameters:
CStr1: char const *
CStr2: char const *
"""
return _snap.TRStr_CmpI(*args)
def TRStr_GetNullRStr():
"""TRStr_GetNullRStr() -> TRStr"""
return _snap.TRStr_GetNullRStr()
class TStr(object):
"""Proxy of C++ TStr class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TStr
def __init__(self, *args):
"""
__init__(TStr self) -> TStr
__init__(TStr self, TStr Str) -> TStr
Parameters:
Str: TStr const &
__init__(TStr self, TChA ChA) -> TStr
Parameters:
ChA: TChA const &
__init__(TStr self, TSStr SStr) -> TStr
Parameters:
SStr: TSStr const &
__init__(TStr self, char const * CStr) -> TStr
Parameters:
CStr: char const *
__init__(TStr self, char const & Ch) -> TStr
Parameters:
Ch: char const &
__init__(TStr self, TMem Mem) -> TStr
Parameters:
Mem: TMem const &
__init__(TStr self, PSIn const & SIn) -> TStr
Parameters:
SIn: PSIn const &
__init__(TStr self, TSIn SIn, bool const & IsSmall=False) -> TStr
Parameters:
SIn: TSIn &
IsSmall: bool const &
__init__(TStr self, TSIn SIn) -> TStr
Parameters:
SIn: TSIn &
"""
_snap.TStr_swiginit(self,_snap.new_TStr(*args))
def Load(self, *args):
"""
Load(TStr self, TSIn SIn, bool const & IsSmall=False)
Parameters:
SIn: TSIn &
IsSmall: bool const &
Load(TStr self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TStr_Load(self, *args)
def Save(self, *args):
"""
Save(TStr self, TSOut SOut, bool const & IsSmall=False)
Parameters:
SOut: TSOut &
IsSmall: bool const &
Save(TStr self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TStr_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TStr self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TStr_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TStr self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TStr_SaveXml(self, *args)
def __iadd__(self, *args):
"""
__iadd__(TStr self, TStr Str) -> TStr
Parameters:
Str: TStr const &
__iadd__(TStr self, char const * CStr) -> TStr
Parameters:
CStr: char const *
"""
return _snap.TStr___iadd__(self, *args)
def __eq__(self, *args):
"""
__eq__(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
__eq__(TStr self, char const * CStr) -> bool
Parameters:
CStr: char const *
"""
return _snap.TStr___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TStr self, char const * CStr) -> bool
Parameters:
CStr: char const *
"""
return _snap.TStr___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TStr self) -> int
Parameters:
self: TStr const *
"""
return _snap.TStr_GetMemUsed(self)
def CStr(self, *args):
"""
CStr(TStr self) -> char
CStr(TStr self) -> char const *
Parameters:
self: TStr const *
"""
return _snap.TStr_CStr(self, *args)
def PutCh(self, *args):
"""
PutCh(TStr self, int const & ChN, char const & Ch)
Parameters:
ChN: int const &
Ch: char const &
"""
return _snap.TStr_PutCh(self, *args)
def GetCh(self, *args):
"""
GetCh(TStr self, int const & ChN) -> char
Parameters:
ChN: int const &
"""
return _snap.TStr_GetCh(self, *args)
def LastCh(self):
"""
LastCh(TStr self) -> char
Parameters:
self: TStr const *
"""
return _snap.TStr_LastCh(self)
def Clr(self):
"""
Clr(TStr self)
Parameters:
self: TStr *
"""
return _snap.TStr_Clr(self)
def Len(self):
"""
Len(TStr self) -> int
Parameters:
self: TStr const *
"""
return _snap.TStr_Len(self)
def Empty(self):
"""
Empty(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_Empty(self)
def IsUc(self):
"""
IsUc(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsUc(self)
def ToUc(self):
"""
ToUc(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToUc(self)
def GetUc(self):
"""
GetUc(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetUc(self)
def CmpI(self, *args):
"""
CmpI(TStr self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TStr_CmpI(self, *args)
def EqI(self, *args):
"""
EqI(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_EqI(self, *args)
def IsLc(self):
"""
IsLc(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsLc(self)
def ToLc(self):
"""
ToLc(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToLc(self)
def GetLc(self):
"""
GetLc(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetLc(self)
def ToCap(self):
"""
ToCap(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToCap(self)
def GetCap(self):
"""
GetCap(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetCap(self)
def ToTrunc(self):
"""
ToTrunc(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToTrunc(self)
def GetTrunc(self):
"""
GetTrunc(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetTrunc(self)
def ConvUsFromYuAscii(self):
"""
ConvUsFromYuAscii(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ConvUsFromYuAscii(self)
def GetUsFromYuAscii(self):
"""
GetUsFromYuAscii(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetUsFromYuAscii(self)
def ToHex(self):
"""
ToHex(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToHex(self)
def GetHex(self):
"""
GetHex(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetHex(self)
def FromHex(self):
"""
FromHex(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_FromHex(self)
def GetFromHex(self):
"""
GetFromHex(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFromHex(self)
def GetSubStr(self, *args):
"""
GetSubStr(TStr self, int const & BChN, int const & EChN) -> TStr
Parameters:
BChN: int const &
EChN: int const &
GetSubStr(TStr self, int const & BChN) -> TStr
Parameters:
BChN: int const &
"""
return _snap.TStr_GetSubStr(self, *args)
def InsStr(self, *args):
"""
InsStr(TStr self, int const & BChN, TStr Str)
Parameters:
BChN: int const &
Str: TStr const &
"""
return _snap.TStr_InsStr(self, *args)
def DelChAll(self, *args):
"""
DelChAll(TStr self, char const & Ch)
Parameters:
Ch: char const &
"""
return _snap.TStr_DelChAll(self, *args)
def DelSubStr(self, *args):
"""
DelSubStr(TStr self, int const & BChN, int const & EChN)
Parameters:
BChN: int const &
EChN: int const &
"""
return _snap.TStr_DelSubStr(self, *args)
def DelStr(self, *args):
"""
DelStr(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_DelStr(self, *args)
def LeftOf(self, *args):
"""
LeftOf(TStr self, char const & SplitCh) -> TStr
Parameters:
SplitCh: char const &
"""
return _snap.TStr_LeftOf(self, *args)
def LeftOfLast(self, *args):
"""
LeftOfLast(TStr self, char const & SplitCh) -> TStr
Parameters:
SplitCh: char const &
"""
return _snap.TStr_LeftOfLast(self, *args)
def RightOf(self, *args):
"""
RightOf(TStr self, char const & SplitCh) -> TStr
Parameters:
SplitCh: char const &
"""
return _snap.TStr_RightOf(self, *args)
def RightOfLast(self, *args):
"""
RightOfLast(TStr self, char const & SplitCh) -> TStr
Parameters:
SplitCh: char const &
"""
return _snap.TStr_RightOfLast(self, *args)
def SplitOnCh(self, *args):
"""
SplitOnCh(TStr self, TStr LStr, char const & SplitCh, TStr RStr)
Parameters:
LStr: TStr &
SplitCh: char const &
RStr: TStr &
"""
return _snap.TStr_SplitOnCh(self, *args)
def SplitOnLastCh(self, *args):
"""
SplitOnLastCh(TStr self, TStr LStr, char const & SplitCh, TStr RStr)
Parameters:
LStr: TStr &
SplitCh: char const &
RStr: TStr &
"""
return _snap.TStr_SplitOnLastCh(self, *args)
def SplitOnAllCh(self, *args):
"""
SplitOnAllCh(TStr self, char const & SplitCh, TStrV StrV, bool const & SkipEmpty=True)
Parameters:
SplitCh: char const &
StrV: TStrV &
SkipEmpty: bool const &
SplitOnAllCh(TStr self, char const & SplitCh, TStrV StrV)
Parameters:
SplitCh: char const &
StrV: TStrV &
"""
return _snap.TStr_SplitOnAllCh(self, *args)
def SplitOnAllAnyCh(self, *args):
"""
SplitOnAllAnyCh(TStr self, TStr SplitChStr, TStrV StrV, bool const & SkipEmpty=True)
Parameters:
SplitChStr: TStr const &
StrV: TStrV &
SkipEmpty: bool const &
SplitOnAllAnyCh(TStr self, TStr SplitChStr, TStrV StrV)
Parameters:
SplitChStr: TStr const &
StrV: TStrV &
"""
return _snap.TStr_SplitOnAllAnyCh(self, *args)
def SplitOnWs(self, *args):
"""
SplitOnWs(TStr self, TStrV StrV)
Parameters:
StrV: TStrV &
"""
return _snap.TStr_SplitOnWs(self, *args)
def SplitOnNonAlNum(self, *args):
"""
SplitOnNonAlNum(TStr self, TStrV StrV)
Parameters:
StrV: TStrV &
"""
return _snap.TStr_SplitOnNonAlNum(self, *args)
def SplitOnStr(self, *args):
"""
SplitOnStr(TStr self, TStr SplitStr, TStrV StrV)
Parameters:
SplitStr: TStr const &
StrV: TStrV &
SplitOnStr(TStr self, TStr LeftStr, TStr MidStr, TStr RightStr)
Parameters:
LeftStr: TStr &
MidStr: TStr const &
RightStr: TStr &
"""
return _snap.TStr_SplitOnStr(self, *args)
def Mid(self, *args):
"""
Mid(TStr self, int const & BChN, int const & Chs) -> TStr
Parameters:
BChN: int const &
Chs: int const &
Mid(TStr self, int const & BChN) -> TStr
Parameters:
BChN: int const &
"""
return _snap.TStr_Mid(self, *args)
def Left(self, *args):
"""
Left(TStr self, int const & EChN) -> TStr
Parameters:
EChN: int const &
"""
return _snap.TStr_Left(self, *args)
def Right(self, *args):
"""
Right(TStr self, int const & BChN) -> TStr
Parameters:
BChN: int const &
"""
return _snap.TStr_Right(self, *args)
def Slice(self, *args):
"""
Slice(TStr self, int BChN, int EChNP1) -> TStr
Parameters:
BChN: int
EChNP1: int
"""
return _snap.TStr_Slice(self, *args)
def __call__(self, *args):
"""
__call__(TStr self) -> char
__call__(TStr self) -> char const
__call__(TStr self, int const & BChN, int const & EChNP1) -> TStr
Parameters:
BChN: int const &
EChNP1: int const &
"""
return _snap.TStr___call__(self, *args)
def CountCh(self, *args):
"""
CountCh(TStr self, char const & Ch, int const & BChN=0) -> int
Parameters:
Ch: char const &
BChN: int const &
CountCh(TStr self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TStr_CountCh(self, *args)
def SearchCh(self, *args):
"""
SearchCh(TStr self, char const & Ch, int const & BChN=0) -> int
Parameters:
Ch: char const &
BChN: int const &
SearchCh(TStr self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TStr_SearchCh(self, *args)
def SearchChBack(self, *args):
"""
SearchChBack(TStr self, char const & Ch, int BChN=-1) -> int
Parameters:
Ch: char const &
BChN: int
SearchChBack(TStr self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TStr_SearchChBack(self, *args)
def SearchStr(self, *args):
"""
SearchStr(TStr self, TStr Str, int const & BChN=0) -> int
Parameters:
Str: TStr const &
BChN: int const &
SearchStr(TStr self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TStr_SearchStr(self, *args)
def IsChIn(self, *args):
"""
IsChIn(TStr self, char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TStr_IsChIn(self, *args)
def IsStrIn(self, *args):
"""
IsStrIn(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_IsStrIn(self, *args)
def IsPrefix(self, *args):
"""
IsPrefix(TStr self, char const * Str) -> bool
Parameters:
Str: char const *
IsPrefix(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_IsPrefix(self, *args)
def IsSuffix(self, *args):
"""
IsSuffix(TStr self, char const * Str) -> bool
Parameters:
Str: char const *
IsSuffix(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_IsSuffix(self, *args)
def ChangeCh(self, *args):
"""
ChangeCh(TStr self, char const & SrcCh, char const & DstCh, int const & BChN=0) -> int
Parameters:
SrcCh: char const &
DstCh: char const &
BChN: int const &
ChangeCh(TStr self, char const & SrcCh, char const & DstCh) -> int
Parameters:
SrcCh: char const &
DstCh: char const &
"""
return _snap.TStr_ChangeCh(self, *args)
def ChangeChAll(self, *args):
"""
ChangeChAll(TStr self, char const & SrcCh, char const & DstCh) -> int
Parameters:
SrcCh: char const &
DstCh: char const &
"""
return _snap.TStr_ChangeChAll(self, *args)
def ChangeStr(self, *args):
"""
ChangeStr(TStr self, TStr SrcStr, TStr DstStr, int const & BChN=0) -> int
Parameters:
SrcStr: TStr const &
DstStr: TStr const &
BChN: int const &
ChangeStr(TStr self, TStr SrcStr, TStr DstStr) -> int
Parameters:
SrcStr: TStr const &
DstStr: TStr const &
"""
return _snap.TStr_ChangeStr(self, *args)
def ChangeStrAll(self, *args):
"""
ChangeStrAll(TStr self, TStr SrcStr, TStr DstStr, bool const & FromStartP=False) -> int
Parameters:
SrcStr: TStr const &
DstStr: TStr const &
FromStartP: bool const &
ChangeStrAll(TStr self, TStr SrcStr, TStr DstStr) -> int
Parameters:
SrcStr: TStr const &
DstStr: TStr const &
"""
return _snap.TStr_ChangeStrAll(self, *args)
def Reverse(self):
"""
Reverse(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_Reverse(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TStr self) -> int
Parameters:
self: TStr const *
"""
return _snap.TStr_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TStr self) -> int
Parameters:
self: TStr const *
"""
return _snap.TStr_GetSecHashCd(self)
def IsBool(self, *args):
"""
IsBool(TStr self, bool & Val) -> bool
Parameters:
Val: bool &
"""
return _snap.TStr_IsBool(self, *args)
def IsInt(self, *args):
"""
IsInt(TStr self, bool const & Check, int const & MnVal, int const & MxVal, int & Val) -> bool
Parameters:
Check: bool const &
MnVal: int const &
MxVal: int const &
Val: int &
IsInt(TStr self, int & Val) -> bool
Parameters:
Val: int &
IsInt(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsInt(self, *args)
def GetInt(self, *args):
"""
GetInt(TStr self) -> int
GetInt(TStr self, int const & DfVal) -> int
Parameters:
DfVal: int const &
"""
return _snap.TStr_GetInt(self, *args)
def IsUInt(self, *args):
"""
IsUInt(TStr self, bool const & Check, uint const & MnVal, uint const & MxVal, uint & Val) -> bool
Parameters:
Check: bool const &
MnVal: uint const &
MxVal: uint const &
Val: uint &
IsUInt(TStr self, uint & Val) -> bool
Parameters:
Val: uint &
IsUInt(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsUInt(self, *args)
def GetUInt(self, *args):
"""
GetUInt(TStr self) -> uint
GetUInt(TStr self, uint const & DfVal) -> uint
Parameters:
DfVal: uint const &
"""
return _snap.TStr_GetUInt(self, *args)
def IsInt64(self, *args):
"""
IsInt64(TStr self, bool const & Check, int64 const & MnVal, int64 const & MxVal, int64 & Val) -> bool
Parameters:
Check: bool const &
MnVal: int64 const &
MxVal: int64 const &
Val: int64 &
IsInt64(TStr self, int64 & Val) -> bool
Parameters:
Val: int64 &
IsInt64(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsInt64(self, *args)
def GetInt64(self, *args):
"""
GetInt64(TStr self) -> int64
GetInt64(TStr self, int64 const & DfVal) -> int64
Parameters:
DfVal: int64 const &
"""
return _snap.TStr_GetInt64(self, *args)
def IsUInt64(self, *args):
"""
IsUInt64(TStr self, bool const & Check, uint64 const & MnVal, uint64 const & MxVal, uint64 & Val) -> bool
Parameters:
Check: bool const &
MnVal: uint64 const &
MxVal: uint64 const &
Val: uint64 &
IsUInt64(TStr self, uint64 & Val) -> bool
Parameters:
Val: uint64 &
IsUInt64(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsUInt64(self, *args)
def GetUInt64(self, *args):
"""
GetUInt64(TStr self) -> uint64
GetUInt64(TStr self, uint64 const & DfVal) -> uint64
Parameters:
DfVal: uint64 const &
"""
return _snap.TStr_GetUInt64(self, *args)
def IsHexInt(self, *args):
"""
IsHexInt(TStr self, bool const & Check, int const & MnVal, int const & MxVal, int & Val) -> bool
Parameters:
Check: bool const &
MnVal: int const &
MxVal: int const &
Val: int &
IsHexInt(TStr self, int & Val) -> bool
Parameters:
Val: int &
IsHexInt(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsHexInt(self, *args)
def GetHexInt(self, *args):
"""
GetHexInt(TStr self) -> int
GetHexInt(TStr self, int const & DfVal) -> int
Parameters:
DfVal: int const &
"""
return _snap.TStr_GetHexInt(self, *args)
def IsHexInt64(self, *args):
"""
IsHexInt64(TStr self, bool const & Check, int64 const & MnVal, int64 const & MxVal, int64 & Val) -> bool
Parameters:
Check: bool const &
MnVal: int64 const &
MxVal: int64 const &
Val: int64 &
IsHexInt64(TStr self, int64 & Val) -> bool
Parameters:
Val: int64 &
IsHexInt64(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsHexInt64(self, *args)
def GetHexInt64(self, *args):
"""
GetHexInt64(TStr self) -> int64
GetHexInt64(TStr self, int64 const & DfVal) -> int64
Parameters:
DfVal: int64 const &
"""
return _snap.TStr_GetHexInt64(self, *args)
def IsFlt(self, *args):
"""
IsFlt(TStr self, bool const & Check, double const & MnVal, double const & MxVal, double & Val, char const & DecDelimCh='.') -> bool
Parameters:
Check: bool const &
MnVal: double const &
MxVal: double const &
Val: double &
DecDelimCh: char const &
IsFlt(TStr self, bool const & Check, double const & MnVal, double const & MxVal, double & Val) -> bool
Parameters:
Check: bool const &
MnVal: double const &
MxVal: double const &
Val: double &
IsFlt(TStr self, double & Val) -> bool
Parameters:
Val: double &
IsFlt(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsFlt(self, *args)
def GetFlt(self, *args):
"""
GetFlt(TStr self) -> double
GetFlt(TStr self, double const & DfVal) -> double
Parameters:
DfVal: double const &
"""
return _snap.TStr_GetFlt(self, *args)
def IsWord(self, WsPrefixP=True, FirstUcAllowedP=True):
"""
IsWord(TStr self, bool const & WsPrefixP=True, bool const & FirstUcAllowedP=True) -> bool
Parameters:
WsPrefixP: bool const &
FirstUcAllowedP: bool const &
IsWord(TStr self, bool const & WsPrefixP=True) -> bool
Parameters:
WsPrefixP: bool const &
IsWord(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsWord(self, WsPrefixP, FirstUcAllowedP)
def IsWs(self):
"""
IsWs(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsWs(self)
def IsWcMatch(self, *args):
"""
IsWcMatch(TStr self, int const & StrBChN, TStr WcStr, int const & WcStrBChN, TStrV StarStrV, char const & StarCh='*',
char const & QuestCh='?') -> bool
Parameters:
StrBChN: int const &
WcStr: TStr const &
WcStrBChN: int const &
StarStrV: TStrV &
StarCh: char const &
QuestCh: char const &
IsWcMatch(TStr self, int const & StrBChN, TStr WcStr, int const & WcStrBChN, TStrV StarStrV, char const & StarCh='*') -> bool
Parameters:
StrBChN: int const &
WcStr: TStr const &
WcStrBChN: int const &
StarStrV: TStrV &
StarCh: char const &
IsWcMatch(TStr self, int const & StrBChN, TStr WcStr, int const & WcStrBChN, TStrV StarStrV) -> bool
Parameters:
StrBChN: int const &
WcStr: TStr const &
WcStrBChN: int const &
StarStrV: TStrV &
IsWcMatch(TStr self, TStr WcStr, TStrV StarStrV, char const & StarCh='*', char const & QuestCh='?') -> bool
Parameters:
WcStr: TStr const &
StarStrV: TStrV &
StarCh: char const &
QuestCh: char const &
IsWcMatch(TStr self, TStr WcStr, TStrV StarStrV, char const & StarCh='*') -> bool
Parameters:
WcStr: TStr const &
StarStrV: TStrV &
StarCh: char const &
IsWcMatch(TStr self, TStr WcStr, TStrV StarStrV) -> bool
Parameters:
WcStr: TStr const &
StarStrV: TStrV &
IsWcMatch(TStr self, TStr WcStr, char const & StarCh, char const & QuestCh) -> bool
Parameters:
WcStr: TStr const &
StarCh: char const &
QuestCh: char const &
IsWcMatch(TStr self, TStr WcStr, int const & StarStrN, TStr StarStr) -> bool
Parameters:
WcStr: TStr const &
StarStrN: int const &
StarStr: TStr &
IsWcMatch(TStr self, TStr WcStr) -> bool
Parameters:
WcStr: TStr const &
"""
return _snap.TStr_IsWcMatch(self, *args)
def GetWcMatch(self, *args):
"""
GetWcMatch(TStr self, TStr WcStr, int const & StarStrN=0) -> TStr
Parameters:
WcStr: TStr const &
StarStrN: int const &
GetWcMatch(TStr self, TStr WcStr) -> TStr
Parameters:
WcStr: TStr const &
"""
return _snap.TStr_GetWcMatch(self, *args)
def GetFPath(self):
"""
GetFPath(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFPath(self)
def GetFBase(self):
"""
GetFBase(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFBase(self)
def GetFMid(self):
"""
GetFMid(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFMid(self)
def GetFExt(self):
"""
GetFExt(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFExt(self)
def GetNrFPath(*args):
"""
GetNrFPath(TStr FPath) -> TStr
Parameters:
FPath: TStr const &
"""
return _snap.TStr_GetNrFPath(*args)
GetNrFPath = staticmethod(GetNrFPath)
def GetNrFMid(*args):
"""
GetNrFMid(TStr FMid) -> TStr
Parameters:
FMid: TStr const &
"""
return _snap.TStr_GetNrFMid(*args)
GetNrFMid = staticmethod(GetNrFMid)
def GetNrFExt(*args):
"""
GetNrFExt(TStr FExt) -> TStr
Parameters:
FExt: TStr const &
"""
return _snap.TStr_GetNrFExt(*args)
GetNrFExt = staticmethod(GetNrFExt)
def GetNrNumFExt(*args):
"""
GetNrNumFExt(int const & FExtN) -> TStr
Parameters:
FExtN: int const &
"""
return _snap.TStr_GetNrNumFExt(*args)
GetNrNumFExt = staticmethod(GetNrNumFExt)
def GetNrFNm(*args):
"""
GetNrFNm(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TStr_GetNrFNm(*args)
GetNrFNm = staticmethod(GetNrFNm)
def GetNrAbsFPath(*args):
"""
GetNrAbsFPath(TStr FPath, TStr BaseFPath=TStr()) -> TStr
Parameters:
FPath: TStr const &
BaseFPath: TStr const &
GetNrAbsFPath(TStr FPath) -> TStr
Parameters:
FPath: TStr const &
"""
return _snap.TStr_GetNrAbsFPath(*args)
GetNrAbsFPath = staticmethod(GetNrAbsFPath)
def IsAbsFPath(*args):
"""
IsAbsFPath(TStr FPath) -> bool
Parameters:
FPath: TStr const &
"""
return _snap.TStr_IsAbsFPath(*args)
IsAbsFPath = staticmethod(IsAbsFPath)
def PutFExt(*args):
"""
PutFExt(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExt(*args)
PutFExt = staticmethod(PutFExt)
def PutFExtIfEmpty(*args):
"""
PutFExtIfEmpty(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExtIfEmpty(*args)
PutFExtIfEmpty = staticmethod(PutFExtIfEmpty)
def PutFBase(*args):
"""
PutFBase(TStr FNm, TStr FBase) -> TStr
Parameters:
FNm: TStr const &
FBase: TStr const &
"""
return _snap.TStr_PutFBase(*args)
PutFBase = staticmethod(PutFBase)
def PutFBaseIfEmpty(*args):
"""
PutFBaseIfEmpty(TStr FNm, TStr FBase) -> TStr
Parameters:
FNm: TStr const &
FBase: TStr const &
"""
return _snap.TStr_PutFBaseIfEmpty(*args)
PutFBaseIfEmpty = staticmethod(PutFBaseIfEmpty)
def AddToFMid(*args):
"""
AddToFMid(TStr FNm, TStr ExtFMid) -> TStr
Parameters:
FNm: TStr const &
ExtFMid: TStr const &
"""
return _snap.TStr_AddToFMid(*args)
AddToFMid = staticmethod(AddToFMid)
def GetNumFNm(*args):
"""
GetNumFNm(TStr FNm, int const & Num) -> TStr
Parameters:
FNm: TStr const &
Num: int const &
"""
return _snap.TStr_GetNumFNm(*args)
GetNumFNm = staticmethod(GetNumFNm)
def GetFNmStr(*args):
"""
GetFNmStr(TStr Str, bool const & AlNumOnlyP=True) -> TStr
Parameters:
Str: TStr const &
AlNumOnlyP: bool const &
GetFNmStr(TStr Str) -> TStr
Parameters:
Str: TStr const &
"""
return _snap.TStr_GetFNmStr(*args)
GetFNmStr = staticmethod(GetFNmStr)
def LoadTxt(*args):
"""
LoadTxt(PSIn const & SIn) -> TStr
Parameters:
SIn: PSIn const &
LoadTxt(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TStr_LoadTxt(*args)
LoadTxt = staticmethod(LoadTxt)
def SaveTxt(self, *args):
"""
SaveTxt(TStr self, PSOut const & SOut)
Parameters:
SOut: PSOut const &
SaveTxt(TStr self, TStr FNm)
Parameters:
FNm: TStr const &
"""
return _snap.TStr_SaveTxt(self, *args)
def GetChStr(*args):
"""
GetChStr(char const & Ch) -> TStr
Parameters:
Ch: char const &
"""
return _snap.TStr_GetChStr(*args)
GetChStr = staticmethod(GetChStr)
def GetDChStr(*args):
"""
GetDChStr(char const & Ch1, char const & Ch2) -> TStr
Parameters:
Ch1: char const &
Ch2: char const &
"""
return _snap.TStr_GetDChStr(*args)
GetDChStr = staticmethod(GetDChStr)
def Fmt(*args):
"""
Fmt(char const * FmtStr) -> TStr
Parameters:
FmtStr: char const *
"""
return _snap.TStr_Fmt(*args)
Fmt = staticmethod(Fmt)
def GetSpaceStr(*args):
"""
GetSpaceStr(int const & Spaces) -> TStr
Parameters:
Spaces: int const &
"""
return _snap.TStr_GetSpaceStr(*args)
GetSpaceStr = staticmethod(GetSpaceStr)
def GetCStr(self):
"""
GetCStr(TStr self) -> char *
Parameters:
self: TStr const *
"""
return _snap.TStr_GetCStr(self)
def MkClone(*args):
"""
MkClone(TStr Str) -> TStr
Parameters:
Str: TStr const &
"""
return _snap.TStr_MkClone(*args)
MkClone = staticmethod(MkClone)
def GetNullStr():
"""GetNullStr() -> TStr"""
return _snap.TStr_GetNullStr()
GetNullStr = staticmethod(GetNullStr)
TStr.Load = new_instancemethod(_snap.TStr_Load,None,TStr)
TStr.Save = new_instancemethod(_snap.TStr_Save,None,TStr)
TStr.LoadXml = new_instancemethod(_snap.TStr_LoadXml,None,TStr)
TStr.SaveXml = new_instancemethod(_snap.TStr_SaveXml,None,TStr)
TStr.__iadd__ = new_instancemethod(_snap.TStr___iadd__,None,TStr)
TStr.__eq__ = new_instancemethod(_snap.TStr___eq__,None,TStr)
TStr.__ne__ = new_instancemethod(_snap.TStr___ne__,None,TStr)
TStr.__lt__ = new_instancemethod(_snap.TStr___lt__,None,TStr)
TStr.GetMemUsed = new_instancemethod(_snap.TStr_GetMemUsed,None,TStr)
TStr.CStr = new_instancemethod(_snap.TStr_CStr,None,TStr)
TStr.PutCh = new_instancemethod(_snap.TStr_PutCh,None,TStr)
TStr.GetCh = new_instancemethod(_snap.TStr_GetCh,None,TStr)
TStr.LastCh = new_instancemethod(_snap.TStr_LastCh,None,TStr)
TStr.Clr = new_instancemethod(_snap.TStr_Clr,None,TStr)
TStr.Len = new_instancemethod(_snap.TStr_Len,None,TStr)
TStr.Empty = new_instancemethod(_snap.TStr_Empty,None,TStr)
TStr.IsUc = new_instancemethod(_snap.TStr_IsUc,None,TStr)
TStr.ToUc = new_instancemethod(_snap.TStr_ToUc,None,TStr)
TStr.GetUc = new_instancemethod(_snap.TStr_GetUc,None,TStr)
TStr.CmpI = new_instancemethod(_snap.TStr_CmpI,None,TStr)
TStr.EqI = new_instancemethod(_snap.TStr_EqI,None,TStr)
TStr.IsLc = new_instancemethod(_snap.TStr_IsLc,None,TStr)
TStr.ToLc = new_instancemethod(_snap.TStr_ToLc,None,TStr)
TStr.GetLc = new_instancemethod(_snap.TStr_GetLc,None,TStr)
TStr.ToCap = new_instancemethod(_snap.TStr_ToCap,None,TStr)
TStr.GetCap = new_instancemethod(_snap.TStr_GetCap,None,TStr)
TStr.ToTrunc = new_instancemethod(_snap.TStr_ToTrunc,None,TStr)
TStr.GetTrunc = new_instancemethod(_snap.TStr_GetTrunc,None,TStr)
TStr.ConvUsFromYuAscii = new_instancemethod(_snap.TStr_ConvUsFromYuAscii,None,TStr)
TStr.GetUsFromYuAscii = new_instancemethod(_snap.TStr_GetUsFromYuAscii,None,TStr)
TStr.ToHex = new_instancemethod(_snap.TStr_ToHex,None,TStr)
TStr.GetHex = new_instancemethod(_snap.TStr_GetHex,None,TStr)
TStr.FromHex = new_instancemethod(_snap.TStr_FromHex,None,TStr)
TStr.GetFromHex = new_instancemethod(_snap.TStr_GetFromHex,None,TStr)
TStr.GetSubStr = new_instancemethod(_snap.TStr_GetSubStr,None,TStr)
TStr.InsStr = new_instancemethod(_snap.TStr_InsStr,None,TStr)
TStr.DelChAll = new_instancemethod(_snap.TStr_DelChAll,None,TStr)
TStr.DelSubStr = new_instancemethod(_snap.TStr_DelSubStr,None,TStr)
TStr.DelStr = new_instancemethod(_snap.TStr_DelStr,None,TStr)
TStr.LeftOf = new_instancemethod(_snap.TStr_LeftOf,None,TStr)
TStr.LeftOfLast = new_instancemethod(_snap.TStr_LeftOfLast,None,TStr)
TStr.RightOf = new_instancemethod(_snap.TStr_RightOf,None,TStr)
TStr.RightOfLast = new_instancemethod(_snap.TStr_RightOfLast,None,TStr)
TStr.SplitOnCh = new_instancemethod(_snap.TStr_SplitOnCh,None,TStr)
TStr.SplitOnLastCh = new_instancemethod(_snap.TStr_SplitOnLastCh,None,TStr)
TStr.SplitOnAllCh = new_instancemethod(_snap.TStr_SplitOnAllCh,None,TStr)
TStr.SplitOnAllAnyCh = new_instancemethod(_snap.TStr_SplitOnAllAnyCh,None,TStr)
TStr.SplitOnWs = new_instancemethod(_snap.TStr_SplitOnWs,None,TStr)
TStr.SplitOnNonAlNum = new_instancemethod(_snap.TStr_SplitOnNonAlNum,None,TStr)
TStr.SplitOnStr = new_instancemethod(_snap.TStr_SplitOnStr,None,TStr)
TStr.Mid = new_instancemethod(_snap.TStr_Mid,None,TStr)
TStr.Left = new_instancemethod(_snap.TStr_Left,None,TStr)
TStr.Right = new_instancemethod(_snap.TStr_Right,None,TStr)
TStr.Slice = new_instancemethod(_snap.TStr_Slice,None,TStr)
TStr.__call__ = new_instancemethod(_snap.TStr___call__,None,TStr)
TStr.CountCh = new_instancemethod(_snap.TStr_CountCh,None,TStr)
TStr.SearchCh = new_instancemethod(_snap.TStr_SearchCh,None,TStr)
TStr.SearchChBack = new_instancemethod(_snap.TStr_SearchChBack,None,TStr)
TStr.SearchStr = new_instancemethod(_snap.TStr_SearchStr,None,TStr)
TStr.IsChIn = new_instancemethod(_snap.TStr_IsChIn,None,TStr)
TStr.IsStrIn = new_instancemethod(_snap.TStr_IsStrIn,None,TStr)
TStr.IsPrefix = new_instancemethod(_snap.TStr_IsPrefix,None,TStr)
TStr.IsSuffix = new_instancemethod(_snap.TStr_IsSuffix,None,TStr)
TStr.ChangeCh = new_instancemethod(_snap.TStr_ChangeCh,None,TStr)
TStr.ChangeChAll = new_instancemethod(_snap.TStr_ChangeChAll,None,TStr)
TStr.ChangeStr = new_instancemethod(_snap.TStr_ChangeStr,None,TStr)
TStr.ChangeStrAll = new_instancemethod(_snap.TStr_ChangeStrAll,None,TStr)
TStr.Reverse = new_instancemethod(_snap.TStr_Reverse,None,TStr)
TStr.GetPrimHashCd = new_instancemethod(_snap.TStr_GetPrimHashCd,None,TStr)
TStr.GetSecHashCd = new_instancemethod(_snap.TStr_GetSecHashCd,None,TStr)
TStr.IsBool = new_instancemethod(_snap.TStr_IsBool,None,TStr)
TStr.IsInt = new_instancemethod(_snap.TStr_IsInt,None,TStr)
TStr.GetInt = new_instancemethod(_snap.TStr_GetInt,None,TStr)
TStr.IsUInt = new_instancemethod(_snap.TStr_IsUInt,None,TStr)
TStr.GetUInt = new_instancemethod(_snap.TStr_GetUInt,None,TStr)
TStr.IsInt64 = new_instancemethod(_snap.TStr_IsInt64,None,TStr)
TStr.GetInt64 = new_instancemethod(_snap.TStr_GetInt64,None,TStr)
TStr.IsUInt64 = new_instancemethod(_snap.TStr_IsUInt64,None,TStr)
TStr.GetUInt64 = new_instancemethod(_snap.TStr_GetUInt64,None,TStr)
TStr.IsHexInt = new_instancemethod(_snap.TStr_IsHexInt,None,TStr)
TStr.GetHexInt = new_instancemethod(_snap.TStr_GetHexInt,None,TStr)
TStr.IsHexInt64 = new_instancemethod(_snap.TStr_IsHexInt64,None,TStr)
TStr.GetHexInt64 = new_instancemethod(_snap.TStr_GetHexInt64,None,TStr)
TStr.IsFlt = new_instancemethod(_snap.TStr_IsFlt,None,TStr)
TStr.GetFlt = new_instancemethod(_snap.TStr_GetFlt,None,TStr)
TStr.IsWord = new_instancemethod(_snap.TStr_IsWord,None,TStr)
TStr.IsWs = new_instancemethod(_snap.TStr_IsWs,None,TStr)
TStr.IsWcMatch = new_instancemethod(_snap.TStr_IsWcMatch,None,TStr)
TStr.GetWcMatch = new_instancemethod(_snap.TStr_GetWcMatch,None,TStr)
TStr.GetFPath = new_instancemethod(_snap.TStr_GetFPath,None,TStr)
TStr.GetFBase = new_instancemethod(_snap.TStr_GetFBase,None,TStr)
TStr.GetFMid = new_instancemethod(_snap.TStr_GetFMid,None,TStr)
TStr.GetFExt = new_instancemethod(_snap.TStr_GetFExt,None,TStr)
TStr.SaveTxt = new_instancemethod(_snap.TStr_SaveTxt,None,TStr)
TStr.GetCStr = new_instancemethod(_snap.TStr_GetCStr,None,TStr)
TStr_swigregister = _snap.TStr_swigregister
TStr_swigregister(TStr)
def TStr_GetNrFPath(*args):
"""
TStr_GetNrFPath(TStr FPath) -> TStr
Parameters:
FPath: TStr const &
"""
return _snap.TStr_GetNrFPath(*args)
def TStr_GetNrFMid(*args):
"""
TStr_GetNrFMid(TStr FMid) -> TStr
Parameters:
FMid: TStr const &
"""
return _snap.TStr_GetNrFMid(*args)
def TStr_GetNrFExt(*args):
"""
TStr_GetNrFExt(TStr FExt) -> TStr
Parameters:
FExt: TStr const &
"""
return _snap.TStr_GetNrFExt(*args)
def TStr_GetNrNumFExt(*args):
"""
TStr_GetNrNumFExt(int const & FExtN) -> TStr
Parameters:
FExtN: int const &
"""
return _snap.TStr_GetNrNumFExt(*args)
def TStr_GetNrFNm(*args):
"""
TStr_GetNrFNm(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TStr_GetNrFNm(*args)
def TStr_GetNrAbsFPath(*args):
"""
GetNrAbsFPath(TStr FPath, TStr BaseFPath=TStr()) -> TStr
Parameters:
FPath: TStr const &
BaseFPath: TStr const &
TStr_GetNrAbsFPath(TStr FPath) -> TStr
Parameters:
FPath: TStr const &
"""
return _snap.TStr_GetNrAbsFPath(*args)
def TStr_IsAbsFPath(*args):
"""
TStr_IsAbsFPath(TStr FPath) -> bool
Parameters:
FPath: TStr const &
"""
return _snap.TStr_IsAbsFPath(*args)
def TStr_PutFExt(*args):
"""
TStr_PutFExt(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExt(*args)
def TStr_PutFExtIfEmpty(*args):
"""
TStr_PutFExtIfEmpty(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExtIfEmpty(*args)
def TStr_PutFBase(*args):
"""
TStr_PutFBase(TStr FNm, TStr FBase) -> TStr
Parameters:
FNm: TStr const &
FBase: TStr const &
"""
return _snap.TStr_PutFBase(*args)
def TStr_PutFBaseIfEmpty(*args):
"""
TStr_PutFBaseIfEmpty(TStr FNm, TStr FBase) -> TStr
Parameters:
FNm: TStr const &
FBase: TStr const &
"""
return _snap.TStr_PutFBaseIfEmpty(*args)
def TStr_AddToFMid(*args):
"""
TStr_AddToFMid(TStr FNm, TStr ExtFMid) -> TStr
Parameters:
FNm: TStr const &
ExtFMid: TStr const &
"""
return _snap.TStr_AddToFMid(*args)
def TStr_GetNumFNm(*args):
"""
TStr_GetNumFNm(TStr FNm, int const & Num) -> TStr
Parameters:
FNm: TStr const &
Num: int const &
"""
return _snap.TStr_GetNumFNm(*args)
def TStr_GetFNmStr(*args):
"""
GetFNmStr(TStr Str, bool const & AlNumOnlyP=True) -> TStr
Parameters:
Str: TStr const &
AlNumOnlyP: bool const &
TStr_GetFNmStr(TStr Str) -> TStr
Parameters:
Str: TStr const &
"""
return _snap.TStr_GetFNmStr(*args)
def TStr_LoadTxt(*args):
"""
LoadTxt(PSIn const & SIn) -> TStr
Parameters:
SIn: PSIn const &
TStr_LoadTxt(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TStr_LoadTxt(*args)
def TStr_GetChStr(*args):
"""
TStr_GetChStr(char const & Ch) -> TStr
Parameters:
Ch: char const &
"""
return _snap.TStr_GetChStr(*args)
def TStr_GetDChStr(*args):
"""
TStr_GetDChStr(char const & Ch1, char const & Ch2) -> TStr
Parameters:
Ch1: char const &
Ch2: char const &
"""
return _snap.TStr_GetDChStr(*args)
def TStr_Fmt(*args):
"""
TStr_Fmt(char const * FmtStr) -> TStr
Parameters:
FmtStr: char const *
"""
return _snap.TStr_Fmt(*args)
def TStr_GetSpaceStr(*args):
"""
TStr_GetSpaceStr(int const & Spaces) -> TStr
Parameters:
Spaces: int const &
"""
return _snap.TStr_GetSpaceStr(*args)
def TStr_MkClone(*args):
"""
TStr_MkClone(TStr Str) -> TStr
Parameters:
Str: TStr const &
"""
return _snap.TStr_MkClone(*args)
def TStr_GetNullStr():
"""TStr_GetNullStr() -> TStr"""
return _snap.TStr_GetNullStr()
class TStrIn(TSIn):
"""Proxy of C++ TStrIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TStrIn self, TStr _Str) -> TStrIn
Parameters:
_Str: TStr const &
"""
_snap.TStrIn_swiginit(self,_snap.new_TStrIn(*args))
def New(*args):
"""
New(TStr Str) -> PSIn
Parameters:
Str: TStr const &
"""
return _snap.TStrIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TStrIn
TStrIn_swigregister = _snap.TStrIn_swigregister
TStrIn_swigregister(TStrIn)
def TStrIn_New(*args):
"""
TStrIn_New(TStr Str) -> PSIn
Parameters:
Str: TStr const &
"""
return _snap.TStrIn_New(*args)
class TDbStr(object):
"""Proxy of C++ TDbStr class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Str1 = _swig_property(_snap.TDbStr_Str1_get, _snap.TDbStr_Str1_set)
Str2 = _swig_property(_snap.TDbStr_Str2_get, _snap.TDbStr_Str2_set)
def __init__(self, *args):
"""
__init__(TDbStr self) -> TDbStr
__init__(TDbStr self, TDbStr DbStr) -> TDbStr
Parameters:
DbStr: TDbStr const &
__init__(TDbStr self, TStr _Str1) -> TDbStr
Parameters:
_Str1: TStr const &
__init__(TDbStr self, TStr _Str1, TStr _Str2) -> TDbStr
Parameters:
_Str1: TStr const &
_Str2: TStr const &
__init__(TDbStr self, TSIn SIn) -> TDbStr
Parameters:
SIn: TSIn &
"""
_snap.TDbStr_swiginit(self,_snap.new_TDbStr(*args))
def Save(self, *args):
"""
Save(TDbStr self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TDbStr_Save(self, *args)
def __eq__(self, *args):
"""
__eq__(TDbStr self, TDbStr DbStr) -> bool
Parameters:
DbStr: TDbStr const &
"""
return _snap.TDbStr___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TDbStr self, TDbStr DbStr) -> bool
Parameters:
DbStr: TDbStr const &
"""
return _snap.TDbStr___lt__(self, *args)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TDbStr self) -> int
Parameters:
self: TDbStr const *
"""
return _snap.TDbStr_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TDbStr self) -> int
Parameters:
self: TDbStr const *
"""
return _snap.TDbStr_GetSecHashCd(self)
def Empty(self):
"""
Empty(TDbStr self) -> bool
Parameters:
self: TDbStr const *
"""
return _snap.TDbStr_Empty(self)
def Filled(self):
"""
Filled(TDbStr self) -> bool
Parameters:
self: TDbStr const *
"""
return _snap.TDbStr_Filled(self)
__swig_destroy__ = _snap.delete_TDbStr
TDbStr.Save = new_instancemethod(_snap.TDbStr_Save,None,TDbStr)
TDbStr.__eq__ = new_instancemethod(_snap.TDbStr___eq__,None,TDbStr)
TDbStr.__lt__ = new_instancemethod(_snap.TDbStr___lt__,None,TDbStr)
TDbStr.GetPrimHashCd = new_instancemethod(_snap.TDbStr_GetPrimHashCd,None,TDbStr)
TDbStr.GetSecHashCd = new_instancemethod(_snap.TDbStr_GetSecHashCd,None,TDbStr)
TDbStr.Empty = new_instancemethod(_snap.TDbStr_Empty,None,TDbStr)
TDbStr.Filled = new_instancemethod(_snap.TDbStr_Filled,None,TDbStr)
TDbStr_swigregister = _snap.TDbStr_swigregister
TDbStr_swigregister(TDbStr)
class TStrPool(object):
"""Proxy of C++ TStrPool class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TStrPool self, uint const & MxBfLen=0, uint const & _GrowBy=16*1024*1024) -> TStrPool
Parameters:
MxBfLen: uint const &
_GrowBy: uint const &
__init__(TStrPool self, uint const & MxBfLen=0) -> TStrPool
Parameters:
MxBfLen: uint const &
__init__(TStrPool self) -> TStrPool
__init__(TStrPool self, TSIn SIn, bool LoadCompact=True) -> TStrPool
Parameters:
SIn: TSIn &
LoadCompact: bool
__init__(TStrPool self, TSIn SIn) -> TStrPool
Parameters:
SIn: TSIn &
__init__(TStrPool self, TStrPool Pool) -> TStrPool
Parameters:
Pool: TStrPool const &
"""
_snap.TStrPool_swiginit(self,_snap.new_TStrPool(*args))
__swig_destroy__ = _snap.delete_TStrPool
def New(*args):
"""
New(uint const & _MxBfLen=0, uint const & _GrowBy=16*1024*1024) -> PStrPool
Parameters:
_MxBfLen: uint const &
_GrowBy: uint const &
New(uint const & _MxBfLen=0) -> PStrPool
Parameters:
_MxBfLen: uint const &
New() -> PStrPool
New(TSIn SIn) -> PStrPool
Parameters:
SIn: TSIn &
New(TStr fileName) -> PStrPool
Parameters:
fileName: TStr const &
"""
return _snap.TStrPool_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn, bool LoadCompacted=True) -> PStrPool
Parameters:
SIn: TSIn &
LoadCompacted: bool
Load(TSIn SIn) -> PStrPool
Parameters:
SIn: TSIn &
"""
return _snap.TStrPool_Load(*args)
Load = staticmethod(Load)
def Save(self, *args):
"""
Save(TStrPool self, TSOut SOut)
Parameters:
SOut: TSOut &
Save(TStrPool self, TStr FNm)
Parameters:
FNm: TStr const &
"""
return _snap.TStrPool_Save(self, *args)
def Len(self):
"""
Len(TStrPool self) -> uint
Parameters:
self: TStrPool const *
"""
return _snap.TStrPool_Len(self)
def Size(self):
"""
Size(TStrPool self) -> uint
Parameters:
self: TStrPool const *
"""
return _snap.TStrPool_Size(self)
def Empty(self):
"""
Empty(TStrPool self) -> bool
Parameters:
self: TStrPool const *
"""
return _snap.TStrPool_Empty(self)
def __call__(self):
"""
__call__(TStrPool self) -> char *
Parameters:
self: TStrPool const *
"""
return _snap.TStrPool___call__(self)
def AddStr(self, *args):
"""
AddStr(TStrPool self, char const * Str, uint const & Len) -> uint
Parameters:
Str: char const *
Len: uint const &
AddStr(TStrPool self, char const * Str) -> uint
Parameters:
Str: char const *
AddStr(TStrPool self, TStr Str) -> uint
Parameters:
Str: TStr const &
"""
return _snap.TStrPool_AddStr(self, *args)
def GetCStr(self, *args):
"""
GetCStr(TStrPool self, uint const & Offset) -> char const *
Parameters:
Offset: uint const &
"""
return _snap.TStrPool_GetCStr(self, *args)
def Clr(self, DoDel=False):
"""
Clr(TStrPool self, bool DoDel=False)
Parameters:
DoDel: bool
Clr(TStrPool self)
Parameters:
self: TStrPool *
"""
return _snap.TStrPool_Clr(self, DoDel)
def Cmp(self, *args):
"""
Cmp(TStrPool self, uint const & Offset, char const * Str) -> int
Parameters:
Offset: uint const &
Str: char const *
"""
return _snap.TStrPool_Cmp(self, *args)
def GetPrimHashCd(self, *args):
"""
GetPrimHashCd(TStrPool self, char const * CStr) -> int
Parameters:
CStr: char const *
GetPrimHashCd(TStrPool self, uint const & Offset) -> int
Parameters:
Offset: uint const &
"""
return _snap.TStrPool_GetPrimHashCd(self, *args)
def GetSecHashCd(self, *args):
"""
GetSecHashCd(TStrPool self, char const * CStr) -> int
Parameters:
CStr: char const *
GetSecHashCd(TStrPool self, uint const & Offset) -> int
Parameters:
Offset: uint const &
"""
return _snap.TStrPool_GetSecHashCd(self, *args)
TStrPool.Save = new_instancemethod(_snap.TStrPool_Save,None,TStrPool)
TStrPool.Len = new_instancemethod(_snap.TStrPool_Len,None,TStrPool)
TStrPool.Size = new_instancemethod(_snap.TStrPool_Size,None,TStrPool)
TStrPool.Empty = new_instancemethod(_snap.TStrPool_Empty,None,TStrPool)
TStrPool.__call__ = new_instancemethod(_snap.TStrPool___call__,None,TStrPool)
TStrPool.AddStr = new_instancemethod(_snap.TStrPool_AddStr,None,TStrPool)
TStrPool.GetCStr = new_instancemethod(_snap.TStrPool_GetCStr,None,TStrPool)
TStrPool.Clr = new_instancemethod(_snap.TStrPool_Clr,None,TStrPool)
TStrPool.Cmp = new_instancemethod(_snap.TStrPool_Cmp,None,TStrPool)
TStrPool.GetPrimHashCd = new_instancemethod(_snap.TStrPool_GetPrimHashCd,None,TStrPool)
TStrPool.GetSecHashCd = new_instancemethod(_snap.TStrPool_GetSecHashCd,None,TStrPool)
TStrPool_swigregister = _snap.TStrPool_swigregister
TStrPool_swigregister(TStrPool)
def TStrPool_New(*args):
"""
New(uint const & _MxBfLen=0, uint const & _GrowBy=16*1024*1024) -> PStrPool
Parameters:
_MxBfLen: uint const &
_GrowBy: uint const &
New(uint const & _MxBfLen=0) -> PStrPool
Parameters:
_MxBfLen: uint const &
New() -> PStrPool
New(TSIn SIn) -> PStrPool
Parameters:
SIn: TSIn &
TStrPool_New(TStr fileName) -> PStrPool
Parameters:
fileName: TStr const &
"""
return _snap.TStrPool_New(*args)
def TStrPool_Load(*args):
"""
Load(TSIn SIn, bool LoadCompacted=True) -> PStrPool
Parameters:
SIn: TSIn &
LoadCompacted: bool
TStrPool_Load(TSIn SIn) -> PStrPool
Parameters:
SIn: TSIn &
"""
return _snap.TStrPool_Load(*args)
class TStrPool64(object):
"""Proxy of C++ TStrPool64 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TStrPool64 self, ::TSize _MxBfL=0, ::TSize _GrowBy=16*1024*1024) -> TStrPool64
Parameters:
_MxBfL: ::TSize
_GrowBy: ::TSize
__init__(TStrPool64 self, ::TSize _MxBfL=0) -> TStrPool64
Parameters:
_MxBfL: ::TSize
__init__(TStrPool64 self) -> TStrPool64
__init__(TStrPool64 self, TStrPool64 StrPool) -> TStrPool64
Parameters:
StrPool: TStrPool64 const &
__init__(TStrPool64 self, TSIn SIn, bool LoadCompact=True) -> TStrPool64
Parameters:
SIn: TSIn &
LoadCompact: bool
__init__(TStrPool64 self, TSIn SIn) -> TStrPool64
Parameters:
SIn: TSIn &
"""
_snap.TStrPool64_swiginit(self,_snap.new_TStrPool64(*args))
__swig_destroy__ = _snap.delete_TStrPool64
def Save(self, *args):
"""
Save(TStrPool64 self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TStrPool64_Save(self, *args)
def New(MxBfL=0, GrowBy=16*1024*1024):
"""
New(::TSize MxBfL=0, ::TSize GrowBy=16*1024*1024) -> PStrPool64
Parameters:
MxBfL: ::TSize
GrowBy: ::TSize
New(::TSize MxBfL=0) -> PStrPool64
Parameters:
MxBfL: ::TSize
New() -> PStrPool64
"""
return _snap.TStrPool64_New(MxBfL, GrowBy)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn, bool LoadCompact=True) -> PStrPool64
Parameters:
SIn: TSIn &
LoadCompact: bool
Load(TSIn SIn) -> PStrPool64
Parameters:
SIn: TSIn &
"""
return _snap.TStrPool64_Load(*args)
Load = staticmethod(Load)
def GetMemUsed(self):
"""
GetMemUsed(TStrPool64 self) -> uint64
Parameters:
self: TStrPool64 const *
"""
return _snap.TStrPool64_GetMemUsed(self)
def Empty(self):
"""
Empty(TStrPool64 self) -> bool
Parameters:
self: TStrPool64 const *
"""
return _snap.TStrPool64_Empty(self)
def Len(self):
"""
Len(TStrPool64 self) -> uint64
Parameters:
self: TStrPool64 const *
"""
return _snap.TStrPool64_Len(self)
def Reserved(self):
"""
Reserved(TStrPool64 self) -> uint64
Parameters:
self: TStrPool64 const *
"""
return _snap.TStrPool64_Reserved(self)
def Clr(self, DoDel=False):
"""
Clr(TStrPool64 self, bool DoDel=False)
Parameters:
DoDel: bool
Clr(TStrPool64 self)
Parameters:
self: TStrPool64 *
"""
return _snap.TStrPool64_Clr(self, DoDel)
def Cmp(self, *args):
"""
Cmp(TStrPool64 self, uint64 Offset, char const * Str) -> int
Parameters:
Offset: uint64
Str: char const *
"""
return _snap.TStrPool64_Cmp(self, *args)
def AddStr(self, *args):
"""
AddStr(TStrPool64 self, TStr Str) -> uint64
Parameters:
Str: TStr const &
"""
return _snap.TStrPool64_AddStr(self, *args)
TStrPool64.Save = new_instancemethod(_snap.TStrPool64_Save,None,TStrPool64)
TStrPool64.GetMemUsed = new_instancemethod(_snap.TStrPool64_GetMemUsed,None,TStrPool64)
TStrPool64.Empty = new_instancemethod(_snap.TStrPool64_Empty,None,TStrPool64)
TStrPool64.Len = new_instancemethod(_snap.TStrPool64_Len,None,TStrPool64)
TStrPool64.Reserved = new_instancemethod(_snap.TStrPool64_Reserved,None,TStrPool64)
TStrPool64.Clr = new_instancemethod(_snap.TStrPool64_Clr,None,TStrPool64)
TStrPool64.Cmp = new_instancemethod(_snap.TStrPool64_Cmp,None,TStrPool64)
TStrPool64.AddStr = new_instancemethod(_snap.TStrPool64_AddStr,None,TStrPool64)
TStrPool64_swigregister = _snap.TStrPool64_swigregister
TStrPool64_swigregister(TStrPool64)
def TStrPool64_New(MxBfL=0, GrowBy=16*1024*1024):
"""
New(::TSize MxBfL=0, ::TSize GrowBy=16*1024*1024) -> PStrPool64
Parameters:
MxBfL: ::TSize
GrowBy: ::TSize
New(::TSize MxBfL=0) -> PStrPool64
Parameters:
MxBfL: ::TSize
TStrPool64_New() -> PStrPool64
"""
return _snap.TStrPool64_New(MxBfL, GrowBy)
def TStrPool64_Load(*args):
"""
Load(TSIn SIn, bool LoadCompact=True) -> PStrPool64
Parameters:
SIn: TSIn &
LoadCompact: bool
TStrPool64_Load(TSIn SIn) -> PStrPool64
Parameters:
SIn: TSIn &
"""
return _snap.TStrPool64_Load(*args)
class TVoid(object):
"""Proxy of C++ TVoid class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TVoid self) -> TVoid
__init__(TVoid self, TSIn arg2) -> TVoid
Parameters:
arg2: TSIn &
"""
_snap.TVoid_swiginit(self,_snap.new_TVoid(*args))
def Save(self, *args):
"""
Save(TVoid self, TSOut arg2)
Parameters:
arg2: TSOut &
"""
return _snap.TVoid_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TVoid self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TVoid_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TVoid self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TVoid_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TVoid self, TVoid arg2) -> bool
Parameters:
arg2: TVoid const &
"""
return _snap.TVoid___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TVoid self, TVoid arg2) -> bool
Parameters:
arg2: TVoid const &
"""
return _snap.TVoid___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TVoid self) -> int
Parameters:
self: TVoid const *
"""
return _snap.TVoid_GetMemUsed(self)
__swig_destroy__ = _snap.delete_TVoid
TVoid.Save = new_instancemethod(_snap.TVoid_Save,None,TVoid)
TVoid.LoadXml = new_instancemethod(_snap.TVoid_LoadXml,None,TVoid)
TVoid.SaveXml = new_instancemethod(_snap.TVoid_SaveXml,None,TVoid)
TVoid.__eq__ = new_instancemethod(_snap.TVoid___eq__,None,TVoid)
TVoid.__lt__ = new_instancemethod(_snap.TVoid___lt__,None,TVoid)
TVoid.GetMemUsed = new_instancemethod(_snap.TVoid_GetMemUsed,None,TVoid)
TVoid_swigregister = _snap.TVoid_swigregister
TVoid_swigregister(TVoid)
class TBool(object):
"""Proxy of C++ TBool class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TBool_Val_get, _snap.TBool_Val_set)
Rnd = _swig_property(_snap.TBool_Rnd_get, _snap.TBool_Rnd_set)
def __nonzero__(self):
return _snap.TBool___nonzero__(self)
__bool__ = __nonzero__
def __init__(self, *args):
"""
__init__(TBool self) -> TBool
__init__(TBool self, bool const & _Val) -> TBool
Parameters:
_Val: bool const &
__init__(TBool self, TSIn SIn) -> TBool
Parameters:
SIn: TSIn &
"""
_snap.TBool_swiginit(self,_snap.new_TBool(*args))
def Load(self, *args):
"""
Load(TBool self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TBool_Load(self, *args)
def Save(self, *args):
"""
Save(TBool self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TBool_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TBool self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TBool_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TBool self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TBool_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TBool self, TBool Bool) -> bool
Parameters:
Bool: TBool const &
"""
return _snap.TBool___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TBool self, TBool Bool) -> bool
Parameters:
Bool: TBool const &
"""
return _snap.TBool___lt__(self, *args)
def __call__(self):
"""
__call__(TBool self) -> bool
Parameters:
self: TBool const *
"""
return _snap.TBool___call__(self)
def GetMemUsed(self):
"""
GetMemUsed(TBool self) -> int
Parameters:
self: TBool const *
"""
return _snap.TBool_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TBool self) -> int
Parameters:
self: TBool const *
"""
return _snap.TBool_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TBool self) -> int
Parameters:
self: TBool const *
"""
return _snap.TBool_GetSecHashCd(self)
def GetRnd():
"""GetRnd() -> bool"""
return _snap.TBool_GetRnd()
GetRnd = staticmethod(GetRnd)
def GetYNStr(*args):
"""
GetYNStr(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_GetYNStr(*args)
GetYNStr = staticmethod(GetYNStr)
def GetYesNoStr(*args):
"""
GetYesNoStr(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_GetYesNoStr(*args)
GetYesNoStr = staticmethod(GetYesNoStr)
def Get01Str(*args):
"""
Get01Str(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_Get01Str(*args)
Get01Str = staticmethod(Get01Str)
def IsValStr(*args):
"""
IsValStr(TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TBool_IsValStr(*args)
IsValStr = staticmethod(IsValStr)
def GetValFromStr(*args):
"""
GetValFromStr(TStr Str) -> bool
Parameters:
Str: TStr const &
GetValFromStr(TStr Str, bool const & DfVal) -> bool
Parameters:
Str: TStr const &
DfVal: bool const &
"""
return _snap.TBool_GetValFromStr(*args)
GetValFromStr = staticmethod(GetValFromStr)
__swig_destroy__ = _snap.delete_TBool
TBool.Load = new_instancemethod(_snap.TBool_Load,None,TBool)
TBool.Save = new_instancemethod(_snap.TBool_Save,None,TBool)
TBool.LoadXml = new_instancemethod(_snap.TBool_LoadXml,None,TBool)
TBool.SaveXml = new_instancemethod(_snap.TBool_SaveXml,None,TBool)
TBool.__eq__ = new_instancemethod(_snap.TBool___eq__,None,TBool)
TBool.__lt__ = new_instancemethod(_snap.TBool___lt__,None,TBool)
TBool.__call__ = new_instancemethod(_snap.TBool___call__,None,TBool)
TBool.GetMemUsed = new_instancemethod(_snap.TBool_GetMemUsed,None,TBool)
TBool.GetPrimHashCd = new_instancemethod(_snap.TBool_GetPrimHashCd,None,TBool)
TBool.GetSecHashCd = new_instancemethod(_snap.TBool_GetSecHashCd,None,TBool)
TBool_swigregister = _snap.TBool_swigregister
TBool_swigregister(TBool)
TBool.Mn = _snap.cvar.TBool_Mn
TBool.Mx = _snap.cvar.TBool_Mx
TBool.Vals = _snap.cvar.TBool_Vals
TBool.FalseStr = _snap.cvar.TBool_FalseStr
TBool.TrueStr = _snap.cvar.TBool_TrueStr
TBool.NStr = _snap.cvar.TBool_NStr
TBool.YStr = _snap.cvar.TBool_YStr
TBool.NoStr = _snap.cvar.TBool_NoStr
TBool.YesStr = _snap.cvar.TBool_YesStr
def TBool_GetRnd():
"""TBool_GetRnd() -> bool"""
return _snap.TBool_GetRnd()
def TBool_GetYNStr(*args):
"""
TBool_GetYNStr(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_GetYNStr(*args)
def TBool_GetYesNoStr(*args):
"""
TBool_GetYesNoStr(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_GetYesNoStr(*args)
def TBool_Get01Str(*args):
"""
TBool_Get01Str(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_Get01Str(*args)
def TBool_IsValStr(*args):
"""
TBool_IsValStr(TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TBool_IsValStr(*args)
def TBool_GetValFromStr(*args):
"""
GetValFromStr(TStr Str) -> bool
Parameters:
Str: TStr const &
TBool_GetValFromStr(TStr Str, bool const & DfVal) -> bool
Parameters:
Str: TStr const &
DfVal: bool const &
"""
return _snap.TBool_GetValFromStr(*args)
class TCh(object):
"""Proxy of C++ TCh class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TCh_Val_get, _snap.TCh_Val_set)
def __init__(self, *args):
"""
__init__(TCh self) -> TCh
__init__(TCh self, char const & _Val) -> TCh
Parameters:
_Val: char const &
__init__(TCh self, TSIn SIn) -> TCh
Parameters:
SIn: TSIn &
"""
_snap.TCh_swiginit(self,_snap.new_TCh(*args))
def Save(self, *args):
"""
Save(TCh self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TCh_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TCh self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TCh_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TCh self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TCh_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TCh self, TCh Ch) -> bool
Parameters:
Ch: TCh const &
"""
return _snap.TCh___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TCh self, TCh Ch) -> bool
Parameters:
Ch: TCh const &
"""
return _snap.TCh___lt__(self, *args)
def __call__(self):
"""
__call__(TCh self) -> char
Parameters:
self: TCh const *
"""
return _snap.TCh___call__(self)
def GetMemUsed(self):
"""
GetMemUsed(TCh self) -> int
Parameters:
self: TCh const *
"""
return _snap.TCh_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TCh self) -> int
Parameters:
self: TCh const *
"""
return _snap.TCh_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TCh self) -> int
Parameters:
self: TCh const *
"""
return _snap.TCh_GetSecHashCd(self)
def IsWs(*args):
"""
IsWs(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsWs(*args)
IsWs = staticmethod(IsWs)
def IsAlpha(*args):
"""
IsAlpha(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsAlpha(*args)
IsAlpha = staticmethod(IsAlpha)
def IsNum(*args):
"""
IsNum(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsNum(*args)
IsNum = staticmethod(IsNum)
def IsAlNum(*args):
"""
IsAlNum(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsAlNum(*args)
IsAlNum = staticmethod(IsAlNum)
def GetNum(*args):
"""
GetNum(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetNum(*args)
GetNum = staticmethod(GetNum)
def IsHex(*args):
"""
IsHex(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsHex(*args)
IsHex = staticmethod(IsHex)
def GetHex(*args):
"""
GetHex(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetHex(*args)
GetHex = staticmethod(GetHex)
def GetHexCh(*args):
"""
GetHexCh(int const & Val) -> char
Parameters:
Val: int const &
"""
return _snap.TCh_GetHexCh(*args)
GetHexCh = staticmethod(GetHexCh)
def IsUc(*args):
"""
IsUc(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_IsUc(*args)
IsUc = staticmethod(IsUc)
def GetUc(*args):
"""
GetUc(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_GetUc(*args)
GetUc = staticmethod(GetUc)
def GetUsFromYuAscii(*args):
"""
GetUsFromYuAscii(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_GetUsFromYuAscii(*args)
GetUsFromYuAscii = staticmethod(GetUsFromYuAscii)
__swig_destroy__ = _snap.delete_TCh
TCh.Save = new_instancemethod(_snap.TCh_Save,None,TCh)
TCh.LoadXml = new_instancemethod(_snap.TCh_LoadXml,None,TCh)
TCh.SaveXml = new_instancemethod(_snap.TCh_SaveXml,None,TCh)
TCh.__eq__ = new_instancemethod(_snap.TCh___eq__,None,TCh)
TCh.__lt__ = new_instancemethod(_snap.TCh___lt__,None,TCh)
TCh.__call__ = new_instancemethod(_snap.TCh___call__,None,TCh)
TCh.GetMemUsed = new_instancemethod(_snap.TCh_GetMemUsed,None,TCh)
TCh.GetPrimHashCd = new_instancemethod(_snap.TCh_GetPrimHashCd,None,TCh)
TCh.GetSecHashCd = new_instancemethod(_snap.TCh_GetSecHashCd,None,TCh)
TCh_swigregister = _snap.TCh_swigregister
TCh_swigregister(TCh)
TCh.Mn = _snap.cvar.TCh_Mn
TCh.Mx = _snap.cvar.TCh_Mx
TCh.Vals = _snap.cvar.TCh_Vals
TCh.NullCh = _snap.cvar.TCh_NullCh
TCh.TabCh = _snap.cvar.TCh_TabCh
TCh.LfCh = _snap.cvar.TCh_LfCh
TCh.CrCh = _snap.cvar.TCh_CrCh
TCh.EofCh = _snap.cvar.TCh_EofCh
TCh.HashCh = _snap.cvar.TCh_HashCh
def TCh_IsWs(*args):
"""
TCh_IsWs(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsWs(*args)
def TCh_IsAlpha(*args):
"""
TCh_IsAlpha(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsAlpha(*args)
def TCh_IsNum(*args):
"""
TCh_IsNum(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsNum(*args)
def TCh_IsAlNum(*args):
"""
TCh_IsAlNum(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsAlNum(*args)
def TCh_GetNum(*args):
"""
TCh_GetNum(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetNum(*args)
def TCh_IsHex(*args):
"""
TCh_IsHex(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsHex(*args)
def TCh_GetHex(*args):
"""
TCh_GetHex(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetHex(*args)
def TCh_GetHexCh(*args):
"""
TCh_GetHexCh(int const & Val) -> char
Parameters:
Val: int const &
"""
return _snap.TCh_GetHexCh(*args)
def TCh_IsUc(*args):
"""
TCh_IsUc(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_IsUc(*args)
def TCh_GetUc(*args):
"""
TCh_GetUc(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_GetUc(*args)
def TCh_GetUsFromYuAscii(*args):
"""
TCh_GetUsFromYuAscii(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_GetUsFromYuAscii(*args)
class TUCh(object):
"""Proxy of C++ TUCh class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TUCh_Val_get, _snap.TUCh_Val_set)
def __init__(self, *args):
"""
__init__(TUCh self) -> TUCh
__init__(TUCh self, uchar const & _Val) -> TUCh
Parameters:
_Val: uchar const &
__init__(TUCh self, TSIn SIn) -> TUCh
Parameters:
SIn: TSIn &
"""
_snap.TUCh_swiginit(self,_snap.new_TUCh(*args))
def Save(self, *args):
"""
Save(TUCh self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TUCh_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TUCh self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TUCh_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TUCh self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TUCh_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TUCh self, TUCh UCh) -> bool
Parameters:
UCh: TUCh const &
"""
return _snap.TUCh___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TUCh self, TUCh UCh) -> bool
Parameters:
UCh: TUCh const &
"""
return _snap.TUCh___lt__(self, *args)
def __call__(self):
"""
__call__(TUCh self) -> uchar
Parameters:
self: TUCh const *
"""
return _snap.TUCh___call__(self)
def GetMemUsed(self):
"""
GetMemUsed(TUCh self) -> int
Parameters:
self: TUCh const *
"""
return _snap.TUCh_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TUCh self) -> int
Parameters:
self: TUCh const *
"""
return _snap.TUCh_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TUCh self) -> int
Parameters:
self: TUCh const *
"""
return _snap.TUCh_GetSecHashCd(self)
__swig_destroy__ = _snap.delete_TUCh
TUCh.Save = new_instancemethod(_snap.TUCh_Save,None,TUCh)
TUCh.LoadXml = new_instancemethod(_snap.TUCh_LoadXml,None,TUCh)
TUCh.SaveXml = new_instancemethod(_snap.TUCh_SaveXml,None,TUCh)
TUCh.__eq__ = new_instancemethod(_snap.TUCh___eq__,None,TUCh)
TUCh.__lt__ = new_instancemethod(_snap.TUCh___lt__,None,TUCh)
TUCh.__call__ = new_instancemethod(_snap.TUCh___call__,None,TUCh)
TUCh.GetMemUsed = new_instancemethod(_snap.TUCh_GetMemUsed,None,TUCh)
TUCh.GetPrimHashCd = new_instancemethod(_snap.TUCh_GetPrimHashCd,None,TUCh)
TUCh.GetSecHashCd = new_instancemethod(_snap.TUCh_GetSecHashCd,None,TUCh)
TUCh_swigregister = _snap.TUCh_swigregister
TUCh_swigregister(TUCh)
TUCh.Mn = _snap.cvar.TUCh_Mn
TUCh.Mx = _snap.cvar.TUCh_Mx
TUCh.Vals = _snap.cvar.TUCh_Vals
class TSInt(object):
"""Proxy of C++ TSInt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TSInt_Val_get, _snap.TSInt_Val_set)
def __init__(self, *args):
"""
__init__(TSInt self) -> TSInt
__init__(TSInt self, int16 const & _Val) -> TSInt
Parameters:
_Val: int16 const &
__init__(TSInt self, TSIn SIn) -> TSInt
Parameters:
SIn: TSIn &
"""
_snap.TSInt_swiginit(self,_snap.new_TSInt(*args))
def Load(self, *args):
"""
Load(TSInt self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TSInt_Load(self, *args)
def Save(self, *args):
"""
Save(TSInt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TSInt_Save(self, *args)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TSInt self) -> int
Parameters:
self: TSInt const *
"""
return _snap.TSInt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TSInt self) -> int
Parameters:
self: TSInt const *
"""
return _snap.TSInt_GetSecHashCd(self)
__swig_destroy__ = _snap.delete_TSInt
TSInt.Load = new_instancemethod(_snap.TSInt_Load,None,TSInt)
TSInt.Save = new_instancemethod(_snap.TSInt_Save,None,TSInt)
TSInt.GetPrimHashCd = new_instancemethod(_snap.TSInt_GetPrimHashCd,None,TSInt)
TSInt.GetSecHashCd = new_instancemethod(_snap.TSInt_GetSecHashCd,None,TSInt)
TSInt_swigregister = _snap.TSInt_swigregister
TSInt_swigregister(TSInt)
class TInt(object):
"""Proxy of C++ TInt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TInt_Val_get, _snap.TInt_Val_set)
Rnd = _swig_property(_snap.TInt_Rnd_get, _snap.TInt_Rnd_set)
def __init__(self, *args):
"""
__init__(TInt self) -> TInt
__init__(TInt self, int const & _Val) -> TInt
Parameters:
_Val: int const &
__init__(TInt self, TSIn SIn) -> TInt
Parameters:
SIn: TSIn &
"""
_snap.TInt_swiginit(self,_snap.new_TInt(*args))
def Load(self, *args):
"""
Load(TInt self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TInt_Load(self, *args)
def Save(self, *args):
"""
Save(TInt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TInt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TInt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TInt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TInt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TInt_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TInt self, TInt Int) -> bool
Parameters:
Int: TInt const &
__eq__(TInt self, int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TInt self, int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TInt self, TInt Int) -> bool
Parameters:
Int: TInt const &
__lt__(TInt self, int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt___lt__(self, *args)
def __call__(self):
"""
__call__(TInt self) -> int
Parameters:
self: TInt const *
"""
return _snap.TInt___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TInt self, int const & Int) -> TInt
Parameters:
Int: int const &
"""
return _snap.TInt___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TInt self, int const & Int) -> TInt
Parameters:
Int: int const &
"""
return _snap.TInt___isub__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TInt self) -> int
Parameters:
self: TInt const *
"""
return _snap.TInt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TInt self) -> int
Parameters:
self: TInt const *
"""
return _snap.TInt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TInt self) -> int
Parameters:
self: TInt const *
"""
return _snap.TInt_GetSecHashCd(self)
def Abs(*args):
"""
Abs(int const & Int) -> int
Parameters:
Int: int const &
"""
return _snap.TInt_Abs(*args)
Abs = staticmethod(Abs)
def Sign(*args):
"""
Sign(int const & Int) -> int
Parameters:
Int: int const &
"""
return _snap.TInt_Sign(*args)
Sign = staticmethod(Sign)
def Swap(*args):
"""
Swap(int & Int1, int & Int2)
Parameters:
Int1: int &
Int2: int &
"""
return _snap.TInt_Swap(*args)
Swap = staticmethod(Swap)
def GetRnd(Range=0):
"""
GetRnd(int const & Range=0) -> int
Parameters:
Range: int const &
GetRnd() -> int
"""
return _snap.TInt_GetRnd(Range)
GetRnd = staticmethod(GetRnd)
def IsOdd(*args):
"""
IsOdd(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsOdd(*args)
IsOdd = staticmethod(IsOdd)
def IsEven(*args):
"""
IsEven(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsEven(*args)
IsEven = staticmethod(IsEven)
def GetMn(*args):
"""
GetMn(int const & Int1, int const & Int2) -> int
Parameters:
Int1: int const &
Int2: int const &
GetMn(int const & Int1, int const & Int2, int const & Int3) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
GetMn(int const & Int1, int const & Int2, int const & Int3, int const & Int4) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
Int4: int const &
"""
return _snap.TInt_GetMn(*args)
GetMn = staticmethod(GetMn)
def GetMx(*args):
"""
GetMx(int const & Int1, int const & Int2) -> int
Parameters:
Int1: int const &
Int2: int const &
GetMx(int const & Int1, int const & Int2, int const & Int3) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
GetMx(int const & Int1, int const & Int2, int const & Int3, int const & Int4) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
Int4: int const &
"""
return _snap.TInt_GetMx(*args)
GetMx = staticmethod(GetMx)
def GetInRng(*args):
"""
GetInRng(int const & Val, int const & Mn, int const & Mx) -> int
Parameters:
Val: int const &
Mn: int const &
Mx: int const &
"""
return _snap.TInt_GetInRng(*args)
GetInRng = staticmethod(GetInRng)
def GetHexStr(*args):
"""
GetHexStr(int const & Val) -> TStr
Parameters:
Val: int const &
GetHexStr(TInt Int) -> TStr
Parameters:
Int: TInt const &
"""
return _snap.TInt_GetHexStr(*args)
GetHexStr = staticmethod(GetHexStr)
def GetKiloStr(*args):
"""
GetKiloStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetKiloStr(*args)
GetKiloStr = staticmethod(GetKiloStr)
def GetMegaStr(*args):
"""
GetMegaStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetMegaStr(*args)
GetMegaStr = staticmethod(GetMegaStr)
def SaveFrugalInt(*args):
"""
SaveFrugalInt(char * pDest, int i) -> char *
Parameters:
pDest: char *
i: int
"""
return _snap.TInt_SaveFrugalInt(*args)
SaveFrugalInt = staticmethod(SaveFrugalInt)
def LoadFrugalInt(*args):
"""
LoadFrugalInt(char * pSrc, int & i) -> char *
Parameters:
pSrc: char *
i: int &
"""
return _snap.TInt_LoadFrugalInt(*args)
LoadFrugalInt = staticmethod(LoadFrugalInt)
def TestFrugalInt():
"""TestFrugalInt()"""
return _snap.TInt_TestFrugalInt()
TestFrugalInt = staticmethod(TestFrugalInt)
def SaveFrugalIntV(*args):
"""
SaveFrugalIntV(TSOut SOut, TIntV IntV)
Parameters:
SOut: TSOut &
IntV: TVec< TInt,int > const &
"""
return _snap.TInt_SaveFrugalIntV(*args)
SaveFrugalIntV = staticmethod(SaveFrugalIntV)
def LoadFrugalIntV(*args):
"""
LoadFrugalIntV(TSIn SIn, TIntV IntV, bool ClrP=True)
Parameters:
SIn: TSIn &
IntV: TVec< TInt,int > &
ClrP: bool
LoadFrugalIntV(TSIn SIn, TIntV IntV)
Parameters:
SIn: TSIn &
IntV: TVec< TInt,int > &
"""
return _snap.TInt_LoadFrugalIntV(*args)
LoadFrugalIntV = staticmethod(LoadFrugalIntV)
__swig_destroy__ = _snap.delete_TInt
TInt.Load = new_instancemethod(_snap.TInt_Load,None,TInt)
TInt.Save = new_instancemethod(_snap.TInt_Save,None,TInt)
TInt.LoadXml = new_instancemethod(_snap.TInt_LoadXml,None,TInt)
TInt.SaveXml = new_instancemethod(_snap.TInt_SaveXml,None,TInt)
TInt.__eq__ = new_instancemethod(_snap.TInt___eq__,None,TInt)
TInt.__ne__ = new_instancemethod(_snap.TInt___ne__,None,TInt)
TInt.__lt__ = new_instancemethod(_snap.TInt___lt__,None,TInt)
TInt.__call__ = new_instancemethod(_snap.TInt___call__,None,TInt)
TInt.__iadd__ = new_instancemethod(_snap.TInt___iadd__,None,TInt)
TInt.__isub__ = new_instancemethod(_snap.TInt___isub__,None,TInt)
TInt.GetMemUsed = new_instancemethod(_snap.TInt_GetMemUsed,None,TInt)
TInt.GetPrimHashCd = new_instancemethod(_snap.TInt_GetPrimHashCd,None,TInt)
TInt.GetSecHashCd = new_instancemethod(_snap.TInt_GetSecHashCd,None,TInt)
TInt_swigregister = _snap.TInt_swigregister
TInt_swigregister(TInt)
TInt.Mn = _snap.cvar.TInt_Mn
TInt.Mx = _snap.cvar.TInt_Mx
TInt.Kilo = _snap.cvar.TInt_Kilo
TInt.Mega = _snap.cvar.TInt_Mega
TInt.Giga = _snap.cvar.TInt_Giga
def TInt_Abs(*args):
"""
TInt_Abs(int const & Int) -> int
Parameters:
Int: int const &
"""
return _snap.TInt_Abs(*args)
def TInt_Sign(*args):
"""
TInt_Sign(int const & Int) -> int
Parameters:
Int: int const &
"""
return _snap.TInt_Sign(*args)
def TInt_Swap(*args):
"""
TInt_Swap(int & Int1, int & Int2)
Parameters:
Int1: int &
Int2: int &
"""
return _snap.TInt_Swap(*args)
def TInt_GetRnd(Range=0):
"""
GetRnd(int const & Range=0) -> int
Parameters:
Range: int const &
TInt_GetRnd() -> int
"""
return _snap.TInt_GetRnd(Range)
def TInt_IsOdd(*args):
"""
TInt_IsOdd(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsOdd(*args)
def TInt_IsEven(*args):
"""
TInt_IsEven(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsEven(*args)
def TInt_GetMn(*args):
"""
GetMn(int const & Int1, int const & Int2) -> int
Parameters:
Int1: int const &
Int2: int const &
GetMn(int const & Int1, int const & Int2, int const & Int3) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
TInt_GetMn(int const & Int1, int const & Int2, int const & Int3, int const & Int4) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
Int4: int const &
"""
return _snap.TInt_GetMn(*args)
def TInt_GetMx(*args):
"""
GetMx(int const & Int1, int const & Int2) -> int
Parameters:
Int1: int const &
Int2: int const &
GetMx(int const & Int1, int const & Int2, int const & Int3) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
TInt_GetMx(int const & Int1, int const & Int2, int const & Int3, int const & Int4) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
Int4: int const &
"""
return _snap.TInt_GetMx(*args)
def TInt_GetInRng(*args):
"""
TInt_GetInRng(int const & Val, int const & Mn, int const & Mx) -> int
Parameters:
Val: int const &
Mn: int const &
Mx: int const &
"""
return _snap.TInt_GetInRng(*args)
def TInt_GetHexStr(*args):
"""
GetHexStr(int const & Val) -> TStr
Parameters:
Val: int const &
TInt_GetHexStr(TInt Int) -> TStr
Parameters:
Int: TInt const &
"""
return _snap.TInt_GetHexStr(*args)
def TInt_GetKiloStr(*args):
"""
TInt_GetKiloStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetKiloStr(*args)
def TInt_GetMegaStr(*args):
"""
TInt_GetMegaStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetMegaStr(*args)
def TInt_SaveFrugalInt(*args):
"""
TInt_SaveFrugalInt(char * pDest, int i) -> char *
Parameters:
pDest: char *
i: int
"""
return _snap.TInt_SaveFrugalInt(*args)
def TInt_LoadFrugalInt(*args):
"""
TInt_LoadFrugalInt(char * pSrc, int & i) -> char *
Parameters:
pSrc: char *
i: int &
"""
return _snap.TInt_LoadFrugalInt(*args)
def TInt_TestFrugalInt():
"""TInt_TestFrugalInt()"""
return _snap.TInt_TestFrugalInt()
def TInt_SaveFrugalIntV(*args):
"""
TInt_SaveFrugalIntV(TSOut SOut, TIntV IntV)
Parameters:
SOut: TSOut &
IntV: TVec< TInt,int > const &
"""
return _snap.TInt_SaveFrugalIntV(*args)
def TInt_LoadFrugalIntV(*args):
"""
LoadFrugalIntV(TSIn SIn, TIntV IntV, bool ClrP=True)
Parameters:
SIn: TSIn &
IntV: TVec< TInt,int > &
ClrP: bool
TInt_LoadFrugalIntV(TSIn SIn, TIntV IntV)
Parameters:
SIn: TSIn &
IntV: TVec< TInt,int > &
"""
return _snap.TInt_LoadFrugalIntV(*args)
class TUInt(object):
"""Proxy of C++ TUInt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TUInt_Val_get, _snap.TUInt_Val_set)
Rnd = _swig_property(_snap.TUInt_Rnd_get, _snap.TUInt_Rnd_set)
def __init__(self, *args):
"""
__init__(TUInt self) -> TUInt
__init__(TUInt self, uint const & _Val) -> TUInt
Parameters:
_Val: uint const &
__init__(TUInt self, TSIn SIn) -> TUInt
Parameters:
SIn: TSIn &
"""
_snap.TUInt_swiginit(self,_snap.new_TUInt(*args))
def Load(self, *args):
"""
Load(TUInt self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TUInt_Load(self, *args)
def Save(self, *args):
"""
Save(TUInt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TUInt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TUInt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TUInt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TUInt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TUInt_SaveXml(self, *args)
def __call__(self, *args):
"""
__call__(TUInt self) -> uint
__call__(TUInt self) -> uint &
Parameters:
self: TUInt *
"""
return _snap.TUInt___call__(self, *args)
def __invert__(self):
"""
__invert__(TUInt self) -> TUInt
Parameters:
self: TUInt *
"""
return _snap.TUInt___invert__(self)
def __iand__(self, *args):
"""
__iand__(TUInt self, TUInt UInt) -> TUInt
Parameters:
UInt: TUInt const &
"""
return _snap.TUInt___iand__(self, *args)
def __ior__(self, *args):
"""
__ior__(TUInt self, TUInt UInt) -> TUInt
Parameters:
UInt: TUInt const &
"""
return _snap.TUInt___ior__(self, *args)
def __ixor__(self, *args):
"""
__ixor__(TUInt self, TUInt UInt) -> TUInt
Parameters:
UInt: TUInt const &
"""
return _snap.TUInt___ixor__(self, *args)
def __irshift__(self, *args):
"""
__irshift__(TUInt self, int const & ShiftBits) -> TUInt
Parameters:
ShiftBits: int const &
"""
return _snap.TUInt___irshift__(self, *args)
def __ilshift__(self, *args):
"""
__ilshift__(TUInt self, int const & ShiftBits) -> TUInt
Parameters:
ShiftBits: int const &
"""
return _snap.TUInt___ilshift__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TUInt self) -> int
Parameters:
self: TUInt const *
"""
return _snap.TUInt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TUInt self) -> int
Parameters:
self: TUInt const *
"""
return _snap.TUInt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TUInt self) -> int
Parameters:
self: TUInt const *
"""
return _snap.TUInt_GetSecHashCd(self)
def GetRnd(Range=0):
"""
GetRnd(uint const & Range=0) -> uint
Parameters:
Range: uint const &
GetRnd() -> uint
"""
return _snap.TUInt_GetRnd(Range)
GetRnd = staticmethod(GetRnd)
def GetKiloStr(*args):
"""
GetKiloStr(uint const & Val) -> TStr
Parameters:
Val: uint const &
"""
return _snap.TUInt_GetKiloStr(*args)
GetKiloStr = staticmethod(GetKiloStr)
def GetMegaStr(*args):
"""
GetMegaStr(uint const & Val) -> TStr
Parameters:
Val: uint const &
"""
return _snap.TUInt_GetMegaStr(*args)
GetMegaStr = staticmethod(GetMegaStr)
def JavaUIntToCppUInt(*args):
"""
JavaUIntToCppUInt(uint const & JavaUInt) -> uint
Parameters:
JavaUInt: uint const &
"""
return _snap.TUInt_JavaUIntToCppUInt(*args)
JavaUIntToCppUInt = staticmethod(JavaUIntToCppUInt)
def IsIpStr(*args):
"""
IsIpStr(TStr IpStr, uint & Ip, char const & SplitCh='.') -> bool
Parameters:
IpStr: TStr const &
Ip: uint &
SplitCh: char const &
IsIpStr(TStr IpStr, uint & Ip) -> bool
Parameters:
IpStr: TStr const &
Ip: uint &
IsIpStr(TStr IpStr, char const & SplitCh='.') -> bool
Parameters:
IpStr: TStr const &
SplitCh: char const &
IsIpStr(TStr IpStr) -> bool
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_IsIpStr(*args)
IsIpStr = staticmethod(IsIpStr)
def GetUIntFromIpStr(*args):
"""
GetUIntFromIpStr(TStr IpStr, char const & SplitCh='.') -> uint
Parameters:
IpStr: TStr const &
SplitCh: char const &
GetUIntFromIpStr(TStr IpStr) -> uint
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_GetUIntFromIpStr(*args)
GetUIntFromIpStr = staticmethod(GetUIntFromIpStr)
def GetStrFromIpUInt(*args):
"""
GetStrFromIpUInt(uint const & Ip) -> TStr
Parameters:
Ip: uint const &
"""
return _snap.TUInt_GetStrFromIpUInt(*args)
GetStrFromIpUInt = staticmethod(GetStrFromIpUInt)
def IsIpv6Str(*args):
"""
IsIpv6Str(TStr IpStr, char const & SplitCh=':') -> bool
Parameters:
IpStr: TStr const &
SplitCh: char const &
IsIpv6Str(TStr IpStr) -> bool
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_IsIpv6Str(*args)
IsIpv6Str = staticmethod(IsIpv6Str)
__swig_destroy__ = _snap.delete_TUInt
TUInt.Load = new_instancemethod(_snap.TUInt_Load,None,TUInt)
TUInt.Save = new_instancemethod(_snap.TUInt_Save,None,TUInt)
TUInt.LoadXml = new_instancemethod(_snap.TUInt_LoadXml,None,TUInt)
TUInt.SaveXml = new_instancemethod(_snap.TUInt_SaveXml,None,TUInt)
TUInt.__call__ = new_instancemethod(_snap.TUInt___call__,None,TUInt)
TUInt.__invert__ = new_instancemethod(_snap.TUInt___invert__,None,TUInt)
TUInt.__iand__ = new_instancemethod(_snap.TUInt___iand__,None,TUInt)
TUInt.__ior__ = new_instancemethod(_snap.TUInt___ior__,None,TUInt)
TUInt.__ixor__ = new_instancemethod(_snap.TUInt___ixor__,None,TUInt)
TUInt.__irshift__ = new_instancemethod(_snap.TUInt___irshift__,None,TUInt)
TUInt.__ilshift__ = new_instancemethod(_snap.TUInt___ilshift__,None,TUInt)
TUInt.GetMemUsed = new_instancemethod(_snap.TUInt_GetMemUsed,None,TUInt)
TUInt.GetPrimHashCd = new_instancemethod(_snap.TUInt_GetPrimHashCd,None,TUInt)
TUInt.GetSecHashCd = new_instancemethod(_snap.TUInt_GetSecHashCd,None,TUInt)
TUInt_swigregister = _snap.TUInt_swigregister
TUInt_swigregister(TUInt)
TUInt.Mn = _snap.cvar.TUInt_Mn
TUInt.Mx = _snap.cvar.TUInt_Mx
def TUInt_GetRnd(Range=0):
"""
GetRnd(uint const & Range=0) -> uint
Parameters:
Range: uint const &
TUInt_GetRnd() -> uint
"""
return _snap.TUInt_GetRnd(Range)
def TUInt_GetKiloStr(*args):
"""
TUInt_GetKiloStr(uint const & Val) -> TStr
Parameters:
Val: uint const &
"""
return _snap.TUInt_GetKiloStr(*args)
def TUInt_GetMegaStr(*args):
"""
TUInt_GetMegaStr(uint const & Val) -> TStr
Parameters:
Val: uint const &
"""
return _snap.TUInt_GetMegaStr(*args)
def TUInt_JavaUIntToCppUInt(*args):
"""
TUInt_JavaUIntToCppUInt(uint const & JavaUInt) -> uint
Parameters:
JavaUInt: uint const &
"""
return _snap.TUInt_JavaUIntToCppUInt(*args)
def TUInt_IsIpStr(*args):
"""
IsIpStr(TStr IpStr, uint & Ip, char const & SplitCh='.') -> bool
Parameters:
IpStr: TStr const &
Ip: uint &
SplitCh: char const &
IsIpStr(TStr IpStr, uint & Ip) -> bool
Parameters:
IpStr: TStr const &
Ip: uint &
IsIpStr(TStr IpStr, char const & SplitCh='.') -> bool
Parameters:
IpStr: TStr const &
SplitCh: char const &
TUInt_IsIpStr(TStr IpStr) -> bool
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_IsIpStr(*args)
def TUInt_GetUIntFromIpStr(*args):
"""
GetUIntFromIpStr(TStr IpStr, char const & SplitCh='.') -> uint
Parameters:
IpStr: TStr const &
SplitCh: char const &
TUInt_GetUIntFromIpStr(TStr IpStr) -> uint
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_GetUIntFromIpStr(*args)
def TUInt_GetStrFromIpUInt(*args):
"""
TUInt_GetStrFromIpUInt(uint const & Ip) -> TStr
Parameters:
Ip: uint const &
"""
return _snap.TUInt_GetStrFromIpUInt(*args)
def TUInt_IsIpv6Str(*args):
"""
IsIpv6Str(TStr IpStr, char const & SplitCh=':') -> bool
Parameters:
IpStr: TStr const &
SplitCh: char const &
TUInt_IsIpv6Str(TStr IpStr) -> bool
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_IsIpv6Str(*args)
class TUInt64(object):
"""Proxy of C++ TUInt64 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TUInt64_Val_get, _snap.TUInt64_Val_set)
def __init__(self, *args):
"""
__init__(TUInt64 self) -> TUInt64
__init__(TUInt64 self, TUInt64 Int) -> TUInt64
Parameters:
Int: TUInt64 const &
__init__(TUInt64 self, uint64 const & Int) -> TUInt64
Parameters:
Int: uint64 const &
__init__(TUInt64 self, uint const & MsVal, uint const & LsVal) -> TUInt64
Parameters:
MsVal: uint const &
LsVal: uint const &
__init__(TUInt64 self, void * Pt) -> TUInt64
Parameters:
Pt: void *
__init__(TUInt64 self, TSIn SIn) -> TUInt64
Parameters:
SIn: TSIn &
"""
_snap.TUInt64_swiginit(self,_snap.new_TUInt64(*args))
def Load(self, *args):
"""
Load(TUInt64 self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TUInt64_Load(self, *args)
def Save(self, *args):
"""
Save(TUInt64 self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TUInt64_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TUInt64 self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TUInt64_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TUInt64 self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TUInt64_SaveXml(self, *args)
def __iadd__(self, *args):
"""
__iadd__(TUInt64 self, TUInt64 Int) -> TUInt64
Parameters:
Int: TUInt64 const &
"""
return _snap.TUInt64___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TUInt64 self, TUInt64 Int) -> TUInt64
Parameters:
Int: TUInt64 const &
"""
return _snap.TUInt64___isub__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TUInt64 self) -> int
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TUInt64 self) -> int
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TUInt64 self) -> int
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetSecHashCd(self)
def GetMsVal(self):
"""
GetMsVal(TUInt64 self) -> uint
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetMsVal(self)
def GetLsVal(self):
"""
GetLsVal(TUInt64 self) -> uint
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetLsVal(self)
def GetHexStr(*args):
"""
GetHexStr(TUInt64 Int) -> TStr
Parameters:
Int: TUInt64 const &
"""
return _snap.TUInt64_GetHexStr(*args)
GetHexStr = staticmethod(GetHexStr)
def GetKiloStr(*args):
"""
GetKiloStr(uint64 const & Val) -> TStr
Parameters:
Val: uint64 const &
"""
return _snap.TUInt64_GetKiloStr(*args)
GetKiloStr = staticmethod(GetKiloStr)
def GetMegaStr(*args):
"""
GetMegaStr(uint64 const & Val) -> TStr
Parameters:
Val: uint64 const &
"""
return _snap.TUInt64_GetMegaStr(*args)
GetMegaStr = staticmethod(GetMegaStr)
__swig_destroy__ = _snap.delete_TUInt64
TUInt64.Load = new_instancemethod(_snap.TUInt64_Load,None,TUInt64)
TUInt64.Save = new_instancemethod(_snap.TUInt64_Save,None,TUInt64)
TUInt64.LoadXml = new_instancemethod(_snap.TUInt64_LoadXml,None,TUInt64)
TUInt64.SaveXml = new_instancemethod(_snap.TUInt64_SaveXml,None,TUInt64)
TUInt64.__iadd__ = new_instancemethod(_snap.TUInt64___iadd__,None,TUInt64)
TUInt64.__isub__ = new_instancemethod(_snap.TUInt64___isub__,None,TUInt64)
TUInt64.GetMemUsed = new_instancemethod(_snap.TUInt64_GetMemUsed,None,TUInt64)
TUInt64.GetPrimHashCd = new_instancemethod(_snap.TUInt64_GetPrimHashCd,None,TUInt64)
TUInt64.GetSecHashCd = new_instancemethod(_snap.TUInt64_GetSecHashCd,None,TUInt64)
TUInt64.GetMsVal = new_instancemethod(_snap.TUInt64_GetMsVal,None,TUInt64)
TUInt64.GetLsVal = new_instancemethod(_snap.TUInt64_GetLsVal,None,TUInt64)
TUInt64_swigregister = _snap.TUInt64_swigregister
TUInt64_swigregister(TUInt64)
TUInt64.Mn = _snap.cvar.TUInt64_Mn
TUInt64.Mx = _snap.cvar.TUInt64_Mx
def TUInt64_GetHexStr(*args):
"""
TUInt64_GetHexStr(TUInt64 Int) -> TStr
Parameters:
Int: TUInt64 const &
"""
return _snap.TUInt64_GetHexStr(*args)
def TUInt64_GetKiloStr(*args):
"""
TUInt64_GetKiloStr(uint64 const & Val) -> TStr
Parameters:
Val: uint64 const &
"""
return _snap.TUInt64_GetKiloStr(*args)
def TUInt64_GetMegaStr(*args):
"""
TUInt64_GetMegaStr(uint64 const & Val) -> TStr
Parameters:
Val: uint64 const &
"""
return _snap.TUInt64_GetMegaStr(*args)
class TFlt(object):
"""Proxy of C++ TFlt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TFlt_Val_get, _snap.TFlt_Val_set)
Rnd = _swig_property(_snap.TFlt_Rnd_get, _snap.TFlt_Rnd_set)
def __init__(self, *args):
"""
__init__(TFlt self) -> TFlt
__init__(TFlt self, double const & _Val) -> TFlt
Parameters:
_Val: double const &
__init__(TFlt self, TSIn SIn) -> TFlt
Parameters:
SIn: TSIn &
__init__(TFlt self, TSIn SIn, bool const & IsTxt) -> TFlt
Parameters:
SIn: TSIn &
IsTxt: bool const &
"""
_snap.TFlt_swiginit(self,_snap.new_TFlt(*args))
def Load(self, *args):
"""
Load(TFlt self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TFlt_Load(self, *args)
def Save(self, *args):
"""
Save(TFlt self, TSOut SOut)
Parameters:
SOut: TSOut &
Save(TFlt self, TSOut SOut, bool const & IsTxt)
Parameters:
SOut: TSOut &
IsTxt: bool const &
"""
return _snap.TFlt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TFlt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TFlt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TFlt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TFlt_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TFlt self, TFlt Flt) -> bool
Parameters:
Flt: TFlt const &
__eq__(TFlt self, double const & Flt) -> bool
Parameters:
Flt: double const &
"""
return _snap.TFlt___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TFlt self, double const & Flt) -> bool
Parameters:
Flt: double const &
"""
return _snap.TFlt___ne__(self, *args)
def __call__(self):
"""
__call__(TFlt self) -> double
Parameters:
self: TFlt const *
"""
return _snap.TFlt___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TFlt self, double const & Flt) -> TFlt
Parameters:
Flt: double const &
"""
return _snap.TFlt___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TFlt self, double const & Flt) -> TFlt
Parameters:
Flt: double const &
"""
return _snap.TFlt___isub__(self, *args)
def __imul__(self, *args):
"""
__imul__(TFlt self, double const & Flt) -> TFlt
Parameters:
Flt: double const &
"""
return _snap.TFlt___imul__(self, *args)
def __idiv__(self, *args):
"""
__idiv__(TFlt self, double const & Flt) -> TFlt
Parameters:
Flt: double const &
"""
return _snap.TFlt___idiv__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TFlt self) -> int
Parameters:
self: TFlt const *
"""
return _snap.TFlt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TFlt self) -> int
Parameters:
self: TFlt const *
"""
return _snap.TFlt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TFlt self) -> int
Parameters:
self: TFlt const *
"""
return _snap.TFlt_GetSecHashCd(self)
def Abs(*args):
"""
Abs(double const & Flt) -> double
Parameters:
Flt: double const &
"""
return _snap.TFlt_Abs(*args)
Abs = staticmethod(Abs)
def Sign(*args):
"""
Sign(double const & Flt) -> int
Parameters:
Flt: double const &
"""
return _snap.TFlt_Sign(*args)
Sign = staticmethod(Sign)
def Round(*args):
"""
Round(double const & Flt) -> int
Parameters:
Flt: double const &
"""
return _snap.TFlt_Round(*args)
Round = staticmethod(Round)
def GetRnd():
"""GetRnd() -> double"""
return _snap.TFlt_GetRnd()
GetRnd = staticmethod(GetRnd)
def Eq6(*args):
"""
Eq6(double const & LFlt, double const & RFlt) -> bool
Parameters:
LFlt: double const &
RFlt: double const &
"""
return _snap.TFlt_Eq6(*args)
Eq6 = staticmethod(Eq6)
def GetMn(*args):
"""
GetMn(double const & Flt1, double const & Flt2) -> double
Parameters:
Flt1: double const &
Flt2: double const &
GetMn(double const & Flt1, double const & Flt2, double const & Flt3) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const &
GetMn(double const & Flt1, double const & Flt2, double const & Flt3, double const & Flt4) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const &
Flt4: double const &
"""
return _snap.TFlt_GetMn(*args)
GetMn = staticmethod(GetMn)
def GetMx(*args):
"""
GetMx(double const & Flt1, double const & Flt2) -> double
Parameters:
Flt1: double const &
Flt2: double const &
GetMx(double const & Flt1, double const & Flt2, double const Flt3) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const
GetMx(double const & Flt1, double const & Flt2, double const Flt3, double const & Flt4) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const
Flt4: double const &
"""
return _snap.TFlt_GetMx(*args)
GetMx = staticmethod(GetMx)
def GetInRng(*args):
"""
GetInRng(double const & Val, double const & Mn, double const & Mx) -> double
Parameters:
Val: double const &
Mn: double const &
Mx: double const &
"""
return _snap.TFlt_GetInRng(*args)
GetInRng = staticmethod(GetInRng)
def IsNum(self, *args):
"""
IsNum(TFlt self, double const & Val) -> bool
Parameters:
Val: double const &
IsNum(TFlt self) -> bool
Parameters:
self: TFlt const *
"""
return _snap.TFlt_IsNum(self, *args)
def IsNan(self, *args):
"""
IsNan(TFlt self, double const & Val) -> bool
Parameters:
Val: double const &
IsNan(TFlt self) -> bool
Parameters:
self: TFlt const *
"""
return _snap.TFlt_IsNan(self, *args)
def GetPrcStr(*args):
"""
GetPrcStr(double const & RelVal, double const & FullVal) -> TStr
Parameters:
RelVal: double const &
FullVal: double const &
"""
return _snap.TFlt_GetPrcStr(*args)
GetPrcStr = staticmethod(GetPrcStr)
def GetKiloStr(*args):
"""
GetKiloStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetKiloStr(*args)
GetKiloStr = staticmethod(GetKiloStr)
def GetMegaStr(*args):
"""
GetMegaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetMegaStr(*args)
GetMegaStr = staticmethod(GetMegaStr)
def GetGigaStr(*args):
"""
GetGigaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetGigaStr(*args)
GetGigaStr = staticmethod(GetGigaStr)
__swig_destroy__ = _snap.delete_TFlt
TFlt.Load = new_instancemethod(_snap.TFlt_Load,None,TFlt)
TFlt.Save = new_instancemethod(_snap.TFlt_Save,None,TFlt)
TFlt.LoadXml = new_instancemethod(_snap.TFlt_LoadXml,None,TFlt)
TFlt.SaveXml = new_instancemethod(_snap.TFlt_SaveXml,None,TFlt)
TFlt.__eq__ = new_instancemethod(_snap.TFlt___eq__,None,TFlt)
TFlt.__ne__ = new_instancemethod(_snap.TFlt___ne__,None,TFlt)
TFlt.__call__ = new_instancemethod(_snap.TFlt___call__,None,TFlt)
TFlt.__iadd__ = new_instancemethod(_snap.TFlt___iadd__,None,TFlt)
TFlt.__isub__ = new_instancemethod(_snap.TFlt___isub__,None,TFlt)
TFlt.__imul__ = new_instancemethod(_snap.TFlt___imul__,None,TFlt)
TFlt.__idiv__ = new_instancemethod(_snap.TFlt___idiv__,None,TFlt)
TFlt.GetMemUsed = new_instancemethod(_snap.TFlt_GetMemUsed,None,TFlt)
TFlt.GetPrimHashCd = new_instancemethod(_snap.TFlt_GetPrimHashCd,None,TFlt)
TFlt.GetSecHashCd = new_instancemethod(_snap.TFlt_GetSecHashCd,None,TFlt)
TFlt.IsNum = new_instancemethod(_snap.TFlt_IsNum,None,TFlt)
TFlt.IsNan = new_instancemethod(_snap.TFlt_IsNan,None,TFlt)
TFlt_swigregister = _snap.TFlt_swigregister
TFlt_swigregister(TFlt)
TFlt.Mn = _snap.cvar.TFlt_Mn
TFlt.Mx = _snap.cvar.TFlt_Mx
TFlt.NInf = _snap.cvar.TFlt_NInf
TFlt.PInf = _snap.cvar.TFlt_PInf
TFlt.Eps = _snap.cvar.TFlt_Eps
TFlt.EpsHalf = _snap.cvar.TFlt_EpsHalf
def TFlt_Abs(*args):
"""
TFlt_Abs(double const & Flt) -> double
Parameters:
Flt: double const &
"""
return _snap.TFlt_Abs(*args)
def TFlt_Sign(*args):
"""
TFlt_Sign(double const & Flt) -> int
Parameters:
Flt: double const &
"""
return _snap.TFlt_Sign(*args)
def TFlt_Round(*args):
"""
TFlt_Round(double const & Flt) -> int
Parameters:
Flt: double const &
"""
return _snap.TFlt_Round(*args)
def TFlt_GetRnd():
"""TFlt_GetRnd() -> double"""
return _snap.TFlt_GetRnd()
def TFlt_Eq6(*args):
"""
TFlt_Eq6(double const & LFlt, double const & RFlt) -> bool
Parameters:
LFlt: double const &
RFlt: double const &
"""
return _snap.TFlt_Eq6(*args)
def TFlt_GetMn(*args):
"""
GetMn(double const & Flt1, double const & Flt2) -> double
Parameters:
Flt1: double const &
Flt2: double const &
GetMn(double const & Flt1, double const & Flt2, double const & Flt3) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const &
TFlt_GetMn(double const & Flt1, double const & Flt2, double const & Flt3, double const & Flt4) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const &
Flt4: double const &
"""
return _snap.TFlt_GetMn(*args)
def TFlt_GetMx(*args):
"""
GetMx(double const & Flt1, double const & Flt2) -> double
Parameters:
Flt1: double const &
Flt2: double const &
GetMx(double const & Flt1, double const & Flt2, double const Flt3) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const
TFlt_GetMx(double const & Flt1, double const & Flt2, double const Flt3, double const & Flt4) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const
Flt4: double const &
"""
return _snap.TFlt_GetMx(*args)
def TFlt_GetInRng(*args):
"""
TFlt_GetInRng(double const & Val, double const & Mn, double const & Mx) -> double
Parameters:
Val: double const &
Mn: double const &
Mx: double const &
"""
return _snap.TFlt_GetInRng(*args)
def TFlt_GetPrcStr(*args):
"""
TFlt_GetPrcStr(double const & RelVal, double const & FullVal) -> TStr
Parameters:
RelVal: double const &
FullVal: double const &
"""
return _snap.TFlt_GetPrcStr(*args)
def TFlt_GetKiloStr(*args):
"""
TFlt_GetKiloStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetKiloStr(*args)
def TFlt_GetMegaStr(*args):
"""
TFlt_GetMegaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetMegaStr(*args)
def TFlt_GetGigaStr(*args):
"""
TFlt_GetGigaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetGigaStr(*args)
class TAscFlt(TFlt):
"""Proxy of C++ TAscFlt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TAscFlt self) -> TAscFlt
__init__(TAscFlt self, double const & Val) -> TAscFlt
Parameters:
Val: double const &
__init__(TAscFlt self, TSIn SIn) -> TAscFlt
Parameters:
SIn: TSIn &
"""
_snap.TAscFlt_swiginit(self,_snap.new_TAscFlt(*args))
def Save(self, *args):
"""
Save(TAscFlt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TAscFlt_Save(self, *args)
__swig_destroy__ = _snap.delete_TAscFlt
TAscFlt.Save = new_instancemethod(_snap.TAscFlt_Save,None,TAscFlt)
TAscFlt_swigregister = _snap.TAscFlt_swigregister
TAscFlt_swigregister(TAscFlt)
class TSFlt(object):
"""Proxy of C++ TSFlt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TSFlt_Val_get, _snap.TSFlt_Val_set)
def __init__(self, *args):
"""
__init__(TSFlt self) -> TSFlt
__init__(TSFlt self, sdouble const & _Val) -> TSFlt
Parameters:
_Val: sdouble const &
__init__(TSFlt self, TSIn SIn) -> TSFlt
Parameters:
SIn: TSIn &
"""
_snap.TSFlt_swiginit(self,_snap.new_TSFlt(*args))
def Save(self, *args):
"""
Save(TSFlt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TSFlt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TSFlt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TSFlt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TSFlt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TSFlt_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TSFlt self, TSFlt SFlt) -> bool
Parameters:
SFlt: TSFlt const &
__eq__(TSFlt self, double const & Flt) -> bool
Parameters:
Flt: double const &
"""
return _snap.TSFlt___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TSFlt self, double const & Flt) -> bool
Parameters:
Flt: double const &
"""
return _snap.TSFlt___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TSFlt self, TSFlt SFlt) -> bool
Parameters:
SFlt: TSFlt const &
"""
return _snap.TSFlt___lt__(self, *args)
def __call__(self):
"""
__call__(TSFlt self) -> sdouble
Parameters:
self: TSFlt const *
"""
return _snap.TSFlt___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TSFlt self, double const & SFlt) -> TSFlt
Parameters:
SFlt: double const &
"""
return _snap.TSFlt___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TSFlt self, double const & SFlt) -> TSFlt
Parameters:
SFlt: double const &
"""
return _snap.TSFlt___isub__(self, *args)
def __imul__(self, *args):
"""
__imul__(TSFlt self, double const & SFlt) -> TSFlt
Parameters:
SFlt: double const &
"""
return _snap.TSFlt___imul__(self, *args)
def __idiv__(self, *args):
"""
__idiv__(TSFlt self, double const & SFlt) -> TSFlt
Parameters:
SFlt: double const &
"""
return _snap.TSFlt___idiv__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TSFlt self) -> int
Parameters:
self: TSFlt const *
"""
return _snap.TSFlt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TSFlt self) -> int
Parameters:
self: TSFlt const *
"""
return _snap.TSFlt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TSFlt self) -> int
Parameters:
self: TSFlt const *
"""
return _snap.TSFlt_GetSecHashCd(self)
__swig_destroy__ = _snap.delete_TSFlt
TSFlt.Save = new_instancemethod(_snap.TSFlt_Save,None,TSFlt)
TSFlt.LoadXml = new_instancemethod(_snap.TSFlt_LoadXml,None,TSFlt)
TSFlt.SaveXml = new_instancemethod(_snap.TSFlt_SaveXml,None,TSFlt)
TSFlt.__eq__ = new_instancemethod(_snap.TSFlt___eq__,None,TSFlt)
TSFlt.__ne__ = new_instancemethod(_snap.TSFlt___ne__,None,TSFlt)
TSFlt.__lt__ = new_instancemethod(_snap.TSFlt___lt__,None,TSFlt)
TSFlt.__call__ = new_instancemethod(_snap.TSFlt___call__,None,TSFlt)
TSFlt.__iadd__ = new_instancemethod(_snap.TSFlt___iadd__,None,TSFlt)
TSFlt.__isub__ = new_instancemethod(_snap.TSFlt___isub__,None,TSFlt)
TSFlt.__imul__ = new_instancemethod(_snap.TSFlt___imul__,None,TSFlt)
TSFlt.__idiv__ = new_instancemethod(_snap.TSFlt___idiv__,None,TSFlt)
TSFlt.GetMemUsed = new_instancemethod(_snap.TSFlt_GetMemUsed,None,TSFlt)
TSFlt.GetPrimHashCd = new_instancemethod(_snap.TSFlt_GetPrimHashCd,None,TSFlt)
TSFlt.GetSecHashCd = new_instancemethod(_snap.TSFlt_GetSecHashCd,None,TSFlt)
TSFlt_swigregister = _snap.TSFlt_swigregister
TSFlt_swigregister(TSFlt)
TSFlt.Mn = _snap.cvar.TSFlt_Mn
TSFlt.Mx = _snap.cvar.TSFlt_Mx
class TLFlt(object):
"""Proxy of C++ TLFlt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TLFlt_Val_get, _snap.TLFlt_Val_set)
def __init__(self, *args):
"""
__init__(TLFlt self) -> TLFlt
__init__(TLFlt self, ldouble const & _Val) -> TLFlt
Parameters:
_Val: ldouble const &
__init__(TLFlt self, TSIn SIn) -> TLFlt
Parameters:
SIn: TSIn &
"""
_snap.TLFlt_swiginit(self,_snap.new_TLFlt(*args))
def Save(self, *args):
"""
Save(TLFlt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TLFlt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TLFlt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TLFlt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TLFlt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TLFlt_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TLFlt self, TLFlt LFlt) -> bool
Parameters:
LFlt: TLFlt const &
__eq__(TLFlt self, ldouble const & LFlt) -> bool
Parameters:
LFlt: ldouble const &
"""
return _snap.TLFlt___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TLFlt self, ldouble const & LFlt) -> bool
Parameters:
LFlt: ldouble const &
"""
return _snap.TLFlt___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TLFlt self, TLFlt LFlt) -> bool
Parameters:
LFlt: TLFlt const &
"""
return _snap.TLFlt___lt__(self, *args)
def __call__(self):
"""
__call__(TLFlt self) -> ldouble
Parameters:
self: TLFlt const *
"""
return _snap.TLFlt___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TLFlt self, ldouble const & LFlt) -> TLFlt
Parameters:
LFlt: ldouble const &
"""
return _snap.TLFlt___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TLFlt self, ldouble const & LFlt) -> TLFlt
Parameters:
LFlt: ldouble const &
"""
return _snap.TLFlt___isub__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TLFlt self) -> int
Parameters:
self: TLFlt const *
"""
return _snap.TLFlt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TLFlt self) -> int
Parameters:
self: TLFlt const *
"""
return _snap.TLFlt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TLFlt self) -> int
Parameters:
self: TLFlt const *
"""
return _snap.TLFlt_GetSecHashCd(self)
__swig_destroy__ = _snap.delete_TLFlt
TLFlt.Save = new_instancemethod(_snap.TLFlt_Save,None,TLFlt)
TLFlt.LoadXml = new_instancemethod(_snap.TLFlt_LoadXml,None,TLFlt)
TLFlt.SaveXml = new_instancemethod(_snap.TLFlt_SaveXml,None,TLFlt)
TLFlt.__eq__ = new_instancemethod(_snap.TLFlt___eq__,None,TLFlt)
TLFlt.__ne__ = new_instancemethod(_snap.TLFlt___ne__,None,TLFlt)
TLFlt.__lt__ = new_instancemethod(_snap.TLFlt___lt__,None,TLFlt)
TLFlt.__call__ = new_instancemethod(_snap.TLFlt___call__,None,TLFlt)
TLFlt.__iadd__ = new_instancemethod(_snap.TLFlt___iadd__,None,TLFlt)
TLFlt.__isub__ = new_instancemethod(_snap.TLFlt___isub__,None,TLFlt)
TLFlt.GetMemUsed = new_instancemethod(_snap.TLFlt_GetMemUsed,None,TLFlt)
TLFlt.GetPrimHashCd = new_instancemethod(_snap.TLFlt_GetPrimHashCd,None,TLFlt)
TLFlt.GetSecHashCd = new_instancemethod(_snap.TLFlt_GetSecHashCd,None,TLFlt)
TLFlt_swigregister = _snap.TLFlt_swigregister
TLFlt_swigregister(TLFlt)
TLFlt.Mn = _snap.cvar.TLFlt_Mn
TLFlt.Mx = _snap.cvar.TLFlt_Mx
class TFltRect(object):
"""Proxy of C++ TFltRect class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
MnX = _swig_property(_snap.TFltRect_MnX_get, _snap.TFltRect_MnX_set)
MnY = _swig_property(_snap.TFltRect_MnY_get, _snap.TFltRect_MnY_set)
MxX = _swig_property(_snap.TFltRect_MxX_get, _snap.TFltRect_MxX_set)
MxY = _swig_property(_snap.TFltRect_MxY_get, _snap.TFltRect_MxY_set)
def __init__(self, *args):
"""
__init__(TFltRect self) -> TFltRect
__init__(TFltRect self, TFltRect FltRect) -> TFltRect
Parameters:
FltRect: TFltRect const &
__init__(TFltRect self, double const & _MnX, double const & _MnY, double const & _MxX, double const & _MxY) -> TFltRect
Parameters:
_MnX: double const &
_MnY: double const &
_MxX: double const &
_MxY: double const &
__init__(TFltRect self, TSIn SIn) -> TFltRect
Parameters:
SIn: TSIn &
"""
_snap.TFltRect_swiginit(self,_snap.new_TFltRect(*args))
def Save(self, *args):
"""
Save(TFltRect self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TFltRect_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TFltRect self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TFltRect_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TFltRect self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TFltRect_SaveXml(self, *args)
def GetMnX(self):
"""
GetMnX(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetMnX(self)
def GetMnY(self):
"""
GetMnY(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetMnY(self)
def GetMxX(self):
"""
GetMxX(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetMxX(self)
def GetMxY(self):
"""
GetMxY(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetMxY(self)
def GetXLen(self):
"""
GetXLen(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetXLen(self)
def GetYLen(self):
"""
GetYLen(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetYLen(self)
def GetXCenter(self):
"""
GetXCenter(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetXCenter(self)
def GetYCenter(self):
"""
GetYCenter(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetYCenter(self)
def IsXYIn(self, *args):
"""
IsXYIn(TFltRect self, double const & X, double const & Y) -> bool
Parameters:
X: double const &
Y: double const &
"""
return _snap.TFltRect_IsXYIn(self, *args)
def Intersection(*args):
"""
Intersection(TFltRect Rect1, TFltRect Rect2) -> bool
Parameters:
Rect1: TFltRect const &
Rect2: TFltRect const &
"""
return _snap.TFltRect_Intersection(*args)
Intersection = staticmethod(Intersection)
__swig_destroy__ = _snap.delete_TFltRect
TFltRect.Save = new_instancemethod(_snap.TFltRect_Save,None,TFltRect)
TFltRect.LoadXml = new_instancemethod(_snap.TFltRect_LoadXml,None,TFltRect)
TFltRect.SaveXml = new_instancemethod(_snap.TFltRect_SaveXml,None,TFltRect)
TFltRect.GetMnX = new_instancemethod(_snap.TFltRect_GetMnX,None,TFltRect)
TFltRect.GetMnY = new_instancemethod(_snap.TFltRect_GetMnY,None,TFltRect)
TFltRect.GetMxX = new_instancemethod(_snap.TFltRect_GetMxX,None,TFltRect)
TFltRect.GetMxY = new_instancemethod(_snap.TFltRect_GetMxY,None,TFltRect)
TFltRect.GetXLen = new_instancemethod(_snap.TFltRect_GetXLen,None,TFltRect)
TFltRect.GetYLen = new_instancemethod(_snap.TFltRect_GetYLen,None,TFltRect)
TFltRect.GetXCenter = new_instancemethod(_snap.TFltRect_GetXCenter,None,TFltRect)
TFltRect.GetYCenter = new_instancemethod(_snap.TFltRect_GetYCenter,None,TFltRect)
TFltRect.IsXYIn = new_instancemethod(_snap.TFltRect_IsXYIn,None,TFltRect)
TFltRect_swigregister = _snap.TFltRect_swigregister
TFltRect_swigregister(TFltRect)
def TFltRect_Intersection(*args):
"""
TFltRect_Intersection(TFltRect Rect1, TFltRect Rect2) -> bool
Parameters:
Rect1: TFltRect const &
Rect2: TFltRect const &
"""
return _snap.TFltRect_Intersection(*args)
class TIntV(object):
"""Proxy of C++ TVec<(TInt,int)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TIntV
def __init__(self, *args):
"""
__init__(TVec<(TInt,int)> self) -> TIntV
__init__(TVec<(TInt,int)> self, TIntV Vec) -> TIntV
Parameters:
Vec: TVec< TInt,int > const &
__init__(TVec<(TInt,int)> self, int const & _Vals) -> TIntV
Parameters:
_Vals: int const &
__init__(TVec<(TInt,int)> self, int const & _MxVals, int const & _Vals) -> TIntV
Parameters:
_MxVals: int const &
_Vals: int const &
__init__(TVec<(TInt,int)> self, TInt _ValT, int const & _Vals) -> TIntV
Parameters:
_ValT: TInt *
_Vals: int const &
__init__(TVec<(TInt,int)> self, TSIn SIn) -> TIntV
Parameters:
SIn: TSIn &
"""
_snap.TIntV_swiginit(self,_snap.new_TIntV(*args))
def Load(self, *args):
"""
Load(TIntV self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TIntV_Load(self, *args)
def Save(self, *args):
"""
Save(TIntV self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TIntV_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TIntV self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TIntV self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TIntV_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TIntV self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TIntV_SaveXml(self, *args)
def __add__(self, *args):
"""
__add__(TIntV self, TInt Val) -> TIntV
Parameters:
Val: TInt const &
"""
return _snap.TIntV___add__(self, *args)
def __eq__(self, *args):
"""
__eq__(TIntV self, TIntV Vec) -> bool
Parameters:
Vec: TVec< TInt,int > const &
"""
return _snap.TIntV___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntV self, TIntV Vec) -> bool
Parameters:
Vec: TVec< TInt,int > const &
"""
return _snap.TIntV___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetMemUsed(self)
def GetMemSize(self):
"""
GetMemSize(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetMemSize(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetSecHashCd(self)
def Gen(self, *args):
"""
Gen(TIntV self, int const & _Vals)
Parameters:
_Vals: int const &
Gen(TIntV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TIntV_Gen(self, *args)
def GenExt(self, *args):
"""
GenExt(TIntV self, TInt _ValT, int const & _Vals)
Parameters:
_ValT: TInt *
_Vals: int const &
"""
return _snap.TIntV_GenExt(self, *args)
def IsExt(self):
"""
IsExt(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_IsExt(self)
def Reserve(self, *args):
"""
Reserve(TIntV self, int const & _MxVals)
Parameters:
_MxVals: int const &
Reserve(TIntV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TIntV_Reserve(self, *args)
def Clr(self, *args):
"""
Clr(TIntV self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TIntV self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Clr(self, *args)
def Trunc(self, *args):
"""
Trunc(TIntV self, int const & _Vals=-1)
Parameters:
_Vals: int const &
Trunc(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Trunc(self, *args)
def Pack(self):
"""
Pack(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Pack(self)
def MoveFrom(self, *args):
"""
MoveFrom(TIntV self, TIntV Vec)
Parameters:
Vec: TVec< TInt,int > &
"""
return _snap.TIntV_MoveFrom(self, *args)
def Empty(self):
"""
Empty(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_Empty(self)
def Len(self):
"""
Len(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_Len(self)
def Reserved(self):
"""
Reserved(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_Reserved(self)
def Last(self, *args):
"""
Last(TIntV self) -> TInt
Last(TIntV self) -> TInt
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Last(self, *args)
def LastValN(self):
"""
LastValN(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_LastValN(self)
def LastLast(self, *args):
"""
LastLast(TIntV self) -> TInt
LastLast(TIntV self) -> TInt
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_LastLast(self, *args)
def BegI(self):
"""
BegI(TIntV self) -> TInt
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_BegI(self)
def EndI(self):
"""
EndI(TIntV self) -> TInt
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_EndI(self)
def GetI(self, *args):
"""
GetI(TIntV self, int const & ValN) -> TInt
Parameters:
ValN: int const &
"""
return _snap.TIntV_GetI(self, *args)
def AddV(self, *args):
"""
AddV(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_AddV(self, *args)
def AddSorted(self, *args):
"""
AddSorted(TIntV self, TInt Val, bool const & Asc=True, int const & _MxVals=-1) -> int
Parameters:
Val: TInt const &
Asc: bool const &
_MxVals: int const &
AddSorted(TIntV self, TInt Val, bool const & Asc=True) -> int
Parameters:
Val: TInt const &
Asc: bool const &
AddSorted(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_AddSorted(self, *args)
def AddBackSorted(self, *args):
"""
AddBackSorted(TIntV self, TInt Val, bool const & Asc) -> int
Parameters:
Val: TInt const &
Asc: bool const &
"""
return _snap.TIntV_AddBackSorted(self, *args)
def AddVMerged(self, *args):
"""
AddVMerged(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_AddVMerged(self, *args)
def AddUnique(self, *args):
"""
AddUnique(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_AddUnique(self, *args)
def GetVal(self, *args):
"""
GetVal(TIntV self, int const & ValN) -> TInt
Parameters:
ValN: int const &
GetVal(TIntV self, int const & ValN) -> TInt
Parameters:
ValN: int const &
"""
return _snap.TIntV_GetVal(self, *args)
def GetSubValV(self, *args):
"""
GetSubValV(TIntV self, int const & BValN, int const & EValN, TIntV ValV)
Parameters:
BValN: int const &
EValN: int const &
ValV: TVec< TInt,int > &
"""
return _snap.TIntV_GetSubValV(self, *args)
def Ins(self, *args):
"""
Ins(TIntV self, int const & ValN, TInt Val)
Parameters:
ValN: int const &
Val: TInt const &
"""
return _snap.TIntV_Ins(self, *args)
def Del(self, *args):
"""
Del(TIntV self, int const & ValN)
Parameters:
ValN: int const &
Del(TIntV self, int const & MnValN, int const & MxValN)
Parameters:
MnValN: int const &
MxValN: int const &
"""
return _snap.TIntV_Del(self, *args)
def DelLast(self):
"""
DelLast(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_DelLast(self)
def DelIfIn(self, *args):
"""
DelIfIn(TIntV self, TInt Val) -> bool
Parameters:
Val: TInt const &
"""
return _snap.TIntV_DelIfIn(self, *args)
def DelAll(self, *args):
"""
DelAll(TIntV self, TInt Val)
Parameters:
Val: TInt const &
"""
return _snap.TIntV_DelAll(self, *args)
def PutAll(self, *args):
"""
PutAll(TIntV self, TInt Val)
Parameters:
Val: TInt const &
"""
return _snap.TIntV_PutAll(self, *args)
def Swap(self, *args):
"""
Swap(TIntV self, TIntV Vec)
Parameters:
Vec: TVec< TInt,int > &
Swap(TIntV self, int const & ValN1, int const & ValN2)
Parameters:
ValN1: int const &
ValN2: int const &
"""
return _snap.TIntV_Swap(self, *args)
def SwapI(*args):
"""
SwapI(TInt LVal, TInt RVal)
Parameters:
LVal: TVec< TInt,int >::TIter
RVal: TVec< TInt,int >::TIter
"""
return _snap.TIntV_SwapI(*args)
SwapI = staticmethod(SwapI)
def NextPerm(self):
"""
NextPerm(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_NextPerm(self)
def PrevPerm(self):
"""
PrevPerm(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_PrevPerm(self)
def GetPivotValN(self, *args):
"""
GetPivotValN(TIntV self, int const & LValN, int const & RValN) -> int
Parameters:
LValN: int const &
RValN: int const &
"""
return _snap.TIntV_GetPivotValN(self, *args)
def BSort(self, *args):
"""
BSort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntV_BSort(self, *args)
def ISort(self, *args):
"""
ISort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntV_ISort(self, *args)
def Partition(self, *args):
"""
Partition(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc) -> int
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntV_Partition(self, *args)
def QSort(self, *args):
"""
QSort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntV_QSort(self, *args)
def Sort(self, Asc=True):
"""
Sort(TIntV self, bool const & Asc=True)
Parameters:
Asc: bool const &
Sort(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Sort(self, Asc)
def IsSorted(self, Asc=True):
"""
IsSorted(TIntV self, bool const & Asc=True) -> bool
Parameters:
Asc: bool const &
IsSorted(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_IsSorted(self, Asc)
def Shuffle(self, *args):
"""
Shuffle(TIntV self, TRnd Rnd)
Parameters:
Rnd: TRnd &
"""
return _snap.TIntV_Shuffle(self, *args)
def Reverse(self, *args):
"""
Reverse(TIntV self)
Reverse(TIntV self, int LValN, int RValN)
Parameters:
LValN: int
RValN: int
"""
return _snap.TIntV_Reverse(self, *args)
def Merge(self):
"""
Merge(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Merge(self)
def Intrs(self, *args):
"""
Intrs(TIntV self, TIntV ValV)
Parameters:
ValV: TVec< TInt,int > const &
Intrs(TIntV self, TIntV ValV, TIntV DstValV)
Parameters:
ValV: TVec< TInt,int > const &
DstValV: TVec< TInt,int > &
"""
return _snap.TIntV_Intrs(self, *args)
def Union(self, *args):
"""
Union(TIntV self, TIntV ValV)
Parameters:
ValV: TVec< TInt,int > const &
Union(TIntV self, TIntV ValV, TIntV DstValV)
Parameters:
ValV: TVec< TInt,int > const &
DstValV: TVec< TInt,int > &
"""
return _snap.TIntV_Union(self, *args)
def Diff(self, *args):
"""
Diff(TIntV self, TIntV ValV)
Parameters:
ValV: TVec< TInt,int > const &
Diff(TIntV self, TIntV ValV, TIntV DstValV)
Parameters:
ValV: TVec< TInt,int > const &
DstValV: TVec< TInt,int > &
"""
return _snap.TIntV_Diff(self, *args)
def IntrsLen(self, *args):
"""
IntrsLen(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_IntrsLen(self, *args)
def UnionLen(self, *args):
"""
UnionLen(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_UnionLen(self, *args)
def Count(self, *args):
"""
Count(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_Count(self, *args)
def SearchBin(self, *args):
"""
SearchBin(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
SearchBin(TIntV self, TInt Val, int & InsValN) -> int
Parameters:
Val: TInt const &
InsValN: int &
"""
return _snap.TIntV_SearchBin(self, *args)
def SearchForw(self, *args):
"""
SearchForw(TIntV self, TInt Val, int const & BValN=0) -> int
Parameters:
Val: TInt const &
BValN: int const &
SearchForw(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_SearchForw(self, *args)
def SearchBack(self, *args):
"""
SearchBack(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_SearchBack(self, *args)
def SearchVForw(self, *args):
"""
SearchVForw(TIntV self, TIntV ValV, int const & BValN=0) -> int
Parameters:
ValV: TVec< TInt,int > const &
BValN: int const &
SearchVForw(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_SearchVForw(self, *args)
def IsIn(self, *args):
"""
IsIn(TIntV self, TInt Val) -> bool
Parameters:
Val: TInt const &
IsIn(TIntV self, TInt Val, int & ValN) -> bool
Parameters:
Val: TInt const &
ValN: int &
"""
return _snap.TIntV_IsIn(self, *args)
def IsInBin(self, *args):
"""
IsInBin(TIntV self, TInt Val) -> bool
Parameters:
Val: TInt const &
"""
return _snap.TIntV_IsInBin(self, *args)
def GetDat(self, *args):
"""
GetDat(TIntV self, TInt Val) -> TInt
Parameters:
Val: TInt const &
"""
return _snap.TIntV_GetDat(self, *args)
def GetAddDat(self, *args):
"""
GetAddDat(TIntV self, TInt Val) -> TInt
Parameters:
Val: TInt const &
"""
return _snap.TIntV_GetAddDat(self, *args)
def GetMxValN(self):
"""
GetMxValN(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetMxValN(self)
def GetV(*args):
"""
GetV(TInt Val1) -> TIntV
Parameters:
Val1: TInt const &
GetV(TInt Val1, TInt Val2) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7, TInt Val8) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
Val8: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7, TInt Val8,
TInt Val9) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
Val8: TInt const &
Val9: TInt const &
"""
return _snap.TIntV_GetV(*args)
GetV = staticmethod(GetV)
def Add(self, *args):
"""
Add(TIntV self) -> int
Add(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
Add(TIntV self, TInt Val, int const & ResizeLen) -> int
Parameters:
Val: TInt const &
ResizeLen: int const &
Add(TIntV self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntV_Add(self, *args)
def AddMerged(self, *args):
"""
AddMerged(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
AddMerged(TIntV self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntV_AddMerged(self, *args)
TIntV.Load = new_instancemethod(_snap.TIntV_Load,None,TIntV)
TIntV.Save = new_instancemethod(_snap.TIntV_Save,None,TIntV)
TIntV.LoadXml = new_instancemethod(_snap.TIntV_LoadXml,None,TIntV)
TIntV.SaveXml = new_instancemethod(_snap.TIntV_SaveXml,None,TIntV)
TIntV.__add__ = new_instancemethod(_snap.TIntV___add__,None,TIntV)
TIntV.__eq__ = new_instancemethod(_snap.TIntV___eq__,None,TIntV)
TIntV.__lt__ = new_instancemethod(_snap.TIntV___lt__,None,TIntV)
TIntV.GetMemUsed = new_instancemethod(_snap.TIntV_GetMemUsed,None,TIntV)
TIntV.GetMemSize = new_instancemethod(_snap.TIntV_GetMemSize,None,TIntV)
TIntV.GetPrimHashCd = new_instancemethod(_snap.TIntV_GetPrimHashCd,None,TIntV)
TIntV.GetSecHashCd = new_instancemethod(_snap.TIntV_GetSecHashCd,None,TIntV)
TIntV.Gen = new_instancemethod(_snap.TIntV_Gen,None,TIntV)
TIntV.GenExt = new_instancemethod(_snap.TIntV_GenExt,None,TIntV)
TIntV.IsExt = new_instancemethod(_snap.TIntV_IsExt,None,TIntV)
TIntV.Reserve = new_instancemethod(_snap.TIntV_Reserve,None,TIntV)
TIntV.Clr = new_instancemethod(_snap.TIntV_Clr,None,TIntV)
TIntV.Trunc = new_instancemethod(_snap.TIntV_Trunc,None,TIntV)
TIntV.Pack = new_instancemethod(_snap.TIntV_Pack,None,TIntV)
TIntV.MoveFrom = new_instancemethod(_snap.TIntV_MoveFrom,None,TIntV)
TIntV.Empty = new_instancemethod(_snap.TIntV_Empty,None,TIntV)
TIntV.Len = new_instancemethod(_snap.TIntV_Len,None,TIntV)
TIntV.Reserved = new_instancemethod(_snap.TIntV_Reserved,None,TIntV)
TIntV.Last = new_instancemethod(_snap.TIntV_Last,None,TIntV)
TIntV.LastValN = new_instancemethod(_snap.TIntV_LastValN,None,TIntV)
TIntV.LastLast = new_instancemethod(_snap.TIntV_LastLast,None,TIntV)
TIntV.BegI = new_instancemethod(_snap.TIntV_BegI,None,TIntV)
TIntV.EndI = new_instancemethod(_snap.TIntV_EndI,None,TIntV)
TIntV.GetI = new_instancemethod(_snap.TIntV_GetI,None,TIntV)
TIntV.AddV = new_instancemethod(_snap.TIntV_AddV,None,TIntV)
TIntV.AddSorted = new_instancemethod(_snap.TIntV_AddSorted,None,TIntV)
TIntV.AddBackSorted = new_instancemethod(_snap.TIntV_AddBackSorted,None,TIntV)
TIntV.AddVMerged = new_instancemethod(_snap.TIntV_AddVMerged,None,TIntV)
TIntV.AddUnique = new_instancemethod(_snap.TIntV_AddUnique,None,TIntV)
TIntV.GetVal = new_instancemethod(_snap.TIntV_GetVal,None,TIntV)
TIntV.GetSubValV = new_instancemethod(_snap.TIntV_GetSubValV,None,TIntV)
TIntV.Ins = new_instancemethod(_snap.TIntV_Ins,None,TIntV)
TIntV.Del = new_instancemethod(_snap.TIntV_Del,None,TIntV)
TIntV.DelLast = new_instancemethod(_snap.TIntV_DelLast,None,TIntV)
TIntV.DelIfIn = new_instancemethod(_snap.TIntV_DelIfIn,None,TIntV)
TIntV.DelAll = new_instancemethod(_snap.TIntV_DelAll,None,TIntV)
TIntV.PutAll = new_instancemethod(_snap.TIntV_PutAll,None,TIntV)
TIntV.Swap = new_instancemethod(_snap.TIntV_Swap,None,TIntV)
TIntV.NextPerm = new_instancemethod(_snap.TIntV_NextPerm,None,TIntV)
TIntV.PrevPerm = new_instancemethod(_snap.TIntV_PrevPerm,None,TIntV)
TIntV.GetPivotValN = new_instancemethod(_snap.TIntV_GetPivotValN,None,TIntV)
TIntV.BSort = new_instancemethod(_snap.TIntV_BSort,None,TIntV)
TIntV.ISort = new_instancemethod(_snap.TIntV_ISort,None,TIntV)
TIntV.Partition = new_instancemethod(_snap.TIntV_Partition,None,TIntV)
TIntV.QSort = new_instancemethod(_snap.TIntV_QSort,None,TIntV)
TIntV.Sort = new_instancemethod(_snap.TIntV_Sort,None,TIntV)
TIntV.IsSorted = new_instancemethod(_snap.TIntV_IsSorted,None,TIntV)
TIntV.Shuffle = new_instancemethod(_snap.TIntV_Shuffle,None,TIntV)
TIntV.Reverse = new_instancemethod(_snap.TIntV_Reverse,None,TIntV)
TIntV.Merge = new_instancemethod(_snap.TIntV_Merge,None,TIntV)
TIntV.Intrs = new_instancemethod(_snap.TIntV_Intrs,None,TIntV)
TIntV.Union = new_instancemethod(_snap.TIntV_Union,None,TIntV)
TIntV.Diff = new_instancemethod(_snap.TIntV_Diff,None,TIntV)
TIntV.IntrsLen = new_instancemethod(_snap.TIntV_IntrsLen,None,TIntV)
TIntV.UnionLen = new_instancemethod(_snap.TIntV_UnionLen,None,TIntV)
TIntV.Count = new_instancemethod(_snap.TIntV_Count,None,TIntV)
TIntV.SearchBin = new_instancemethod(_snap.TIntV_SearchBin,None,TIntV)
TIntV.SearchForw = new_instancemethod(_snap.TIntV_SearchForw,None,TIntV)
TIntV.SearchBack = new_instancemethod(_snap.TIntV_SearchBack,None,TIntV)
TIntV.SearchVForw = new_instancemethod(_snap.TIntV_SearchVForw,None,TIntV)
TIntV.IsIn = new_instancemethod(_snap.TIntV_IsIn,None,TIntV)
TIntV.IsInBin = new_instancemethod(_snap.TIntV_IsInBin,None,TIntV)
TIntV.GetDat = new_instancemethod(_snap.TIntV_GetDat,None,TIntV)
TIntV.GetAddDat = new_instancemethod(_snap.TIntV_GetAddDat,None,TIntV)
TIntV.GetMxValN = new_instancemethod(_snap.TIntV_GetMxValN,None,TIntV)
TIntV.Add = new_instancemethod(_snap.TIntV_Add,None,TIntV)
TIntV.AddMerged = new_instancemethod(_snap.TIntV_AddMerged,None,TIntV)
TIntV_swigregister = _snap.TIntV_swigregister
TIntV_swigregister(TIntV)
def TIntV_SwapI(*args):
"""
TIntV_SwapI(TInt LVal, TInt RVal)
Parameters:
LVal: TVec< TInt,int >::TIter
RVal: TVec< TInt,int >::TIter
"""
return _snap.TIntV_SwapI(*args)
def TIntV_GetV(*args):
"""
GetV(TInt Val1) -> TIntV
Parameters:
Val1: TInt const &
GetV(TInt Val1, TInt Val2) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7, TInt Val8) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
Val8: TInt const &
TIntV_GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7, TInt Val8,
TInt Val9) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
Val8: TInt const &
Val9: TInt const &
"""
return _snap.TIntV_GetV(*args)
class TIntIntVV(object):
"""Proxy of C++ TVec<(TVec<(TInt,int)>,int)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TIntIntVV
def __init__(self, *args):
"""
__init__(TVec<(TVec<(TInt,int)>,int)> self) -> TIntIntVV
__init__(TVec<(TVec<(TInt,int)>,int)> self, TIntIntVV Vec) -> TIntIntVV
Parameters:
Vec: TVec< TVec< TInt,int >,int > const &
__init__(TVec<(TVec<(TInt,int)>,int)> self, int const & _Vals) -> TIntIntVV
Parameters:
_Vals: int const &
__init__(TVec<(TVec<(TInt,int)>,int)> self, int const & _MxVals, int const & _Vals) -> TIntIntVV
Parameters:
_MxVals: int const &
_Vals: int const &
__init__(TVec<(TVec<(TInt,int)>,int)> self, TIntV _ValT, int const & _Vals) -> TIntIntVV
Parameters:
_ValT: TVec< TInt,int > *
_Vals: int const &
__init__(TVec<(TVec<(TInt,int)>,int)> self, TSIn SIn) -> TIntIntVV
Parameters:
SIn: TSIn &
"""
_snap.TIntIntVV_swiginit(self,_snap.new_TIntIntVV(*args))
def Load(self, *args):
"""
Load(TIntIntVV self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TIntIntVV_Load(self, *args)
def Save(self, *args):
"""
Save(TIntIntVV self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TIntIntVV_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TIntIntVV self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TIntIntVV self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TIntIntVV_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TIntIntVV self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TIntIntVV_SaveXml(self, *args)
def __add__(self, *args):
"""
__add__(TIntIntVV self, TIntV Val) -> TIntIntVV
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV___add__(self, *args)
def __eq__(self, *args):
"""
__eq__(TIntIntVV self, TIntIntVV Vec) -> bool
Parameters:
Vec: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntIntVV self, TIntIntVV Vec) -> bool
Parameters:
Vec: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetMemUsed(self)
def GetMemSize(self):
"""
GetMemSize(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetMemSize(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetSecHashCd(self)
def Gen(self, *args):
"""
Gen(TIntIntVV self, int const & _Vals)
Parameters:
_Vals: int const &
Gen(TIntIntVV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TIntIntVV_Gen(self, *args)
def GenExt(self, *args):
"""
GenExt(TIntIntVV self, TIntV _ValT, int const & _Vals)
Parameters:
_ValT: TVec< TInt,int > *
_Vals: int const &
"""
return _snap.TIntIntVV_GenExt(self, *args)
def IsExt(self):
"""
IsExt(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_IsExt(self)
def Reserve(self, *args):
"""
Reserve(TIntIntVV self, int const & _MxVals)
Parameters:
_MxVals: int const &
Reserve(TIntIntVV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TIntIntVV_Reserve(self, *args)
def Clr(self, *args):
"""
Clr(TIntIntVV self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TIntIntVV self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Clr(self, *args)
def Trunc(self, *args):
"""
Trunc(TIntIntVV self, int const & _Vals=-1)
Parameters:
_Vals: int const &
Trunc(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Trunc(self, *args)
def Pack(self):
"""
Pack(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Pack(self)
def MoveFrom(self, *args):
"""
MoveFrom(TIntIntVV self, TIntIntVV Vec)
Parameters:
Vec: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_MoveFrom(self, *args)
def Empty(self):
"""
Empty(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_Empty(self)
def Len(self):
"""
Len(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_Len(self)
def Reserved(self):
"""
Reserved(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_Reserved(self)
def Last(self, *args):
"""
Last(TIntIntVV self) -> TIntV
Last(TIntIntVV self) -> TIntV
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Last(self, *args)
def LastValN(self):
"""
LastValN(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_LastValN(self)
def LastLast(self, *args):
"""
LastLast(TIntIntVV self) -> TIntV
LastLast(TIntIntVV self) -> TIntV
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_LastLast(self, *args)
def BegI(self):
"""
BegI(TIntIntVV self) -> TIntV
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_BegI(self)
def EndI(self):
"""
EndI(TIntIntVV self) -> TIntV
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_EndI(self)
def GetI(self, *args):
"""
GetI(TIntIntVV self, int const & ValN) -> TIntV
Parameters:
ValN: int const &
"""
return _snap.TIntIntVV_GetI(self, *args)
def AddV(self, *args):
"""
AddV(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_AddV(self, *args)
def AddSorted(self, *args):
"""
AddSorted(TIntIntVV self, TIntV Val, bool const & Asc=True, int const & _MxVals=-1) -> int
Parameters:
Val: TVec< TInt,int > const &
Asc: bool const &
_MxVals: int const &
AddSorted(TIntIntVV self, TIntV Val, bool const & Asc=True) -> int
Parameters:
Val: TVec< TInt,int > const &
Asc: bool const &
AddSorted(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_AddSorted(self, *args)
def AddBackSorted(self, *args):
"""
AddBackSorted(TIntIntVV self, TIntV Val, bool const & Asc) -> int
Parameters:
Val: TVec< TInt,int > const &
Asc: bool const &
"""
return _snap.TIntIntVV_AddBackSorted(self, *args)
def AddVMerged(self, *args):
"""
AddVMerged(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_AddVMerged(self, *args)
def AddUnique(self, *args):
"""
AddUnique(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_AddUnique(self, *args)
def GetVal(self, *args):
"""
GetVal(TIntIntVV self, int const & ValN) -> TIntV
Parameters:
ValN: int const &
GetVal(TIntIntVV self, int const & ValN) -> TIntV
Parameters:
ValN: int const &
"""
return _snap.TIntIntVV_GetVal(self, *args)
def GetSubValV(self, *args):
"""
GetSubValV(TIntIntVV self, int const & BValN, int const & EValN, TIntIntVV ValV)
Parameters:
BValN: int const &
EValN: int const &
ValV: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_GetSubValV(self, *args)
def Ins(self, *args):
"""
Ins(TIntIntVV self, int const & ValN, TIntV Val)
Parameters:
ValN: int const &
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_Ins(self, *args)
def Del(self, *args):
"""
Del(TIntIntVV self, int const & ValN)
Parameters:
ValN: int const &
Del(TIntIntVV self, int const & MnValN, int const & MxValN)
Parameters:
MnValN: int const &
MxValN: int const &
"""
return _snap.TIntIntVV_Del(self, *args)
def DelLast(self):
"""
DelLast(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_DelLast(self)
def DelIfIn(self, *args):
"""
DelIfIn(TIntIntVV self, TIntV Val) -> bool
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_DelIfIn(self, *args)
def DelAll(self, *args):
"""
DelAll(TIntIntVV self, TIntV Val)
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_DelAll(self, *args)
def PutAll(self, *args):
"""
PutAll(TIntIntVV self, TIntV Val)
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_PutAll(self, *args)
def Swap(self, *args):
"""
Swap(TIntIntVV self, TIntIntVV Vec)
Parameters:
Vec: TVec< TVec< TInt,int >,int > &
Swap(TIntIntVV self, int const & ValN1, int const & ValN2)
Parameters:
ValN1: int const &
ValN2: int const &
"""
return _snap.TIntIntVV_Swap(self, *args)
def SwapI(*args):
"""
SwapI(TIntV LVal, TIntV RVal)
Parameters:
LVal: TVec< TVec< TInt,int >,int >::TIter
RVal: TVec< TVec< TInt,int >,int >::TIter
"""
return _snap.TIntIntVV_SwapI(*args)
SwapI = staticmethod(SwapI)
def NextPerm(self):
"""
NextPerm(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_NextPerm(self)
def PrevPerm(self):
"""
PrevPerm(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_PrevPerm(self)
def GetPivotValN(self, *args):
"""
GetPivotValN(TIntIntVV self, int const & LValN, int const & RValN) -> int
Parameters:
LValN: int const &
RValN: int const &
"""
return _snap.TIntIntVV_GetPivotValN(self, *args)
def BSort(self, *args):
"""
BSort(TIntIntVV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntIntVV_BSort(self, *args)
def ISort(self, *args):
"""
ISort(TIntIntVV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntIntVV_ISort(self, *args)
def Partition(self, *args):
"""
Partition(TIntIntVV self, int const & MnLValN, int const & MxRValN, bool const & Asc) -> int
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntIntVV_Partition(self, *args)
def QSort(self, *args):
"""
QSort(TIntIntVV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntIntVV_QSort(self, *args)
def Sort(self, Asc=True):
"""
Sort(TIntIntVV self, bool const & Asc=True)
Parameters:
Asc: bool const &
Sort(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Sort(self, Asc)
def IsSorted(self, Asc=True):
"""
IsSorted(TIntIntVV self, bool const & Asc=True) -> bool
Parameters:
Asc: bool const &
IsSorted(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_IsSorted(self, Asc)
def Shuffle(self, *args):
"""
Shuffle(TIntIntVV self, TRnd Rnd)
Parameters:
Rnd: TRnd &
"""
return _snap.TIntIntVV_Shuffle(self, *args)
def Reverse(self, *args):
"""
Reverse(TIntIntVV self)
Reverse(TIntIntVV self, int LValN, int RValN)
Parameters:
LValN: int
RValN: int
"""
return _snap.TIntIntVV_Reverse(self, *args)
def Merge(self):
"""
Merge(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Merge(self)
def Intrs(self, *args):
"""
Intrs(TIntIntVV self, TIntIntVV ValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
Intrs(TIntIntVV self, TIntIntVV ValV, TIntIntVV DstValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
DstValV: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_Intrs(self, *args)
def Union(self, *args):
"""
Union(TIntIntVV self, TIntIntVV ValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
Union(TIntIntVV self, TIntIntVV ValV, TIntIntVV DstValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
DstValV: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_Union(self, *args)
def Diff(self, *args):
"""
Diff(TIntIntVV self, TIntIntVV ValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
Diff(TIntIntVV self, TIntIntVV ValV, TIntIntVV DstValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
DstValV: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_Diff(self, *args)
def IntrsLen(self, *args):
"""
IntrsLen(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_IntrsLen(self, *args)
def UnionLen(self, *args):
"""
UnionLen(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_UnionLen(self, *args)
def Count(self, *args):
"""
Count(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_Count(self, *args)
def SearchBin(self, *args):
"""
SearchBin(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
SearchBin(TIntIntVV self, TIntV Val, int & InsValN) -> int
Parameters:
Val: TVec< TInt,int > const &
InsValN: int &
"""
return _snap.TIntIntVV_SearchBin(self, *args)
def SearchForw(self, *args):
"""
SearchForw(TIntIntVV self, TIntV Val, int const & BValN=0) -> int
Parameters:
Val: TVec< TInt,int > const &
BValN: int const &
SearchForw(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_SearchForw(self, *args)
def SearchBack(self, *args):
"""
SearchBack(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_SearchBack(self, *args)
def SearchVForw(self, *args):
"""
SearchVForw(TIntIntVV self, TIntIntVV ValV, int const & BValN=0) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
BValN: int const &
SearchVForw(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_SearchVForw(self, *args)
def IsIn(self, *args):
"""
IsIn(TIntIntVV self, TIntV Val) -> bool
Parameters:
Val: TVec< TInt,int > const &
IsIn(TIntIntVV self, TIntV Val, int & ValN) -> bool
Parameters:
Val: TVec< TInt,int > const &
ValN: int &
"""
return _snap.TIntIntVV_IsIn(self, *args)
def IsInBin(self, *args):
"""
IsInBin(TIntIntVV self, TIntV Val) -> bool
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_IsInBin(self, *args)
def GetDat(self, *args):
"""
GetDat(TIntIntVV self, TIntV Val) -> TIntV
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetDat(self, *args)
def GetAddDat(self, *args):
"""
GetAddDat(TIntIntVV self, TIntV Val) -> TIntV
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetAddDat(self, *args)
def GetMxValN(self):
"""
GetMxValN(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetMxValN(self)
def GetV(*args):
"""
GetV(TIntV Val1) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7,
TIntV Val8) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
Val8: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7,
TIntV Val8, TIntV Val9) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
Val8: TVec< TInt,int > const &
Val9: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetV(*args)
GetV = staticmethod(GetV)
TIntIntVV.Load = new_instancemethod(_snap.TIntIntVV_Load,None,TIntIntVV)
TIntIntVV.Save = new_instancemethod(_snap.TIntIntVV_Save,None,TIntIntVV)
TIntIntVV.LoadXml = new_instancemethod(_snap.TIntIntVV_LoadXml,None,TIntIntVV)
TIntIntVV.SaveXml = new_instancemethod(_snap.TIntIntVV_SaveXml,None,TIntIntVV)
TIntIntVV.__add__ = new_instancemethod(_snap.TIntIntVV___add__,None,TIntIntVV)
TIntIntVV.__eq__ = new_instancemethod(_snap.TIntIntVV___eq__,None,TIntIntVV)
TIntIntVV.__lt__ = new_instancemethod(_snap.TIntIntVV___lt__,None,TIntIntVV)
TIntIntVV.GetMemUsed = new_instancemethod(_snap.TIntIntVV_GetMemUsed,None,TIntIntVV)
TIntIntVV.GetMemSize = new_instancemethod(_snap.TIntIntVV_GetMemSize,None,TIntIntVV)
TIntIntVV.GetPrimHashCd = new_instancemethod(_snap.TIntIntVV_GetPrimHashCd,None,TIntIntVV)
TIntIntVV.GetSecHashCd = new_instancemethod(_snap.TIntIntVV_GetSecHashCd,None,TIntIntVV)
TIntIntVV.Gen = new_instancemethod(_snap.TIntIntVV_Gen,None,TIntIntVV)
TIntIntVV.GenExt = new_instancemethod(_snap.TIntIntVV_GenExt,None,TIntIntVV)
TIntIntVV.IsExt = new_instancemethod(_snap.TIntIntVV_IsExt,None,TIntIntVV)
TIntIntVV.Reserve = new_instancemethod(_snap.TIntIntVV_Reserve,None,TIntIntVV)
TIntIntVV.Clr = new_instancemethod(_snap.TIntIntVV_Clr,None,TIntIntVV)
TIntIntVV.Trunc = new_instancemethod(_snap.TIntIntVV_Trunc,None,TIntIntVV)
TIntIntVV.Pack = new_instancemethod(_snap.TIntIntVV_Pack,None,TIntIntVV)
TIntIntVV.MoveFrom = new_instancemethod(_snap.TIntIntVV_MoveFrom,None,TIntIntVV)
TIntIntVV.Empty = new_instancemethod(_snap.TIntIntVV_Empty,None,TIntIntVV)
TIntIntVV.Len = new_instancemethod(_snap.TIntIntVV_Len,None,TIntIntVV)
TIntIntVV.Reserved = new_instancemethod(_snap.TIntIntVV_Reserved,None,TIntIntVV)
TIntIntVV.Last = new_instancemethod(_snap.TIntIntVV_Last,None,TIntIntVV)
TIntIntVV.LastValN = new_instancemethod(_snap.TIntIntVV_LastValN,None,TIntIntVV)
TIntIntVV.LastLast = new_instancemethod(_snap.TIntIntVV_LastLast,None,TIntIntVV)
TIntIntVV.BegI = new_instancemethod(_snap.TIntIntVV_BegI,None,TIntIntVV)
TIntIntVV.EndI = new_instancemethod(_snap.TIntIntVV_EndI,None,TIntIntVV)
TIntIntVV.GetI = new_instancemethod(_snap.TIntIntVV_GetI,None,TIntIntVV)
TIntIntVV.AddV = new_instancemethod(_snap.TIntIntVV_AddV,None,TIntIntVV)
TIntIntVV.AddSorted = new_instancemethod(_snap.TIntIntVV_AddSorted,None,TIntIntVV)
TIntIntVV.AddBackSorted = new_instancemethod(_snap.TIntIntVV_AddBackSorted,None,TIntIntVV)
TIntIntVV.AddVMerged = new_instancemethod(_snap.TIntIntVV_AddVMerged,None,TIntIntVV)
TIntIntVV.AddUnique = new_instancemethod(_snap.TIntIntVV_AddUnique,None,TIntIntVV)
TIntIntVV.GetVal = new_instancemethod(_snap.TIntIntVV_GetVal,None,TIntIntVV)
TIntIntVV.GetSubValV = new_instancemethod(_snap.TIntIntVV_GetSubValV,None,TIntIntVV)
TIntIntVV.Ins = new_instancemethod(_snap.TIntIntVV_Ins,None,TIntIntVV)
TIntIntVV.Del = new_instancemethod(_snap.TIntIntVV_Del,None,TIntIntVV)
TIntIntVV.DelLast = new_instancemethod(_snap.TIntIntVV_DelLast,None,TIntIntVV)
TIntIntVV.DelIfIn = new_instancemethod(_snap.TIntIntVV_DelIfIn,None,TIntIntVV)
TIntIntVV.DelAll = new_instancemethod(_snap.TIntIntVV_DelAll,None,TIntIntVV)
TIntIntVV.PutAll = new_instancemethod(_snap.TIntIntVV_PutAll,None,TIntIntVV)
TIntIntVV.Swap = new_instancemethod(_snap.TIntIntVV_Swap,None,TIntIntVV)
TIntIntVV.NextPerm = new_instancemethod(_snap.TIntIntVV_NextPerm,None,TIntIntVV)
TIntIntVV.PrevPerm = new_instancemethod(_snap.TIntIntVV_PrevPerm,None,TIntIntVV)
TIntIntVV.GetPivotValN = new_instancemethod(_snap.TIntIntVV_GetPivotValN,None,TIntIntVV)
TIntIntVV.BSort = new_instancemethod(_snap.TIntIntVV_BSort,None,TIntIntVV)
TIntIntVV.ISort = new_instancemethod(_snap.TIntIntVV_ISort,None,TIntIntVV)
TIntIntVV.Partition = new_instancemethod(_snap.TIntIntVV_Partition,None,TIntIntVV)
TIntIntVV.QSort = new_instancemethod(_snap.TIntIntVV_QSort,None,TIntIntVV)
TIntIntVV.Sort = new_instancemethod(_snap.TIntIntVV_Sort,None,TIntIntVV)
TIntIntVV.IsSorted = new_instancemethod(_snap.TIntIntVV_IsSorted,None,TIntIntVV)
TIntIntVV.Shuffle = new_instancemethod(_snap.TIntIntVV_Shuffle,None,TIntIntVV)
TIntIntVV.Reverse = new_instancemethod(_snap.TIntIntVV_Reverse,None,TIntIntVV)
TIntIntVV.Merge = new_instancemethod(_snap.TIntIntVV_Merge,None,TIntIntVV)
TIntIntVV.Intrs = new_instancemethod(_snap.TIntIntVV_Intrs,None,TIntIntVV)
TIntIntVV.Union = new_instancemethod(_snap.TIntIntVV_Union,None,TIntIntVV)
TIntIntVV.Diff = new_instancemethod(_snap.TIntIntVV_Diff,None,TIntIntVV)
TIntIntVV.IntrsLen = new_instancemethod(_snap.TIntIntVV_IntrsLen,None,TIntIntVV)
TIntIntVV.UnionLen = new_instancemethod(_snap.TIntIntVV_UnionLen,None,TIntIntVV)
TIntIntVV.Count = new_instancemethod(_snap.TIntIntVV_Count,None,TIntIntVV)
TIntIntVV.SearchBin = new_instancemethod(_snap.TIntIntVV_SearchBin,None,TIntIntVV)
TIntIntVV.SearchForw = new_instancemethod(_snap.TIntIntVV_SearchForw,None,TIntIntVV)
TIntIntVV.SearchBack = new_instancemethod(_snap.TIntIntVV_SearchBack,None,TIntIntVV)
TIntIntVV.SearchVForw = new_instancemethod(_snap.TIntIntVV_SearchVForw,None,TIntIntVV)
TIntIntVV.IsIn = new_instancemethod(_snap.TIntIntVV_IsIn,None,TIntIntVV)
TIntIntVV.IsInBin = new_instancemethod(_snap.TIntIntVV_IsInBin,None,TIntIntVV)
TIntIntVV.GetDat = new_instancemethod(_snap.TIntIntVV_GetDat,None,TIntIntVV)
TIntIntVV.GetAddDat = new_instancemethod(_snap.TIntIntVV_GetAddDat,None,TIntIntVV)
TIntIntVV.GetMxValN = new_instancemethod(_snap.TIntIntVV_GetMxValN,None,TIntIntVV)
TIntIntVV_swigregister = _snap.TIntIntVV_swigregister
TIntIntVV_swigregister(TIntIntVV)
def TIntIntVV_SwapI(*args):
"""
TIntIntVV_SwapI(TIntV LVal, TIntV RVal)
Parameters:
LVal: TVec< TVec< TInt,int >,int >::TIter
RVal: TVec< TVec< TInt,int >,int >::TIter
"""
return _snap.TIntIntVV_SwapI(*args)
def TIntIntVV_GetV(*args):
"""
GetV(TIntV Val1) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7,
TIntV Val8) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
Val8: TVec< TInt,int > const &
TIntIntVV_GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7,
TIntV Val8, TIntV Val9) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
Val8: TVec< TInt,int > const &
Val9: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetV(*args)
class TIntIntVH(object):
"""Proxy of C++ THash<(TInt,TVec<(TInt,int)>)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
HashPrimes = _snap.TIntIntVH_HashPrimes
def __init__(self, *args):
"""
__init__(THash<(TInt,TVec<(TInt,int)>)> self) -> TIntIntVH
__init__(THash<(TInt,TVec<(TInt,int)>)> self, TIntIntVH Hash) -> TIntIntVH
Parameters:
Hash: THash< TInt,TVec< TInt,int > > const &
__init__(THash<(TInt,TVec<(TInt,int)>)> self, int const & ExpectVals, bool const & _AutoSizeP=False) -> TIntIntVH
Parameters:
ExpectVals: int const &
_AutoSizeP: bool const &
__init__(THash<(TInt,TVec<(TInt,int)>)> self, int const & ExpectVals) -> TIntIntVH
Parameters:
ExpectVals: int const &
__init__(THash<(TInt,TVec<(TInt,int)>)> self, TSIn SIn) -> TIntIntVH
Parameters:
SIn: TSIn &
"""
_snap.TIntIntVH_swiginit(self,_snap.new_TIntIntVH(*args))
def Load(self, *args):
"""
Load(TIntIntVH self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TIntIntVH_Load(self, *args)
def Save(self, *args):
"""
Save(TIntIntVH self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TIntIntVH_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TIntIntVH self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TIntIntVH self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TIntIntVH_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TIntIntVH self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TIntIntVH_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TIntIntVH self, TIntIntVH Hash) -> bool
Parameters:
Hash: THash< TInt,TVec< TInt,int > > const &
"""
return _snap.TIntIntVH___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntIntVH self, TIntIntVH Hash) -> bool
Parameters:
Hash: THash< TInt,TVec< TInt,int > > const &
"""
return _snap.TIntIntVH___lt__(self, *args)
def __call__(self, *args):
"""
__call__(TIntIntVH self, TInt Key) -> TIntV
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH___call__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TIntIntVH self) -> ::TSize
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_GetMemUsed(self)
def BegI(self):
"""
BegI(TIntIntVH self) -> THash< TInt,TVec< TInt,int > >::TIter
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_BegI(self)
def EndI(self):
"""
EndI(TIntIntVH self) -> THash< TInt,TVec< TInt,int > >::TIter
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_EndI(self)
def GetI(self, *args):
"""
GetI(TIntIntVH self, TInt Key) -> THash< TInt,TVec< TInt,int > >::TIter
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_GetI(self, *args)
def Gen(self, *args):
"""
Gen(TIntIntVH self, int const & ExpectVals)
Parameters:
ExpectVals: int const &
"""
return _snap.TIntIntVH_Gen(self, *args)
def Clr(self, *args):
"""
Clr(TIntIntVH self, bool const & DoDel=True, int const & NoDelLim=-1, bool const & ResetDat=True)
Parameters:
DoDel: bool const &
NoDelLim: int const &
ResetDat: bool const &
Clr(TIntIntVH self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TIntIntVH self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_Clr(self, *args)
def Empty(self):
"""
Empty(TIntIntVH self) -> bool
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_Empty(self)
def Len(self):
"""
Len(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_Len(self)
def GetPorts(self):
"""
GetPorts(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_GetPorts(self)
def IsAutoSize(self):
"""
IsAutoSize(TIntIntVH self) -> bool
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_IsAutoSize(self)
def GetMxKeyIds(self):
"""
GetMxKeyIds(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_GetMxKeyIds(self)
def GetReservedKeyIds(self):
"""
GetReservedKeyIds(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_GetReservedKeyIds(self)
def IsKeyIdEqKeyN(self):
"""
IsKeyIdEqKeyN(TIntIntVH self) -> bool
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_IsKeyIdEqKeyN(self)
def DelKey(self, *args):
"""
DelKey(TIntIntVH self, TInt Key)
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_DelKey(self, *args)
def DelIfKey(self, *args):
"""
DelIfKey(TIntIntVH self, TInt Key) -> bool
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_DelIfKey(self, *args)
def DelKeyId(self, *args):
"""
DelKeyId(TIntIntVH self, int const & KeyId)
Parameters:
KeyId: int const &
"""
return _snap.TIntIntVH_DelKeyId(self, *args)
def DelKeyIdV(self, *args):
"""
DelKeyIdV(TIntIntVH self, TIntV KeyIdV)
Parameters:
KeyIdV: TIntV const &
"""
return _snap.TIntIntVH_DelKeyIdV(self, *args)
def MarkDelKey(self, *args):
"""
MarkDelKey(TIntIntVH self, TInt Key)
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_MarkDelKey(self, *args)
def MarkDelKeyId(self, *args):
"""
MarkDelKeyId(TIntIntVH self, int const & KeyId)
Parameters:
KeyId: int const &
"""
return _snap.TIntIntVH_MarkDelKeyId(self, *args)
def GetKey(self, *args):
"""
GetKey(TIntIntVH self, int const & KeyId) -> TInt
Parameters:
KeyId: int const &
"""
return _snap.TIntIntVH_GetKey(self, *args)
def GetKeyId(self, *args):
"""
GetKeyId(TIntIntVH self, TInt Key) -> int
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_GetKeyId(self, *args)
def GetRndKeyId(self, *args):
"""
GetRndKeyId(TIntIntVH self, TRnd Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndKeyId(TIntIntVH self, TRnd Rnd, double const & EmptyFrac) -> int
Parameters:
Rnd: TRnd &
EmptyFrac: double const &
"""
return _snap.TIntIntVH_GetRndKeyId(self, *args)
def IsKeyId(self, *args):
"""
IsKeyId(TIntIntVH self, int const & KeyId) -> bool
Parameters:
KeyId: int const &
"""
return _snap.TIntIntVH_IsKeyId(self, *args)
def GetKeyDat(self, *args):
"""
GetKeyDat(TIntIntVH self, int const & KeyId, TInt Key, TIntV Dat)
Parameters:
KeyId: int const &
Key: TInt &
Dat: TVec< TInt,int > &
"""
return _snap.TIntIntVH_GetKeyDat(self, *args)
def IsKeyGetDat(self, *args):
"""
IsKeyGetDat(TIntIntVH self, TInt Key, TIntV Dat) -> bool
Parameters:
Key: TInt const &
Dat: TVec< TInt,int > &
"""
return _snap.TIntIntVH_IsKeyGetDat(self, *args)
def FFirstKeyId(self):
"""
FFirstKeyId(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_FFirstKeyId(self)
def FNextKeyId(self, *args):
"""
FNextKeyId(TIntIntVH self, int & KeyId) -> bool
Parameters:
KeyId: int &
"""
return _snap.TIntIntVH_FNextKeyId(self, *args)
def GetKeyV(self, *args):
"""
GetKeyV(TIntIntVH self, TIntV KeyV)
Parameters:
KeyV: TVec< TInt > &
"""
return _snap.TIntIntVH_GetKeyV(self, *args)
def GetDatV(self, *args):
"""
GetDatV(TIntIntVH self, TIntIntVV DatV)
Parameters:
DatV: TVec< TVec< TInt,int > > &
"""
return _snap.TIntIntVH_GetDatV(self, *args)
def GetKeyDatPrV(self, *args):
"""
GetKeyDatPrV(TIntIntVH self, TVec< TPair< TInt,TVec< TInt,int > > > & KeyDatPrV)
Parameters:
KeyDatPrV: TVec< TPair< TInt,TVec< TInt,int > > > &
"""
return _snap.TIntIntVH_GetKeyDatPrV(self, *args)
def GetDatKeyPrV(self, *args):
"""
GetDatKeyPrV(TIntIntVH self, TVec< TPair< TVec< TInt,int >,TInt > > & DatKeyPrV)
Parameters:
DatKeyPrV: TVec< TPair< TVec< TInt,int >,TInt > > &
"""
return _snap.TIntIntVH_GetDatKeyPrV(self, *args)
def GetKeyDatKdV(self, *args):
"""
GetKeyDatKdV(TIntIntVH self, TVec< TKeyDat< TInt,TVec< TInt,int > > > & KeyDatKdV)
Parameters:
KeyDatKdV: TVec< TKeyDat< TInt,TVec< TInt,int > > > &
"""
return _snap.TIntIntVH_GetKeyDatKdV(self, *args)
def GetDatKeyKdV(self, *args):
"""
GetDatKeyKdV(TIntIntVH self, TVec< TKeyDat< TVec< TInt,int >,TInt > > & DatKeyKdV)
Parameters:
DatKeyKdV: TVec< TKeyDat< TVec< TInt,int >,TInt > > &
"""
return _snap.TIntIntVH_GetDatKeyKdV(self, *args)
def Swap(self, *args):
"""
Swap(TIntIntVH self, TIntIntVH Hash)
Parameters:
Hash: THash< TInt,TVec< TInt,int > > &
"""
return _snap.TIntIntVH_Swap(self, *args)
def Defrag(self):
"""
Defrag(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_Defrag(self)
def Pack(self):
"""
Pack(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_Pack(self)
def Sort(self, *args):
"""
Sort(TIntIntVH self, bool const & CmpKey, bool const & Asc)
Parameters:
CmpKey: bool const &
Asc: bool const &
"""
return _snap.TIntIntVH_Sort(self, *args)
def SortByKey(self, Asc=True):
"""
SortByKey(TIntIntVH self, bool const & Asc=True)
Parameters:
Asc: bool const &
SortByKey(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_SortByKey(self, Asc)
def SortByDat(self, Asc=True):
"""
SortByDat(TIntIntVH self, bool const & Asc=True)
Parameters:
Asc: bool const &
SortByDat(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_SortByDat(self, Asc)
def AddKey(self, *args):
"""
AddKey(TIntIntVH self, TInt Key) -> int
Parameters:
Key: TInt const &
AddKey(TIntIntVH self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntIntVH_AddKey(self, *args)
def IsKey(self, *args):
"""
IsKey(TIntIntVH self, TInt Key) -> bool
Parameters:
Key: TInt const &
IsKey(TIntIntVH self, TInt Key, int & KeyId) -> bool
Parameters:
Key: TInt const &
KeyId: int &
IsKey(TIntIntVH self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntIntVH_IsKey(self, *args)
def GetDat(self, *args):
"""
GetDat(TIntIntVH self, TInt Key) -> TIntV
Parameters:
Key: TInt const &
GetDat(TIntIntVH self, TInt Key) -> TIntV
Parameters:
Key: TInt const &
GetDat(TIntIntVH self, int Val) -> TIntV
Parameters:
Val: int
"""
return _snap.TIntIntVH_GetDat(self, *args)
__swig_destroy__ = _snap.delete_TIntIntVH
TIntIntVH.Load = new_instancemethod(_snap.TIntIntVH_Load,None,TIntIntVH)
TIntIntVH.Save = new_instancemethod(_snap.TIntIntVH_Save,None,TIntIntVH)
TIntIntVH.LoadXml = new_instancemethod(_snap.TIntIntVH_LoadXml,None,TIntIntVH)
TIntIntVH.SaveXml = new_instancemethod(_snap.TIntIntVH_SaveXml,None,TIntIntVH)
TIntIntVH.__eq__ = new_instancemethod(_snap.TIntIntVH___eq__,None,TIntIntVH)
TIntIntVH.__lt__ = new_instancemethod(_snap.TIntIntVH___lt__,None,TIntIntVH)
TIntIntVH.__call__ = new_instancemethod(_snap.TIntIntVH___call__,None,TIntIntVH)
TIntIntVH.GetMemUsed = new_instancemethod(_snap.TIntIntVH_GetMemUsed,None,TIntIntVH)
TIntIntVH.BegI = new_instancemethod(_snap.TIntIntVH_BegI,None,TIntIntVH)
TIntIntVH.EndI = new_instancemethod(_snap.TIntIntVH_EndI,None,TIntIntVH)
TIntIntVH.GetI = new_instancemethod(_snap.TIntIntVH_GetI,None,TIntIntVH)
TIntIntVH.Gen = new_instancemethod(_snap.TIntIntVH_Gen,None,TIntIntVH)
TIntIntVH.Clr = new_instancemethod(_snap.TIntIntVH_Clr,None,TIntIntVH)
TIntIntVH.Empty = new_instancemethod(_snap.TIntIntVH_Empty,None,TIntIntVH)
TIntIntVH.Len = new_instancemethod(_snap.TIntIntVH_Len,None,TIntIntVH)
TIntIntVH.GetPorts = new_instancemethod(_snap.TIntIntVH_GetPorts,None,TIntIntVH)
TIntIntVH.IsAutoSize = new_instancemethod(_snap.TIntIntVH_IsAutoSize,None,TIntIntVH)
TIntIntVH.GetMxKeyIds = new_instancemethod(_snap.TIntIntVH_GetMxKeyIds,None,TIntIntVH)
TIntIntVH.GetReservedKeyIds = new_instancemethod(_snap.TIntIntVH_GetReservedKeyIds,None,TIntIntVH)
TIntIntVH.IsKeyIdEqKeyN = new_instancemethod(_snap.TIntIntVH_IsKeyIdEqKeyN,None,TIntIntVH)
TIntIntVH.DelKey = new_instancemethod(_snap.TIntIntVH_DelKey,None,TIntIntVH)
TIntIntVH.DelIfKey = new_instancemethod(_snap.TIntIntVH_DelIfKey,None,TIntIntVH)
TIntIntVH.DelKeyId = new_instancemethod(_snap.TIntIntVH_DelKeyId,None,TIntIntVH)
TIntIntVH.DelKeyIdV = new_instancemethod(_snap.TIntIntVH_DelKeyIdV,None,TIntIntVH)
TIntIntVH.MarkDelKey = new_instancemethod(_snap.TIntIntVH_MarkDelKey,None,TIntIntVH)
TIntIntVH.MarkDelKeyId = new_instancemethod(_snap.TIntIntVH_MarkDelKeyId,None,TIntIntVH)
TIntIntVH.GetKey = new_instancemethod(_snap.TIntIntVH_GetKey,None,TIntIntVH)
TIntIntVH.GetKeyId = new_instancemethod(_snap.TIntIntVH_GetKeyId,None,TIntIntVH)
TIntIntVH.GetRndKeyId = new_instancemethod(_snap.TIntIntVH_GetRndKeyId,None,TIntIntVH)
TIntIntVH.IsKeyId = new_instancemethod(_snap.TIntIntVH_IsKeyId,None,TIntIntVH)
TIntIntVH.GetKeyDat = new_instancemethod(_snap.TIntIntVH_GetKeyDat,None,TIntIntVH)
TIntIntVH.IsKeyGetDat = new_instancemethod(_snap.TIntIntVH_IsKeyGetDat,None,TIntIntVH)
TIntIntVH.FFirstKeyId = new_instancemethod(_snap.TIntIntVH_FFirstKeyId,None,TIntIntVH)
TIntIntVH.FNextKeyId = new_instancemethod(_snap.TIntIntVH_FNextKeyId,None,TIntIntVH)
TIntIntVH.GetKeyV = new_instancemethod(_snap.TIntIntVH_GetKeyV,None,TIntIntVH)
TIntIntVH.GetDatV = new_instancemethod(_snap.TIntIntVH_GetDatV,None,TIntIntVH)
TIntIntVH.GetKeyDatPrV = new_instancemethod(_snap.TIntIntVH_GetKeyDatPrV,None,TIntIntVH)
TIntIntVH.GetDatKeyPrV = new_instancemethod(_snap.TIntIntVH_GetDatKeyPrV,None,TIntIntVH)
TIntIntVH.GetKeyDatKdV = new_instancemethod(_snap.TIntIntVH_GetKeyDatKdV,None,TIntIntVH)
TIntIntVH.GetDatKeyKdV = new_instancemethod(_snap.TIntIntVH_GetDatKeyKdV,None,TIntIntVH)
TIntIntVH.Swap = new_instancemethod(_snap.TIntIntVH_Swap,None,TIntIntVH)
TIntIntVH.Defrag = new_instancemethod(_snap.TIntIntVH_Defrag,None,TIntIntVH)
TIntIntVH.Pack = new_instancemethod(_snap.TIntIntVH_Pack,None,TIntIntVH)
TIntIntVH.Sort = new_instancemethod(_snap.TIntIntVH_Sort,None,TIntIntVH)
TIntIntVH.SortByKey = new_instancemethod(_snap.TIntIntVH_SortByKey,None,TIntIntVH)
TIntIntVH.SortByDat = new_instancemethod(_snap.TIntIntVH_SortByDat,None,TIntIntVH)
TIntIntVH.AddKey = new_instancemethod(_snap.TIntIntVH_AddKey,None,TIntIntVH)
TIntIntVH.IsKey = new_instancemethod(_snap.TIntIntVH_IsKey,None,TIntIntVH)
TIntIntVH.GetDat = new_instancemethod(_snap.TIntIntVH_GetDat,None,TIntIntVH)
TIntIntVH_swigregister = _snap.TIntIntVH_swigregister
TIntIntVH_swigregister(TIntIntVH)
class TIntH(object):
"""Proxy of C++ THash<(TInt,TInt)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
HashPrimes = _snap.TIntH_HashPrimes
def __init__(self, *args):
"""
__init__(THash<(TInt,TInt)> self) -> TIntH
__init__(THash<(TInt,TInt)> self, TIntH Hash) -> TIntH
Parameters:
Hash: THash< TInt,TInt > const &
__init__(THash<(TInt,TInt)> self, int const & ExpectVals, bool const & _AutoSizeP=False) -> TIntH
Parameters:
ExpectVals: int const &
_AutoSizeP: bool const &
__init__(THash<(TInt,TInt)> self, int const & ExpectVals) -> TIntH
Parameters:
ExpectVals: int const &
__init__(THash<(TInt,TInt)> self, TSIn SIn) -> TIntH
Parameters:
SIn: TSIn &
"""
_snap.TIntH_swiginit(self,_snap.new_TIntH(*args))
def Load(self, *args):
"""
Load(TIntH self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TIntH_Load(self, *args)
def Save(self, *args):
"""
Save(TIntH self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TIntH_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TIntH self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TIntH self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TIntH_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TIntH self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TIntH_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TIntH self, TIntH Hash) -> bool
Parameters:
Hash: THash< TInt,TInt > const &
"""
return _snap.TIntH___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntH self, TIntH Hash) -> bool
Parameters:
Hash: THash< TInt,TInt > const &
"""
return _snap.TIntH___lt__(self, *args)
def __call__(self, *args):
"""
__call__(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
"""
return _snap.TIntH___call__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TIntH self) -> ::TSize
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_GetMemUsed(self)
def BegI(self):
"""
BegI(TIntH self) -> TIntHI
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_BegI(self)
def EndI(self):
"""
EndI(TIntH self) -> TIntHI
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_EndI(self)
def GetI(self, *args):
"""
GetI(TIntH self, TInt Key) -> TIntHI
Parameters:
Key: TInt const &
"""
return _snap.TIntH_GetI(self, *args)
def Gen(self, *args):
"""
Gen(TIntH self, int const & ExpectVals)
Parameters:
ExpectVals: int const &
"""
return _snap.TIntH_Gen(self, *args)
def Clr(self, *args):
"""
Clr(TIntH self, bool const & DoDel=True, int const & NoDelLim=-1, bool const & ResetDat=True)
Parameters:
DoDel: bool const &
NoDelLim: int const &
ResetDat: bool const &
Clr(TIntH self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TIntH self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_Clr(self, *args)
def Empty(self):
"""
Empty(TIntH self) -> bool
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_Empty(self)
def Len(self):
"""
Len(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_Len(self)
def GetPorts(self):
"""
GetPorts(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_GetPorts(self)
def IsAutoSize(self):
"""
IsAutoSize(TIntH self) -> bool
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_IsAutoSize(self)
def GetMxKeyIds(self):
"""
GetMxKeyIds(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_GetMxKeyIds(self)
def GetReservedKeyIds(self):
"""
GetReservedKeyIds(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_GetReservedKeyIds(self)
def IsKeyIdEqKeyN(self):
"""
IsKeyIdEqKeyN(TIntH self) -> bool
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_IsKeyIdEqKeyN(self)
def AddDatId(self, *args):
"""
AddDatId(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
"""
return _snap.TIntH_AddDatId(self, *args)
def DelKey(self, *args):
"""
DelKey(TIntH self, TInt Key)
Parameters:
Key: TInt const &
"""
return _snap.TIntH_DelKey(self, *args)
def DelIfKey(self, *args):
"""
DelIfKey(TIntH self, TInt Key) -> bool
Parameters:
Key: TInt const &
"""
return _snap.TIntH_DelIfKey(self, *args)
def DelKeyId(self, *args):
"""
DelKeyId(TIntH self, int const & KeyId)
Parameters:
KeyId: int const &
"""
return _snap.TIntH_DelKeyId(self, *args)
def DelKeyIdV(self, *args):
"""
DelKeyIdV(TIntH self, TIntV KeyIdV)
Parameters:
KeyIdV: TIntV const &
"""
return _snap.TIntH_DelKeyIdV(self, *args)
def MarkDelKey(self, *args):
"""
MarkDelKey(TIntH self, TInt Key)
Parameters:
Key: TInt const &
"""
return _snap.TIntH_MarkDelKey(self, *args)
def MarkDelKeyId(self, *args):
"""
MarkDelKeyId(TIntH self, int const & KeyId)
Parameters:
KeyId: int const &
"""
return _snap.TIntH_MarkDelKeyId(self, *args)
def GetKey(self, *args):
"""
GetKey(TIntH self, int const & KeyId) -> TInt
Parameters:
KeyId: int const &
"""
return _snap.TIntH_GetKey(self, *args)
def GetKeyId(self, *args):
"""
GetKeyId(TIntH self, TInt Key) -> int
Parameters:
Key: TInt const &
"""
return _snap.TIntH_GetKeyId(self, *args)
def GetRndKeyId(self, *args):
"""
GetRndKeyId(TIntH self, TRnd Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndKeyId(TIntH self, TRnd Rnd, double const & EmptyFrac) -> int
Parameters:
Rnd: TRnd &
EmptyFrac: double const &
"""
return _snap.TIntH_GetRndKeyId(self, *args)
def IsKeyId(self, *args):
"""
IsKeyId(TIntH self, int const & KeyId) -> bool
Parameters:
KeyId: int const &
"""
return _snap.TIntH_IsKeyId(self, *args)
def GetKeyDat(self, *args):
"""
GetKeyDat(TIntH self, int const & KeyId, TInt Key, TInt Dat)
Parameters:
KeyId: int const &
Key: TInt &
Dat: TInt &
"""
return _snap.TIntH_GetKeyDat(self, *args)
def IsKeyGetDat(self, *args):
"""
IsKeyGetDat(TIntH self, TInt Key, TInt Dat) -> bool
Parameters:
Key: TInt const &
Dat: TInt &
"""
return _snap.TIntH_IsKeyGetDat(self, *args)
def FFirstKeyId(self):
"""
FFirstKeyId(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_FFirstKeyId(self)
def FNextKeyId(self, *args):
"""
FNextKeyId(TIntH self, int & KeyId) -> bool
Parameters:
KeyId: int &
"""
return _snap.TIntH_FNextKeyId(self, *args)
def GetKeyV(self, *args):
"""
GetKeyV(TIntH self, TIntV KeyV)
Parameters:
KeyV: TVec< TInt > &
"""
return _snap.TIntH_GetKeyV(self, *args)
def GetDatV(self, *args):
"""
GetDatV(TIntH self, TIntV DatV)
Parameters:
DatV: TVec< TInt > &
"""
return _snap.TIntH_GetDatV(self, *args)
def GetKeyDatPrV(self, *args):
"""
GetKeyDatPrV(TIntH self, TVec< TPair< TInt,TInt > > & KeyDatPrV)
Parameters:
KeyDatPrV: TVec< TPair< TInt,TInt > > &
"""
return _snap.TIntH_GetKeyDatPrV(self, *args)
def GetDatKeyPrV(self, *args):
"""
GetDatKeyPrV(TIntH self, TVec< TPair< TInt,TInt > > & DatKeyPrV)
Parameters:
DatKeyPrV: TVec< TPair< TInt,TInt > > &
"""
return _snap.TIntH_GetDatKeyPrV(self, *args)
def GetKeyDatKdV(self, *args):
"""
GetKeyDatKdV(TIntH self, TVec< TKeyDat< TInt,TInt > > & KeyDatKdV)
Parameters:
KeyDatKdV: TVec< TKeyDat< TInt,TInt > > &
"""
return _snap.TIntH_GetKeyDatKdV(self, *args)
def GetDatKeyKdV(self, *args):
"""
GetDatKeyKdV(TIntH self, TVec< TKeyDat< TInt,TInt > > & DatKeyKdV)
Parameters:
DatKeyKdV: TVec< TKeyDat< TInt,TInt > > &
"""
return _snap.TIntH_GetDatKeyKdV(self, *args)
def Swap(self, *args):
"""
Swap(TIntH self, TIntH Hash)
Parameters:
Hash: THash< TInt,TInt > &
"""
return _snap.TIntH_Swap(self, *args)
def Defrag(self):
"""
Defrag(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_Defrag(self)
def Pack(self):
"""
Pack(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_Pack(self)
def Sort(self, *args):
"""
Sort(TIntH self, bool const & CmpKey, bool const & Asc)
Parameters:
CmpKey: bool const &
Asc: bool const &
"""
return _snap.TIntH_Sort(self, *args)
def SortByKey(self, Asc=True):
"""
SortByKey(TIntH self, bool const & Asc=True)
Parameters:
Asc: bool const &
SortByKey(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_SortByKey(self, Asc)
def SortByDat(self, Asc=True):
"""
SortByDat(TIntH self, bool const & Asc=True)
Parameters:
Asc: bool const &
SortByDat(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_SortByDat(self, Asc)
def AddKey(self, *args):
"""
AddKey(TIntH self, TInt Key) -> int
Parameters:
Key: TInt const &
AddKey(TIntH self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntH_AddKey(self, *args)
def IsKey(self, *args):
"""
IsKey(TIntH self, TInt Key) -> bool
Parameters:
Key: TInt const &
IsKey(TIntH self, TInt Key, int & KeyId) -> bool
Parameters:
Key: TInt const &
KeyId: int &
IsKey(TIntH self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntH_IsKey(self, *args)
def GetDat(self, *args):
"""
GetDat(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
GetDat(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
GetDat(TIntH self, int Val) -> TInt
Parameters:
Val: int
"""
return _snap.TIntH_GetDat(self, *args)
def AddDat(self, *args):
"""
AddDat(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
AddDat(TIntH self, TInt Key, TInt Dat) -> TInt
Parameters:
Key: TInt const &
Dat: TInt const &
AddDat(TIntH self, int Key, int Val) -> TInt
Parameters:
Key: int
Val: int
"""
return _snap.TIntH_AddDat(self, *args)
__swig_destroy__ = _snap.delete_TIntH
TIntH.Load = new_instancemethod(_snap.TIntH_Load,None,TIntH)
TIntH.Save = new_instancemethod(_snap.TIntH_Save,None,TIntH)
TIntH.LoadXml = new_instancemethod(_snap.TIntH_LoadXml,None,TIntH)
TIntH.SaveXml = new_instancemethod(_snap.TIntH_SaveXml,None,TIntH)
TIntH.__eq__ = new_instancemethod(_snap.TIntH___eq__,None,TIntH)
TIntH.__lt__ = new_instancemethod(_snap.TIntH___lt__,None,TIntH)
TIntH.__call__ = new_instancemethod(_snap.TIntH___call__,None,TIntH)
TIntH.GetMemUsed = new_instancemethod(_snap.TIntH_GetMemUsed,None,TIntH)
TIntH.BegI = new_instancemethod(_snap.TIntH_BegI,None,TIntH)
TIntH.EndI = new_instancemethod(_snap.TIntH_EndI,None,TIntH)
TIntH.GetI = new_instancemethod(_snap.TIntH_GetI,None,TIntH)
TIntH.Gen = new_instancemethod(_snap.TIntH_Gen,None,TIntH)
TIntH.Clr = new_instancemethod(_snap.TIntH_Clr,None,TIntH)
TIntH.Empty = new_instancemethod(_snap.TIntH_Empty,None,TIntH)
TIntH.Len = new_instancemethod(_snap.TIntH_Len,None,TIntH)
TIntH.GetPorts = new_instancemethod(_snap.TIntH_GetPorts,None,TIntH)
TIntH.IsAutoSize = new_instancemethod(_snap.TIntH_IsAutoSize,None,TIntH)
TIntH.GetMxKeyIds = new_instancemethod(_snap.TIntH_GetMxKeyIds,None,TIntH)
TIntH.GetReservedKeyIds = new_instancemethod(_snap.TIntH_GetReservedKeyIds,None,TIntH)
TIntH.IsKeyIdEqKeyN = new_instancemethod(_snap.TIntH_IsKeyIdEqKeyN,None,TIntH)
TIntH.AddDatId = new_instancemethod(_snap.TIntH_AddDatId,None,TIntH)
TIntH.DelKey = new_instancemethod(_snap.TIntH_DelKey,None,TIntH)
TIntH.DelIfKey = new_instancemethod(_snap.TIntH_DelIfKey,None,TIntH)
TIntH.DelKeyId = new_instancemethod(_snap.TIntH_DelKeyId,None,TIntH)
TIntH.DelKeyIdV = new_instancemethod(_snap.TIntH_DelKeyIdV,None,TIntH)
TIntH.MarkDelKey = new_instancemethod(_snap.TIntH_MarkDelKey,None,TIntH)
TIntH.MarkDelKeyId = new_instancemethod(_snap.TIntH_MarkDelKeyId,None,TIntH)
TIntH.GetKey = new_instancemethod(_snap.TIntH_GetKey,None,TIntH)
TIntH.GetKeyId = new_instancemethod(_snap.TIntH_GetKeyId,None,TIntH)
TIntH.GetRndKeyId = new_instancemethod(_snap.TIntH_GetRndKeyId,None,TIntH)
TIntH.IsKeyId = new_instancemethod(_snap.TIntH_IsKeyId,None,TIntH)
TIntH.GetKeyDat = new_instancemethod(_snap.TIntH_GetKeyDat,None,TIntH)
TIntH.IsKeyGetDat = new_instancemethod(_snap.TIntH_IsKeyGetDat,None,TIntH)
TIntH.FFirstKeyId = new_instancemethod(_snap.TIntH_FFirstKeyId,None,TIntH)
TIntH.FNextKeyId = new_instancemethod(_snap.TIntH_FNextKeyId,None,TIntH)
TIntH.GetKeyV = new_instancemethod(_snap.TIntH_GetKeyV,None,TIntH)
TIntH.GetDatV = new_instancemethod(_snap.TIntH_GetDatV,None,TIntH)
TIntH.GetKeyDatPrV = new_instancemethod(_snap.TIntH_GetKeyDatPrV,None,TIntH)
TIntH.GetDatKeyPrV = new_instancemethod(_snap.TIntH_GetDatKeyPrV,None,TIntH)
TIntH.GetKeyDatKdV = new_instancemethod(_snap.TIntH_GetKeyDatKdV,None,TIntH)
TIntH.GetDatKeyKdV = new_instancemethod(_snap.TIntH_GetDatKeyKdV,None,TIntH)
TIntH.Swap = new_instancemethod(_snap.TIntH_Swap,None,TIntH)
TIntH.Defrag = new_instancemethod(_snap.TIntH_Defrag,None,TIntH)
TIntH.Pack = new_instancemethod(_snap.TIntH_Pack,None,TIntH)
TIntH.Sort = new_instancemethod(_snap.TIntH_Sort,None,TIntH)
TIntH.SortByKey = new_instancemethod(_snap.TIntH_SortByKey,None,TIntH)
TIntH.SortByDat = new_instancemethod(_snap.TIntH_SortByDat,None,TIntH)
TIntH.AddKey = new_instancemethod(_snap.TIntH_AddKey,None,TIntH)
TIntH.IsKey = new_instancemethod(_snap.TIntH_IsKey,None,TIntH)
TIntH.GetDat = new_instancemethod(_snap.TIntH_GetDat,None,TIntH)
TIntH.AddDat = new_instancemethod(_snap.TIntH_AddDat,None,TIntH)
TIntH_swigregister = _snap.TIntH_swigregister
TIntH_swigregister(TIntH)
class TIntHI(object):
"""Proxy of C++ THashKeyDatI<(TInt,TInt)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(THashKeyDatI<(TInt,TInt)> self) -> TIntHI
__init__(THashKeyDatI<(TInt,TInt)> self, TIntHI _HashKeyDatI) -> TIntHI
Parameters:
_HashKeyDatI: THashKeyDatI< TInt,TInt > const &
__init__(THashKeyDatI<(TInt,TInt)> self, THashKeyDatI< TInt,TInt >::THKeyDat const * _KeyDatI, THashKeyDatI< TInt,TInt >::THKeyDat const * _EndI) -> TIntHI
Parameters:
_KeyDatI: THashKeyDatI< TInt,TInt >::THKeyDat const *
_EndI: THashKeyDatI< TInt,TInt >::THKeyDat const *
"""
_snap.TIntHI_swiginit(self,_snap.new_TIntHI(*args))
def __eq__(self, *args):
"""
__eq__(TIntHI self, TIntHI HashKeyDatI) -> bool
Parameters:
HashKeyDatI: THashKeyDatI< TInt,TInt > const &
"""
return _snap.TIntHI___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntHI self, TIntHI HashKeyDatI) -> bool
Parameters:
HashKeyDatI: THashKeyDatI< TInt,TInt > const &
"""
return _snap.TIntHI___lt__(self, *args)
def __ref__(self):
"""
__ref__(TIntHI self) -> THashKeyDatI< TInt,TInt >::THKeyDat &
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI___ref__(self)
def __call__(self):
"""
__call__(TIntHI self) -> THashKeyDatI< TInt,TInt >::THKeyDat &
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI___call__(self)
def __deref__(self):
"""
__deref__(TIntHI self) -> THashKeyDatI< TInt,TInt >::THKeyDat *
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI___deref__(self)
def Next(self):
"""
Next(TIntHI self) -> TIntHI
Parameters:
self: THashKeyDatI< TInt,TInt > *
"""
return _snap.TIntHI_Next(self)
def IsEmpty(self):
"""
IsEmpty(TIntHI self) -> bool
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI_IsEmpty(self)
def IsEnd(self):
"""
IsEnd(TIntHI self) -> bool
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI_IsEnd(self)
def GetKey(self):
"""
GetKey(TIntHI self) -> TInt
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI_GetKey(self)
def GetDat(self, *args):
"""
GetDat(TIntHI self) -> TInt
GetDat(TIntHI self) -> TInt
Parameters:
self: THashKeyDatI< TInt,TInt > *
"""
return _snap.TIntHI_GetDat(self, *args)
__swig_destroy__ = _snap.delete_TIntHI
TIntHI.__eq__ = new_instancemethod(_snap.TIntHI___eq__,None,TIntHI)
TIntHI.__lt__ = new_instancemethod(_snap.TIntHI___lt__,None,TIntHI)
TIntHI.__ref__ = new_instancemethod(_snap.TIntHI___ref__,None,TIntHI)
TIntHI.__call__ = new_instancemethod(_snap.TIntHI___call__,None,TIntHI)
TIntHI.__deref__ = new_instancemethod(_snap.TIntHI___deref__,None,TIntHI)
TIntHI.Next = new_instancemethod(_snap.TIntHI_Next,None,TIntHI)
TIntHI.IsEmpty = new_instancemethod(_snap.TIntHI_IsEmpty,None,TIntHI)
TIntHI.IsEnd = new_instancemethod(_snap.TIntHI_IsEnd,None,TIntHI)
TIntHI.GetKey = new_instancemethod(_snap.TIntHI_GetKey,None,TIntHI)
TIntHI.GetDat = new_instancemethod(_snap.TIntHI_GetDat,None,TIntHI)
TIntHI_swigregister = _snap.TIntHI_swigregister
TIntHI_swigregister(TIntHI)
class TStrV(object):
"""Proxy of C++ TVec<(TStr,int)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TStrV
def __init__(self, *args):
"""
__init__(TVec<(TStr,int)> self) -> TStrV
__init__(TVec<(TStr,int)> self, TStrV Vec) -> TStrV
Parameters:
Vec: TVec< TStr,int > const &
__init__(TVec<(TStr,int)> self, int const & _Vals) -> TStrV
Parameters:
_Vals: int const &
__init__(TVec<(TStr,int)> self, int const & _MxVals, int const & _Vals) -> TStrV
Parameters:
_MxVals: int const &
_Vals: int const &
__init__(TVec<(TStr,int)> self, TStr _ValT, int const & _Vals) -> TStrV
Parameters:
_ValT: TStr *
_Vals: int const &
__init__(TVec<(TStr,int)> self, TSIn SIn) -> TStrV
Parameters:
SIn: TSIn &
"""
_snap.TStrV_swiginit(self,_snap.new_TStrV(*args))
def Load(self, *args):
"""
Load(TStrV self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TStrV_Load(self, *args)
def Save(self, *args):
"""
Save(TStrV self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TStrV_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TStrV self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TStrV self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TStrV_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TStrV self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TStrV_SaveXml(self, *args)
def __add__(self, *args):
"""
__add__(TStrV self, TStr Val) -> TStrV
Parameters:
Val: TStr const &
"""
return _snap.TStrV___add__(self, *args)
def __eq__(self, *args):
"""
__eq__(TStrV self, TStrV Vec) -> bool
Parameters:
Vec: TVec< TStr,int > const &
"""
return _snap.TStrV___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TStrV self, TStrV Vec) -> bool
Parameters:
Vec: TVec< TStr,int > const &
"""
return _snap.TStrV___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetMemUsed(self)
def GetMemSize(self):
"""
GetMemSize(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetMemSize(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetSecHashCd(self)
def Gen(self, *args):
"""
Gen(TStrV self, int const & _Vals)
Parameters:
_Vals: int const &
Gen(TStrV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TStrV_Gen(self, *args)
def GenExt(self, *args):
"""
GenExt(TStrV self, TStr _ValT, int const & _Vals)
Parameters:
_ValT: TStr *
_Vals: int const &
"""
return _snap.TStrV_GenExt(self, *args)
def IsExt(self):
"""
IsExt(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_IsExt(self)
def Reserve(self, *args):
"""
Reserve(TStrV self, int const & _MxVals)
Parameters:
_MxVals: int const &
Reserve(TStrV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TStrV_Reserve(self, *args)
def Clr(self, *args):
"""
Clr(TStrV self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TStrV self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Clr(self, *args)
def Trunc(self, *args):
"""
Trunc(TStrV self, int const & _Vals=-1)
Parameters:
_Vals: int const &
Trunc(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Trunc(self, *args)
def Pack(self):
"""
Pack(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Pack(self)
def MoveFrom(self, *args):
"""
MoveFrom(TStrV self, TStrV Vec)
Parameters:
Vec: TVec< TStr,int > &
"""
return _snap.TStrV_MoveFrom(self, *args)
def Empty(self):
"""
Empty(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_Empty(self)
def Len(self):
"""
Len(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_Len(self)
def Reserved(self):
"""
Reserved(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_Reserved(self)
def Last(self, *args):
"""
Last(TStrV self) -> TStr
Last(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Last(self, *args)
def LastValN(self):
"""
LastValN(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_LastValN(self)
def LastLast(self, *args):
"""
LastLast(TStrV self) -> TStr
LastLast(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_LastLast(self, *args)
def BegI(self):
"""
BegI(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_BegI(self)
def EndI(self):
"""
EndI(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_EndI(self)
def GetI(self, *args):
"""
GetI(TStrV self, int const & ValN) -> TStr
Parameters:
ValN: int const &
"""
return _snap.TStrV_GetI(self, *args)
def AddV(self, *args):
"""
AddV(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_AddV(self, *args)
def AddSorted(self, *args):
"""
AddSorted(TStrV self, TStr Val, bool const & Asc=True, int const & _MxVals=-1) -> int
Parameters:
Val: TStr const &
Asc: bool const &
_MxVals: int const &
AddSorted(TStrV self, TStr Val, bool const & Asc=True) -> int
Parameters:
Val: TStr const &
Asc: bool const &
AddSorted(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_AddSorted(self, *args)
def AddBackSorted(self, *args):
"""
AddBackSorted(TStrV self, TStr Val, bool const & Asc) -> int
Parameters:
Val: TStr const &
Asc: bool const &
"""
return _snap.TStrV_AddBackSorted(self, *args)
def AddVMerged(self, *args):
"""
AddVMerged(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_AddVMerged(self, *args)
def AddUnique(self, *args):
"""
AddUnique(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_AddUnique(self, *args)
def GetVal(self, *args):
"""
GetVal(TStrV self, int const & ValN) -> TStr
Parameters:
ValN: int const &
GetVal(TStrV self, int const & ValN) -> TStr
Parameters:
ValN: int const &
"""
return _snap.TStrV_GetVal(self, *args)
def GetSubValV(self, *args):
"""
GetSubValV(TStrV self, int const & BValN, int const & EValN, TStrV ValV)
Parameters:
BValN: int const &
EValN: int const &
ValV: TVec< TStr,int > &
"""
return _snap.TStrV_GetSubValV(self, *args)
def Ins(self, *args):
"""
Ins(TStrV self, int const & ValN, TStr Val)
Parameters:
ValN: int const &
Val: TStr const &
"""
return _snap.TStrV_Ins(self, *args)
def Del(self, *args):
"""
Del(TStrV self, int const & ValN)
Parameters:
ValN: int const &
Del(TStrV self, int const & MnValN, int const & MxValN)
Parameters:
MnValN: int const &
MxValN: int const &
"""
return _snap.TStrV_Del(self, *args)
def DelLast(self):
"""
DelLast(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_DelLast(self)
def DelIfIn(self, *args):
"""
DelIfIn(TStrV self, TStr Val) -> bool
Parameters:
Val: TStr const &
"""
return _snap.TStrV_DelIfIn(self, *args)
def DelAll(self, *args):
"""
DelAll(TStrV self, TStr Val)
Parameters:
Val: TStr const &
"""
return _snap.TStrV_DelAll(self, *args)
def PutAll(self, *args):
"""
PutAll(TStrV self, TStr Val)
Parameters:
Val: TStr const &
"""
return _snap.TStrV_PutAll(self, *args)
def Swap(self, *args):
"""
Swap(TStrV self, TStrV Vec)
Parameters:
Vec: TVec< TStr,int > &
Swap(TStrV self, int const & ValN1, int const & ValN2)
Parameters:
ValN1: int const &
ValN2: int const &
"""
return _snap.TStrV_Swap(self, *args)
def SwapI(*args):
"""
SwapI(TStr LVal, TStr RVal)
Parameters:
LVal: TVec< TStr,int >::TIter
RVal: TVec< TStr,int >::TIter
"""
return _snap.TStrV_SwapI(*args)
SwapI = staticmethod(SwapI)
def NextPerm(self):
"""
NextPerm(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_NextPerm(self)
def PrevPerm(self):
"""
PrevPerm(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_PrevPerm(self)
def GetPivotValN(self, *args):
"""
GetPivotValN(TStrV self, int const & LValN, int const & RValN) -> int
Parameters:
LValN: int const &
RValN: int const &
"""
return _snap.TStrV_GetPivotValN(self, *args)
def BSort(self, *args):
"""
BSort(TStrV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TStrV_BSort(self, *args)
def ISort(self, *args):
"""
ISort(TStrV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TStrV_ISort(self, *args)
def Partition(self, *args):
"""
Partition(TStrV self, int const & MnLValN, int const & MxRValN, bool const & Asc) -> int
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TStrV_Partition(self, *args)
def QSort(self, *args):
"""
QSort(TStrV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TStrV_QSort(self, *args)
def Sort(self, Asc=True):
"""
Sort(TStrV self, bool const & Asc=True)
Parameters:
Asc: bool const &
Sort(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Sort(self, Asc)
def IsSorted(self, Asc=True):
"""
IsSorted(TStrV self, bool const & Asc=True) -> bool
Parameters:
Asc: bool const &
IsSorted(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_IsSorted(self, Asc)
def Shuffle(self, *args):
"""
Shuffle(TStrV self, TRnd Rnd)
Parameters:
Rnd: TRnd &
"""
return _snap.TStrV_Shuffle(self, *args)
def Reverse(self, *args):
"""
Reverse(TStrV self)
Reverse(TStrV self, int LValN, int RValN)
Parameters:
LValN: int
RValN: int
"""
return _snap.TStrV_Reverse(self, *args)
def Merge(self):
"""
Merge(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Merge(self)
def Intrs(self, *args):
"""
Intrs(TStrV self, TStrV ValV)
Parameters:
ValV: TVec< TStr,int > const &
Intrs(TStrV self, TStrV ValV, TStrV DstValV)
Parameters:
ValV: TVec< TStr,int > const &
DstValV: TVec< TStr,int > &
"""
return _snap.TStrV_Intrs(self, *args)
def Union(self, *args):
"""
Union(TStrV self, TStrV ValV)
Parameters:
ValV: TVec< TStr,int > const &
Union(TStrV self, TStrV ValV, TStrV DstValV)
Parameters:
ValV: TVec< TStr,int > const &
DstValV: TVec< TStr,int > &
"""
return _snap.TStrV_Union(self, *args)
def Diff(self, *args):
"""
Diff(TStrV self, TStrV ValV)
Parameters:
ValV: TVec< TStr,int > const &
Diff(TStrV self, TStrV ValV, TStrV DstValV)
Parameters:
ValV: TVec< TStr,int > const &
DstValV: TVec< TStr,int > &
"""
return _snap.TStrV_Diff(self, *args)
def IntrsLen(self, *args):
"""
IntrsLen(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_IntrsLen(self, *args)
def UnionLen(self, *args):
"""
UnionLen(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_UnionLen(self, *args)
def Count(self, *args):
"""
Count(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_Count(self, *args)
def SearchBin(self, *args):
"""
SearchBin(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
SearchBin(TStrV self, TStr Val, int & InsValN) -> int
Parameters:
Val: TStr const &
InsValN: int &
"""
return _snap.TStrV_SearchBin(self, *args)
def SearchForw(self, *args):
"""
SearchForw(TStrV self, TStr Val, int const & BValN=0) -> int
Parameters:
Val: TStr const &
BValN: int const &
SearchForw(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_SearchForw(self, *args)
def SearchBack(self, *args):
"""
SearchBack(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_SearchBack(self, *args)
def SearchVForw(self, *args):
"""
SearchVForw(TStrV self, TStrV ValV, int const & BValN=0) -> int
Parameters:
ValV: TVec< TStr,int > const &
BValN: int const &
SearchVForw(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_SearchVForw(self, *args)
def IsIn(self, *args):
"""
IsIn(TStrV self, TStr Val) -> bool
Parameters:
Val: TStr const &
IsIn(TStrV self, TStr Val, int & ValN) -> bool
Parameters:
Val: TStr const &
ValN: int &
"""
return _snap.TStrV_IsIn(self, *args)
def IsInBin(self, *args):
"""
IsInBin(TStrV self, TStr Val) -> bool
Parameters:
Val: TStr const &
"""
return _snap.TStrV_IsInBin(self, *args)
def GetDat(self, *args):
"""
GetDat(TStrV self, TStr Val) -> TStr
Parameters:
Val: TStr const &
"""
return _snap.TStrV_GetDat(self, *args)
def GetAddDat(self, *args):
"""
GetAddDat(TStrV self, TStr Val) -> TStr
Parameters:
Val: TStr const &
"""
return _snap.TStrV_GetAddDat(self, *args)
def GetMxValN(self):
"""
GetMxValN(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetMxValN(self)
def GetV(*args):
"""
GetV(TStr Val1) -> TStrV
Parameters:
Val1: TStr const &
GetV(TStr Val1, TStr Val2) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7, TStr Val8) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
Val8: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7, TStr Val8,
TStr Val9) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
Val8: TStr const &
Val9: TStr const &
"""
return _snap.TStrV_GetV(*args)
GetV = staticmethod(GetV)
TStrV.Load = new_instancemethod(_snap.TStrV_Load,None,TStrV)
TStrV.Save = new_instancemethod(_snap.TStrV_Save,None,TStrV)
TStrV.LoadXml = new_instancemethod(_snap.TStrV_LoadXml,None,TStrV)
TStrV.SaveXml = new_instancemethod(_snap.TStrV_SaveXml,None,TStrV)
TStrV.__add__ = new_instancemethod(_snap.TStrV___add__,None,TStrV)
TStrV.__eq__ = new_instancemethod(_snap.TStrV___eq__,None,TStrV)
TStrV.__lt__ = new_instancemethod(_snap.TStrV___lt__,None,TStrV)
TStrV.GetMemUsed = new_instancemethod(_snap.TStrV_GetMemUsed,None,TStrV)
TStrV.GetMemSize = new_instancemethod(_snap.TStrV_GetMemSize,None,TStrV)
TStrV.GetPrimHashCd = new_instancemethod(_snap.TStrV_GetPrimHashCd,None,TStrV)
TStrV.GetSecHashCd = new_instancemethod(_snap.TStrV_GetSecHashCd,None,TStrV)
TStrV.Gen = new_instancemethod(_snap.TStrV_Gen,None,TStrV)
TStrV.GenExt = new_instancemethod(_snap.TStrV_GenExt,None,TStrV)
TStrV.IsExt = new_instancemethod(_snap.TStrV_IsExt,None,TStrV)
TStrV.Reserve = new_instancemethod(_snap.TStrV_Reserve,None,TStrV)
TStrV.Clr = new_instancemethod(_snap.TStrV_Clr,None,TStrV)
TStrV.Trunc = new_instancemethod(_snap.TStrV_Trunc,None,TStrV)
TStrV.Pack = new_instancemethod(_snap.TStrV_Pack,None,TStrV)
TStrV.MoveFrom = new_instancemethod(_snap.TStrV_MoveFrom,None,TStrV)
TStrV.Empty = new_instancemethod(_snap.TStrV_Empty,None,TStrV)
TStrV.Len = new_instancemethod(_snap.TStrV_Len,None,TStrV)
TStrV.Reserved = new_instancemethod(_snap.TStrV_Reserved,None,TStrV)
TStrV.Last = new_instancemethod(_snap.TStrV_Last,None,TStrV)
TStrV.LastValN = new_instancemethod(_snap.TStrV_LastValN,None,TStrV)
TStrV.LastLast = new_instancemethod(_snap.TStrV_LastLast,None,TStrV)
TStrV.BegI = new_instancemethod(_snap.TStrV_BegI,None,TStrV)
TStrV.EndI = new_instancemethod(_snap.TStrV_EndI,None,TStrV)
TStrV.GetI = new_instancemethod(_snap.TStrV_GetI,None,TStrV)
TStrV.AddV = new_instancemethod(_snap.TStrV_AddV,None,TStrV)
TStrV.AddSorted = new_instancemethod(_snap.TStrV_AddSorted,None,TStrV)
TStrV.AddBackSorted = new_instancemethod(_snap.TStrV_AddBackSorted,None,TStrV)
TStrV.AddVMerged = new_instancemethod(_snap.TStrV_AddVMerged,None,TStrV)
TStrV.AddUnique = new_instancemethod(_snap.TStrV_AddUnique,None,TStrV)
TStrV.GetVal = new_instancemethod(_snap.TStrV_GetVal,None,TStrV)
TStrV.GetSubValV = new_instancemethod(_snap.TStrV_GetSubValV,None,TStrV)
TStrV.Ins = new_instancemethod(_snap.TStrV_Ins,None,TStrV)
TStrV.Del = new_instancemethod(_snap.TStrV_Del,None,TStrV)
TStrV.DelLast = new_instancemethod(_snap.TStrV_DelLast,None,TStrV)
TStrV.DelIfIn = new_instancemethod(_snap.TStrV_DelIfIn,None,TStrV)
TStrV.DelAll = new_instancemethod(_snap.TStrV_DelAll,None,TStrV)
TStrV.PutAll = new_instancemethod(_snap.TStrV_PutAll,None,TStrV)
TStrV.Swap = new_instancemethod(_snap.TStrV_Swap,None,TStrV)
TStrV.NextPerm = new_instancemethod(_snap.TStrV_NextPerm,None,TStrV)
TStrV.PrevPerm = new_instancemethod(_snap.TStrV_PrevPerm,None,TStrV)
TStrV.GetPivotValN = new_instancemethod(_snap.TStrV_GetPivotValN,None,TStrV)
TStrV.BSort = new_instancemethod(_snap.TStrV_BSort,None,TStrV)
TStrV.ISort = new_instancemethod(_snap.TStrV_ISort,None,TStrV)
TStrV.Partition = new_instancemethod(_snap.TStrV_Partition,None,TStrV)
TStrV.QSort = new_instancemethod(_snap.TStrV_QSort,None,TStrV)
TStrV.Sort = new_instancemethod(_snap.TStrV_Sort,None,TStrV)
TStrV.IsSorted = new_instancemethod(_snap.TStrV_IsSorted,None,TStrV)
TStrV.Shuffle = new_instancemethod(_snap.TStrV_Shuffle,None,TStrV)
TStrV.Reverse = new_instancemethod(_snap.TStrV_Reverse,None,TStrV)
TStrV.Merge = new_instancemethod(_snap.TStrV_Merge,None,TStrV)
TStrV.Intrs = new_instancemethod(_snap.TStrV_Intrs,None,TStrV)
TStrV.Union = new_instancemethod(_snap.TStrV_Union,None,TStrV)
TStrV.Diff = new_instancemethod(_snap.TStrV_Diff,None,TStrV)
TStrV.IntrsLen = new_instancemethod(_snap.TStrV_IntrsLen,None,TStrV)
TStrV.UnionLen = new_instancemethod(_snap.TStrV_UnionLen,None,TStrV)
TStrV.Count = new_instancemethod(_snap.TStrV_Count,None,TStrV)
TStrV.SearchBin = new_instancemethod(_snap.TStrV_SearchBin,None,TStrV)
TStrV.SearchForw = new_instancemethod(_snap.TStrV_SearchForw,None,TStrV)
TStrV.SearchBack = new_instancemethod(_snap.TStrV_SearchBack,None,TStrV)
TStrV.SearchVForw = new_instancemethod(_snap.TStrV_SearchVForw,None,TStrV)
TStrV.IsIn = new_instancemethod(_snap.TStrV_IsIn,None,TStrV)
TStrV.IsInBin = new_instancemethod(_snap.TStrV_IsInBin,None,TStrV)
TStrV.GetDat = new_instancemethod(_snap.TStrV_GetDat,None,TStrV)
TStrV.GetAddDat = new_instancemethod(_snap.TStrV_GetAddDat,None,TStrV)
TStrV.GetMxValN = new_instancemethod(_snap.TStrV_GetMxValN,None,TStrV)
TStrV_swigregister = _snap.TStrV_swigregister
TStrV_swigregister(TStrV)
def TStrV_SwapI(*args):
"""
TStrV_SwapI(TStr LVal, TStr RVal)
Parameters:
LVal: TVec< TStr,int >::TIter
RVal: TVec< TStr,int >::TIter
"""
return _snap.TStrV_SwapI(*args)
def TStrV_GetV(*args):
"""
GetV(TStr Val1) -> TStrV
Parameters:
Val1: TStr const &
GetV(TStr Val1, TStr Val2) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7, TStr Val8) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
Val8: TStr const &
TStrV_GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7, TStr Val8,
TStr Val9) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
Val8: TStr const &
Val9: TStr const &
"""
return _snap.TStrV_GetV(*args)
class TNGraphNodeI(object):
"""Proxy of C++ TNGraphNodeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNGraphNodeI self) -> TNGraphNodeI
__init__(TNGraphNodeI self, TNGraph::TNodeI const & NodeI) -> TNGraphNodeI
Parameters:
NodeI: TNGraph::TNodeI const &
"""
_snap.TNGraphNodeI_swiginit(self,_snap.new_TNGraphNodeI(*args))
def Next(self):
"""
Next(TNGraphNodeI self) -> TNGraphNodeI
Parameters:
self: TNGraphNodeI *
"""
return _snap.TNGraphNodeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNGraphNodeI self, TNGraphNodeI NodeI) -> bool
Parameters:
NodeI: TNGraphNodeI const &
"""
return _snap.TNGraphNodeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNGraphNodeI self, TNGraphNodeI NodeI) -> bool
Parameters:
NodeI: TNGraphNodeI const &
"""
return _snap.TNGraphNodeI___eq__(self, *args)
def GetId(self):
"""
GetId(TNGraphNodeI self) -> int
Parameters:
self: TNGraphNodeI const *
"""
return _snap.TNGraphNodeI_GetId(self)
def GetDeg(self):
"""
GetDeg(TNGraphNodeI self) -> int
Parameters:
self: TNGraphNodeI const *
"""
return _snap.TNGraphNodeI_GetDeg(self)
def GetInDeg(self):
"""
GetInDeg(TNGraphNodeI self) -> int
Parameters:
self: TNGraphNodeI const *
"""
return _snap.TNGraphNodeI_GetInDeg(self)
def GetOutDeg(self):
"""
GetOutDeg(TNGraphNodeI self) -> int
Parameters:
self: TNGraphNodeI const *
"""
return _snap.TNGraphNodeI_GetOutDeg(self)
def GetInNId(self, *args):
"""
GetInNId(TNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNGraphNodeI_GetInNId(self, *args)
def GetOutNId(self, *args):
"""
GetOutNId(TNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNGraphNodeI_GetOutNId(self, *args)
def GetNbrNId(self, *args):
"""
GetNbrNId(TNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNGraphNodeI_GetNbrNId(self, *args)
def IsInNId(self, *args):
"""
IsInNId(TNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNGraphNodeI_IsInNId(self, *args)
def IsOutNId(self, *args):
"""
IsOutNId(TNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNGraphNodeI_IsOutNId(self, *args)
def IsNbrNId(self, *args):
"""
IsNbrNId(TNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNGraphNodeI_IsNbrNId(self, *args)
__swig_destroy__ = _snap.delete_TNGraphNodeI
TNGraphNodeI.Next = new_instancemethod(_snap.TNGraphNodeI_Next,None,TNGraphNodeI)
TNGraphNodeI.__lt__ = new_instancemethod(_snap.TNGraphNodeI___lt__,None,TNGraphNodeI)
TNGraphNodeI.__eq__ = new_instancemethod(_snap.TNGraphNodeI___eq__,None,TNGraphNodeI)
TNGraphNodeI.GetId = new_instancemethod(_snap.TNGraphNodeI_GetId,None,TNGraphNodeI)
TNGraphNodeI.GetDeg = new_instancemethod(_snap.TNGraphNodeI_GetDeg,None,TNGraphNodeI)
TNGraphNodeI.GetInDeg = new_instancemethod(_snap.TNGraphNodeI_GetInDeg,None,TNGraphNodeI)
TNGraphNodeI.GetOutDeg = new_instancemethod(_snap.TNGraphNodeI_GetOutDeg,None,TNGraphNodeI)
TNGraphNodeI.GetInNId = new_instancemethod(_snap.TNGraphNodeI_GetInNId,None,TNGraphNodeI)
TNGraphNodeI.GetOutNId = new_instancemethod(_snap.TNGraphNodeI_GetOutNId,None,TNGraphNodeI)
TNGraphNodeI.GetNbrNId = new_instancemethod(_snap.TNGraphNodeI_GetNbrNId,None,TNGraphNodeI)
TNGraphNodeI.IsInNId = new_instancemethod(_snap.TNGraphNodeI_IsInNId,None,TNGraphNodeI)
TNGraphNodeI.IsOutNId = new_instancemethod(_snap.TNGraphNodeI_IsOutNId,None,TNGraphNodeI)
TNGraphNodeI.IsNbrNId = new_instancemethod(_snap.TNGraphNodeI_IsNbrNId,None,TNGraphNodeI)
TNGraphNodeI_swigregister = _snap.TNGraphNodeI_swigregister
TNGraphNodeI_swigregister(TNGraphNodeI)
class TNGraphEdgeI(object):
"""Proxy of C++ TNGraphEdgeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNGraphEdgeI self) -> TNGraphEdgeI
__init__(TNGraphEdgeI self, TNGraph::TEdgeI const & EdgeI) -> TNGraphEdgeI
Parameters:
EdgeI: TNGraph::TEdgeI const &
"""
_snap.TNGraphEdgeI_swiginit(self,_snap.new_TNGraphEdgeI(*args))
def Next(self):
"""
Next(TNGraphEdgeI self) -> TNGraphEdgeI
Parameters:
self: TNGraphEdgeI *
"""
return _snap.TNGraphEdgeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNGraphEdgeI self, TNGraphEdgeI EdgeI) -> bool
Parameters:
EdgeI: TNGraphEdgeI const &
"""
return _snap.TNGraphEdgeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNGraphEdgeI self, TNGraphEdgeI EdgeI) -> bool
Parameters:
EdgeI: TNGraphEdgeI const &
"""
return _snap.TNGraphEdgeI___eq__(self, *args)
def GetId(self):
"""
GetId(TNGraphEdgeI self) -> int
Parameters:
self: TNGraphEdgeI const *
"""
return _snap.TNGraphEdgeI_GetId(self)
def GetSrcNId(self):
"""
GetSrcNId(TNGraphEdgeI self) -> int
Parameters:
self: TNGraphEdgeI const *
"""
return _snap.TNGraphEdgeI_GetSrcNId(self)
def GetDstNId(self):
"""
GetDstNId(TNGraphEdgeI self) -> int
Parameters:
self: TNGraphEdgeI const *
"""
return _snap.TNGraphEdgeI_GetDstNId(self)
__swig_destroy__ = _snap.delete_TNGraphEdgeI
TNGraphEdgeI.Next = new_instancemethod(_snap.TNGraphEdgeI_Next,None,TNGraphEdgeI)
TNGraphEdgeI.__lt__ = new_instancemethod(_snap.TNGraphEdgeI___lt__,None,TNGraphEdgeI)
TNGraphEdgeI.__eq__ = new_instancemethod(_snap.TNGraphEdgeI___eq__,None,TNGraphEdgeI)
TNGraphEdgeI.GetId = new_instancemethod(_snap.TNGraphEdgeI_GetId,None,TNGraphEdgeI)
TNGraphEdgeI.GetSrcNId = new_instancemethod(_snap.TNGraphEdgeI_GetSrcNId,None,TNGraphEdgeI)
TNGraphEdgeI.GetDstNId = new_instancemethod(_snap.TNGraphEdgeI_GetDstNId,None,TNGraphEdgeI)
TNGraphEdgeI_swigregister = _snap.TNGraphEdgeI_swigregister
TNGraphEdgeI_swigregister(TNGraphEdgeI)
class TUNGraphNodeI(object):
"""Proxy of C++ TUNGraphNodeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TUNGraphNodeI self) -> TUNGraphNodeI
__init__(TUNGraphNodeI self, TUNGraph::TNodeI const & NodeI) -> TUNGraphNodeI
Parameters:
NodeI: TUNGraph::TNodeI const &
"""
_snap.TUNGraphNodeI_swiginit(self,_snap.new_TUNGraphNodeI(*args))
def Next(self):
"""
Next(TUNGraphNodeI self) -> TUNGraphNodeI
Parameters:
self: TUNGraphNodeI *
"""
return _snap.TUNGraphNodeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TUNGraphNodeI self, TUNGraphNodeI NodeI) -> bool
Parameters:
NodeI: TUNGraphNodeI const &
"""
return _snap.TUNGraphNodeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TUNGraphNodeI self, TUNGraphNodeI NodeI) -> bool
Parameters:
NodeI: TUNGraphNodeI const &
"""
return _snap.TUNGraphNodeI___eq__(self, *args)
def GetId(self):
"""
GetId(TUNGraphNodeI self) -> int
Parameters:
self: TUNGraphNodeI const *
"""
return _snap.TUNGraphNodeI_GetId(self)
def GetDeg(self):
"""
GetDeg(TUNGraphNodeI self) -> int
Parameters:
self: TUNGraphNodeI const *
"""
return _snap.TUNGraphNodeI_GetDeg(self)
def GetInDeg(self):
"""
GetInDeg(TUNGraphNodeI self) -> int
Parameters:
self: TUNGraphNodeI const *
"""
return _snap.TUNGraphNodeI_GetInDeg(self)
def GetOutDeg(self):
"""
GetOutDeg(TUNGraphNodeI self) -> int
Parameters:
self: TUNGraphNodeI const *
"""
return _snap.TUNGraphNodeI_GetOutDeg(self)
def GetInNId(self, *args):
"""
GetInNId(TUNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TUNGraphNodeI_GetInNId(self, *args)
def GetOutNId(self, *args):
"""
GetOutNId(TUNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TUNGraphNodeI_GetOutNId(self, *args)
def GetNbrNId(self, *args):
"""
GetNbrNId(TUNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TUNGraphNodeI_GetNbrNId(self, *args)
def IsInNId(self, *args):
"""
IsInNId(TUNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraphNodeI_IsInNId(self, *args)
def IsOutNId(self, *args):
"""
IsOutNId(TUNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraphNodeI_IsOutNId(self, *args)
def IsNbrNId(self, *args):
"""
IsNbrNId(TUNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraphNodeI_IsNbrNId(self, *args)
__swig_destroy__ = _snap.delete_TUNGraphNodeI
TUNGraphNodeI.Next = new_instancemethod(_snap.TUNGraphNodeI_Next,None,TUNGraphNodeI)
TUNGraphNodeI.__lt__ = new_instancemethod(_snap.TUNGraphNodeI___lt__,None,TUNGraphNodeI)
TUNGraphNodeI.__eq__ = new_instancemethod(_snap.TUNGraphNodeI___eq__,None,TUNGraphNodeI)
TUNGraphNodeI.GetId = new_instancemethod(_snap.TUNGraphNodeI_GetId,None,TUNGraphNodeI)
TUNGraphNodeI.GetDeg = new_instancemethod(_snap.TUNGraphNodeI_GetDeg,None,TUNGraphNodeI)
TUNGraphNodeI.GetInDeg = new_instancemethod(_snap.TUNGraphNodeI_GetInDeg,None,TUNGraphNodeI)
TUNGraphNodeI.GetOutDeg = new_instancemethod(_snap.TUNGraphNodeI_GetOutDeg,None,TUNGraphNodeI)
TUNGraphNodeI.GetInNId = new_instancemethod(_snap.TUNGraphNodeI_GetInNId,None,TUNGraphNodeI)
TUNGraphNodeI.GetOutNId = new_instancemethod(_snap.TUNGraphNodeI_GetOutNId,None,TUNGraphNodeI)
TUNGraphNodeI.GetNbrNId = new_instancemethod(_snap.TUNGraphNodeI_GetNbrNId,None,TUNGraphNodeI)
TUNGraphNodeI.IsInNId = new_instancemethod(_snap.TUNGraphNodeI_IsInNId,None,TUNGraphNodeI)
TUNGraphNodeI.IsOutNId = new_instancemethod(_snap.TUNGraphNodeI_IsOutNId,None,TUNGraphNodeI)
TUNGraphNodeI.IsNbrNId = new_instancemethod(_snap.TUNGraphNodeI_IsNbrNId,None,TUNGraphNodeI)
TUNGraphNodeI_swigregister = _snap.TUNGraphNodeI_swigregister
TUNGraphNodeI_swigregister(TUNGraphNodeI)
class TUNGraphEdgeI(object):
"""Proxy of C++ TUNGraphEdgeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TUNGraphEdgeI self) -> TUNGraphEdgeI
__init__(TUNGraphEdgeI self, TUNGraph::TEdgeI const & EdgeI) -> TUNGraphEdgeI
Parameters:
EdgeI: TUNGraph::TEdgeI const &
"""
_snap.TUNGraphEdgeI_swiginit(self,_snap.new_TUNGraphEdgeI(*args))
def Next(self):
"""
Next(TUNGraphEdgeI self) -> TUNGraphEdgeI
Parameters:
self: TUNGraphEdgeI *
"""
return _snap.TUNGraphEdgeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TUNGraphEdgeI self, TUNGraphEdgeI EdgeI) -> bool
Parameters:
EdgeI: TUNGraphEdgeI const &
"""
return _snap.TUNGraphEdgeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TUNGraphEdgeI self, TUNGraphEdgeI EdgeI) -> bool
Parameters:
EdgeI: TUNGraphEdgeI const &
"""
return _snap.TUNGraphEdgeI___eq__(self, *args)
def GetId(self):
"""
GetId(TUNGraphEdgeI self) -> int
Parameters:
self: TUNGraphEdgeI const *
"""
return _snap.TUNGraphEdgeI_GetId(self)
def GetSrcNId(self):
"""
GetSrcNId(TUNGraphEdgeI self) -> int
Parameters:
self: TUNGraphEdgeI const *
"""
return _snap.TUNGraphEdgeI_GetSrcNId(self)
def GetDstNId(self):
"""
GetDstNId(TUNGraphEdgeI self) -> int
Parameters:
self: TUNGraphEdgeI const *
"""
return _snap.TUNGraphEdgeI_GetDstNId(self)
__swig_destroy__ = _snap.delete_TUNGraphEdgeI
TUNGraphEdgeI.Next = new_instancemethod(_snap.TUNGraphEdgeI_Next,None,TUNGraphEdgeI)
TUNGraphEdgeI.__lt__ = new_instancemethod(_snap.TUNGraphEdgeI___lt__,None,TUNGraphEdgeI)
TUNGraphEdgeI.__eq__ = new_instancemethod(_snap.TUNGraphEdgeI___eq__,None,TUNGraphEdgeI)
TUNGraphEdgeI.GetId = new_instancemethod(_snap.TUNGraphEdgeI_GetId,None,TUNGraphEdgeI)
TUNGraphEdgeI.GetSrcNId = new_instancemethod(_snap.TUNGraphEdgeI_GetSrcNId,None,TUNGraphEdgeI)
TUNGraphEdgeI.GetDstNId = new_instancemethod(_snap.TUNGraphEdgeI_GetDstNId,None,TUNGraphEdgeI)
TUNGraphEdgeI_swigregister = _snap.TUNGraphEdgeI_swigregister
TUNGraphEdgeI_swigregister(TUNGraphEdgeI)
class TNEANetNodeI(object):
"""Proxy of C++ TNEANetNodeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetNodeI self) -> TNEANetNodeI
__init__(TNEANetNodeI self, TNEANet::TNodeI const & NodeI) -> TNEANetNodeI
Parameters:
NodeI: TNEANet::TNodeI const &
"""
_snap.TNEANetNodeI_swiginit(self,_snap.new_TNEANetNodeI(*args))
def Next(self):
"""
Next(TNEANetNodeI self) -> TNEANetNodeI
Parameters:
self: TNEANetNodeI *
"""
return _snap.TNEANetNodeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetNodeI self, TNEANetNodeI NodeI) -> bool
Parameters:
NodeI: TNEANetNodeI const &
"""
return _snap.TNEANetNodeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetNodeI self, TNEANetNodeI NodeI) -> bool
Parameters:
NodeI: TNEANetNodeI const &
"""
return _snap.TNEANetNodeI___eq__(self, *args)
def GetId(self):
"""
GetId(TNEANetNodeI self) -> int
Parameters:
self: TNEANetNodeI const *
"""
return _snap.TNEANetNodeI_GetId(self)
def GetDeg(self):
"""
GetDeg(TNEANetNodeI self) -> int
Parameters:
self: TNEANetNodeI const *
"""
return _snap.TNEANetNodeI_GetDeg(self)
def GetInDeg(self):
"""
GetInDeg(TNEANetNodeI self) -> int
Parameters:
self: TNEANetNodeI const *
"""
return _snap.TNEANetNodeI_GetInDeg(self)
def GetOutDeg(self):
"""
GetOutDeg(TNEANetNodeI self) -> int
Parameters:
self: TNEANetNodeI const *
"""
return _snap.TNEANetNodeI_GetOutDeg(self)
def GetInNId(self, *args):
"""
GetInNId(TNEANetNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNEANetNodeI_GetInNId(self, *args)
def GetOutNId(self, *args):
"""
GetOutNId(TNEANetNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNEANetNodeI_GetOutNId(self, *args)
def GetNbrNId(self, *args):
"""
GetNbrNId(TNEANetNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNEANetNodeI_GetNbrNId(self, *args)
def IsInNId(self, *args):
"""
IsInNId(TNEANetNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEANetNodeI_IsInNId(self, *args)
def IsOutNId(self, *args):
"""
IsOutNId(TNEANetNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEANetNodeI_IsOutNId(self, *args)
def IsNbrNId(self, *args):
"""
IsNbrNId(TNEANetNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEANetNodeI_IsNbrNId(self, *args)
__swig_destroy__ = _snap.delete_TNEANetNodeI
TNEANetNodeI.Next = new_instancemethod(_snap.TNEANetNodeI_Next,None,TNEANetNodeI)
TNEANetNodeI.__lt__ = new_instancemethod(_snap.TNEANetNodeI___lt__,None,TNEANetNodeI)
TNEANetNodeI.__eq__ = new_instancemethod(_snap.TNEANetNodeI___eq__,None,TNEANetNodeI)
TNEANetNodeI.GetId = new_instancemethod(_snap.TNEANetNodeI_GetId,None,TNEANetNodeI)
TNEANetNodeI.GetDeg = new_instancemethod(_snap.TNEANetNodeI_GetDeg,None,TNEANetNodeI)
TNEANetNodeI.GetInDeg = new_instancemethod(_snap.TNEANetNodeI_GetInDeg,None,TNEANetNodeI)
TNEANetNodeI.GetOutDeg = new_instancemethod(_snap.TNEANetNodeI_GetOutDeg,None,TNEANetNodeI)
TNEANetNodeI.GetInNId = new_instancemethod(_snap.TNEANetNodeI_GetInNId,None,TNEANetNodeI)
TNEANetNodeI.GetOutNId = new_instancemethod(_snap.TNEANetNodeI_GetOutNId,None,TNEANetNodeI)
TNEANetNodeI.GetNbrNId = new_instancemethod(_snap.TNEANetNodeI_GetNbrNId,None,TNEANetNodeI)
TNEANetNodeI.IsInNId = new_instancemethod(_snap.TNEANetNodeI_IsInNId,None,TNEANetNodeI)
TNEANetNodeI.IsOutNId = new_instancemethod(_snap.TNEANetNodeI_IsOutNId,None,TNEANetNodeI)
TNEANetNodeI.IsNbrNId = new_instancemethod(_snap.TNEANetNodeI_IsNbrNId,None,TNEANetNodeI)
TNEANetNodeI_swigregister = _snap.TNEANetNodeI_swigregister
TNEANetNodeI_swigregister(TNEANetNodeI)
class TNEANetEdgeI(object):
"""Proxy of C++ TNEANetEdgeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetEdgeI self) -> TNEANetEdgeI
__init__(TNEANetEdgeI self, TNEANet::TEdgeI const & EdgeI) -> TNEANetEdgeI
Parameters:
EdgeI: TNEANet::TEdgeI const &
"""
_snap.TNEANetEdgeI_swiginit(self,_snap.new_TNEANetEdgeI(*args))
def Next(self):
"""
Next(TNEANetEdgeI self) -> TNEANetEdgeI
Parameters:
self: TNEANetEdgeI *
"""
return _snap.TNEANetEdgeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetEdgeI self, TNEANetEdgeI EdgeI) -> bool
Parameters:
EdgeI: TNEANetEdgeI const &
"""
return _snap.TNEANetEdgeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetEdgeI self, TNEANetEdgeI EdgeI) -> bool
Parameters:
EdgeI: TNEANetEdgeI const &
"""
return _snap.TNEANetEdgeI___eq__(self, *args)
def GetId(self):
"""
GetId(TNEANetEdgeI self) -> int
Parameters:
self: TNEANetEdgeI const *
"""
return _snap.TNEANetEdgeI_GetId(self)
def GetSrcNId(self):
"""
GetSrcNId(TNEANetEdgeI self) -> int
Parameters:
self: TNEANetEdgeI const *
"""
return _snap.TNEANetEdgeI_GetSrcNId(self)
def GetDstNId(self):
"""
GetDstNId(TNEANetEdgeI self) -> int
Parameters:
self: TNEANetEdgeI const *
"""
return _snap.TNEANetEdgeI_GetDstNId(self)
__swig_destroy__ = _snap.delete_TNEANetEdgeI
TNEANetEdgeI.Next = new_instancemethod(_snap.TNEANetEdgeI_Next,None,TNEANetEdgeI)
TNEANetEdgeI.__lt__ = new_instancemethod(_snap.TNEANetEdgeI___lt__,None,TNEANetEdgeI)
TNEANetEdgeI.__eq__ = new_instancemethod(_snap.TNEANetEdgeI___eq__,None,TNEANetEdgeI)
TNEANetEdgeI.GetId = new_instancemethod(_snap.TNEANetEdgeI_GetId,None,TNEANetEdgeI)
TNEANetEdgeI.GetSrcNId = new_instancemethod(_snap.TNEANetEdgeI_GetSrcNId,None,TNEANetEdgeI)
TNEANetEdgeI.GetDstNId = new_instancemethod(_snap.TNEANetEdgeI_GetDstNId,None,TNEANetEdgeI)
TNEANetEdgeI_swigregister = _snap.TNEANetEdgeI_swigregister
TNEANetEdgeI_swigregister(TNEANetEdgeI)
class TNEANetAIntI(object):
"""Proxy of C++ TNEANetAIntI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetAIntI self) -> TNEANetAIntI
__init__(TNEANetAIntI self, TIntVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAIntI
Parameters:
HIter: TIntVecIter const &
attribute: TStr
isEdgeIter: bool
GraphPt: TNEANet const *
__init__(TNEANetAIntI self, TNEANet::TAIntI const & I) -> TNEANetAIntI
Parameters:
I: TNEANet::TAIntI const &
"""
_snap.TNEANetAIntI_swiginit(self,_snap.new_TNEANetAIntI(*args))
def Next(self):
"""
Next(TNEANetAIntI self) -> TNEANetAIntI
Parameters:
self: TNEANetAIntI *
"""
return _snap.TNEANetAIntI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetAIntI self, TNEANetAIntI I) -> bool
Parameters:
I: TNEANetAIntI const &
"""
return _snap.TNEANetAIntI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetAIntI self, TNEANetAIntI I) -> bool
Parameters:
I: TNEANetAIntI const &
"""
return _snap.TNEANetAIntI___eq__(self, *args)
def GetDat(self):
"""
GetDat(TNEANetAIntI self) -> int
Parameters:
self: TNEANetAIntI const *
"""
return _snap.TNEANetAIntI_GetDat(self)
def IsDeleted(self):
"""
IsDeleted(TNEANetAIntI self) -> bool
Parameters:
self: TNEANetAIntI const *
"""
return _snap.TNEANetAIntI_IsDeleted(self)
__swig_destroy__ = _snap.delete_TNEANetAIntI
TNEANetAIntI.Next = new_instancemethod(_snap.TNEANetAIntI_Next,None,TNEANetAIntI)
TNEANetAIntI.__lt__ = new_instancemethod(_snap.TNEANetAIntI___lt__,None,TNEANetAIntI)
TNEANetAIntI.__eq__ = new_instancemethod(_snap.TNEANetAIntI___eq__,None,TNEANetAIntI)
TNEANetAIntI.GetDat = new_instancemethod(_snap.TNEANetAIntI_GetDat,None,TNEANetAIntI)
TNEANetAIntI.IsDeleted = new_instancemethod(_snap.TNEANetAIntI_IsDeleted,None,TNEANetAIntI)
TNEANetAIntI_swigregister = _snap.TNEANetAIntI_swigregister
TNEANetAIntI_swigregister(TNEANetAIntI)
class TNEANetAStrI(object):
"""Proxy of C++ TNEANetAStrI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetAStrI self) -> TNEANetAStrI
__init__(TNEANetAStrI self, TStrVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAStrI
Parameters:
HIter: TStrVecIter const &
attribute: TStr
isEdgeIter: bool
GraphPt: TNEANet const *
__init__(TNEANetAStrI self, TNEANet::TAStrI const & I) -> TNEANetAStrI
Parameters:
I: TNEANet::TAStrI const &
"""
_snap.TNEANetAStrI_swiginit(self,_snap.new_TNEANetAStrI(*args))
def Next(self):
"""
Next(TNEANetAStrI self) -> TNEANetAStrI
Parameters:
self: TNEANetAStrI *
"""
return _snap.TNEANetAStrI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetAStrI self, TNEANetAStrI I) -> bool
Parameters:
I: TNEANetAStrI const &
"""
return _snap.TNEANetAStrI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetAStrI self, TNEANetAStrI I) -> bool
Parameters:
I: TNEANetAStrI const &
"""
return _snap.TNEANetAStrI___eq__(self, *args)
def GetDat(self):
"""
GetDat(TNEANetAStrI self) -> char *
Parameters:
self: TNEANetAStrI const *
"""
return _snap.TNEANetAStrI_GetDat(self)
def IsDeleted(self):
"""
IsDeleted(TNEANetAStrI self) -> bool
Parameters:
self: TNEANetAStrI const *
"""
return _snap.TNEANetAStrI_IsDeleted(self)
__swig_destroy__ = _snap.delete_TNEANetAStrI
TNEANetAStrI.Next = new_instancemethod(_snap.TNEANetAStrI_Next,None,TNEANetAStrI)
TNEANetAStrI.__lt__ = new_instancemethod(_snap.TNEANetAStrI___lt__,None,TNEANetAStrI)
TNEANetAStrI.__eq__ = new_instancemethod(_snap.TNEANetAStrI___eq__,None,TNEANetAStrI)
TNEANetAStrI.GetDat = new_instancemethod(_snap.TNEANetAStrI_GetDat,None,TNEANetAStrI)
TNEANetAStrI.IsDeleted = new_instancemethod(_snap.TNEANetAStrI_IsDeleted,None,TNEANetAStrI)
TNEANetAStrI_swigregister = _snap.TNEANetAStrI_swigregister
TNEANetAStrI_swigregister(TNEANetAStrI)
class TNEANetAFltI(object):
"""Proxy of C++ TNEANetAFltI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetAFltI self) -> TNEANetAFltI
__init__(TNEANetAFltI self, TFltVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAFltI
Parameters:
HIter: TFltVecIter const &
attribute: TStr
isEdgeIter: bool
GraphPt: TNEANet const *
__init__(TNEANetAFltI self, TNEANet::TAFltI const & I) -> TNEANetAFltI
Parameters:
I: TNEANet::TAFltI const &
"""
_snap.TNEANetAFltI_swiginit(self,_snap.new_TNEANetAFltI(*args))
def Next(self):
"""
Next(TNEANetAFltI self) -> TNEANetAFltI
Parameters:
self: TNEANetAFltI *
"""
return _snap.TNEANetAFltI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetAFltI self, TNEANetAFltI I) -> bool
Parameters:
I: TNEANetAFltI const &
"""
return _snap.TNEANetAFltI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetAFltI self, TNEANetAFltI I) -> bool
Parameters:
I: TNEANetAFltI const &
"""
return _snap.TNEANetAFltI___eq__(self, *args)
def GetDat(self):
"""
GetDat(TNEANetAFltI self) -> double
Parameters:
self: TNEANetAFltI const *
"""
return _snap.TNEANetAFltI_GetDat(self)
def IsDeleted(self):
"""
IsDeleted(TNEANetAFltI self) -> bool
Parameters:
self: TNEANetAFltI const *
"""
return _snap.TNEANetAFltI_IsDeleted(self)
__swig_destroy__ = _snap.delete_TNEANetAFltI
TNEANetAFltI.Next = new_instancemethod(_snap.TNEANetAFltI_Next,None,TNEANetAFltI)
TNEANetAFltI.__lt__ = new_instancemethod(_snap.TNEANetAFltI___lt__,None,TNEANetAFltI)
TNEANetAFltI.__eq__ = new_instancemethod(_snap.TNEANetAFltI___eq__,None,TNEANetAFltI)
TNEANetAFltI.GetDat = new_instancemethod(_snap.TNEANetAFltI_GetDat,None,TNEANetAFltI)
TNEANetAFltI.IsDeleted = new_instancemethod(_snap.TNEANetAFltI_IsDeleted,None,TNEANetAFltI)
TNEANetAFltI_swigregister = _snap.TNEANetAFltI_swigregister
TNEANetAFltI_swigregister(TNEANetAFltI)
def TPrGraph(*args):
"""
TPrGraph(PUNGraph G) -> TUNGraph
Parameters:
G: PUNGraph
"""
return _snap.TPrGraph(*args)
def accept_array(*args):
"""
accept_array(int [] array) -> int
Parameters:
array: int []
"""
return _snap.accept_array(*args)
def print_array(*args):
"""
print_array(int * x, int length)
Parameters:
x: int *
length: int
"""
return _snap.print_array(*args)
def PyTFltV(*args):
"""
PyTFltV(double [10] x) -> TFltV
Parameters:
x: double [10]
"""
return _snap.PyTFltV(*args)
def PyToTIntV(*args):
"""
PyToTIntV(int * array) -> TIntV
Parameters:
array: int *
"""
return _snap.PyToTIntV(*args)
def count(*args):
"""
count(char * str, char c) -> int
Parameters:
str: char *
c: char
"""
return _snap.count(*args)
def TIntVToPy(*args):
"""
TIntVToPy(TIntV originalList)
Parameters:
originalList: TIntV
"""
return _snap.TIntVToPy(*args)
class TNEANet(object):
"""Proxy of C++ TNEANet class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANet self) -> TNEANet
__init__(TNEANet self, int const & Nodes, int const & Edges) -> TNEANet
Parameters:
Nodes: int const &
Edges: int const &
__init__(TNEANet self, TNEANet Graph) -> TNEANet
Parameters:
Graph: TNEANet const &
__init__(TNEANet self, TSIn SIn) -> TNEANet
Parameters:
SIn: TSIn &
"""
_snap.TNEANet_swiginit(self,_snap.new_TNEANet(*args))
def Save(self, *args):
"""
Save(TNEANet self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TNEANet_Save(self, *args)
def New(*args):
"""
New() -> PNEANet
New(int const & Nodes, int const & Edges) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEANet_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PNEANet
Parameters:
SIn: TSIn &
"""
return _snap.TNEANet_Load(*args)
Load = staticmethod(Load)
def HasFlag(self, *args):
"""
HasFlag(TNEANet self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.TNEANet_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(TNEANet self) -> int
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(TNEANet self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TNEANet self) -> int
AddNode(TNEANet self, TNEANet::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
"""
return _snap.TNEANet_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TNEANet self, int const & NId)
Parameters:
NId: int const &
DelNode(TNEANet self, TNEANet::TNode const & NodeI)
Parameters:
NodeI: TNEANet::TNode const &
"""
return _snap.TNEANet_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TNEANet self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEANet_IsNode(self, *args)
def GetNI(self, *args):
"""
GetNI(TNEANet self, int const & NId) -> TNEANet::TNodeI
Parameters:
NId: int const &
"""
return _snap.TNEANet_GetNI(self, *args)
def GetNAIntI(self, *args):
"""
GetNAIntI(TNEANet self, TStr attr, int const & NId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.TNEANet_GetNAIntI(self, *args)
def GetNAStrI(self, *args):
"""
GetNAStrI(TNEANet self, TStr attr, int const & NId) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.TNEANet_GetNAStrI(self, *args)
def GetNAFltI(self, *args):
"""
GetNAFltI(TNEANet self, TStr attr, int const & NId) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.TNEANet_GetNAFltI(self, *args)
def AttrNameNI(self, *args):
"""
AttrNameNI(TNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
AttrNameNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_AttrNameNI(self, *args)
def AttrValueNI(self, *args):
"""
AttrValueNI(TNEANet self, TInt NId, TStrV Values)
Parameters:
NId: TInt const &
Values: TStrV &
AttrValueNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.TNEANet_AttrValueNI(self, *args)
def IntAttrNameNI(self, *args):
"""
IntAttrNameNI(TNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
IntAttrNameNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_IntAttrNameNI(self, *args)
def IntAttrValueNI(self, *args):
"""
IntAttrValueNI(TNEANet self, TInt NId, TIntV Values)
Parameters:
NId: TInt const &
Values: TIntV &
IntAttrValueNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TIntV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.TNEANet_IntAttrValueNI(self, *args)
def StrAttrNameNI(self, *args):
"""
StrAttrNameNI(TNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
StrAttrNameNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_StrAttrNameNI(self, *args)
def StrAttrValueNI(self, *args):
"""
StrAttrValueNI(TNEANet self, TInt NId, TStrV Values)
Parameters:
NId: TInt const &
Values: TStrV &
StrAttrValueNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.TNEANet_StrAttrValueNI(self, *args)
def FltAttrNameNI(self, *args):
"""
FltAttrNameNI(TNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
FltAttrNameNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_FltAttrNameNI(self, *args)
def FltAttrValueNI(self, *args):
"""
FltAttrValueNI(TNEANet self, TInt NId, TFltV & Values)
Parameters:
NId: TInt const &
Values: TFltV &
FltAttrValueNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TFltV & Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.TNEANet_FltAttrValueNI(self, *args)
def AttrNameEI(self, *args):
"""
AttrNameEI(TNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
AttrNameEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_AttrNameEI(self, *args)
def AttrValueEI(self, *args):
"""
AttrValueEI(TNEANet self, TInt EId, TStrV Values)
Parameters:
EId: TInt const &
Values: TStrV &
AttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.TNEANet_AttrValueEI(self, *args)
def IntAttrNameEI(self, *args):
"""
IntAttrNameEI(TNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
IntAttrNameEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_IntAttrNameEI(self, *args)
def IntAttrValueEI(self, *args):
"""
IntAttrValueEI(TNEANet self, TInt EId, TIntV Values)
Parameters:
EId: TInt const &
Values: TIntV &
IntAttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TIntV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.TNEANet_IntAttrValueEI(self, *args)
def StrAttrNameEI(self, *args):
"""
StrAttrNameEI(TNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
StrAttrNameEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_StrAttrNameEI(self, *args)
def StrAttrValueEI(self, *args):
"""
StrAttrValueEI(TNEANet self, TInt EId, TStrV Values)
Parameters:
EId: TInt const &
Values: TStrV &
StrAttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.TNEANet_StrAttrValueEI(self, *args)
def FltAttrNameEI(self, *args):
"""
FltAttrNameEI(TNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
FltAttrNameEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_FltAttrNameEI(self, *args)
def FltAttrValueEI(self, *args):
"""
FltAttrValueEI(TNEANet self, TInt EId, TFltV & Values)
Parameters:
EId: TInt const &
Values: TFltV &
FltAttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TFltV & Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.TNEANet_FltAttrValueEI(self, *args)
def GetEAIntI(self, *args):
"""
GetEAIntI(TNEANet self, TStr attr, int const & EId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.TNEANet_GetEAIntI(self, *args)
def GetEAStrI(self, *args):
"""
GetEAStrI(TNEANet self, TStr attr, int const & EId) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.TNEANet_GetEAStrI(self, *args)
def GetEAFltI(self, *args):
"""
GetEAFltI(TNEANet self, TStr attr, int const & EId) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.TNEANet_GetEAFltI(self, *args)
def GetMxNId(self):
"""
GetMxNId(TNEANet self) -> int
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(TNEANet self) -> int
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TNEANet self, int const & SrcNId, int const & DstNId, int EId=-1) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int
AddEdge(TNEANet self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(TNEANet self, TNEANet::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TNEANet::TEdgeI const &
"""
return _snap.TNEANet_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TNEANet self, int const & EId)
Parameters:
EId: int const &
DelEdge(TNEANet self, int const & SrcNId, int const & DstNId, bool const & IsDir=True)
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
DelEdge(TNEANet self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEANet_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TNEANet self, int const & EId) -> bool
Parameters:
EId: int const &
IsEdge(TNEANet self, int const & SrcNId, int const & DstNId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
IsEdge(TNEANet self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsEdge(TNEANet self, int const & SrcNId, int const & DstNId, int & EId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
IsDir: bool const &
IsEdge(TNEANet self, int const & SrcNId, int const & DstNId, int & EId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
"""
return _snap.TNEANet_IsEdge(self, *args)
def GetEId(self, *args):
"""
GetEId(TNEANet self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEANet_GetEId(self, *args)
def GetEI(self, *args):
"""
GetEI(TNEANet self, int const & SrcNId, int const & DstNId) -> TNEANet::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEANet_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TNEANet self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TNEANet self) -> int
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TNEANet self, TRnd Rnd=Rnd) -> TNEANet::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TNEANet self) -> TNEANet::TNodeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndNI(self, *args)
def GetRndEId(self, *args):
"""
GetRndEId(TNEANet self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndEId(TNEANet self) -> int
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndEId(self, *args)
def GetRndEI(self, *args):
"""
GetRndEI(TNEANet self, TRnd Rnd=Rnd) -> TNEANet::TEdgeI
Parameters:
Rnd: TRnd &
GetRndEI(TNEANet self) -> TNEANet::TEdgeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndEI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TNEANet self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TNEANet_GetNIdV(self, *args)
def GetEIdV(self, *args):
"""
GetEIdV(TNEANet self, TIntV EIdV)
Parameters:
EIdV: TIntV &
"""
return _snap.TNEANet_GetEIdV(self, *args)
def Empty(self):
"""
Empty(TNEANet self) -> bool
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_Empty(self)
def Clr(self):
"""
Clr(TNEANet self)
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_Clr(self)
def Reserve(self, *args):
"""
Reserve(TNEANet self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEANet_Reserve(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TNEANet self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TNEANet self)
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TNEANet self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TNEANet self) -> bool
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TNEANet self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TNEANet self)
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_Dump(self, *args)
def AddIntAttrDatN(self, *args):
"""
AddIntAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TInt value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TInt const &
attr: TStr const &
AddIntAttrDatN(TNEANet self, int const & NId, TInt value, TStr attr) -> int
Parameters:
NId: int const &
value: TInt const &
attr: TStr const &
"""
return _snap.TNEANet_AddIntAttrDatN(self, *args)
def AddStrAttrDatN(self, *args):
"""
AddStrAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TStr const &
attr: TStr const &
AddStrAttrDatN(TNEANet self, int const & NId, TStr value, TStr attr) -> int
Parameters:
NId: int const &
value: TStr const &
attr: TStr const &
"""
return _snap.TNEANet_AddStrAttrDatN(self, *args)
def AddFltAttrDatN(self, *args):
"""
AddFltAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TFlt value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TFlt const &
attr: TStr const &
AddFltAttrDatN(TNEANet self, int const & NId, TFlt value, TStr attr) -> int
Parameters:
NId: int const &
value: TFlt const &
attr: TStr const &
"""
return _snap.TNEANet_AddFltAttrDatN(self, *args)
def AddIntAttrDatE(self, *args):
"""
AddIntAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TInt value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TInt const &
attr: TStr const &
AddIntAttrDatE(TNEANet self, int const & EId, TInt value, TStr attr) -> int
Parameters:
EId: int const &
value: TInt const &
attr: TStr const &
"""
return _snap.TNEANet_AddIntAttrDatE(self, *args)
def AddStrAttrDatE(self, *args):
"""
AddStrAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TStr const &
attr: TStr const &
AddStrAttrDatE(TNEANet self, int const & EId, TStr value, TStr attr) -> int
Parameters:
EId: int const &
value: TStr const &
attr: TStr const &
"""
return _snap.TNEANet_AddStrAttrDatE(self, *args)
def AddFltAttrDatE(self, *args):
"""
AddFltAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TFlt value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TFlt const &
attr: TStr const &
AddFltAttrDatE(TNEANet self, int const & EId, TFlt value, TStr attr) -> int
Parameters:
EId: int const &
value: TFlt const &
attr: TStr const &
"""
return _snap.TNEANet_AddFltAttrDatE(self, *args)
def GetIntAttrDatN(self, *args):
"""
GetIntAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TInt
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetIntAttrDatN(TNEANet self, int const & NId, TStr attr) -> TInt
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetIntAttrDatN(self, *args)
def GetStrAttrDatN(self, *args):
"""
GetStrAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TStr
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetStrAttrDatN(TNEANet self, int const & NId, TStr attr) -> TStr
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetStrAttrDatN(self, *args)
def GetFltAttrDatN(self, *args):
"""
GetFltAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TFlt
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetFltAttrDatN(TNEANet self, int const & NId, TStr attr) -> TFlt
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetFltAttrDatN(self, *args)
def GetIntAttrDatE(self, *args):
"""
GetIntAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TInt
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetIntAttrDatE(TNEANet self, int const & EId, TStr attr) -> TInt
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetIntAttrDatE(self, *args)
def GetStrAttrDatE(self, *args):
"""
GetStrAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TStr
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetStrAttrDatE(TNEANet self, int const & EId, TStr attr) -> TStr
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetStrAttrDatE(self, *args)
def GetFltAttrDatE(self, *args):
"""
GetFltAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TFlt
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetFltAttrDatE(TNEANet self, int const & EId, TStr attr) -> TFlt
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetFltAttrDatE(self, *args)
def DelAttrDatN(self, *args):
"""
DelAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
DelAttrDatN(TNEANet self, int const & NId, TStr attr) -> int
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.TNEANet_DelAttrDatN(self, *args)
def DelAttrDatE(self, *args):
"""
DelAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
DelAttrDatE(TNEANet self, int const & EId, TStr attr) -> int
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.TNEANet_DelAttrDatE(self, *args)
def AddIntAttrN(self, *args):
"""
AddIntAttrN(TNEANet self, TStr attr, TInt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TInt
AddIntAttrN(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddIntAttrN(self, *args)
def AddStrAttrN(self, *args):
"""
AddStrAttrN(TNEANet self, TStr attr, TStr defaultValue=TStr::GetNullStr()) -> int
Parameters:
attr: TStr const &
defaultValue: TStr
AddStrAttrN(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddStrAttrN(self, *args)
def AddFltAttrN(self, *args):
"""
AddFltAttrN(TNEANet self, TStr attr, TFlt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TFlt
AddFltAttrN(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddFltAttrN(self, *args)
def AddIntAttrE(self, *args):
"""
AddIntAttrE(TNEANet self, TStr attr, TInt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TInt
AddIntAttrE(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddIntAttrE(self, *args)
def AddStrAttrE(self, *args):
"""
AddStrAttrE(TNEANet self, TStr attr, TStr defaultValue=TStr::GetNullStr()) -> int
Parameters:
attr: TStr const &
defaultValue: TStr
AddStrAttrE(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddStrAttrE(self, *args)
def AddFltAttrE(self, *args):
"""
AddFltAttrE(TNEANet self, TStr attr, TFlt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TFlt
AddFltAttrE(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddFltAttrE(self, *args)
def DelAttrN(self, *args):
"""
DelAttrN(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_DelAttrN(self, *args)
def DelAttrE(self, *args):
"""
DelAttrE(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_DelAttrE(self, *args)
def NodeAttrIsDeleted(self, *args):
"""
NodeAttrIsDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_NodeAttrIsDeleted(self, *args)
def NodeAttrIsIntDeleted(self, *args):
"""
NodeAttrIsIntDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_NodeAttrIsIntDeleted(self, *args)
def NodeAttrIsStrDeleted(self, *args):
"""
NodeAttrIsStrDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_NodeAttrIsStrDeleted(self, *args)
def NodeAttrIsFltDeleted(self, *args):
"""
NodeAttrIsFltDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_NodeAttrIsFltDeleted(self, *args)
def EdgeAttrIsDeleted(self, *args):
"""
EdgeAttrIsDeleted(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_EdgeAttrIsDeleted(self, *args)
def EdgeAttrIsIntDeleted(self, *args):
"""
EdgeAttrIsIntDeleted(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_EdgeAttrIsIntDeleted(self, *args)
def EdgeAttrIsStrDeleted(self, *args):
"""
EdgeAttrIsStrDeleted(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_EdgeAttrIsStrDeleted(self, *args)
def EdgeAttrIsFltDeleted(self, *args):
"""
EdgeAttrIsFltDeleted(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_EdgeAttrIsFltDeleted(self, *args)
def GetNodeAttrValue(self, *args):
"""
GetNodeAttrValue(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> TStr
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_GetNodeAttrValue(self, *args)
def GetEdgeAttrValue(self, *args):
"""
GetEdgeAttrValue(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> TStr
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_GetEdgeAttrValue(self, *args)
def BegNI(self, *args):
"""
BegNI(TNEANet self) -> TNEANet::TNodeI
BegNI(TNEANet self) -> TNEANetNodeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_BegNI(self, *args)
def EndNI(self, *args):
"""
EndNI(TNEANet self) -> TNEANet::TNodeI
EndNI(TNEANet self) -> TNEANetNodeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_EndNI(self, *args)
def BegEI(self, *args):
"""
BegEI(TNEANet self) -> TNEANet::TEdgeI
BegEI(TNEANet self) -> TNEANetEdgeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_BegEI(self, *args)
def EndEI(self, *args):
"""
EndEI(TNEANet self) -> TNEANet::TEdgeI
EndEI(TNEANet self) -> TNEANetEdgeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_EndEI(self, *args)
def BegNAIntI(self, *args):
"""
BegNAIntI(TNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
BegNAIntI(TNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegNAIntI(self, *args)
def EndNAIntI(self, *args):
"""
EndNAIntI(TNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EndNAIntI(TNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndNAIntI(self, *args)
def BegNAStrI(self, *args):
"""
BegNAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegNAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegNAStrI(self, *args)
def EndNAStrI(self, *args):
"""
EndNAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EndNAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndNAStrI(self, *args)
def BegNAFltI(self, *args):
"""
BegNAFltI(TNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
BegNAFltI(TNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegNAFltI(self, *args)
def EndNAFltI(self, *args):
"""
EndNAFltI(TNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EndNAFltI(TNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndNAFltI(self, *args)
def BegEAIntI(self, *args):
"""
BegEAIntI(TNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
BegEAIntI(TNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegEAIntI(self, *args)
def EndEAIntI(self, *args):
"""
EndEAIntI(TNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EndEAIntI(TNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndEAIntI(self, *args)
def BegEAStrI(self, *args):
"""
BegEAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegEAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegEAStrI(self, *args)
def EndEAStrI(self, *args):
"""
EndEAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EndEAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndEAStrI(self, *args)
def BegEAFltI(self, *args):
"""
BegEAFltI(TNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
BegEAFltI(TNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegEAFltI(self, *args)
def EndEAFltI(self, *args):
"""
EndEAFltI(TNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EndEAFltI(TNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndEAFltI(self, *args)
__swig_destroy__ = _snap.delete_TNEANet
TNEANet.Save = new_instancemethod(_snap.TNEANet_Save,None,TNEANet)
TNEANet.HasFlag = new_instancemethod(_snap.TNEANet_HasFlag,None,TNEANet)
TNEANet.GetNodes = new_instancemethod(_snap.TNEANet_GetNodes,None,TNEANet)
TNEANet.AddNode = new_instancemethod(_snap.TNEANet_AddNode,None,TNEANet)
TNEANet.DelNode = new_instancemethod(_snap.TNEANet_DelNode,None,TNEANet)
TNEANet.IsNode = new_instancemethod(_snap.TNEANet_IsNode,None,TNEANet)
TNEANet.GetNI = new_instancemethod(_snap.TNEANet_GetNI,None,TNEANet)
TNEANet.GetNAIntI = new_instancemethod(_snap.TNEANet_GetNAIntI,None,TNEANet)
TNEANet.GetNAStrI = new_instancemethod(_snap.TNEANet_GetNAStrI,None,TNEANet)
TNEANet.GetNAFltI = new_instancemethod(_snap.TNEANet_GetNAFltI,None,TNEANet)
TNEANet.AttrNameNI = new_instancemethod(_snap.TNEANet_AttrNameNI,None,TNEANet)
TNEANet.AttrValueNI = new_instancemethod(_snap.TNEANet_AttrValueNI,None,TNEANet)
TNEANet.IntAttrNameNI = new_instancemethod(_snap.TNEANet_IntAttrNameNI,None,TNEANet)
TNEANet.IntAttrValueNI = new_instancemethod(_snap.TNEANet_IntAttrValueNI,None,TNEANet)
TNEANet.StrAttrNameNI = new_instancemethod(_snap.TNEANet_StrAttrNameNI,None,TNEANet)
TNEANet.StrAttrValueNI = new_instancemethod(_snap.TNEANet_StrAttrValueNI,None,TNEANet)
TNEANet.FltAttrNameNI = new_instancemethod(_snap.TNEANet_FltAttrNameNI,None,TNEANet)
TNEANet.FltAttrValueNI = new_instancemethod(_snap.TNEANet_FltAttrValueNI,None,TNEANet)
TNEANet.AttrNameEI = new_instancemethod(_snap.TNEANet_AttrNameEI,None,TNEANet)
TNEANet.AttrValueEI = new_instancemethod(_snap.TNEANet_AttrValueEI,None,TNEANet)
TNEANet.IntAttrNameEI = new_instancemethod(_snap.TNEANet_IntAttrNameEI,None,TNEANet)
TNEANet.IntAttrValueEI = new_instancemethod(_snap.TNEANet_IntAttrValueEI,None,TNEANet)
TNEANet.StrAttrNameEI = new_instancemethod(_snap.TNEANet_StrAttrNameEI,None,TNEANet)
TNEANet.StrAttrValueEI = new_instancemethod(_snap.TNEANet_StrAttrValueEI,None,TNEANet)
TNEANet.FltAttrNameEI = new_instancemethod(_snap.TNEANet_FltAttrNameEI,None,TNEANet)
TNEANet.FltAttrValueEI = new_instancemethod(_snap.TNEANet_FltAttrValueEI,None,TNEANet)
TNEANet.GetEAIntI = new_instancemethod(_snap.TNEANet_GetEAIntI,None,TNEANet)
TNEANet.GetEAStrI = new_instancemethod(_snap.TNEANet_GetEAStrI,None,TNEANet)
TNEANet.GetEAFltI = new_instancemethod(_snap.TNEANet_GetEAFltI,None,TNEANet)
TNEANet.GetMxNId = new_instancemethod(_snap.TNEANet_GetMxNId,None,TNEANet)
TNEANet.GetEdges = new_instancemethod(_snap.TNEANet_GetEdges,None,TNEANet)
TNEANet.AddEdge = new_instancemethod(_snap.TNEANet_AddEdge,None,TNEANet)
TNEANet.DelEdge = new_instancemethod(_snap.TNEANet_DelEdge,None,TNEANet)
TNEANet.IsEdge = new_instancemethod(_snap.TNEANet_IsEdge,None,TNEANet)
TNEANet.GetEId = new_instancemethod(_snap.TNEANet_GetEId,None,TNEANet)
TNEANet.GetEI = new_instancemethod(_snap.TNEANet_GetEI,None,TNEANet)
TNEANet.GetRndNId = new_instancemethod(_snap.TNEANet_GetRndNId,None,TNEANet)
TNEANet.GetRndNI = new_instancemethod(_snap.TNEANet_GetRndNI,None,TNEANet)
TNEANet.GetRndEId = new_instancemethod(_snap.TNEANet_GetRndEId,None,TNEANet)
TNEANet.GetRndEI = new_instancemethod(_snap.TNEANet_GetRndEI,None,TNEANet)
TNEANet.GetNIdV = new_instancemethod(_snap.TNEANet_GetNIdV,None,TNEANet)
TNEANet.GetEIdV = new_instancemethod(_snap.TNEANet_GetEIdV,None,TNEANet)
TNEANet.Empty = new_instancemethod(_snap.TNEANet_Empty,None,TNEANet)
TNEANet.Clr = new_instancemethod(_snap.TNEANet_Clr,None,TNEANet)
TNEANet.Reserve = new_instancemethod(_snap.TNEANet_Reserve,None,TNEANet)
TNEANet.Defrag = new_instancemethod(_snap.TNEANet_Defrag,None,TNEANet)
TNEANet.IsOk = new_instancemethod(_snap.TNEANet_IsOk,None,TNEANet)
TNEANet.Dump = new_instancemethod(_snap.TNEANet_Dump,None,TNEANet)
TNEANet.AddIntAttrDatN = new_instancemethod(_snap.TNEANet_AddIntAttrDatN,None,TNEANet)
TNEANet.AddStrAttrDatN = new_instancemethod(_snap.TNEANet_AddStrAttrDatN,None,TNEANet)
TNEANet.AddFltAttrDatN = new_instancemethod(_snap.TNEANet_AddFltAttrDatN,None,TNEANet)
TNEANet.AddIntAttrDatE = new_instancemethod(_snap.TNEANet_AddIntAttrDatE,None,TNEANet)
TNEANet.AddStrAttrDatE = new_instancemethod(_snap.TNEANet_AddStrAttrDatE,None,TNEANet)
TNEANet.AddFltAttrDatE = new_instancemethod(_snap.TNEANet_AddFltAttrDatE,None,TNEANet)
TNEANet.GetIntAttrDatN = new_instancemethod(_snap.TNEANet_GetIntAttrDatN,None,TNEANet)
TNEANet.GetStrAttrDatN = new_instancemethod(_snap.TNEANet_GetStrAttrDatN,None,TNEANet)
TNEANet.GetFltAttrDatN = new_instancemethod(_snap.TNEANet_GetFltAttrDatN,None,TNEANet)
TNEANet.GetIntAttrDatE = new_instancemethod(_snap.TNEANet_GetIntAttrDatE,None,TNEANet)
TNEANet.GetStrAttrDatE = new_instancemethod(_snap.TNEANet_GetStrAttrDatE,None,TNEANet)
TNEANet.GetFltAttrDatE = new_instancemethod(_snap.TNEANet_GetFltAttrDatE,None,TNEANet)
TNEANet.DelAttrDatN = new_instancemethod(_snap.TNEANet_DelAttrDatN,None,TNEANet)
TNEANet.DelAttrDatE = new_instancemethod(_snap.TNEANet_DelAttrDatE,None,TNEANet)
TNEANet.AddIntAttrN = new_instancemethod(_snap.TNEANet_AddIntAttrN,None,TNEANet)
TNEANet.AddStrAttrN = new_instancemethod(_snap.TNEANet_AddStrAttrN,None,TNEANet)
TNEANet.AddFltAttrN = new_instancemethod(_snap.TNEANet_AddFltAttrN,None,TNEANet)
TNEANet.AddIntAttrE = new_instancemethod(_snap.TNEANet_AddIntAttrE,None,TNEANet)
TNEANet.AddStrAttrE = new_instancemethod(_snap.TNEANet_AddStrAttrE,None,TNEANet)
TNEANet.AddFltAttrE = new_instancemethod(_snap.TNEANet_AddFltAttrE,None,TNEANet)
TNEANet.DelAttrN = new_instancemethod(_snap.TNEANet_DelAttrN,None,TNEANet)
TNEANet.DelAttrE = new_instancemethod(_snap.TNEANet_DelAttrE,None,TNEANet)
TNEANet.NodeAttrIsDeleted = new_instancemethod(_snap.TNEANet_NodeAttrIsDeleted,None,TNEANet)
TNEANet.NodeAttrIsIntDeleted = new_instancemethod(_snap.TNEANet_NodeAttrIsIntDeleted,None,TNEANet)
TNEANet.NodeAttrIsStrDeleted = new_instancemethod(_snap.TNEANet_NodeAttrIsStrDeleted,None,TNEANet)
TNEANet.NodeAttrIsFltDeleted = new_instancemethod(_snap.TNEANet_NodeAttrIsFltDeleted,None,TNEANet)
TNEANet.EdgeAttrIsDeleted = new_instancemethod(_snap.TNEANet_EdgeAttrIsDeleted,None,TNEANet)
TNEANet.EdgeAttrIsIntDeleted = new_instancemethod(_snap.TNEANet_EdgeAttrIsIntDeleted,None,TNEANet)
TNEANet.EdgeAttrIsStrDeleted = new_instancemethod(_snap.TNEANet_EdgeAttrIsStrDeleted,None,TNEANet)
TNEANet.EdgeAttrIsFltDeleted = new_instancemethod(_snap.TNEANet_EdgeAttrIsFltDeleted,None,TNEANet)
TNEANet.GetNodeAttrValue = new_instancemethod(_snap.TNEANet_GetNodeAttrValue,None,TNEANet)
TNEANet.GetEdgeAttrValue = new_instancemethod(_snap.TNEANet_GetEdgeAttrValue,None,TNEANet)
TNEANet.BegNI = new_instancemethod(_snap.TNEANet_BegNI,None,TNEANet)
TNEANet.EndNI = new_instancemethod(_snap.TNEANet_EndNI,None,TNEANet)
TNEANet.BegEI = new_instancemethod(_snap.TNEANet_BegEI,None,TNEANet)
TNEANet.EndEI = new_instancemethod(_snap.TNEANet_EndEI,None,TNEANet)
TNEANet.BegNAIntI = new_instancemethod(_snap.TNEANet_BegNAIntI,None,TNEANet)
TNEANet.EndNAIntI = new_instancemethod(_snap.TNEANet_EndNAIntI,None,TNEANet)
TNEANet.BegNAStrI = new_instancemethod(_snap.TNEANet_BegNAStrI,None,TNEANet)
TNEANet.EndNAStrI = new_instancemethod(_snap.TNEANet_EndNAStrI,None,TNEANet)
TNEANet.BegNAFltI = new_instancemethod(_snap.TNEANet_BegNAFltI,None,TNEANet)
TNEANet.EndNAFltI = new_instancemethod(_snap.TNEANet_EndNAFltI,None,TNEANet)
TNEANet.BegEAIntI = new_instancemethod(_snap.TNEANet_BegEAIntI,None,TNEANet)
TNEANet.EndEAIntI = new_instancemethod(_snap.TNEANet_EndEAIntI,None,TNEANet)
TNEANet.BegEAStrI = new_instancemethod(_snap.TNEANet_BegEAStrI,None,TNEANet)
TNEANet.EndEAStrI = new_instancemethod(_snap.TNEANet_EndEAStrI,None,TNEANet)
TNEANet.BegEAFltI = new_instancemethod(_snap.TNEANet_BegEAFltI,None,TNEANet)
TNEANet.EndEAFltI = new_instancemethod(_snap.TNEANet_EndEAFltI,None,TNEANet)
TNEANet_swigregister = _snap.TNEANet_swigregister
TNEANet_swigregister(TNEANet)
def TNEANet_New(*args):
"""
New() -> PNEANet
TNEANet_New(int const & Nodes, int const & Edges) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEANet_New(*args)
def TNEANet_Load(*args):
"""
TNEANet_Load(TSIn SIn) -> PNEANet
Parameters:
SIn: TSIn &
"""
return _snap.TNEANet_Load(*args)
def PercentDegree(*args):
"""
PercentDegree(PNEANet Graph, int const Threshold=0) -> double
Parameters:
Graph: TPt< TNEANet > const &
Threshold: int const
PercentDegree(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.PercentDegree(*args)
def PercentMxWcc(*args):
"""
PercentMxWcc(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.PercentMxWcc(*args)
def PercentMxScc(*args):
"""
PercentMxScc(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.PercentMxScc(*args)
def LoadEdgeList(*args):
"""
LoadEdgeList(TStr InFNm, int const & SrcColId=0, int const & DstColId=1) -> PNEANet
Parameters:
InFNm: TStr const &
SrcColId: int const &
DstColId: int const &
LoadEdgeList(TStr InFNm, int const & SrcColId=0) -> PNEANet
Parameters:
InFNm: TStr const &
SrcColId: int const &
LoadEdgeList(TStr InFNm) -> PNEANet
Parameters:
InFNm: TStr const &
LoadEdgeList(TStr InFNm, int const & SrcColId, int const & DstColId, char const & Separator) -> PNEANet
Parameters:
InFNm: TStr const &
SrcColId: int const &
DstColId: int const &
Separator: char const &
"""
return _snap.LoadEdgeList(*args)
def PrintGraphStatTable(*args):
"""
PrintGraphStatTable(PNEANet G, TStr OutFNm, TStr Desc="")
Parameters:
G: TPt< TNEANet > const &
OutFNm: TStr
Desc: TStr
PrintGraphStatTable(PNEANet G, TStr OutFNm)
Parameters:
G: TPt< TNEANet > const &
OutFNm: TStr
"""
return _snap.PrintGraphStatTable(*args)
def GenRndGnm(*args):
"""
GenRndGnm(int const & Nodes, int const & Edges, bool const & IsDir=True, TRnd Rnd=Rnd) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
IsDir: bool const &
Rnd: TRnd &
GenRndGnm(int const & Nodes, int const & Edges, bool const & IsDir=True) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
IsDir: bool const &
GenRndGnm(int const & Nodes, int const & Edges) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.GenRndGnm(*args)
def NodesGTEDegree(*args):
"""
NodesGTEDegree(PNEANet Graph, int const Threshold=0) -> int
Parameters:
Graph: TPt< TNEANet > const &
Threshold: int const
NodesGTEDegree(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.NodesGTEDegree(*args)
def MxDegree(*args):
"""
MxDegree(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.MxDegree(*args)
def MxSccSz(*args):
"""
MxSccSz(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.MxSccSz(*args)
def MxWccSz(*args):
"""
MxWccSz(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.MxWccSz(*args)
class PNEANet(object):
"""Proxy of C++ TPt<(TNEANet)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
__repr__ = _swig_repr
def New():
"""New() -> PNEANet"""
return _snap.PNEANet_New()
New = staticmethod(New)
__swig_destroy__ = _snap.delete_PNEANet
def Save(self, *args):
"""
Save(PNEANet self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.PNEANet_Save(self, *args)
def __deref__(self):
"""
__deref__(PNEANet self) -> TNEANet
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet___deref__(self)
def __ref__(self):
"""
__ref__(PNEANet self) -> TNEANet
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet___ref__(self)
def __call__(self):
"""
__call__(PNEANet self) -> TNEANet
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet___call__(self)
def Empty(self):
"""
Empty(PNEANet self) -> bool
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_Empty(self)
def Clr(self):
"""
Clr(PNEANet self)
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_Clr(self)
def GetRefs(self):
"""
GetRefs(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_GetRefs(self)
def Load(self, *args):
"""
Load(PNEANet self, TSIn SIn) -> PNEANet
Parameters:
SIn: TSIn &
"""
return _snap.PNEANet_Load(self, *args)
def HasFlag(self, *args):
"""
HasFlag(PNEANet self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.PNEANet_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(PNEANet self, int NId=-1) -> int
Parameters:
NId: int
AddNode(PNEANet self) -> int
AddNode(PNEANet self, TNEANet::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
"""
return _snap.PNEANet_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(PNEANet self, int const & NId)
Parameters:
NId: int const &
DelNode(PNEANet self, TNEANet::TNode const & NodeI)
Parameters:
NodeI: TNEANet::TNode const &
"""
return _snap.PNEANet_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(PNEANet self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.PNEANet_IsNode(self, *args)
def BegNI(self, *args):
"""
BegNI(PNEANet self) -> TNEANet::TNodeI
BegNI(PNEANet self) -> TNEANetNodeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_BegNI(self, *args)
def EndNI(self, *args):
"""
EndNI(PNEANet self) -> TNEANet::TNodeI
EndNI(PNEANet self) -> TNEANetNodeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_EndNI(self, *args)
def GetNI(self, *args):
"""
GetNI(PNEANet self, int const & NId) -> TNEANet::TNodeI
Parameters:
NId: int const &
"""
return _snap.PNEANet_GetNI(self, *args)
def BegNAIntI(self, *args):
"""
BegNAIntI(PNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
BegNAIntI(PNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegNAIntI(self, *args)
def EndNAIntI(self, *args):
"""
EndNAIntI(PNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EndNAIntI(PNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndNAIntI(self, *args)
def GetNAIntI(self, *args):
"""
GetNAIntI(PNEANet self, TStr attr, int const & NId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.PNEANet_GetNAIntI(self, *args)
def BegNAStrI(self, *args):
"""
BegNAStrI(PNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegNAStrI(PNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegNAStrI(self, *args)
def EndNAStrI(self, *args):
"""
EndNAStrI(PNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EndNAStrI(PNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndNAStrI(self, *args)
def GetNAStrI(self, *args):
"""
GetNAStrI(PNEANet self, TStr attr, int const & NId) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.PNEANet_GetNAStrI(self, *args)
def BegNAFltI(self, *args):
"""
BegNAFltI(PNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
BegNAFltI(PNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegNAFltI(self, *args)
def EndNAFltI(self, *args):
"""
EndNAFltI(PNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EndNAFltI(PNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndNAFltI(self, *args)
def GetNAFltI(self, *args):
"""
GetNAFltI(PNEANet self, TStr attr, int const & NId) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.PNEANet_GetNAFltI(self, *args)
def AttrNameNI(self, *args):
"""
AttrNameNI(PNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
AttrNameNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_AttrNameNI(self, *args)
def AttrValueNI(self, *args):
"""
AttrValueNI(PNEANet self, TInt NId, TStrV Values)
Parameters:
NId: TInt const &
Values: TStrV &
AttrValueNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.PNEANet_AttrValueNI(self, *args)
def IntAttrNameNI(self, *args):
"""
IntAttrNameNI(PNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
IntAttrNameNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_IntAttrNameNI(self, *args)
def IntAttrValueNI(self, *args):
"""
IntAttrValueNI(PNEANet self, TInt NId, TIntV Values)
Parameters:
NId: TInt const &
Values: TIntV &
IntAttrValueNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TIntV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.PNEANet_IntAttrValueNI(self, *args)
def StrAttrNameNI(self, *args):
"""
StrAttrNameNI(PNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
StrAttrNameNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_StrAttrNameNI(self, *args)
def StrAttrValueNI(self, *args):
"""
StrAttrValueNI(PNEANet self, TInt NId, TStrV Values)
Parameters:
NId: TInt const &
Values: TStrV &
StrAttrValueNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.PNEANet_StrAttrValueNI(self, *args)
def FltAttrNameNI(self, *args):
"""
FltAttrNameNI(PNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
FltAttrNameNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_FltAttrNameNI(self, *args)
def FltAttrValueNI(self, *args):
"""
FltAttrValueNI(PNEANet self, TInt NId, TFltV & Values)
Parameters:
NId: TInt const &
Values: TFltV &
FltAttrValueNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TFltV & Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.PNEANet_FltAttrValueNI(self, *args)
def AttrNameEI(self, *args):
"""
AttrNameEI(PNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
AttrNameEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_AttrNameEI(self, *args)
def AttrValueEI(self, *args):
"""
AttrValueEI(PNEANet self, TInt EId, TStrV Values)
Parameters:
EId: TInt const &
Values: TStrV &
AttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.PNEANet_AttrValueEI(self, *args)
def IntAttrNameEI(self, *args):
"""
IntAttrNameEI(PNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
IntAttrNameEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_IntAttrNameEI(self, *args)
def IntAttrValueEI(self, *args):
"""
IntAttrValueEI(PNEANet self, TInt EId, TIntV Values)
Parameters:
EId: TInt const &
Values: TIntV &
IntAttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TIntV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.PNEANet_IntAttrValueEI(self, *args)
def StrAttrNameEI(self, *args):
"""
StrAttrNameEI(PNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
StrAttrNameEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_StrAttrNameEI(self, *args)
def StrAttrValueEI(self, *args):
"""
StrAttrValueEI(PNEANet self, TInt EId, TStrV Values)
Parameters:
EId: TInt const &
Values: TStrV &
StrAttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.PNEANet_StrAttrValueEI(self, *args)
def FltAttrNameEI(self, *args):
"""
FltAttrNameEI(PNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
FltAttrNameEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_FltAttrNameEI(self, *args)
def FltAttrValueEI(self, *args):
"""
FltAttrValueEI(PNEANet self, TInt EId, TFltV & Values)
Parameters:
EId: TInt const &
Values: TFltV &
FltAttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TFltV & Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.PNEANet_FltAttrValueEI(self, *args)
def BegEAIntI(self, *args):
"""
BegEAIntI(PNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
BegEAIntI(PNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegEAIntI(self, *args)
def EndEAIntI(self, *args):
"""
EndEAIntI(PNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EndEAIntI(PNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndEAIntI(self, *args)
def GetEAIntI(self, *args):
"""
GetEAIntI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.PNEANet_GetEAIntI(self, *args)
def BegEAStrI(self, *args):
"""
BegEAStrI(PNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegEAStrI(PNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegEAStrI(self, *args)
def EndEAStrI(self, *args):
"""
EndEAStrI(PNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EndEAStrI(PNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndEAStrI(self, *args)
def GetEAStrI(self, *args):
"""
GetEAStrI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.PNEANet_GetEAStrI(self, *args)
def BegEAFltI(self, *args):
"""
BegEAFltI(PNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
BegEAFltI(PNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegEAFltI(self, *args)
def EndEAFltI(self, *args):
"""
EndEAFltI(PNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EndEAFltI(PNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndEAFltI(self, *args)
def GetEAFltI(self, *args):
"""
GetEAFltI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.PNEANet_GetEAFltI(self, *args)
def GetMxNId(self):
"""
GetMxNId(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(PNEANet self, int const & SrcNId, int const & DstNId, int EId=-1) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int
AddEdge(PNEANet self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(PNEANet self, TNEANet::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TNEANet::TEdgeI const &
"""
return _snap.PNEANet_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(PNEANet self, int const & EId)
Parameters:
EId: int const &
DelEdge(PNEANet self, int const & SrcNId, int const & DstNId, bool const & IsDir=True)
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
DelEdge(PNEANet self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.PNEANet_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(PNEANet self, int const & EId) -> bool
Parameters:
EId: int const &
IsEdge(PNEANet self, int const & SrcNId, int const & DstNId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
IsEdge(PNEANet self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsEdge(PNEANet self, int const & SrcNId, int const & DstNId, int & EId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
IsDir: bool const &
IsEdge(PNEANet self, int const & SrcNId, int const & DstNId, int & EId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
"""
return _snap.PNEANet_IsEdge(self, *args)
def GetEId(self, *args):
"""
GetEId(PNEANet self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.PNEANet_GetEId(self, *args)
def BegEI(self, *args):
"""
BegEI(PNEANet self) -> TNEANet::TEdgeI
BegEI(PNEANet self) -> TNEANetEdgeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_BegEI(self, *args)
def EndEI(self, *args):
"""
EndEI(PNEANet self) -> TNEANet::TEdgeI
EndEI(PNEANet self) -> TNEANetEdgeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_EndEI(self, *args)
def GetEI(self, *args):
"""
GetEI(PNEANet self, int const & SrcNId, int const & DstNId) -> TNEANet::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.PNEANet_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(PNEANet self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(PNEANet self, TRnd Rnd=Rnd) -> TNEANet::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(PNEANet self) -> TNEANet::TNodeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_GetRndNI(self, *args)
def GetRndEId(self, *args):
"""
GetRndEId(PNEANet self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndEId(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_GetRndEId(self, *args)
def GetRndEI(self, *args):
"""
GetRndEI(PNEANet self, TRnd Rnd=Rnd) -> TNEANet::TEdgeI
Parameters:
Rnd: TRnd &
GetRndEI(PNEANet self) -> TNEANet::TEdgeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_GetRndEI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(PNEANet self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.PNEANet_GetNIdV(self, *args)
def GetEIdV(self, *args):
"""
GetEIdV(PNEANet self, TIntV EIdV)
Parameters:
EIdV: TIntV &
"""
return _snap.PNEANet_GetEIdV(self, *args)
def Reserve(self, *args):
"""
Reserve(PNEANet self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.PNEANet_Reserve(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(PNEANet self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(PNEANet self)
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(PNEANet self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(PNEANet self) -> bool
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(PNEANet self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(PNEANet self)
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_Dump(self, *args)
def AddIntAttrDatN(self, *args):
"""
AddIntAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TInt value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TInt const &
attr: TStr const &
AddIntAttrDatN(PNEANet self, int const & NId, TInt value, TStr attr) -> int
Parameters:
NId: int const &
value: TInt const &
attr: TStr const &
"""
return _snap.PNEANet_AddIntAttrDatN(self, *args)
def AddStrAttrDatN(self, *args):
"""
AddStrAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TStr const &
attr: TStr const &
AddStrAttrDatN(PNEANet self, int const & NId, TStr value, TStr attr) -> int
Parameters:
NId: int const &
value: TStr const &
attr: TStr const &
"""
return _snap.PNEANet_AddStrAttrDatN(self, *args)
def AddFltAttrDatN(self, *args):
"""
AddFltAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TFlt value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TFlt const &
attr: TStr const &
AddFltAttrDatN(PNEANet self, int const & NId, TFlt value, TStr attr) -> int
Parameters:
NId: int const &
value: TFlt const &
attr: TStr const &
"""
return _snap.PNEANet_AddFltAttrDatN(self, *args)
def AddIntAttrDatE(self, *args):
"""
AddIntAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TInt value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TInt const &
attr: TStr const &
AddIntAttrDatE(PNEANet self, int const & EId, TInt value, TStr attr) -> int
Parameters:
EId: int const &
value: TInt const &
attr: TStr const &
"""
return _snap.PNEANet_AddIntAttrDatE(self, *args)
def AddStrAttrDatE(self, *args):
"""
AddStrAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TStr const &
attr: TStr const &
AddStrAttrDatE(PNEANet self, int const & EId, TStr value, TStr attr) -> int
Parameters:
EId: int const &
value: TStr const &
attr: TStr const &
"""
return _snap.PNEANet_AddStrAttrDatE(self, *args)
def AddFltAttrDatE(self, *args):
"""
AddFltAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TFlt value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TFlt const &
attr: TStr const &
AddFltAttrDatE(PNEANet self, int const & EId, TFlt value, TStr attr) -> int
Parameters:
EId: int const &
value: TFlt const &
attr: TStr const &
"""
return _snap.PNEANet_AddFltAttrDatE(self, *args)
def GetIntAttrDatN(self, *args):
"""
GetIntAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TInt
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetIntAttrDatN(PNEANet self, int const & NId, TStr attr) -> TInt
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetIntAttrDatN(self, *args)
def GetStrAttrDatN(self, *args):
"""
GetStrAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TStr
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetStrAttrDatN(PNEANet self, int const & NId, TStr attr) -> TStr
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetStrAttrDatN(self, *args)
def GetFltAttrDatN(self, *args):
"""
GetFltAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TFlt
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetFltAttrDatN(PNEANet self, int const & NId, TStr attr) -> TFlt
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetFltAttrDatN(self, *args)
def GetIntAttrDatE(self, *args):
"""
GetIntAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TInt
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetIntAttrDatE(PNEANet self, int const & EId, TStr attr) -> TInt
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetIntAttrDatE(self, *args)
def GetStrAttrDatE(self, *args):
"""
GetStrAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TStr
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetStrAttrDatE(PNEANet self, int const & EId, TStr attr) -> TStr
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetStrAttrDatE(self, *args)
def GetFltAttrDatE(self, *args):
"""
GetFltAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TFlt
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetFltAttrDatE(PNEANet self, int const & EId, TStr attr) -> TFlt
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetFltAttrDatE(self, *args)
def DelAttrDatN(self, *args):
"""
DelAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
DelAttrDatN(PNEANet self, int const & NId, TStr attr) -> int
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.PNEANet_DelAttrDatN(self, *args)
def DelAttrDatE(self, *args):
"""
DelAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
DelAttrDatE(PNEANet self, int const & EId, TStr attr) -> int
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.PNEANet_DelAttrDatE(self, *args)
def AddIntAttrN(self, *args):
"""
AddIntAttrN(PNEANet self, TStr attr, TInt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TInt
AddIntAttrN(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddIntAttrN(self, *args)
def AddStrAttrN(self, *args):
"""
AddStrAttrN(PNEANet self, TStr attr, TStr defaultValue=TStr::GetNullStr()) -> int
Parameters:
attr: TStr const &
defaultValue: TStr
AddStrAttrN(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddStrAttrN(self, *args)
def AddFltAttrN(self, *args):
"""
AddFltAttrN(PNEANet self, TStr attr, TFlt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TFlt
AddFltAttrN(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddFltAttrN(self, *args)
def AddIntAttrE(self, *args):
"""
AddIntAttrE(PNEANet self, TStr attr, TInt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TInt
AddIntAttrE(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddIntAttrE(self, *args)
def AddStrAttrE(self, *args):
"""
AddStrAttrE(PNEANet self, TStr attr, TStr defaultValue=TStr::GetNullStr()) -> int
Parameters:
attr: TStr const &
defaultValue: TStr
AddStrAttrE(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddStrAttrE(self, *args)
def AddFltAttrE(self, *args):
"""
AddFltAttrE(PNEANet self, TStr attr, TFlt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TFlt
AddFltAttrE(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddFltAttrE(self, *args)
def DelAttrN(self, *args):
"""
DelAttrN(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_DelAttrN(self, *args)
def DelAttrE(self, *args):
"""
DelAttrE(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_DelAttrE(self, *args)
def NodeAttrIsDeleted(self, *args):
"""
NodeAttrIsDeleted(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_NodeAttrIsDeleted(self, *args)
def NodeAttrIsIntDeleted(self, *args):
"""
NodeAttrIsIntDeleted(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_NodeAttrIsIntDeleted(self, *args)
def NodeAttrIsStrDeleted(self, *args):
"""
NodeAttrIsStrDeleted(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_NodeAttrIsStrDeleted(self, *args)
def NodeAttrIsFltDeleted(self, *args):
"""
NodeAttrIsFltDeleted(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_NodeAttrIsFltDeleted(self, *args)
def EdgeAttrIsDeleted(self, *args):
"""
EdgeAttrIsDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsDeleted(self, *args)
def EdgeAttrIsIntDeleted(self, *args):
"""
EdgeAttrIsIntDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsIntDeleted(self, *args)
def EdgeAttrIsStrDeleted(self, *args):
"""
EdgeAttrIsStrDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsStrDeleted(self, *args)
def EdgeAttrIsFltDeleted(self, *args):
"""
EdgeAttrIsFltDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsFltDeleted(self, *args)
def GetNodeAttrValue(self, *args):
"""
GetNodeAttrValue(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> TStr
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_GetNodeAttrValue(self, *args)
def GetEdgeAttrValue(self, *args):
"""
GetEdgeAttrValue(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> TStr
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_GetEdgeAttrValue(self, *args)
PNEANet.Save = new_instancemethod(_snap.PNEANet_Save,None,PNEANet)
PNEANet.__deref__ = new_instancemethod(_snap.PNEANet___deref__,None,PNEANet)
PNEANet.__ref__ = new_instancemethod(_snap.PNEANet___ref__,None,PNEANet)
PNEANet.__call__ = new_instancemethod(_snap.PNEANet___call__,None,PNEANet)
PNEANet.Empty = new_instancemethod(_snap.PNEANet_Empty,None,PNEANet)
PNEANet.Clr = new_instancemethod(_snap.PNEANet_Clr,None,PNEANet)
PNEANet.GetRefs = new_instancemethod(_snap.PNEANet_GetRefs,None,PNEANet)
PNEANet.Load = new_instancemethod(_snap.PNEANet_Load,None,PNEANet)
PNEANet.HasFlag = new_instancemethod(_snap.PNEANet_HasFlag,None,PNEANet)
PNEANet.GetNodes = new_instancemethod(_snap.PNEANet_GetNodes,None,PNEANet)
PNEANet.AddNode = new_instancemethod(_snap.PNEANet_AddNode,None,PNEANet)
PNEANet.DelNode = new_instancemethod(_snap.PNEANet_DelNode,None,PNEANet)
PNEANet.IsNode = new_instancemethod(_snap.PNEANet_IsNode,None,PNEANet)
PNEANet.BegNI = new_instancemethod(_snap.PNEANet_BegNI,None,PNEANet)
PNEANet.EndNI = new_instancemethod(_snap.PNEANet_EndNI,None,PNEANet)
PNEANet.GetNI = new_instancemethod(_snap.PNEANet_GetNI,None,PNEANet)
PNEANet.BegNAIntI = new_instancemethod(_snap.PNEANet_BegNAIntI,None,PNEANet)
PNEANet.EndNAIntI = new_instancemethod(_snap.PNEANet_EndNAIntI,None,PNEANet)
PNEANet.GetNAIntI = new_instancemethod(_snap.PNEANet_GetNAIntI,None,PNEANet)
PNEANet.BegNAStrI = new_instancemethod(_snap.PNEANet_BegNAStrI,None,PNEANet)
PNEANet.EndNAStrI = new_instancemethod(_snap.PNEANet_EndNAStrI,None,PNEANet)
PNEANet.GetNAStrI = new_instancemethod(_snap.PNEANet_GetNAStrI,None,PNEANet)
PNEANet.BegNAFltI = new_instancemethod(_snap.PNEANet_BegNAFltI,None,PNEANet)
PNEANet.EndNAFltI = new_instancemethod(_snap.PNEANet_EndNAFltI,None,PNEANet)
PNEANet.GetNAFltI = new_instancemethod(_snap.PNEANet_GetNAFltI,None,PNEANet)
PNEANet.AttrNameNI = new_instancemethod(_snap.PNEANet_AttrNameNI,None,PNEANet)
PNEANet.AttrValueNI = new_instancemethod(_snap.PNEANet_AttrValueNI,None,PNEANet)
PNEANet.IntAttrNameNI = new_instancemethod(_snap.PNEANet_IntAttrNameNI,None,PNEANet)
PNEANet.IntAttrValueNI = new_instancemethod(_snap.PNEANet_IntAttrValueNI,None,PNEANet)
PNEANet.StrAttrNameNI = new_instancemethod(_snap.PNEANet_StrAttrNameNI,None,PNEANet)
PNEANet.StrAttrValueNI = new_instancemethod(_snap.PNEANet_StrAttrValueNI,None,PNEANet)
PNEANet.FltAttrNameNI = new_instancemethod(_snap.PNEANet_FltAttrNameNI,None,PNEANet)
PNEANet.FltAttrValueNI = new_instancemethod(_snap.PNEANet_FltAttrValueNI,None,PNEANet)
PNEANet.AttrNameEI = new_instancemethod(_snap.PNEANet_AttrNameEI,None,PNEANet)
PNEANet.AttrValueEI = new_instancemethod(_snap.PNEANet_AttrValueEI,None,PNEANet)
PNEANet.IntAttrNameEI = new_instancemethod(_snap.PNEANet_IntAttrNameEI,None,PNEANet)
PNEANet.IntAttrValueEI = new_instancemethod(_snap.PNEANet_IntAttrValueEI,None,PNEANet)
PNEANet.StrAttrNameEI = new_instancemethod(_snap.PNEANet_StrAttrNameEI,None,PNEANet)
PNEANet.StrAttrValueEI = new_instancemethod(_snap.PNEANet_StrAttrValueEI,None,PNEANet)
PNEANet.FltAttrNameEI = new_instancemethod(_snap.PNEANet_FltAttrNameEI,None,PNEANet)
PNEANet.FltAttrValueEI = new_instancemethod(_snap.PNEANet_FltAttrValueEI,None,PNEANet)
PNEANet.BegEAIntI = new_instancemethod(_snap.PNEANet_BegEAIntI,None,PNEANet)
PNEANet.EndEAIntI = new_instancemethod(_snap.PNEANet_EndEAIntI,None,PNEANet)
PNEANet.GetEAIntI = new_instancemethod(_snap.PNEANet_GetEAIntI,None,PNEANet)
PNEANet.BegEAStrI = new_instancemethod(_snap.PNEANet_BegEAStrI,None,PNEANet)
PNEANet.EndEAStrI = new_instancemethod(_snap.PNEANet_EndEAStrI,None,PNEANet)
PNEANet.GetEAStrI = new_instancemethod(_snap.PNEANet_GetEAStrI,None,PNEANet)
PNEANet.BegEAFltI = new_instancemethod(_snap.PNEANet_BegEAFltI,None,PNEANet)
PNEANet.EndEAFltI = new_instancemethod(_snap.PNEANet_EndEAFltI,None,PNEANet)
PNEANet.GetEAFltI = new_instancemethod(_snap.PNEANet_GetEAFltI,None,PNEANet)
PNEANet.GetMxNId = new_instancemethod(_snap.PNEANet_GetMxNId,None,PNEANet)
PNEANet.GetEdges = new_instancemethod(_snap.PNEANet_GetEdges,None,PNEANet)
PNEANet.AddEdge = new_instancemethod(_snap.PNEANet_AddEdge,None,PNEANet)
PNEANet.DelEdge = new_instancemethod(_snap.PNEANet_DelEdge,None,PNEANet)
PNEANet.IsEdge = new_instancemethod(_snap.PNEANet_IsEdge,None,PNEANet)
PNEANet.GetEId = new_instancemethod(_snap.PNEANet_GetEId,None,PNEANet)
PNEANet.BegEI = new_instancemethod(_snap.PNEANet_BegEI,None,PNEANet)
PNEANet.EndEI = new_instancemethod(_snap.PNEANet_EndEI,None,PNEANet)
PNEANet.GetEI = new_instancemethod(_snap.PNEANet_GetEI,None,PNEANet)
PNEANet.GetRndNId = new_instancemethod(_snap.PNEANet_GetRndNId,None,PNEANet)
PNEANet.GetRndNI = new_instancemethod(_snap.PNEANet_GetRndNI,None,PNEANet)
PNEANet.GetRndEId = new_instancemethod(_snap.PNEANet_GetRndEId,None,PNEANet)
PNEANet.GetRndEI = new_instancemethod(_snap.PNEANet_GetRndEI,None,PNEANet)
PNEANet.GetNIdV = new_instancemethod(_snap.PNEANet_GetNIdV,None,PNEANet)
PNEANet.GetEIdV = new_instancemethod(_snap.PNEANet_GetEIdV,None,PNEANet)
PNEANet.Reserve = new_instancemethod(_snap.PNEANet_Reserve,None,PNEANet)
PNEANet.Defrag = new_instancemethod(_snap.PNEANet_Defrag,None,PNEANet)
PNEANet.IsOk = new_instancemethod(_snap.PNEANet_IsOk,None,PNEANet)
PNEANet.Dump = new_instancemethod(_snap.PNEANet_Dump,None,PNEANet)
PNEANet.AddIntAttrDatN = new_instancemethod(_snap.PNEANet_AddIntAttrDatN,None,PNEANet)
PNEANet.AddStrAttrDatN = new_instancemethod(_snap.PNEANet_AddStrAttrDatN,None,PNEANet)
PNEANet.AddFltAttrDatN = new_instancemethod(_snap.PNEANet_AddFltAttrDatN,None,PNEANet)
PNEANet.AddIntAttrDatE = new_instancemethod(_snap.PNEANet_AddIntAttrDatE,None,PNEANet)
PNEANet.AddStrAttrDatE = new_instancemethod(_snap.PNEANet_AddStrAttrDatE,None,PNEANet)
PNEANet.AddFltAttrDatE = new_instancemethod(_snap.PNEANet_AddFltAttrDatE,None,PNEANet)
PNEANet.GetIntAttrDatN = new_instancemethod(_snap.PNEANet_GetIntAttrDatN,None,PNEANet)
PNEANet.GetStrAttrDatN = new_instancemethod(_snap.PNEANet_GetStrAttrDatN,None,PNEANet)
PNEANet.GetFltAttrDatN = new_instancemethod(_snap.PNEANet_GetFltAttrDatN,None,PNEANet)
PNEANet.GetIntAttrDatE = new_instancemethod(_snap.PNEANet_GetIntAttrDatE,None,PNEANet)
PNEANet.GetStrAttrDatE = new_instancemethod(_snap.PNEANet_GetStrAttrDatE,None,PNEANet)
PNEANet.GetFltAttrDatE = new_instancemethod(_snap.PNEANet_GetFltAttrDatE,None,PNEANet)
PNEANet.DelAttrDatN = new_instancemethod(_snap.PNEANet_DelAttrDatN,None,PNEANet)
PNEANet.DelAttrDatE = new_instancemethod(_snap.PNEANet_DelAttrDatE,None,PNEANet)
PNEANet.AddIntAttrN = new_instancemethod(_snap.PNEANet_AddIntAttrN,None,PNEANet)
PNEANet.AddStrAttrN = new_instancemethod(_snap.PNEANet_AddStrAttrN,None,PNEANet)
PNEANet.AddFltAttrN = new_instancemethod(_snap.PNEANet_AddFltAttrN,None,PNEANet)
PNEANet.AddIntAttrE = new_instancemethod(_snap.PNEANet_AddIntAttrE,None,PNEANet)
PNEANet.AddStrAttrE = new_instancemethod(_snap.PNEANet_AddStrAttrE,None,PNEANet)
PNEANet.AddFltAttrE = new_instancemethod(_snap.PNEANet_AddFltAttrE,None,PNEANet)
PNEANet.DelAttrN = new_instancemethod(_snap.PNEANet_DelAttrN,None,PNEANet)
PNEANet.DelAttrE = new_instancemethod(_snap.PNEANet_DelAttrE,None,PNEANet)
PNEANet.NodeAttrIsDeleted = new_instancemethod(_snap.PNEANet_NodeAttrIsDeleted,None,PNEANet)
PNEANet.NodeAttrIsIntDeleted = new_instancemethod(_snap.PNEANet_NodeAttrIsIntDeleted,None,PNEANet)
PNEANet.NodeAttrIsStrDeleted = new_instancemethod(_snap.PNEANet_NodeAttrIsStrDeleted,None,PNEANet)
PNEANet.NodeAttrIsFltDeleted = new_instancemethod(_snap.PNEANet_NodeAttrIsFltDeleted,None,PNEANet)
PNEANet.EdgeAttrIsDeleted = new_instancemethod(_snap.PNEANet_EdgeAttrIsDeleted,None,PNEANet)
PNEANet.EdgeAttrIsIntDeleted = new_instancemethod(_snap.PNEANet_EdgeAttrIsIntDeleted,None,PNEANet)
PNEANet.EdgeAttrIsStrDeleted = new_instancemethod(_snap.PNEANet_EdgeAttrIsStrDeleted,None,PNEANet)
PNEANet.EdgeAttrIsFltDeleted = new_instancemethod(_snap.PNEANet_EdgeAttrIsFltDeleted,None,PNEANet)
PNEANet.GetNodeAttrValue = new_instancemethod(_snap.PNEANet_GetNodeAttrValue,None,PNEANet)
PNEANet.GetEdgeAttrValue = new_instancemethod(_snap.PNEANet_GetEdgeAttrValue,None,PNEANet)
PNEANet_swigregister = _snap.PNEANet_swigregister
PNEANet_swigregister(PNEANet)
def PNEANet_New():
"""PNEANet_New() -> PNEANet"""
return _snap.PNEANet_New()
def GetNodeWcc(*args):
"""
GetNodeWcc(PNEANet Graph, int const & NId, TIntV CnCom)
Parameters:
Graph: TPt< TNEANet > const &
NId: int const &
CnCom: TIntV &
"""
return _snap.GetNodeWcc(*args)
def IsConnected(*args):
"""
IsConnected(PNEANet Graph) -> bool
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.IsConnected(*args)
def IsWeaklyConn(*args):
"""
IsWeaklyConn(PNEANet Graph) -> bool
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.IsWeaklyConn(*args)
def GetWccSzCnt(*args):
"""
GetWccSzCnt(PNEANet Graph, TIntPrV & WccSzCnt)
Parameters:
Graph: TPt< TNEANet > const &
WccSzCnt: TIntPrV &
"""
return _snap.GetWccSzCnt(*args)
def GetWccs(*args):
"""
GetWccs(PNEANet Graph, TCnComV & CnComV)
Parameters:
Graph: TPt< TNEANet > const &
CnComV: TCnComV &
"""
return _snap.GetWccs(*args)
def GetSccSzCnt(*args):
"""
GetSccSzCnt(PNEANet Graph, TIntPrV & SccSzCnt)
Parameters:
Graph: TPt< TNEANet > const &
SccSzCnt: TIntPrV &
"""
return _snap.GetSccSzCnt(*args)
def GetSccs(*args):
"""
GetSccs(PNEANet Graph, TCnComV & CnComV)
Parameters:
Graph: TPt< TNEANet > const &
CnComV: TCnComV &
"""
return _snap.GetSccs(*args)
def GetMxWccSz(*args):
"""
GetMxWccSz(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxWccSz(*args)
def GetMxWcc(*args):
"""
GetMxWcc(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxWcc(*args)
def GetMxScc(*args):
"""
GetMxScc(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxScc(*args)
def GetMxBiCon(*args):
"""
GetMxBiCon(PUNGraph const & Graph, bool const & RenumberNodes=False) -> PUNGraph
Parameters:
Graph: PUNGraph const &
RenumberNodes: bool const &
GetMxBiCon(PUNGraph const & Graph) -> PUNGraph
Parameters:
Graph: PUNGraph const &
GetMxBiCon(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxBiCon(*args)
def CntInDegNodes(*args):
"""
CntInDegNodes(PNEANet Graph, int const & NodeInDeg) -> int
Parameters:
Graph: TPt< TNEANet > const &
NodeInDeg: int const &
"""
return _snap.CntInDegNodes(*args)
def CntOutDegNodes(*args):
"""
CntOutDegNodes(PNEANet Graph, int const & NodeOutDeg) -> int
Parameters:
Graph: TPt< TNEANet > const &
NodeOutDeg: int const &
"""
return _snap.CntOutDegNodes(*args)
def CntDegNodes(*args):
"""
CntDegNodes(PNEANet Graph, int const & NodeDeg) -> int
Parameters:
Graph: TPt< TNEANet > const &
NodeDeg: int const &
"""
return _snap.CntDegNodes(*args)
def CntNonZNodes(*args):
"""
CntNonZNodes(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntNonZNodes(*args)
def CntEdgesToSet(*args):
"""
CntEdgesToSet(PNEANet Graph, int const & NId, TIntSet const & NodeSet) -> int
Parameters:
Graph: TPt< TNEANet > const &
NId: int const &
NodeSet: TIntSet const &
"""
return _snap.CntEdgesToSet(*args)
def GetMxDegNId(*args):
"""
GetMxDegNId(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxDegNId(*args)
def GetMxInDegNId(*args):
"""
GetMxInDegNId(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxInDegNId(*args)
def GetMxOutDegNId(*args):
"""
GetMxOutDegNId(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxOutDegNId(*args)
def GetInDegCnt(*args):
"""
GetInDegCnt(PNEANet Graph, TIntPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TIntPrV &
GetInDegCnt(PNEANet Graph, TFltPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TFltPrV &
"""
return _snap.GetInDegCnt(*args)
def GetOutDegCnt(*args):
"""
GetOutDegCnt(PNEANet Graph, TIntPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TIntPrV &
GetOutDegCnt(PNEANet Graph, TFltPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TFltPrV &
"""
return _snap.GetOutDegCnt(*args)
def GetDegCnt(*args):
"""
GetDegCnt(PNEANet Graph, TIntPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TIntPrV &
GetDegCnt(PNEANet Graph, TFltPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TFltPrV &
"""
return _snap.GetDegCnt(*args)
def GetDegSeqV(*args):
"""
GetDegSeqV(PNEANet Graph, TIntV DegV)
Parameters:
Graph: TPt< TNEANet > const &
DegV: TIntV &
GetDegSeqV(PNEANet Graph, TIntV InDegV, TIntV OutDegV)
Parameters:
Graph: TPt< TNEANet > const &
InDegV: TIntV &
OutDegV: TIntV &
"""
return _snap.GetDegSeqV(*args)
def GetNodeInDegV(*args):
"""
GetNodeInDegV(PNEANet Graph, TIntPrV & NIdInDegV)
Parameters:
Graph: TPt< TNEANet > const &
NIdInDegV: TIntPrV &
"""
return _snap.GetNodeInDegV(*args)
def GetNodeOutDegV(*args):
"""
GetNodeOutDegV(PNEANet Graph, TIntPrV & NIdOutDegV)
Parameters:
Graph: TPt< TNEANet > const &
NIdOutDegV: TIntPrV &
"""
return _snap.GetNodeOutDegV(*args)
def CntUniqUndirEdges(*args):
"""
CntUniqUndirEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntUniqUndirEdges(*args)
def CntUniqDirEdges(*args):
"""
CntUniqDirEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntUniqDirEdges(*args)
def CntUniqBiDirEdges(*args):
"""
CntUniqBiDirEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntUniqBiDirEdges(*args)
def CntSelfEdges(*args):
"""
CntSelfEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntSelfEdges(*args)
def GetBfsTree(*args):
"""
GetBfsTree(PNEANet Graph, int const & StartNId, bool const & FollowOut, bool const & FollowIn) -> PNGraph
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
FollowOut: bool const &
FollowIn: bool const &
"""
return _snap.GetBfsTree(*args)
def GetSubTreeSz(*args):
"""
GetSubTreeSz(PNEANet Graph, int const & StartNId, bool const & FollowOut, bool const & FollowIn,
int & TreeSz, int & TreeDepth) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
FollowOut: bool const &
FollowIn: bool const &
TreeSz: int &
TreeDepth: int &
"""
return _snap.GetSubTreeSz(*args)
def GetNodesAtHop(*args):
"""
GetNodesAtHop(PNEANet Graph, int const & StartNId, int const & Hop, TIntV NIdV, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
Hop: int const &
NIdV: TIntV &
IsDir: bool const &
GetNodesAtHop(PNEANet Graph, int const & StartNId, int const & Hop, TIntV NIdV) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
Hop: int const &
NIdV: TIntV &
"""
return _snap.GetNodesAtHop(*args)
def GetNodesAtHops(*args):
"""
GetNodesAtHops(PNEANet Graph, int const & StartNId, TIntPrV & HopCntV, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
HopCntV: TIntPrV &
IsDir: bool const &
GetNodesAtHops(PNEANet Graph, int const & StartNId, TIntPrV & HopCntV) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
HopCntV: TIntPrV &
"""
return _snap.GetNodesAtHops(*args)
def GetShortPath(*args):
"""
GetShortPath(PNEANet Graph, int const & SrcNId, int const & DstNId, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
GetShortPath(PNEANet Graph, int const & SrcNId, int const & DstNId) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
DstNId: int const &
GetShortPath(PNEANet Graph, int const & SrcNId, TIntH NIdToDistH, bool const & IsDir=False, int const & MaxDist=Mx) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
NIdToDistH: TIntH &
IsDir: bool const &
MaxDist: int const &
GetShortPath(PNEANet Graph, int const & SrcNId, TIntH NIdToDistH, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
NIdToDistH: TIntH &
IsDir: bool const &
GetShortPath(PNEANet Graph, int const & SrcNId, TIntH NIdToDistH) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
NIdToDistH: TIntH &
"""
return _snap.GetShortPath(*args)
def GetBfsFullDiam(*args):
"""
GetBfsFullDiam(PNEANet Graph, int const & NTestNodes, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
IsDir: bool const &
GetBfsFullDiam(PNEANet Graph, int const & NTestNodes) -> int
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
"""
return _snap.GetBfsFullDiam(*args)
def GetBfsEffDiam(*args):
"""
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes, bool const & IsDir=False) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
IsDir: bool const &
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes, bool const & IsDir, double & EffDiam, int & FullDiam) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
IsDir: bool const &
EffDiam: double &
FullDiam: int &
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes, bool const & IsDir, double & EffDiam, int & FullDiam,
double & AvgSPL) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
IsDir: bool const &
EffDiam: double &
FullDiam: int &
AvgSPL: double &
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes, TIntV SubGraphNIdV, bool const & IsDir, double & EffDiam,
int & FullDiam) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
SubGraphNIdV: TIntV const &
IsDir: bool const &
EffDiam: double &
FullDiam: int &
"""
return _snap.GetBfsEffDiam(*args)
def DrawGViz(*args):
"""
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm, TStr Desc=TStr(), bool const & NodeLabels=False,
TIntStrH const & NIdColorH=TIntStrH())
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
Desc: TStr const &
NodeLabels: bool const &
NIdColorH: TIntStrH const &
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm, TStr Desc=TStr(), bool const & NodeLabels=False)
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
Desc: TStr const &
NodeLabels: bool const &
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm, TStr Desc=TStr())
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
Desc: TStr const &
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm)
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm, TStr Desc, TIntStrH const & NodeLabelH)
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
Desc: TStr const &
NodeLabelH: TIntStrH const &
"""
return _snap.DrawGViz(*args)
def GetClustCf(*args):
"""
GetClustCf(PNEANet Graph, int SampleNodes=-1) -> double
Parameters:
Graph: TPt< TNEANet > const &
SampleNodes: int
GetClustCf(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
GetClustCf(PNEANet Graph, TFltPrV & DegToCCfV, int SampleNodes=-1) -> double
Parameters:
Graph: TPt< TNEANet > const &
DegToCCfV: TFltPrV &
SampleNodes: int
GetClustCf(PNEANet Graph, TFltPrV & DegToCCfV) -> double
Parameters:
Graph: TPt< TNEANet > const &
DegToCCfV: TFltPrV &
GetClustCf(PNEANet Graph, TFltPrV & DegToCCfV, int64 & ClosedTriads, int64 & OpenTriads, int SampleNodes=-1) -> double
Parameters:
Graph: TPt< TNEANet > const &
DegToCCfV: TFltPrV &
ClosedTriads: int64 &
OpenTriads: int64 &
SampleNodes: int
GetClustCf(PNEANet Graph, TFltPrV & DegToCCfV, int64 & ClosedTriads, int64 & OpenTriads) -> double
Parameters:
Graph: TPt< TNEANet > const &
DegToCCfV: TFltPrV &
ClosedTriads: int64 &
OpenTriads: int64 &
"""
return _snap.GetClustCf(*args)
def GetNodeClustCf(*args):
"""
GetNodeClustCf(PNEANet Graph, int const & NId) -> double
Parameters:
Graph: TPt< TNEANet > const &
NId: int const &
GetNodeClustCf(PNEANet Graph, TIntFltH & NIdCCfH)
Parameters:
Graph: TPt< TNEANet > const &
NIdCCfH: TIntFltH &
"""
return _snap.GetNodeClustCf(*args)
def GetTriads(*args):
"""
GetTriads(PNEANet Graph, int SampleNodes=-1) -> int64
Parameters:
Graph: TPt< TNEANet > const &
SampleNodes: int
GetTriads(PNEANet Graph) -> int64
Parameters:
Graph: TPt< TNEANet > const &
GetTriads(PNEANet Graph, int64 & ClosedTriads, int64 & OpenTriads, int SampleNodes) -> int64
Parameters:
Graph: TPt< TNEANet > const &
ClosedTriads: int64 &
OpenTriads: int64 &
SampleNodes: int
GetTriads(PNEANet Graph, TIntTrV & NIdCOTriadV, int SampleNodes=-1)
Parameters:
Graph: TPt< TNEANet > const &
NIdCOTriadV: TIntTrV &
SampleNodes: int
GetTriads(PNEANet Graph, TIntTrV & NIdCOTriadV)
Parameters:
Graph: TPt< TNEANet > const &
NIdCOTriadV: TIntTrV &
"""
return _snap.GetTriads(*args)
def GetTriadEdges(*args):
"""
GetTriadEdges(PNEANet Graph, int SampleEdges=-1) -> int
Parameters:
Graph: TPt< TNEANet > const &
SampleEdges: int
GetTriadEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetTriadEdges(*args)
def GetTriadParticip(*args):
"""
GetTriadParticip(PNEANet Graph, TIntPrV & TriadCntV)
Parameters:
Graph: TPt< TNEANet > const &
TriadCntV: TIntPrV &
"""
return _snap.GetTriadParticip(*args)
def GetCmnNbrs(*args):
"""
GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2) -> int
Parameters:
Graph: TPt< TNEANet > const &
NId1: int const &
NId2: int const &
GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2, TIntV NbrV) -> int
Parameters:
Graph: TPt< TNEANet > const &
NId1: int const &
NId2: int const &
NbrV: TIntV &
"""
return _snap.GetCmnNbrs(*args)
def GetModularity(*args):
"""
GetModularity(PNEANet G, TIntV NIdV, int GEdges=-1) -> double
Parameters:
G: TPt< TNEANet > const &
NIdV: TIntV const &
GEdges: int
GetModularity(PNEANet G, TIntV NIdV) -> double
Parameters:
G: TPt< TNEANet > const &
NIdV: TIntV const &
GetModularity(PNEANet G, TCnComV const & CmtyV, int GEdges=-1) -> double
Parameters:
G: TPt< TNEANet > const &
CmtyV: TCnComV const &
GEdges: int
GetModularity(PNEANet G, TCnComV const & CmtyV) -> double
Parameters:
G: TPt< TNEANet > const &
CmtyV: TCnComV const &
"""
return _snap.GetModularity(*args)
def GetEdgesInOut(*args):
"""
GetEdgesInOut(PNEANet Graph, TIntV NIdV, int & EdgesIn, int & EdgesOut)
Parameters:
Graph: TPt< TNEANet > const &
NIdV: TIntV const &
EdgesIn: int &
EdgesOut: int &
"""
return _snap.GetEdgesInOut(*args)
def GetAnf(*args):
"""
GetAnf(PNEANet Graph, int const & SrcNId, TIntFltKdV & DistNbrsV, int const & MxDist, bool const & IsDir,
int const & NApprox=32)
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
DistNbrsV: TIntFltKdV &
MxDist: int const &
IsDir: bool const &
NApprox: int const &
GetAnf(PNEANet Graph, int const & SrcNId, TIntFltKdV & DistNbrsV, int const & MxDist, bool const & IsDir)
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
DistNbrsV: TIntFltKdV &
MxDist: int const &
IsDir: bool const &
GetAnf(PNEANet Graph, TIntFltKdV & DistNbrsV, int const & MxDist, bool const & IsDir, int const & NApprox=32)
Parameters:
Graph: TPt< TNEANet > const &
DistNbrsV: TIntFltKdV &
MxDist: int const &
IsDir: bool const &
NApprox: int const &
GetAnf(PNEANet Graph, TIntFltKdV & DistNbrsV, int const & MxDist, bool const & IsDir)
Parameters:
Graph: TPt< TNEANet > const &
DistNbrsV: TIntFltKdV &
MxDist: int const &
IsDir: bool const &
"""
return _snap.GetAnf(*args)
def GetAnfEffDiam(*args):
"""
GetAnfEffDiam(PNEANet Graph, bool const & IsDir, double const & Percentile, int const & NApprox) -> double
Parameters:
Graph: TPt< TNEANet > const &
IsDir: bool const &
Percentile: double const &
NApprox: int const &
GetAnfEffDiam(PNEANet Graph, int const NRuns=1, int NApprox=-1) -> double
Parameters:
Graph: TPt< TNEANet > const &
NRuns: int const
NApprox: int
GetAnfEffDiam(PNEANet Graph, int const NRuns=1) -> double
Parameters:
Graph: TPt< TNEANet > const &
NRuns: int const
GetAnfEffDiam(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetAnfEffDiam(*args) | setup/snap.py |
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _snap.SWIG_PyInstanceMethod_New(func)
else:
from new import instancemethod as new_instancemethod
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_snap', [dirname(__file__)])
except ImportError:
import _snap
return _snap
if fp is not None:
try:
_mod = imp.load_module('_snap', fp, pathname, description)
finally:
fp.close()
return _mod
_snap = swig_import_helper()
del swig_import_helper
else:
import _snap
del version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
def _swig_setattr_nondynamic_method(set):
def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
def CalcEffDiam(*args):
"""
CalcEffDiam(TIntFltKdV const & DistNbrsCdfV, double const & Percentile=0.9) -> double
Parameters:
DistNbrsCdfV: TIntFltKdV const &
Percentile: double const &
CalcEffDiam(TIntFltKdV const & DistNbrsCdfV) -> double
Parameters:
DistNbrsCdfV: TIntFltKdV const &
CalcEffDiam(TFltPrV const & DistNbrsCdfV, double const & Percentile=0.9) -> double
Parameters:
DistNbrsCdfV: TFltPrV const &
Percentile: double const &
CalcEffDiam(TFltPrV const & DistNbrsCdfV) -> double
Parameters:
DistNbrsCdfV: TFltPrV const &
"""
return _snap.CalcEffDiam(*args)
def CalcEffDiamPdf(*args):
"""
CalcEffDiamPdf(TIntFltKdV const & DistNbrsPdfV, double const & Percentile=0.9) -> double
Parameters:
DistNbrsPdfV: TIntFltKdV const &
Percentile: double const &
CalcEffDiamPdf(TIntFltKdV const & DistNbrsPdfV) -> double
Parameters:
DistNbrsPdfV: TIntFltKdV const &
CalcEffDiamPdf(TFltPrV const & DistNbrsPdfV, double const & Percentile=0.9) -> double
Parameters:
DistNbrsPdfV: TFltPrV const &
Percentile: double const &
CalcEffDiamPdf(TFltPrV const & DistNbrsPdfV) -> double
Parameters:
DistNbrsPdfV: TFltPrV const &
"""
return _snap.CalcEffDiamPdf(*args)
def CalcAvgDiamPdf(*args):
"""
CalcAvgDiamPdf(TIntFltKdV const & DistNbrsPdfV) -> double
Parameters:
DistNbrsPdfV: TIntFltKdV const &
CalcAvgDiamPdf(TFltPrV const & DistNbrsPdfV) -> double
Parameters:
DistNbrsPdfV: TFltPrV const &
"""
return _snap.CalcAvgDiamPdf(*args)
lUndef = _snap.lUndef
lUs = _snap.lUs
lSi = _snap.lSi
def WrNotify(*args):
"""
WrNotify(char const * CaptionCStr, char const * NotifyCStr)
Parameters:
CaptionCStr: char const *
NotifyCStr: char const *
"""
return _snap.WrNotify(*args)
def SaveToErrLog(*args):
"""
SaveToErrLog(char const * MsgCStr)
Parameters:
MsgCStr: char const *
"""
return _snap.SaveToErrLog(*args)
def InfoNotify(*args):
"""
InfoNotify(char const * NotifyCStr)
Parameters:
NotifyCStr: char const *
"""
return _snap.InfoNotify(*args)
def WarnNotify(*args):
"""
WarnNotify(char const * NotifyCStr)
Parameters:
NotifyCStr: char const *
"""
return _snap.WarnNotify(*args)
def ErrNotify(*args):
"""
ErrNotify(char const * NotifyCStr)
Parameters:
NotifyCStr: char const *
"""
return _snap.ErrNotify(*args)
def StatNotify(*args):
"""
StatNotify(char const * NotifyCStr)
Parameters:
NotifyCStr: char const *
"""
return _snap.StatNotify(*args)
def ExeStop(*args):
"""
ExeStop(char const * MsgStr, char const * ReasonStr, char const * CondStr, char const * FNm,
int const & LnN)
Parameters:
MsgStr: char const *
ReasonStr: char const *
CondStr: char const *
FNm: char const *
LnN: int const &
"""
return _snap.ExeStop(*args)
loUndef = _snap.loUndef
loNot = _snap.loNot
loAnd = _snap.loAnd
loOr = _snap.loOr
roUndef = _snap.roUndef
roLs = _snap.roLs
roLEq = _snap.roLEq
roEq = _snap.roEq
roNEq = _snap.roNEq
roGEq = _snap.roGEq
roGt = _snap.roGt
class TCRef(object):
"""Proxy of C++ TCRef class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self):
"""__init__(TCRef self) -> TCRef"""
_snap.TCRef_swiginit(self,_snap.new_TCRef())
__swig_destroy__ = _snap.delete_TCRef
def MkRef(self):
"""
MkRef(TCRef self)
Parameters:
self: TCRef *
"""
return _snap.TCRef_MkRef(self)
def UnRef(self):
"""
UnRef(TCRef self)
Parameters:
self: TCRef *
"""
return _snap.TCRef_UnRef(self)
def NoRef(self):
"""
NoRef(TCRef self) -> bool
Parameters:
self: TCRef const *
"""
return _snap.TCRef_NoRef(self)
def GetRefs(self):
"""
GetRefs(TCRef self) -> int
Parameters:
self: TCRef const *
"""
return _snap.TCRef_GetRefs(self)
TCRef.MkRef = new_instancemethod(_snap.TCRef_MkRef,None,TCRef)
TCRef.UnRef = new_instancemethod(_snap.TCRef_UnRef,None,TCRef)
TCRef.NoRef = new_instancemethod(_snap.TCRef_NoRef,None,TCRef)
TCRef.GetRefs = new_instancemethod(_snap.TCRef_GetRefs,None,TCRef)
TCRef_swigregister = _snap.TCRef_swigregister
TCRef_swigregister(TCRef)
class TSStr(object):
"""Proxy of C++ TSStr class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TSStr self) -> TSStr
__init__(TSStr self, TSStr SStr) -> TSStr
Parameters:
SStr: TSStr const &
__init__(TSStr self, char const * _Bf) -> TSStr
Parameters:
_Bf: char const *
"""
_snap.TSStr_swiginit(self,_snap.new_TSStr(*args))
__swig_destroy__ = _snap.delete_TSStr
def CStr(self, *args):
"""
CStr(TSStr self) -> char
CStr(TSStr self) -> char const *
Parameters:
self: TSStr const *
"""
return _snap.TSStr_CStr(self, *args)
def Empty(self):
"""
Empty(TSStr self) -> bool
Parameters:
self: TSStr const *
"""
return _snap.TSStr_Empty(self)
def Len(self):
"""
Len(TSStr self) -> int
Parameters:
self: TSStr const *
"""
return _snap.TSStr_Len(self)
TSStr.CStr = new_instancemethod(_snap.TSStr_CStr,None,TSStr)
TSStr.Empty = new_instancemethod(_snap.TSStr_Empty,None,TSStr)
TSStr.Len = new_instancemethod(_snap.TSStr_Len,None,TSStr)
TSStr_swigregister = _snap.TSStr_swigregister
TSStr_swigregister(TSStr)
class TConv_Pt64Ints32(object):
"""Proxy of C++ TConv_Pt64Ints32 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TConv_Pt64Ints32 self) -> TConv_Pt64Ints32
__init__(TConv_Pt64Ints32 self, void * Pt) -> TConv_Pt64Ints32
Parameters:
Pt: void *
__init__(TConv_Pt64Ints32 self, uint const & Ms, uint const & Ls) -> TConv_Pt64Ints32
Parameters:
Ms: uint const &
Ls: uint const &
"""
_snap.TConv_Pt64Ints32_swiginit(self,_snap.new_TConv_Pt64Ints32(*args))
def PutPt(self, *args):
"""
PutPt(TConv_Pt64Ints32 self, void * Pt)
Parameters:
Pt: void *
"""
return _snap.TConv_Pt64Ints32_PutPt(self, *args)
def GetPt(self):
"""
GetPt(TConv_Pt64Ints32 self) -> void *
Parameters:
self: TConv_Pt64Ints32 const *
"""
return _snap.TConv_Pt64Ints32_GetPt(self)
def PutUInt64(self, *args):
"""
PutUInt64(TConv_Pt64Ints32 self, uint64 const & _UInt64)
Parameters:
_UInt64: uint64 const &
"""
return _snap.TConv_Pt64Ints32_PutUInt64(self, *args)
def GetUInt64(self):
"""
GetUInt64(TConv_Pt64Ints32 self) -> uint64
Parameters:
self: TConv_Pt64Ints32 const *
"""
return _snap.TConv_Pt64Ints32_GetUInt64(self)
def PutMsUInt32(self, *args):
"""
PutMsUInt32(TConv_Pt64Ints32 self, uint const & Ms)
Parameters:
Ms: uint const &
"""
return _snap.TConv_Pt64Ints32_PutMsUInt32(self, *args)
def GetMsUInt32(self):
"""
GetMsUInt32(TConv_Pt64Ints32 self) -> uint
Parameters:
self: TConv_Pt64Ints32 const *
"""
return _snap.TConv_Pt64Ints32_GetMsUInt32(self)
def PutLsUInt32(self, *args):
"""
PutLsUInt32(TConv_Pt64Ints32 self, uint const & Ls)
Parameters:
Ls: uint const &
"""
return _snap.TConv_Pt64Ints32_PutLsUInt32(self, *args)
def GetLsUInt32(self):
"""
GetLsUInt32(TConv_Pt64Ints32 self) -> uint
Parameters:
self: TConv_Pt64Ints32 const *
"""
return _snap.TConv_Pt64Ints32_GetLsUInt32(self)
__swig_destroy__ = _snap.delete_TConv_Pt64Ints32
TConv_Pt64Ints32.PutPt = new_instancemethod(_snap.TConv_Pt64Ints32_PutPt,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.GetPt = new_instancemethod(_snap.TConv_Pt64Ints32_GetPt,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.PutUInt64 = new_instancemethod(_snap.TConv_Pt64Ints32_PutUInt64,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.GetUInt64 = new_instancemethod(_snap.TConv_Pt64Ints32_GetUInt64,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.PutMsUInt32 = new_instancemethod(_snap.TConv_Pt64Ints32_PutMsUInt32,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.GetMsUInt32 = new_instancemethod(_snap.TConv_Pt64Ints32_GetMsUInt32,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.PutLsUInt32 = new_instancemethod(_snap.TConv_Pt64Ints32_PutLsUInt32,None,TConv_Pt64Ints32)
TConv_Pt64Ints32.GetLsUInt32 = new_instancemethod(_snap.TConv_Pt64Ints32_GetLsUInt32,None,TConv_Pt64Ints32)
TConv_Pt64Ints32_swigregister = _snap.TConv_Pt64Ints32_swigregister
TConv_Pt64Ints32_swigregister(TConv_Pt64Ints32)
class TPairHashImpl1(object):
"""Proxy of C++ TPairHashImpl1 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetHashCd(*args):
"""
GetHashCd(int const hc1, int const hc2) -> int
Parameters:
hc1: int const
hc2: int const
"""
return _snap.TPairHashImpl1_GetHashCd(*args)
GetHashCd = staticmethod(GetHashCd)
def __init__(self):
"""__init__(TPairHashImpl1 self) -> TPairHashImpl1"""
_snap.TPairHashImpl1_swiginit(self,_snap.new_TPairHashImpl1())
__swig_destroy__ = _snap.delete_TPairHashImpl1
TPairHashImpl1_swigregister = _snap.TPairHashImpl1_swigregister
TPairHashImpl1_swigregister(TPairHashImpl1)
def TPairHashImpl1_GetHashCd(*args):
"""
TPairHashImpl1_GetHashCd(int const hc1, int const hc2) -> int
Parameters:
hc1: int const
hc2: int const
"""
return _snap.TPairHashImpl1_GetHashCd(*args)
class TPairHashImpl2(object):
"""Proxy of C++ TPairHashImpl2 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetHashCd(*args):
"""
GetHashCd(int const hc1, int const hc2) -> int
Parameters:
hc1: int const
hc2: int const
"""
return _snap.TPairHashImpl2_GetHashCd(*args)
GetHashCd = staticmethod(GetHashCd)
def __init__(self):
"""__init__(TPairHashImpl2 self) -> TPairHashImpl2"""
_snap.TPairHashImpl2_swiginit(self,_snap.new_TPairHashImpl2())
__swig_destroy__ = _snap.delete_TPairHashImpl2
TPairHashImpl2_swigregister = _snap.TPairHashImpl2_swigregister
TPairHashImpl2_swigregister(TPairHashImpl2)
def TPairHashImpl2_GetHashCd(*args):
"""
TPairHashImpl2_GetHashCd(int const hc1, int const hc2) -> int
Parameters:
hc1: int const
hc2: int const
"""
return _snap.TPairHashImpl2_GetHashCd(*args)
def GetDegreeCentr(*args):
"""
GetDegreeCentr(PUNGraph const & Graph, int const & NId) -> double
Parameters:
Graph: PUNGraph const &
NId: int const &
"""
return _snap.GetDegreeCentr(*args)
def GetFarnessCentr(*args):
"""
GetFarnessCentr(PUNGraph const & Graph, int const & NId) -> double
Parameters:
Graph: PUNGraph const &
NId: int const &
"""
return _snap.GetFarnessCentr(*args)
def GetClosenessCentr(*args):
"""
GetClosenessCentr(PUNGraph const & Graph, int const & NId) -> double
Parameters:
Graph: PUNGraph const &
NId: int const &
"""
return _snap.GetClosenessCentr(*args)
def GetBetweennessCentr(*args):
"""
GetBetweennessCentr(PUNGraph const & Graph, TIntFltH & NIdBtwH, double const & NodeFrac=1.0)
Parameters:
Graph: PUNGraph const &
NIdBtwH: TIntFltH &
NodeFrac: double const &
GetBetweennessCentr(PUNGraph const & Graph, TIntFltH & NIdBtwH)
Parameters:
Graph: PUNGraph const &
NIdBtwH: TIntFltH &
GetBetweennessCentr(PUNGraph const & Graph, TIntPrFltH & EdgeBtwH, double const & NodeFrac=1.0)
Parameters:
Graph: PUNGraph const &
EdgeBtwH: TIntPrFltH &
NodeFrac: double const &
GetBetweennessCentr(PUNGraph const & Graph, TIntPrFltH & EdgeBtwH)
Parameters:
Graph: PUNGraph const &
EdgeBtwH: TIntPrFltH &
GetBetweennessCentr(PUNGraph const & Graph, TIntFltH & NIdBtwH, TIntPrFltH & EdgeBtwH, double const & NodeFrac=1.0)
Parameters:
Graph: PUNGraph const &
NIdBtwH: TIntFltH &
EdgeBtwH: TIntPrFltH &
NodeFrac: double const &
GetBetweennessCentr(PUNGraph const & Graph, TIntFltH & NIdBtwH, TIntPrFltH & EdgeBtwH)
Parameters:
Graph: PUNGraph const &
NIdBtwH: TIntFltH &
EdgeBtwH: TIntPrFltH &
GetBetweennessCentr(PUNGraph const & Graph, TIntV BtwNIdV, TIntFltH & NodeBtwH, bool const & DoNodeCent,
TIntPrFltH & EdgeBtwH, bool const & DoEdgeCent)
Parameters:
Graph: PUNGraph const &
BtwNIdV: TIntV const &
NodeBtwH: TIntFltH &
DoNodeCent: bool const &
EdgeBtwH: TIntPrFltH &
DoEdgeCent: bool const &
"""
return _snap.GetBetweennessCentr(*args)
def GetEigenVectorCentr(*args):
"""
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4, int const & MaxIter=100)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
MaxIter: int const &
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
"""
return _snap.GetEigenVectorCentr(*args)
def CommunityGirvanNewman(*args):
"""
CommunityGirvanNewman(PUNGraph & Graph, TCnComV & CmtyV) -> double
Parameters:
Graph: PUNGraph &
CmtyV: TCnComV &
"""
return _snap.CommunityGirvanNewman(*args)
def CommunityCNM(*args):
"""
CommunityCNM(PUNGraph const & Graph, TCnComV & CmtyV) -> double
Parameters:
Graph: PUNGraph const &
CmtyV: TCnComV &
"""
return _snap.CommunityCNM(*args)
def CmtyGirvanNewmanStep(*args):
"""
CmtyGirvanNewmanStep(PUNGraph & Graph, TIntV Cmty1, TIntV Cmty2)
Parameters:
Graph: PUNGraph &
Cmty1: TIntV &
Cmty2: TIntV &
"""
return _snap.CmtyGirvanNewmanStep(*args)
def GetBiConSzCnt(*args):
"""
GetBiConSzCnt(PUNGraph const & Graph, TIntPrV & SzCntV)
Parameters:
Graph: PUNGraph const &
SzCntV: TIntPrV &
"""
return _snap.GetBiConSzCnt(*args)
def GetBiCon(*args):
"""
GetBiCon(PUNGraph const & Graph, TCnComV & BiCnComV)
Parameters:
Graph: PUNGraph const &
BiCnComV: TCnComV &
"""
return _snap.GetBiCon(*args)
def GetArtPoints(*args):
"""
GetArtPoints(PUNGraph const & Graph, TIntV ArtNIdV)
Parameters:
Graph: PUNGraph const &
ArtNIdV: TIntV &
"""
return _snap.GetArtPoints(*args)
def GetEdgeBridges(*args):
"""
GetEdgeBridges(PUNGraph const & Graph, TIntPrV & EdgeV)
Parameters:
Graph: PUNGraph const &
EdgeV: TIntPrV &
"""
return _snap.GetEdgeBridges(*args)
def Get1CnComSzCnt(*args):
"""
Get1CnComSzCnt(PUNGraph const & Graph, TIntPrV & SzCntV)
Parameters:
Graph: PUNGraph const &
SzCntV: TIntPrV &
"""
return _snap.Get1CnComSzCnt(*args)
def Get1CnCom(*args):
"""
Get1CnCom(PUNGraph const & Graph, TCnComV & Cn1ComV)
Parameters:
Graph: PUNGraph const &
Cn1ComV: TCnComV &
"""
return _snap.Get1CnCom(*args)
class TCnCom(object):
"""Proxy of C++ TCnCom class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
NIdV = _swig_property(_snap.TCnCom_NIdV_get, _snap.TCnCom_NIdV_set)
def __init__(self, *args):
"""
__init__(TCnCom self) -> TCnCom
__init__(TCnCom self, TIntV NodeIdV) -> TCnCom
Parameters:
NodeIdV: TIntV const &
__init__(TCnCom self, TCnCom CC) -> TCnCom
Parameters:
CC: TCnCom const &
__init__(TCnCom self, TSIn SIn) -> TCnCom
Parameters:
SIn: TSIn &
"""
_snap.TCnCom_swiginit(self,_snap.new_TCnCom(*args))
def Save(self, *args):
"""
Save(TCnCom self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TCnCom_Save(self, *args)
def __eq__(self, *args):
"""
__eq__(TCnCom self, TCnCom CC) -> bool
Parameters:
CC: TCnCom const &
"""
return _snap.TCnCom___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TCnCom self, TCnCom CC) -> bool
Parameters:
CC: TCnCom const &
"""
return _snap.TCnCom___lt__(self, *args)
def Len(self):
"""
Len(TCnCom self) -> int
Parameters:
self: TCnCom const *
"""
return _snap.TCnCom_Len(self)
def Empty(self):
"""
Empty(TCnCom self) -> bool
Parameters:
self: TCnCom const *
"""
return _snap.TCnCom_Empty(self)
def Clr(self):
"""
Clr(TCnCom self)
Parameters:
self: TCnCom *
"""
return _snap.TCnCom_Clr(self)
def Add(self, *args):
"""
Add(TCnCom self, int const & NodeId)
Parameters:
NodeId: int const &
"""
return _snap.TCnCom_Add(self, *args)
def __call__(self, *args):
"""
__call__(TCnCom self) -> TIntV
__call__(TCnCom self) -> TIntV
Parameters:
self: TCnCom *
"""
return _snap.TCnCom___call__(self, *args)
def Sort(self, Asc=True):
"""
Sort(TCnCom self, bool const & Asc=True)
Parameters:
Asc: bool const &
Sort(TCnCom self)
Parameters:
self: TCnCom *
"""
return _snap.TCnCom_Sort(self, Asc)
def IsNIdIn(self, *args):
"""
IsNIdIn(TCnCom self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TCnCom_IsNIdIn(self, *args)
def GetRndNId(self):
"""
GetRndNId(TCnCom self) -> TInt
Parameters:
self: TCnCom const *
"""
return _snap.TCnCom_GetRndNId(self)
def Dump(*args):
"""
Dump(TCnComV const & CnComV, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
Desc: TStr const &
Dump(TCnComV const & CnComV)
Parameters:
CnComV: TCnComV const &
"""
return _snap.TCnCom_Dump(*args)
Dump = staticmethod(Dump)
def SaveTxt(*args):
"""
SaveTxt(TCnComV const & CnComV, TStr FNm, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
FNm: TStr const &
Desc: TStr const &
SaveTxt(TCnComV const & CnComV, TStr FNm)
Parameters:
CnComV: TCnComV const &
FNm: TStr const &
"""
return _snap.TCnCom_SaveTxt(*args)
SaveTxt = staticmethod(SaveTxt)
__swig_destroy__ = _snap.delete_TCnCom
TCnCom.Save = new_instancemethod(_snap.TCnCom_Save,None,TCnCom)
TCnCom.__eq__ = new_instancemethod(_snap.TCnCom___eq__,None,TCnCom)
TCnCom.__lt__ = new_instancemethod(_snap.TCnCom___lt__,None,TCnCom)
TCnCom.Len = new_instancemethod(_snap.TCnCom_Len,None,TCnCom)
TCnCom.Empty = new_instancemethod(_snap.TCnCom_Empty,None,TCnCom)
TCnCom.Clr = new_instancemethod(_snap.TCnCom_Clr,None,TCnCom)
TCnCom.Add = new_instancemethod(_snap.TCnCom_Add,None,TCnCom)
TCnCom.__call__ = new_instancemethod(_snap.TCnCom___call__,None,TCnCom)
TCnCom.Sort = new_instancemethod(_snap.TCnCom_Sort,None,TCnCom)
TCnCom.IsNIdIn = new_instancemethod(_snap.TCnCom_IsNIdIn,None,TCnCom)
TCnCom.GetRndNId = new_instancemethod(_snap.TCnCom_GetRndNId,None,TCnCom)
TCnCom_swigregister = _snap.TCnCom_swigregister
TCnCom_swigregister(TCnCom)
def TCnCom_Dump(*args):
"""
Dump(TCnComV const & CnComV, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
Desc: TStr const &
TCnCom_Dump(TCnComV const & CnComV)
Parameters:
CnComV: TCnComV const &
"""
return _snap.TCnCom_Dump(*args)
def TCnCom_SaveTxt(*args):
"""
SaveTxt(TCnComV const & CnComV, TStr FNm, TStr Desc=TStr())
Parameters:
CnComV: TCnComV const &
FNm: TStr const &
Desc: TStr const &
TCnCom_SaveTxt(TCnComV const & CnComV, TStr FNm)
Parameters:
CnComV: TCnComV const &
FNm: TStr const &
"""
return _snap.TCnCom_SaveTxt(*args)
class TArtPointVisitor(object):
"""Proxy of C++ TArtPointVisitor class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
VnLowH = _swig_property(_snap.TArtPointVisitor_VnLowH_get, _snap.TArtPointVisitor_VnLowH_set)
ParentH = _swig_property(_snap.TArtPointVisitor_ParentH_get, _snap.TArtPointVisitor_ParentH_set)
ArtSet = _swig_property(_snap.TArtPointVisitor_ArtSet_get, _snap.TArtPointVisitor_ArtSet_set)
Time = _swig_property(_snap.TArtPointVisitor_Time_get, _snap.TArtPointVisitor_Time_set)
def __init__(self, *args):
"""
__init__(TArtPointVisitor self) -> TArtPointVisitor
__init__(TArtPointVisitor self, int const & Nodes) -> TArtPointVisitor
Parameters:
Nodes: int const &
"""
_snap.TArtPointVisitor_swiginit(self,_snap.new_TArtPointVisitor(*args))
def DiscoverNode(self, *args):
"""
DiscoverNode(TArtPointVisitor self, int NId)
Parameters:
NId: int
"""
return _snap.TArtPointVisitor_DiscoverNode(self, *args)
def FinishNode(self, *args):
"""
FinishNode(TArtPointVisitor self, int const & NId)
Parameters:
NId: int const &
"""
return _snap.TArtPointVisitor_FinishNode(self, *args)
def ExamineEdge(self, *args):
"""
ExamineEdge(TArtPointVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TArtPointVisitor_ExamineEdge(self, *args)
def TreeEdge(self, *args):
"""
TreeEdge(TArtPointVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TArtPointVisitor_TreeEdge(self, *args)
def BackEdge(self, *args):
"""
BackEdge(TArtPointVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TArtPointVisitor_BackEdge(self, *args)
def FwdEdge(self, *args):
"""
FwdEdge(TArtPointVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TArtPointVisitor_FwdEdge(self, *args)
__swig_destroy__ = _snap.delete_TArtPointVisitor
TArtPointVisitor.DiscoverNode = new_instancemethod(_snap.TArtPointVisitor_DiscoverNode,None,TArtPointVisitor)
TArtPointVisitor.FinishNode = new_instancemethod(_snap.TArtPointVisitor_FinishNode,None,TArtPointVisitor)
TArtPointVisitor.ExamineEdge = new_instancemethod(_snap.TArtPointVisitor_ExamineEdge,None,TArtPointVisitor)
TArtPointVisitor.TreeEdge = new_instancemethod(_snap.TArtPointVisitor_TreeEdge,None,TArtPointVisitor)
TArtPointVisitor.BackEdge = new_instancemethod(_snap.TArtPointVisitor_BackEdge,None,TArtPointVisitor)
TArtPointVisitor.FwdEdge = new_instancemethod(_snap.TArtPointVisitor_FwdEdge,None,TArtPointVisitor)
TArtPointVisitor_swigregister = _snap.TArtPointVisitor_swigregister
TArtPointVisitor_swigregister(TArtPointVisitor)
class TBiConVisitor(object):
"""Proxy of C++ TBiConVisitor class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
VnLowH = _swig_property(_snap.TBiConVisitor_VnLowH_get, _snap.TBiConVisitor_VnLowH_set)
ParentH = _swig_property(_snap.TBiConVisitor_ParentH_get, _snap.TBiConVisitor_ParentH_set)
Stack = _swig_property(_snap.TBiConVisitor_Stack_get, _snap.TBiConVisitor_Stack_set)
CnComV = _swig_property(_snap.TBiConVisitor_CnComV_get, _snap.TBiConVisitor_CnComV_set)
NSet = _swig_property(_snap.TBiConVisitor_NSet_get, _snap.TBiConVisitor_NSet_set)
Time = _swig_property(_snap.TBiConVisitor_Time_get, _snap.TBiConVisitor_Time_set)
def __init__(self, *args):
"""
__init__(TBiConVisitor self) -> TBiConVisitor
__init__(TBiConVisitor self, int const & Nodes) -> TBiConVisitor
Parameters:
Nodes: int const &
"""
_snap.TBiConVisitor_swiginit(self,_snap.new_TBiConVisitor(*args))
def DiscoverNode(self, *args):
"""
DiscoverNode(TBiConVisitor self, int NId)
Parameters:
NId: int
"""
return _snap.TBiConVisitor_DiscoverNode(self, *args)
def FinishNode(self, *args):
"""
FinishNode(TBiConVisitor self, int const & NId)
Parameters:
NId: int const &
"""
return _snap.TBiConVisitor_FinishNode(self, *args)
def ExamineEdge(self, *args):
"""
ExamineEdge(TBiConVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TBiConVisitor_ExamineEdge(self, *args)
def TreeEdge(self, *args):
"""
TreeEdge(TBiConVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TBiConVisitor_TreeEdge(self, *args)
def BackEdge(self, *args):
"""
BackEdge(TBiConVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TBiConVisitor_BackEdge(self, *args)
def FwdEdge(self, *args):
"""
FwdEdge(TBiConVisitor self, int const & NId1, int const & NId2)
Parameters:
NId1: int const &
NId2: int const &
"""
return _snap.TBiConVisitor_FwdEdge(self, *args)
__swig_destroy__ = _snap.delete_TBiConVisitor
TBiConVisitor.DiscoverNode = new_instancemethod(_snap.TBiConVisitor_DiscoverNode,None,TBiConVisitor)
TBiConVisitor.FinishNode = new_instancemethod(_snap.TBiConVisitor_FinishNode,None,TBiConVisitor)
TBiConVisitor.ExamineEdge = new_instancemethod(_snap.TBiConVisitor_ExamineEdge,None,TBiConVisitor)
TBiConVisitor.TreeEdge = new_instancemethod(_snap.TBiConVisitor_TreeEdge,None,TBiConVisitor)
TBiConVisitor.BackEdge = new_instancemethod(_snap.TBiConVisitor_BackEdge,None,TBiConVisitor)
TBiConVisitor.FwdEdge = new_instancemethod(_snap.TBiConVisitor_FwdEdge,None,TBiConVisitor)
TBiConVisitor_swigregister = _snap.TBiConVisitor_swigregister
TBiConVisitor_swigregister(TBiConVisitor)
class TForestFire(object):
"""Proxy of C++ TForestFire class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TForestFire self) -> TForestFire
__init__(TForestFire self, PNGraph const & GraphPt, double const & ForwBurnProb, double const & BackBurnProb,
double const & DecayProb=1.0, int const & RndSeed=1) -> TForestFire
Parameters:
GraphPt: PNGraph const &
ForwBurnProb: double const &
BackBurnProb: double const &
DecayProb: double const &
RndSeed: int const &
__init__(TForestFire self, PNGraph const & GraphPt, double const & ForwBurnProb, double const & BackBurnProb,
double const & DecayProb=1.0) -> TForestFire
Parameters:
GraphPt: PNGraph const &
ForwBurnProb: double const &
BackBurnProb: double const &
DecayProb: double const &
__init__(TForestFire self, PNGraph const & GraphPt, double const & ForwBurnProb, double const & BackBurnProb) -> TForestFire
Parameters:
GraphPt: PNGraph const &
ForwBurnProb: double const &
BackBurnProb: double const &
"""
_snap.TForestFire_swiginit(self,_snap.new_TForestFire(*args))
def SetGraph(self, *args):
"""
SetGraph(TForestFire self, PNGraph const & GraphPt)
Parameters:
GraphPt: PNGraph const &
"""
return _snap.TForestFire_SetGraph(self, *args)
def GetGraph(self):
"""
GetGraph(TForestFire self) -> PNGraph
Parameters:
self: TForestFire const *
"""
return _snap.TForestFire_GetGraph(self)
def SetBurnProb(self, *args):
"""
SetBurnProb(TForestFire self, double const & ForwBurnProb, double const & BackBurnProb)
Parameters:
ForwBurnProb: double const &
BackBurnProb: double const &
"""
return _snap.TForestFire_SetBurnProb(self, *args)
def SetProbDecay(self, *args):
"""
SetProbDecay(TForestFire self, double const & DecayProb)
Parameters:
DecayProb: double const &
"""
return _snap.TForestFire_SetProbDecay(self, *args)
def Infect(self, *args):
"""
Infect(TForestFire self, int const & NodeId)
Parameters:
NodeId: int const &
Infect(TForestFire self, TIntV InfectedNIdV)
Parameters:
InfectedNIdV: TIntV const &
"""
return _snap.TForestFire_Infect(self, *args)
def InfectAll(self):
"""
InfectAll(TForestFire self)
Parameters:
self: TForestFire *
"""
return _snap.TForestFire_InfectAll(self)
def InfectRnd(self, *args):
"""
InfectRnd(TForestFire self, int const & NInfect)
Parameters:
NInfect: int const &
"""
return _snap.TForestFire_InfectRnd(self, *args)
def BurnExpFire(self):
"""
BurnExpFire(TForestFire self)
Parameters:
self: TForestFire *
"""
return _snap.TForestFire_BurnExpFire(self)
def BurnGeoFire(self):
"""
BurnGeoFire(TForestFire self)
Parameters:
self: TForestFire *
"""
return _snap.TForestFire_BurnGeoFire(self)
def GetFireTm(self):
"""
GetFireTm(TForestFire self) -> int
Parameters:
self: TForestFire const *
"""
return _snap.TForestFire_GetFireTm(self)
def GetBurned(self):
"""
GetBurned(TForestFire self) -> int
Parameters:
self: TForestFire const *
"""
return _snap.TForestFire_GetBurned(self)
def GetBurnedNId(self, *args):
"""
GetBurnedNId(TForestFire self, int const & NIdN) -> int
Parameters:
NIdN: int const &
"""
return _snap.TForestFire_GetBurnedNId(self, *args)
def GetBurnedNIdV(self, *args):
"""
GetBurnedNIdV(TForestFire self) -> TIntV
GetBurnedNIdV(TForestFire self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TForestFire_GetBurnedNIdV(self, *args)
def PlotFire(self, *args):
"""
PlotFire(TForestFire self, TStr FNmPref, TStr Desc, bool const & PlotAllBurned=False)
Parameters:
FNmPref: TStr const &
Desc: TStr const &
PlotAllBurned: bool const &
PlotFire(TForestFire self, TStr FNmPref, TStr Desc)
Parameters:
FNmPref: TStr const &
Desc: TStr const &
"""
return _snap.TForestFire_PlotFire(self, *args)
def GenGraph(*args):
"""
GenGraph(int const & Nodes, double const & FwdProb, double const & BckProb) -> PNGraph
Parameters:
Nodes: int const &
FwdProb: double const &
BckProb: double const &
"""
return _snap.TForestFire_GenGraph(*args)
GenGraph = staticmethod(GenGraph)
__swig_destroy__ = _snap.delete_TForestFire
TForestFire.SetGraph = new_instancemethod(_snap.TForestFire_SetGraph,None,TForestFire)
TForestFire.GetGraph = new_instancemethod(_snap.TForestFire_GetGraph,None,TForestFire)
TForestFire.SetBurnProb = new_instancemethod(_snap.TForestFire_SetBurnProb,None,TForestFire)
TForestFire.SetProbDecay = new_instancemethod(_snap.TForestFire_SetProbDecay,None,TForestFire)
TForestFire.Infect = new_instancemethod(_snap.TForestFire_Infect,None,TForestFire)
TForestFire.InfectAll = new_instancemethod(_snap.TForestFire_InfectAll,None,TForestFire)
TForestFire.InfectRnd = new_instancemethod(_snap.TForestFire_InfectRnd,None,TForestFire)
TForestFire.BurnExpFire = new_instancemethod(_snap.TForestFire_BurnExpFire,None,TForestFire)
TForestFire.BurnGeoFire = new_instancemethod(_snap.TForestFire_BurnGeoFire,None,TForestFire)
TForestFire.GetFireTm = new_instancemethod(_snap.TForestFire_GetFireTm,None,TForestFire)
TForestFire.GetBurned = new_instancemethod(_snap.TForestFire_GetBurned,None,TForestFire)
TForestFire.GetBurnedNId = new_instancemethod(_snap.TForestFire_GetBurnedNId,None,TForestFire)
TForestFire.GetBurnedNIdV = new_instancemethod(_snap.TForestFire_GetBurnedNIdV,None,TForestFire)
TForestFire.PlotFire = new_instancemethod(_snap.TForestFire_PlotFire,None,TForestFire)
TForestFire_swigregister = _snap.TForestFire_swigregister
TForestFire_swigregister(TForestFire)
def TForestFire_GenGraph(*args):
"""
TForestFire_GenGraph(int const & Nodes, double const & FwdProb, double const & BckProb) -> PNGraph
Parameters:
Nodes: int const &
FwdProb: double const &
BckProb: double const &
"""
return _snap.TForestFire_GenGraph(*args)
class TFfGGen(object):
"""Proxy of C++ TFfGGen class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
srUndef = _snap.TFfGGen_srUndef
srOk = _snap.TFfGGen_srOk
srFlood = _snap.TFfGGen_srFlood
srTimeLimit = _snap.TFfGGen_srTimeLimit
TimeLimitSec = _swig_property(_snap.TFfGGen_TimeLimitSec_get, _snap.TFfGGen_TimeLimitSec_set)
def __init__(self, *args):
"""
__init__(TFfGGen self, bool const & BurnExpFireP, int const & StartNNodes, double const & ForwBurnProb,
double const & BackBurnProb, double const & DecayProb, double const & Take2AmbasPrb,
double const & OrphanPrb) -> TFfGGen
Parameters:
BurnExpFireP: bool const &
StartNNodes: int const &
ForwBurnProb: double const &
BackBurnProb: double const &
DecayProb: double const &
Take2AmbasPrb: double const &
OrphanPrb: double const &
"""
_snap.TFfGGen_swiginit(self,_snap.new_TFfGGen(*args))
def GetGraph(self):
"""
GetGraph(TFfGGen self) -> PNGraph
Parameters:
self: TFfGGen const *
"""
return _snap.TFfGGen_GetGraph(self)
def SetGraph(self, *args):
"""
SetGraph(TFfGGen self, PNGraph const & NGraph)
Parameters:
NGraph: PNGraph const &
"""
return _snap.TFfGGen_SetGraph(self, *args)
def Clr(self):
"""
Clr(TFfGGen self)
Parameters:
self: TFfGGen *
"""
return _snap.TFfGGen_Clr(self)
def GetParamStr(self):
"""
GetParamStr(TFfGGen self) -> TStr
Parameters:
self: TFfGGen const *
"""
return _snap.TFfGGen_GetParamStr(self)
def AddNodes(self, *args):
"""
AddNodes(TFfGGen self, int const & GraphNodes, bool const & FloodStop=True) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
FloodStop: bool const &
AddNodes(TFfGGen self, int const & GraphNodes) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
"""
return _snap.TFfGGen_AddNodes(self, *args)
def GenGraph(self, *args):
"""
GenGraph(TFfGGen self, int const & GraphNodes, bool const & FloodStop=True) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
FloodStop: bool const &
GenGraph(TFfGGen self, int const & GraphNodes) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
GenGraph(TFfGGen self, int const & GraphNodes, PGStatVec & EvolStat, bool const & FloodStop=True) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
EvolStat: PGStatVec &
FloodStop: bool const &
GenGraph(TFfGGen self, int const & GraphNodes, PGStatVec & EvolStat) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
EvolStat: PGStatVec &
"""
return _snap.TFfGGen_GenGraph(self, *args)
def PlotFireSize(self, *args):
"""
PlotFireSize(TFfGGen self, TStr FNmPref, TStr DescStr)
Parameters:
FNmPref: TStr const &
DescStr: TStr const &
"""
return _snap.TFfGGen_PlotFireSize(self, *args)
def GenFFGraphs(*args):
"""
GenFFGraphs(double const & FProb, double const & BProb, TStr FNm)
Parameters:
FProb: double const &
BProb: double const &
FNm: TStr const &
"""
return _snap.TFfGGen_GenFFGraphs(*args)
GenFFGraphs = staticmethod(GenFFGraphs)
__swig_destroy__ = _snap.delete_TFfGGen
TFfGGen.GetGraph = new_instancemethod(_snap.TFfGGen_GetGraph,None,TFfGGen)
TFfGGen.SetGraph = new_instancemethod(_snap.TFfGGen_SetGraph,None,TFfGGen)
TFfGGen.Clr = new_instancemethod(_snap.TFfGGen_Clr,None,TFfGGen)
TFfGGen.GetParamStr = new_instancemethod(_snap.TFfGGen_GetParamStr,None,TFfGGen)
TFfGGen.AddNodes = new_instancemethod(_snap.TFfGGen_AddNodes,None,TFfGGen)
TFfGGen.GenGraph = new_instancemethod(_snap.TFfGGen_GenGraph,None,TFfGGen)
TFfGGen.PlotFireSize = new_instancemethod(_snap.TFfGGen_PlotFireSize,None,TFfGGen)
TFfGGen_swigregister = _snap.TFfGGen_swigregister
TFfGGen_swigregister(TFfGGen)
cvar = _snap.cvar
def TFfGGen_GenFFGraphs(*args):
"""
TFfGGen_GenFFGraphs(double const & FProb, double const & BProb, TStr FNm)
Parameters:
FProb: double const &
BProb: double const &
FNm: TStr const &
"""
return _snap.TFfGGen_GenFFGraphs(*args)
class TUndirFFire(object):
"""Proxy of C++ TUndirFFire class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, _BurnProb=0.3):
"""
__init__(TUndirFFire self, double const & _BurnProb=0.3) -> TUndirFFire
Parameters:
_BurnProb: double const &
__init__(TUndirFFire self) -> TUndirFFire
"""
_snap.TUndirFFire_swiginit(self,_snap.new_TUndirFFire(_BurnProb))
def SetGraph(self, *args):
"""
SetGraph(TUndirFFire self, PUNGraph const & GraphPt)
Parameters:
GraphPt: PUNGraph const &
"""
return _snap.TUndirFFire_SetGraph(self, *args)
def GetGraph(self):
"""
GetGraph(TUndirFFire self) -> PUNGraph
Parameters:
self: TUndirFFire const *
"""
return _snap.TUndirFFire_GetGraph(self)
def GetNBurned(self):
"""
GetNBurned(TUndirFFire self) -> int
Parameters:
self: TUndirFFire const *
"""
return _snap.TUndirFFire_GetNBurned(self)
def GetBurnedNId(self, *args):
"""
GetBurnedNId(TUndirFFire self, int const & n) -> int
Parameters:
n: int const &
"""
return _snap.TUndirFFire_GetBurnedNId(self, *args)
def BurnGeoFire(self, *args):
"""
BurnGeoFire(TUndirFFire self, int const & StartNId) -> int
Parameters:
StartNId: int const &
"""
return _snap.TUndirFFire_BurnGeoFire(self, *args)
def AddNodes(self, *args):
"""
AddNodes(TUndirFFire self, int const & GraphNodes, bool const & FloodStop=True) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
FloodStop: bool const &
AddNodes(TUndirFFire self, int const & GraphNodes) -> TFfGGen::TStopReason
Parameters:
GraphNodes: int const &
"""
return _snap.TUndirFFire_AddNodes(self, *args)
__swig_destroy__ = _snap.delete_TUndirFFire
TUndirFFire.SetGraph = new_instancemethod(_snap.TUndirFFire_SetGraph,None,TUndirFFire)
TUndirFFire.GetGraph = new_instancemethod(_snap.TUndirFFire_GetGraph,None,TUndirFFire)
TUndirFFire.GetNBurned = new_instancemethod(_snap.TUndirFFire_GetNBurned,None,TUndirFFire)
TUndirFFire.GetBurnedNId = new_instancemethod(_snap.TUndirFFire_GetBurnedNId,None,TUndirFFire)
TUndirFFire.BurnGeoFire = new_instancemethod(_snap.TUndirFFire_BurnGeoFire,None,TUndirFFire)
TUndirFFire.AddNodes = new_instancemethod(_snap.TUndirFFire_AddNodes,None,TUndirFFire)
TUndirFFire_swigregister = _snap.TUndirFFire_swigregister
TUndirFFire_swigregister(TUndirFFire)
class TCs(object):
"""Proxy of C++ TCs class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TCs self) -> TCs
__init__(TCs self, TCs Cs) -> TCs
Parameters:
Cs: TCs const &
__init__(TCs self, int const & Int) -> TCs
Parameters:
Int: int const &
"""
_snap.TCs_swiginit(self,_snap.new_TCs(*args))
def __eq__(self, *args):
"""
__eq__(TCs self, TCs Cs) -> bool
Parameters:
Cs: TCs const &
"""
return _snap.TCs___eq__(self, *args)
def __iadd__(self, *args):
"""
__iadd__(TCs self, TCs Cs) -> TCs
Parameters:
Cs: TCs const &
__iadd__(TCs self, char const & Ch) -> TCs
Parameters:
Ch: char const &
__iadd__(TCs self, int const & Int) -> TCs
Parameters:
Int: int const &
"""
return _snap.TCs___iadd__(self, *args)
def Get(self):
"""
Get(TCs self) -> int
Parameters:
self: TCs const *
"""
return _snap.TCs_Get(self)
def GetCsFromBf(*args):
"""
GetCsFromBf(char * Bf, int const & BfL) -> TCs
Parameters:
Bf: char *
BfL: int const &
"""
return _snap.TCs_GetCsFromBf(*args)
GetCsFromBf = staticmethod(GetCsFromBf)
__swig_destroy__ = _snap.delete_TCs
TCs.__eq__ = new_instancemethod(_snap.TCs___eq__,None,TCs)
TCs.__iadd__ = new_instancemethod(_snap.TCs___iadd__,None,TCs)
TCs.Get = new_instancemethod(_snap.TCs_Get,None,TCs)
TCs_swigregister = _snap.TCs_swigregister
TCs_swigregister(TCs)
def TCs_GetCsFromBf(*args):
"""
TCs_GetCsFromBf(char * Bf, int const & BfL) -> TCs
Parameters:
Bf: char *
BfL: int const &
"""
return _snap.TCs_GetCsFromBf(*args)
class TSOutMnp(object):
"""Proxy of C++ TSOutMnp class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
def __call__(self, *args):
"""
__call__(TSOutMnp self, TSOut SOut) -> TSOut
Parameters:
SOut: TSOut &
"""
return _snap.TSOutMnp___call__(self, *args)
__swig_destroy__ = _snap.delete_TSOutMnp
TSOutMnp.__call__ = new_instancemethod(_snap.TSOutMnp___call__,None,TSOutMnp)
TSOutMnp_swigregister = _snap.TSOutMnp_swigregister
TSOutMnp_swigregister(TSOutMnp)
class TSBase(object):
"""Proxy of C++ TSBase class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TSBase self, TSStr Nm) -> TSBase
Parameters:
Nm: TSStr const &
"""
_snap.TSBase_swiginit(self,_snap.new_TSBase(*args))
__swig_destroy__ = _snap.delete_TSBase
def GetSNm(self):
"""
GetSNm(TSBase self) -> TStr
Parameters:
self: TSBase const *
"""
return _snap.TSBase_GetSNm(self)
TSBase.GetSNm = new_instancemethod(_snap.TSBase_GetSNm,None,TSBase)
TSBase_swigregister = _snap.TSBase_swigregister
TSBase_swigregister(TSBase)
class TSIn(TSBase):
"""Proxy of C++ TSIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TSIn
def Eof(self):
"""
Eof(TSIn self) -> bool
Parameters:
self: TSIn *
"""
return _snap.TSIn_Eof(self)
def Len(self):
"""
Len(TSIn self) -> int
Parameters:
self: TSIn const *
"""
return _snap.TSIn_Len(self)
def GetCh(self):
"""
GetCh(TSIn self) -> char
Parameters:
self: TSIn *
"""
return _snap.TSIn_GetCh(self)
def PeekCh(self):
"""
PeekCh(TSIn self) -> char
Parameters:
self: TSIn *
"""
return _snap.TSIn_PeekCh(self)
def GetBf(self, *args):
"""
GetBf(TSIn self, void const * Bf, TSize const & BfL) -> int
Parameters:
Bf: void const *
BfL: TSize const &
"""
return _snap.TSIn_GetBf(self, *args)
def GetNextLnBf(self, *args):
"""
GetNextLnBf(TSIn self, TChA LnChA) -> bool
Parameters:
LnChA: TChA &
"""
return _snap.TSIn_GetNextLnBf(self, *args)
def Reset(self):
"""
Reset(TSIn self)
Parameters:
self: TSIn *
"""
return _snap.TSIn_Reset(self)
def IsFastMode(self):
"""
IsFastMode(TSIn self) -> bool
Parameters:
self: TSIn const *
"""
return _snap.TSIn_IsFastMode(self)
def SetFastMode(self, *args):
"""
SetFastMode(TSIn self, bool const & _FastMode)
Parameters:
_FastMode: bool const &
"""
return _snap.TSIn_SetFastMode(self, *args)
def LoadCs(self):
"""
LoadCs(TSIn self)
Parameters:
self: TSIn *
"""
return _snap.TSIn_LoadCs(self)
def LoadBf(self, *args):
"""
LoadBf(TSIn self, void const * Bf, TSize const & BfL)
Parameters:
Bf: void const *
BfL: TSize const &
"""
return _snap.TSIn_LoadBf(self, *args)
def LoadNewBf(self, *args):
"""
LoadNewBf(TSIn self, int const & BfL) -> void *
Parameters:
BfL: int const &
"""
return _snap.TSIn_LoadNewBf(self, *args)
def Load(self, *args):
"""
Load(TSIn self, bool & Bool)
Parameters:
Bool: bool &
Load(TSIn self, uchar & UCh)
Parameters:
UCh: uchar &
Load(TSIn self, char & Ch)
Parameters:
Ch: char &
Load(TSIn self, short & Short)
Parameters:
Short: short &
Load(TSIn self, ushort & UShort)
Parameters:
UShort: ushort &
Load(TSIn self, int & Int)
Parameters:
Int: int &
Load(TSIn self, uint & UInt)
Parameters:
UInt: uint &
Load(TSIn self, int64 & Int)
Parameters:
Int: int64 &
Load(TSIn self, uint64 & UInt)
Parameters:
UInt: uint64 &
Load(TSIn self, double & Flt)
Parameters:
Flt: double &
Load(TSIn self, sdouble & SFlt)
Parameters:
SFlt: sdouble &
Load(TSIn self, ldouble & LFlt)
Parameters:
LFlt: ldouble &
Load(TSIn self, char *& CStr, int const & MxCStrLen, int const & CStrLen)
Parameters:
CStr: char *&
MxCStrLen: int const &
CStrLen: int const &
Load(TSIn self, char *& CStr)
Parameters:
CStr: char *&
"""
return _snap.TSIn_Load(self, *args)
def __rshift__(self, *args):
"""
__rshift__(TSIn self, bool & Bool) -> TSIn
Parameters:
Bool: bool &
__rshift__(TSIn self, uchar & UCh) -> TSIn
Parameters:
UCh: uchar &
__rshift__(TSIn self, char & Ch) -> TSIn
Parameters:
Ch: char &
__rshift__(TSIn self, short & Sh) -> TSIn
Parameters:
Sh: short &
__rshift__(TSIn self, ushort & USh) -> TSIn
Parameters:
USh: ushort &
__rshift__(TSIn self, int & Int) -> TSIn
Parameters:
Int: int &
__rshift__(TSIn self, uint & UInt) -> TSIn
Parameters:
UInt: uint &
__rshift__(TSIn self, int64 & Int) -> TSIn
Parameters:
Int: int64 &
__rshift__(TSIn self, uint64 & UInt) -> TSIn
Parameters:
UInt: uint64 &
__rshift__(TSIn self, float & Flt) -> TSIn
Parameters:
Flt: float &
__rshift__(TSIn self, double & Double) -> TSIn
Parameters:
Double: double &
__rshift__(TSIn self, long double & LDouble) -> TSIn
Parameters:
LDouble: long double &
"""
return _snap.TSIn___rshift__(self, *args)
def GetNextLn(self, *args):
"""
GetNextLn(TSIn self, TStr LnStr) -> bool
Parameters:
LnStr: TStr &
GetNextLn(TSIn self, TChA LnChA) -> bool
Parameters:
LnChA: TChA &
"""
return _snap.TSIn_GetNextLn(self, *args)
TSIn.Eof = new_instancemethod(_snap.TSIn_Eof,None,TSIn)
TSIn.Len = new_instancemethod(_snap.TSIn_Len,None,TSIn)
TSIn.GetCh = new_instancemethod(_snap.TSIn_GetCh,None,TSIn)
TSIn.PeekCh = new_instancemethod(_snap.TSIn_PeekCh,None,TSIn)
TSIn.GetBf = new_instancemethod(_snap.TSIn_GetBf,None,TSIn)
TSIn.GetNextLnBf = new_instancemethod(_snap.TSIn_GetNextLnBf,None,TSIn)
TSIn.Reset = new_instancemethod(_snap.TSIn_Reset,None,TSIn)
TSIn.IsFastMode = new_instancemethod(_snap.TSIn_IsFastMode,None,TSIn)
TSIn.SetFastMode = new_instancemethod(_snap.TSIn_SetFastMode,None,TSIn)
TSIn.LoadCs = new_instancemethod(_snap.TSIn_LoadCs,None,TSIn)
TSIn.LoadBf = new_instancemethod(_snap.TSIn_LoadBf,None,TSIn)
TSIn.LoadNewBf = new_instancemethod(_snap.TSIn_LoadNewBf,None,TSIn)
TSIn.Load = new_instancemethod(_snap.TSIn_Load,None,TSIn)
TSIn.__rshift__ = new_instancemethod(_snap.TSIn___rshift__,None,TSIn)
TSIn.GetNextLn = new_instancemethod(_snap.TSIn_GetNextLn,None,TSIn)
TSIn_swigregister = _snap.TSIn_swigregister
TSIn_swigregister(TSIn)
TSIn.StdIn = _snap.cvar.TSIn_StdIn
class TSOut(TSBase):
"""Proxy of C++ TSOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TSOut
def EnableLnTrunc(self, *args):
"""
EnableLnTrunc(TSOut self, int const & _MxLnLen)
Parameters:
_MxLnLen: int const &
"""
return _snap.TSOut_EnableLnTrunc(self, *args)
def DisableLnTrunc(self):
"""
DisableLnTrunc(TSOut self)
Parameters:
self: TSOut *
"""
return _snap.TSOut_DisableLnTrunc(self)
def PutBf(self, *args):
"""
PutBf(TSOut self, void const * LBf, TSize const & LBfL) -> int
Parameters:
LBf: void const *
LBfL: TSize const &
"""
return _snap.TSOut_PutBf(self, *args)
def Flush(self):
"""
Flush(TSOut self)
Parameters:
self: TSOut *
"""
return _snap.TSOut_Flush(self)
def GetFileId(self):
"""
GetFileId(TSOut self) -> TFileId
Parameters:
self: TSOut const *
"""
return _snap.TSOut_GetFileId(self)
def PutMem(self, *args):
"""
PutMem(TSOut self, TMem Mem) -> int
Parameters:
Mem: TMem const &
"""
return _snap.TSOut_PutMem(self, *args)
def PutCh(self, *args):
"""
PutCh(TSOut self, char const & Ch) -> int
Parameters:
Ch: char const &
PutCh(TSOut self, char const & Ch, int const & Chs) -> int
Parameters:
Ch: char const &
Chs: int const &
"""
return _snap.TSOut_PutCh(self, *args)
def PutBool(self, *args):
"""
PutBool(TSOut self, bool const & Bool) -> int
Parameters:
Bool: bool const &
"""
return _snap.TSOut_PutBool(self, *args)
def PutInt(self, *args):
"""
PutInt(TSOut self, int const & Int) -> int
Parameters:
Int: int const &
PutInt(TSOut self, int const & Int, char const * FmtStr) -> int
Parameters:
Int: int const &
FmtStr: char const *
"""
return _snap.TSOut_PutInt(self, *args)
def PutUInt(self, *args):
"""
PutUInt(TSOut self, uint const & Int) -> int
Parameters:
Int: uint const &
PutUInt(TSOut self, uint const & Int, char const * FmtStr) -> int
Parameters:
Int: uint const &
FmtStr: char const *
"""
return _snap.TSOut_PutUInt(self, *args)
def PutFlt(self, *args):
"""
PutFlt(TSOut self, double const & Flt) -> int
Parameters:
Flt: double const &
PutFlt(TSOut self, double const & Flt, char const * FmtStr) -> int
Parameters:
Flt: double const &
FmtStr: char const *
"""
return _snap.TSOut_PutFlt(self, *args)
def PutStr(self, *args):
"""
PutStr(TSOut self, char const * CStr) -> int
Parameters:
CStr: char const *
PutStr(TSOut self, TChA ChA) -> int
Parameters:
ChA: TChA const &
PutStr(TSOut self, TStr Str, char const * FmtStr) -> int
Parameters:
Str: TStr const &
FmtStr: char const *
PutStr(TSOut self, TStr Str, bool const & ForceInLn=False) -> int
Parameters:
Str: TStr const &
ForceInLn: bool const &
PutStr(TSOut self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TSOut_PutStr(self, *args)
def PutStrLn(self, *args):
"""
PutStrLn(TSOut self, TStr Str, bool const & ForceInLn=False) -> int
Parameters:
Str: TStr const &
ForceInLn: bool const &
PutStrLn(TSOut self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TSOut_PutStrLn(self, *args)
def PutStrFmt(self, *args):
"""
PutStrFmt(TSOut self, char const * FmtStr) -> int
Parameters:
FmtStr: char const *
"""
return _snap.TSOut_PutStrFmt(self, *args)
def PutStrFmtLn(self, *args):
"""
PutStrFmtLn(TSOut self, char const * FmtStr) -> int
Parameters:
FmtStr: char const *
"""
return _snap.TSOut_PutStrFmtLn(self, *args)
def PutIndent(self, IndentLev=1):
"""
PutIndent(TSOut self, int const & IndentLev=1) -> int
Parameters:
IndentLev: int const &
PutIndent(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutIndent(self, IndentLev)
def PutLn(self, Lns=1):
"""
PutLn(TSOut self, int const & Lns=1) -> int
Parameters:
Lns: int const &
PutLn(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutLn(self, Lns)
def PutDosLn(self, Lns=1):
"""
PutDosLn(TSOut self, int const & Lns=1) -> int
Parameters:
Lns: int const &
PutDosLn(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutDosLn(self, Lns)
def PutSep(self, NextStrLen=0):
"""
PutSep(TSOut self, int const & NextStrLen=0) -> int
Parameters:
NextStrLen: int const &
PutSep(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutSep(self, NextStrLen)
def PutSepLn(self, Lns=0):
"""
PutSepLn(TSOut self, int const & Lns=0) -> int
Parameters:
Lns: int const &
PutSepLn(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutSepLn(self, Lns)
def SaveCs(self):
"""
SaveCs(TSOut self)
Parameters:
self: TSOut *
"""
return _snap.TSOut_SaveCs(self)
def SaveBf(self, *args):
"""
SaveBf(TSOut self, void const * Bf, TSize const & BfL)
Parameters:
Bf: void const *
BfL: TSize const &
"""
return _snap.TSOut_SaveBf(self, *args)
def Save(self, *args):
"""
Save(TSOut self, bool const & Bool)
Parameters:
Bool: bool const &
Save(TSOut self, char const & Ch)
Parameters:
Ch: char const &
Save(TSOut self, uchar const & UCh)
Parameters:
UCh: uchar const &
Save(TSOut self, short const & Short)
Parameters:
Short: short const &
Save(TSOut self, ushort const & UShort)
Parameters:
UShort: ushort const &
Save(TSOut self, int const & Int)
Parameters:
Int: int const &
Save(TSOut self, uint const & UInt)
Parameters:
UInt: uint const &
Save(TSOut self, int64 const & Int)
Parameters:
Int: int64 const &
Save(TSOut self, uint64 const & UInt)
Parameters:
UInt: uint64 const &
Save(TSOut self, double const & Flt)
Parameters:
Flt: double const &
Save(TSOut self, sdouble const & SFlt)
Parameters:
SFlt: sdouble const &
Save(TSOut self, ldouble const & LFlt)
Parameters:
LFlt: ldouble const &
Save(TSOut self, char const * CStr, TSize const & CStrLen)
Parameters:
CStr: char const *
CStrLen: TSize const &
Save(TSOut self, char const * CStr)
Parameters:
CStr: char const *
Save(TSOut self, TSIn SIn, TSize const & BfL=-1)
Parameters:
SIn: TSIn &
BfL: TSize const &
Save(TSOut self, TSIn SIn)
Parameters:
SIn: TSIn &
Save(TSOut self, PSIn const & SIn, TSize const & BfL=-1)
Parameters:
SIn: PSIn const &
BfL: TSize const &
Save(TSOut self, PSIn const & SIn)
Parameters:
SIn: PSIn const &
Save(TSOut self, void const * Bf, TSize const & BfL)
Parameters:
Bf: void const *
BfL: TSize const &
"""
return _snap.TSOut_Save(self, *args)
def __lshift__(self, *args):
"""
__lshift__(TSOut self, bool const & Bool) -> TSOut
Parameters:
Bool: bool const &
__lshift__(TSOut self, uchar const & UCh) -> TSOut
Parameters:
UCh: uchar const &
__lshift__(TSOut self, char const & Ch) -> TSOut
Parameters:
Ch: char const &
__lshift__(TSOut self, short const & Sh) -> TSOut
Parameters:
Sh: short const &
__lshift__(TSOut self, ushort const & USh) -> TSOut
Parameters:
USh: ushort const &
__lshift__(TSOut self, int const & Int) -> TSOut
Parameters:
Int: int const &
__lshift__(TSOut self, uint const & Int) -> TSOut
Parameters:
Int: uint const &
__lshift__(TSOut self, int64 const & Int) -> TSOut
Parameters:
Int: int64 const &
__lshift__(TSOut self, uint64 const & UInt) -> TSOut
Parameters:
UInt: uint64 const &
__lshift__(TSOut self, float const & Flt) -> TSOut
Parameters:
Flt: float const &
__lshift__(TSOut self, double const & Double) -> TSOut
Parameters:
Double: double const &
__lshift__(TSOut self, long double const & LDouble) -> TSOut
Parameters:
LDouble: long double const &
__lshift__(TSOut self, TSOutMnp Mnp) -> TSOut
Parameters:
Mnp: TSOutMnp const &
__lshift__(TSOut self, TSOut &(*)(TSOut &) FuncPt) -> TSOut
Parameters:
FuncPt: TSOut &(*)(TSOut &)
__lshift__(TSOut self, TSIn SIn) -> TSOut
Parameters:
SIn: TSIn &
__lshift__(TSOut self, PSIn & SIn) -> TSOut
Parameters:
SIn: PSIn &
"""
return _snap.TSOut___lshift__(self, *args)
TSOut.EnableLnTrunc = new_instancemethod(_snap.TSOut_EnableLnTrunc,None,TSOut)
TSOut.DisableLnTrunc = new_instancemethod(_snap.TSOut_DisableLnTrunc,None,TSOut)
TSOut.PutBf = new_instancemethod(_snap.TSOut_PutBf,None,TSOut)
TSOut.Flush = new_instancemethod(_snap.TSOut_Flush,None,TSOut)
TSOut.GetFileId = new_instancemethod(_snap.TSOut_GetFileId,None,TSOut)
TSOut.PutMem = new_instancemethod(_snap.TSOut_PutMem,None,TSOut)
TSOut.PutCh = new_instancemethod(_snap.TSOut_PutCh,None,TSOut)
TSOut.PutBool = new_instancemethod(_snap.TSOut_PutBool,None,TSOut)
TSOut.PutInt = new_instancemethod(_snap.TSOut_PutInt,None,TSOut)
TSOut.PutUInt = new_instancemethod(_snap.TSOut_PutUInt,None,TSOut)
TSOut.PutFlt = new_instancemethod(_snap.TSOut_PutFlt,None,TSOut)
TSOut.PutStr = new_instancemethod(_snap.TSOut_PutStr,None,TSOut)
TSOut.PutStrLn = new_instancemethod(_snap.TSOut_PutStrLn,None,TSOut)
TSOut.PutStrFmt = new_instancemethod(_snap.TSOut_PutStrFmt,None,TSOut)
TSOut.PutStrFmtLn = new_instancemethod(_snap.TSOut_PutStrFmtLn,None,TSOut)
TSOut.PutIndent = new_instancemethod(_snap.TSOut_PutIndent,None,TSOut)
TSOut.PutLn = new_instancemethod(_snap.TSOut_PutLn,None,TSOut)
TSOut.PutDosLn = new_instancemethod(_snap.TSOut_PutDosLn,None,TSOut)
TSOut.PutSep = new_instancemethod(_snap.TSOut_PutSep,None,TSOut)
TSOut.PutSepLn = new_instancemethod(_snap.TSOut_PutSepLn,None,TSOut)
TSOut.SaveCs = new_instancemethod(_snap.TSOut_SaveCs,None,TSOut)
TSOut.SaveBf = new_instancemethod(_snap.TSOut_SaveBf,None,TSOut)
TSOut.Save = new_instancemethod(_snap.TSOut_Save,None,TSOut)
TSOut.__lshift__ = new_instancemethod(_snap.TSOut___lshift__,None,TSOut)
TSOut_swigregister = _snap.TSOut_swigregister
TSOut_swigregister(TSOut)
TSOut.StdOut = _snap.cvar.TSOut_StdOut
class TSInOut(TSIn,TSOut):
"""Proxy of C++ TSInOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TSInOut
def SetPos(self, *args):
"""
SetPos(TSInOut self, int const & Pos)
Parameters:
Pos: int const &
"""
return _snap.TSInOut_SetPos(self, *args)
def MovePos(self, *args):
"""
MovePos(TSInOut self, int const & DPos)
Parameters:
DPos: int const &
"""
return _snap.TSInOut_MovePos(self, *args)
def GetPos(self):
"""
GetPos(TSInOut self) -> int
Parameters:
self: TSInOut const *
"""
return _snap.TSInOut_GetPos(self)
def GetSize(self):
"""
GetSize(TSInOut self) -> int
Parameters:
self: TSInOut const *
"""
return _snap.TSInOut_GetSize(self)
def Clr(self):
"""
Clr(TSInOut self)
Parameters:
self: TSInOut *
"""
return _snap.TSInOut_Clr(self)
TSInOut.SetPos = new_instancemethod(_snap.TSInOut_SetPos,None,TSInOut)
TSInOut.MovePos = new_instancemethod(_snap.TSInOut_MovePos,None,TSInOut)
TSInOut.GetPos = new_instancemethod(_snap.TSInOut_GetPos,None,TSInOut)
TSInOut.GetSize = new_instancemethod(_snap.TSInOut_GetSize,None,TSInOut)
TSInOut.Clr = new_instancemethod(_snap.TSInOut_Clr,None,TSInOut)
TSInOut_swigregister = _snap.TSInOut_swigregister
TSInOut_swigregister(TSInOut)
class TStdIn(TSIn):
"""Proxy of C++ TStdIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self):
"""__init__(TStdIn self) -> TStdIn"""
_snap.TStdIn_swiginit(self,_snap.new_TStdIn())
def New():
"""New() -> TPt< TSIn >"""
return _snap.TStdIn_New()
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TStdIn
TStdIn_swigregister = _snap.TStdIn_swigregister
TStdIn_swigregister(TStdIn)
def TStdIn_New():
"""TStdIn_New() -> TPt< TSIn >"""
return _snap.TStdIn_New()
class TStdOut(TSOut):
"""Proxy of C++ TStdOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self):
"""__init__(TStdOut self) -> TStdOut"""
_snap.TStdOut_swiginit(self,_snap.new_TStdOut())
def New():
"""New() -> TPt< TSOut >"""
return _snap.TStdOut_New()
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TStdOut
TStdOut_swigregister = _snap.TStdOut_swigregister
TStdOut_swigregister(TStdOut)
def TStdOut_New():
"""TStdOut_New() -> TPt< TSOut >"""
return _snap.TStdOut_New()
class TFIn(TSIn):
"""Proxy of C++ TFIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TFIn self, TStr FNm) -> TFIn
Parameters:
FNm: TStr const &
__init__(TFIn self, TStr FNm, bool & OpenedP) -> TFIn
Parameters:
FNm: TStr const &
OpenedP: bool &
"""
_snap.TFIn_swiginit(self,_snap.new_TFIn(*args))
def New(*args):
"""
New(TStr FNm) -> PSIn
Parameters:
FNm: TStr const &
New(TStr FNm, bool & OpenedP) -> PSIn
Parameters:
FNm: TStr const &
OpenedP: bool &
"""
return _snap.TFIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TFIn
TFIn_swigregister = _snap.TFIn_swigregister
TFIn_swigregister(TFIn)
def TFIn_New(*args):
"""
New(TStr FNm) -> PSIn
Parameters:
FNm: TStr const &
TFIn_New(TStr FNm, bool & OpenedP) -> PSIn
Parameters:
FNm: TStr const &
OpenedP: bool &
"""
return _snap.TFIn_New(*args)
class TFOut(TSOut):
"""Proxy of C++ TFOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TFOut self, TStr _FNm, bool const & Append=False) -> TFOut
Parameters:
_FNm: TStr const &
Append: bool const &
__init__(TFOut self, TStr _FNm) -> TFOut
Parameters:
_FNm: TStr const &
__init__(TFOut self, TStr _FNm, bool const & Append, bool & OpenedP) -> TFOut
Parameters:
_FNm: TStr const &
Append: bool const &
OpenedP: bool &
"""
_snap.TFOut_swiginit(self,_snap.new_TFOut(*args))
def New(*args):
"""
New(TStr FNm, bool const & Append=False) -> PSOut
Parameters:
FNm: TStr const &
Append: bool const &
New(TStr FNm) -> PSOut
Parameters:
FNm: TStr const &
New(TStr FNm, bool const & Append, bool & OpenedP) -> PSOut
Parameters:
FNm: TStr const &
Append: bool const &
OpenedP: bool &
"""
return _snap.TFOut_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TFOut
TFOut_swigregister = _snap.TFOut_swigregister
TFOut_swigregister(TFOut)
def TFOut_New(*args):
"""
New(TStr FNm, bool const & Append=False) -> PSOut
Parameters:
FNm: TStr const &
Append: bool const &
New(TStr FNm) -> PSOut
Parameters:
FNm: TStr const &
TFOut_New(TStr FNm, bool const & Append, bool & OpenedP) -> PSOut
Parameters:
FNm: TStr const &
Append: bool const &
OpenedP: bool &
"""
return _snap.TFOut_New(*args)
faUndef = _snap.faUndef
faCreate = _snap.faCreate
faUpdate = _snap.faUpdate
faAppend = _snap.faAppend
faRdOnly = _snap.faRdOnly
faRestore = _snap.faRestore
class TMIn(TSIn):
"""Proxy of C++ TMIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TMIn self, void const * _Bf, int const & _BfL, bool const & TakeBf=False) -> TMIn
Parameters:
_Bf: void const *
_BfL: int const &
TakeBf: bool const &
__init__(TMIn self, void const * _Bf, int const & _BfL) -> TMIn
Parameters:
_Bf: void const *
_BfL: int const &
__init__(TMIn self, TSIn SIn) -> TMIn
Parameters:
SIn: TSIn &
__init__(TMIn self, char const * CStr) -> TMIn
Parameters:
CStr: char const *
__init__(TMIn self, TStr Str) -> TMIn
Parameters:
Str: TStr const &
__init__(TMIn self, TChA ChA) -> TMIn
Parameters:
ChA: TChA const &
"""
_snap.TMIn_swiginit(self,_snap.new_TMIn(*args))
def New(*args):
"""
New(void const * _Bf, int const & _BfL, bool const & TakeBf=False) -> PSIn
Parameters:
_Bf: void const *
_BfL: int const &
TakeBf: bool const &
New(void const * _Bf, int const & _BfL) -> PSIn
Parameters:
_Bf: void const *
_BfL: int const &
New(char const * CStr) -> PSIn
Parameters:
CStr: char const *
New(TStr Str) -> PSIn
Parameters:
Str: TStr const &
New(TChA ChA) -> PSIn
Parameters:
ChA: TChA const &
"""
return _snap.TMIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TMIn
def GetBfAddr(self):
"""
GetBfAddr(TMIn self) -> char *
Parameters:
self: TMIn *
"""
return _snap.TMIn_GetBfAddr(self)
TMIn.GetBfAddr = new_instancemethod(_snap.TMIn_GetBfAddr,None,TMIn)
TMIn_swigregister = _snap.TMIn_swigregister
TMIn_swigregister(TMIn)
def TMIn_New(*args):
"""
New(void const * _Bf, int const & _BfL, bool const & TakeBf=False) -> PSIn
Parameters:
_Bf: void const *
_BfL: int const &
TakeBf: bool const &
New(void const * _Bf, int const & _BfL) -> PSIn
Parameters:
_Bf: void const *
_BfL: int const &
New(char const * CStr) -> PSIn
Parameters:
CStr: char const *
New(TStr Str) -> PSIn
Parameters:
Str: TStr const &
TMIn_New(TChA ChA) -> PSIn
Parameters:
ChA: TChA const &
"""
return _snap.TMIn_New(*args)
class TMOut(TSOut):
"""Proxy of C++ TMOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def New(MxBfL=1024):
"""
New(int const & MxBfL=1024) -> PSOut
Parameters:
MxBfL: int const &
New() -> PSOut
"""
return _snap.TMOut_New(MxBfL)
New = staticmethod(New)
def __init__(self, *args):
"""
__init__(TMOut self, int const & _MxBfL=1024) -> TMOut
Parameters:
_MxBfL: int const &
__init__(TMOut self) -> TMOut
__init__(TMOut self, char * _Bf, int const & _MxBfL) -> TMOut
Parameters:
_Bf: char *
_MxBfL: int const &
"""
_snap.TMOut_swiginit(self,_snap.new_TMOut(*args))
__swig_destroy__ = _snap.delete_TMOut
def AppendBf(self, *args):
"""
AppendBf(TMOut self, void const * LBf, TSize const & LBfL)
Parameters:
LBf: void const *
LBfL: TSize const &
"""
return _snap.TMOut_AppendBf(self, *args)
def Len(self):
"""
Len(TMOut self) -> int
Parameters:
self: TMOut const *
"""
return _snap.TMOut_Len(self)
def Clr(self):
"""
Clr(TMOut self)
Parameters:
self: TMOut *
"""
return _snap.TMOut_Clr(self)
def GetCh(self, *args):
"""
GetCh(TMOut self, int const & ChN) -> char
Parameters:
ChN: int const &
"""
return _snap.TMOut_GetCh(self, *args)
def GetAsStr(self):
"""
GetAsStr(TMOut self) -> TStr
Parameters:
self: TMOut const *
"""
return _snap.TMOut_GetAsStr(self)
def CutBf(self, *args):
"""
CutBf(TMOut self, int const & CutBfL)
Parameters:
CutBfL: int const &
"""
return _snap.TMOut_CutBf(self, *args)
def GetSIn(self, *args):
"""
GetSIn(TMOut self, bool const & IsCut=True, int const & CutBfL=-1) -> PSIn
Parameters:
IsCut: bool const &
CutBfL: int const &
GetSIn(TMOut self, bool const & IsCut=True) -> PSIn
Parameters:
IsCut: bool const &
GetSIn(TMOut self) -> PSIn
Parameters:
self: TMOut *
"""
return _snap.TMOut_GetSIn(self, *args)
def GetBfAddr(self):
"""
GetBfAddr(TMOut self) -> char *
Parameters:
self: TMOut const *
"""
return _snap.TMOut_GetBfAddr(self)
def IsCrLfLn(self):
"""
IsCrLfLn(TMOut self) -> bool
Parameters:
self: TMOut const *
"""
return _snap.TMOut_IsCrLfLn(self)
def GetCrLfLn(self):
"""
GetCrLfLn(TMOut self) -> TStr
Parameters:
self: TMOut *
"""
return _snap.TMOut_GetCrLfLn(self)
def IsEolnLn(self):
"""
IsEolnLn(TMOut self) -> bool
Parameters:
self: TMOut const *
"""
return _snap.TMOut_IsEolnLn(self)
def GetEolnLn(self, *args):
"""
GetEolnLn(TMOut self, bool const & DoAddEoln, bool const & DoCutBf) -> TStr
Parameters:
DoAddEoln: bool const &
DoCutBf: bool const &
"""
return _snap.TMOut_GetEolnLn(self, *args)
def MkEolnLn(self):
"""
MkEolnLn(TMOut self)
Parameters:
self: TMOut *
"""
return _snap.TMOut_MkEolnLn(self)
TMOut.AppendBf = new_instancemethod(_snap.TMOut_AppendBf,None,TMOut)
TMOut.Len = new_instancemethod(_snap.TMOut_Len,None,TMOut)
TMOut.Clr = new_instancemethod(_snap.TMOut_Clr,None,TMOut)
TMOut.GetCh = new_instancemethod(_snap.TMOut_GetCh,None,TMOut)
TMOut.GetAsStr = new_instancemethod(_snap.TMOut_GetAsStr,None,TMOut)
TMOut.CutBf = new_instancemethod(_snap.TMOut_CutBf,None,TMOut)
TMOut.GetSIn = new_instancemethod(_snap.TMOut_GetSIn,None,TMOut)
TMOut.GetBfAddr = new_instancemethod(_snap.TMOut_GetBfAddr,None,TMOut)
TMOut.IsCrLfLn = new_instancemethod(_snap.TMOut_IsCrLfLn,None,TMOut)
TMOut.GetCrLfLn = new_instancemethod(_snap.TMOut_GetCrLfLn,None,TMOut)
TMOut.IsEolnLn = new_instancemethod(_snap.TMOut_IsEolnLn,None,TMOut)
TMOut.GetEolnLn = new_instancemethod(_snap.TMOut_GetEolnLn,None,TMOut)
TMOut.MkEolnLn = new_instancemethod(_snap.TMOut_MkEolnLn,None,TMOut)
TMOut_swigregister = _snap.TMOut_swigregister
TMOut_swigregister(TMOut)
def TMOut_New(MxBfL=1024):
"""
New(int const & MxBfL=1024) -> PSOut
Parameters:
MxBfL: int const &
TMOut_New() -> PSOut
"""
return _snap.TMOut_New(MxBfL)
class TChRet(object):
"""Proxy of C++ TChRet class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TChRet self, PSIn const & _SIn, char const & _EofCh=0) -> TChRet
Parameters:
_SIn: PSIn const &
_EofCh: char const &
__init__(TChRet self, PSIn const & _SIn) -> TChRet
Parameters:
_SIn: PSIn const &
"""
_snap.TChRet_swiginit(self,_snap.new_TChRet(*args))
def Eof(self):
"""
Eof(TChRet self) -> bool
Parameters:
self: TChRet const *
"""
return _snap.TChRet_Eof(self)
def GetCh(self):
"""
GetCh(TChRet self) -> char
Parameters:
self: TChRet *
"""
return _snap.TChRet_GetCh(self)
def __call__(self):
"""
__call__(TChRet self) -> char
Parameters:
self: TChRet *
"""
return _snap.TChRet___call__(self)
__swig_destroy__ = _snap.delete_TChRet
TChRet.Eof = new_instancemethod(_snap.TChRet_Eof,None,TChRet)
TChRet.GetCh = new_instancemethod(_snap.TChRet_GetCh,None,TChRet)
TChRet.__call__ = new_instancemethod(_snap.TChRet___call__,None,TChRet)
TChRet_swigregister = _snap.TChRet_swigregister
TChRet_swigregister(TChRet)
class TLnRet(object):
"""Proxy of C++ TLnRet class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TLnRet self, PSIn const & _SIn) -> TLnRet
Parameters:
_SIn: PSIn const &
"""
_snap.TLnRet_swiginit(self,_snap.new_TLnRet(*args))
def NextLn(self, *args):
"""
NextLn(TLnRet self, TStr LnStr) -> bool
Parameters:
LnStr: TStr &
"""
return _snap.TLnRet_NextLn(self, *args)
__swig_destroy__ = _snap.delete_TLnRet
TLnRet.NextLn = new_instancemethod(_snap.TLnRet_NextLn,None,TLnRet)
TLnRet_swigregister = _snap.TLnRet_swigregister
TLnRet_swigregister(TLnRet)
class TFile(object):
"""Proxy of C++ TFile class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def Exists(*args):
"""
Exists(TStr FNm) -> bool
Parameters:
FNm: TStr const &
"""
return _snap.TFile_Exists(*args)
Exists = staticmethod(Exists)
def Del(*args):
"""
Del(TStr FNm, bool const & ThrowExceptP=True)
Parameters:
FNm: TStr const &
ThrowExceptP: bool const &
Del(TStr FNm)
Parameters:
FNm: TStr const &
"""
return _snap.TFile_Del(*args)
Del = staticmethod(Del)
def DelWc(*args):
"""
DelWc(TStr WcStr, bool const & RecurseDirP=False)
Parameters:
WcStr: TStr const &
RecurseDirP: bool const &
DelWc(TStr WcStr)
Parameters:
WcStr: TStr const &
"""
return _snap.TFile_DelWc(*args)
DelWc = staticmethod(DelWc)
def Rename(*args):
"""
Rename(TStr SrcFNm, TStr DstFNm)
Parameters:
SrcFNm: TStr const &
DstFNm: TStr const &
"""
return _snap.TFile_Rename(*args)
Rename = staticmethod(Rename)
def GetUniqueFNm(*args):
"""
GetUniqueFNm(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TFile_GetUniqueFNm(*args)
GetUniqueFNm = staticmethod(GetUniqueFNm)
def __init__(self):
"""__init__(TFile self) -> TFile"""
_snap.TFile_swiginit(self,_snap.new_TFile())
__swig_destroy__ = _snap.delete_TFile
TFile_swigregister = _snap.TFile_swigregister
TFile_swigregister(TFile)
TFile.TxtFExt = _snap.cvar.TFile_TxtFExt
TFile.HtmlFExt = _snap.cvar.TFile_HtmlFExt
TFile.HtmFExt = _snap.cvar.TFile_HtmFExt
TFile.GifFExt = _snap.cvar.TFile_GifFExt
TFile.JarFExt = _snap.cvar.TFile_JarFExt
def TFile_Exists(*args):
"""
TFile_Exists(TStr FNm) -> bool
Parameters:
FNm: TStr const &
"""
return _snap.TFile_Exists(*args)
def TFile_Del(*args):
"""
Del(TStr FNm, bool const & ThrowExceptP=True)
Parameters:
FNm: TStr const &
ThrowExceptP: bool const &
TFile_Del(TStr FNm)
Parameters:
FNm: TStr const &
"""
return _snap.TFile_Del(*args)
def TFile_DelWc(*args):
"""
DelWc(TStr WcStr, bool const & RecurseDirP=False)
Parameters:
WcStr: TStr const &
RecurseDirP: bool const &
TFile_DelWc(TStr WcStr)
Parameters:
WcStr: TStr const &
"""
return _snap.TFile_DelWc(*args)
def TFile_Rename(*args):
"""
TFile_Rename(TStr SrcFNm, TStr DstFNm)
Parameters:
SrcFNm: TStr const &
DstFNm: TStr const &
"""
return _snap.TFile_Rename(*args)
def TFile_GetUniqueFNm(*args):
"""
TFile_GetUniqueFNm(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TFile_GetUniqueFNm(*args)
class TUNGraph(object):
"""Proxy of C++ TUNGraph class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TUNGraph self) -> TUNGraph
__init__(TUNGraph self, int const & Nodes, int const & Edges) -> TUNGraph
Parameters:
Nodes: int const &
Edges: int const &
__init__(TUNGraph self, TUNGraph Graph) -> TUNGraph
Parameters:
Graph: TUNGraph const &
__init__(TUNGraph self, TSIn SIn) -> TUNGraph
Parameters:
SIn: TSIn &
"""
_snap.TUNGraph_swiginit(self,_snap.new_TUNGraph(*args))
def Save(self, *args):
"""
Save(TUNGraph self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TUNGraph_Save(self, *args)
def New(*args):
"""
New() -> PUNGraph
New(int const & Nodes, int const & Edges) -> PUNGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TUNGraph_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PUNGraph
Parameters:
SIn: TSIn &
"""
return _snap.TUNGraph_Load(*args)
Load = staticmethod(Load)
def HasFlag(self, *args):
"""
HasFlag(TUNGraph self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.TUNGraph_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(TUNGraph self) -> int
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(TUNGraph self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TUNGraph self) -> int
AddNode(TUNGraph self, TUNGraph::TNodeI const & NodeI) -> int
Parameters:
NodeI: TUNGraph::TNodeI const &
AddNode(TUNGraph self, int const & NId, TIntV NbrNIdV) -> int
Parameters:
NId: int const &
NbrNIdV: TIntV const &
AddNode(TUNGraph self, int const & NId, TVecPool< TInt > const & Pool, int const & NIdVId) -> int
Parameters:
NId: int const &
Pool: TVecPool< TInt > const &
NIdVId: int const &
"""
return _snap.TUNGraph_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TUNGraph self, int const & NId)
Parameters:
NId: int const &
DelNode(TUNGraph self, TUNGraph::TNode const & NodeI)
Parameters:
NodeI: TUNGraph::TNode const &
"""
return _snap.TUNGraph_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TUNGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraph_IsNode(self, *args)
def BegNI(self):
"""
BegNI(TUNGraph self) -> TUNGraph::TNodeI
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_BegNI(self)
def EndNI(self):
"""
EndNI(TUNGraph self) -> TUNGraph::TNodeI
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_EndNI(self)
def GetNI(self, *args):
"""
GetNI(TUNGraph self, int const & NId) -> TUNGraph::TNodeI
Parameters:
NId: int const &
"""
return _snap.TUNGraph_GetNI(self, *args)
def GetMxNId(self):
"""
GetMxNId(TUNGraph self) -> int
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(TUNGraph self) -> int
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TUNGraph self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(TUNGraph self, TUNGraph::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TUNGraph::TEdgeI const &
"""
return _snap.TUNGraph_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TUNGraph self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TUNGraph_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TUNGraph self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TUNGraph_IsEdge(self, *args)
def BegEI(self):
"""
BegEI(TUNGraph self) -> TUNGraph::TEdgeI
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_BegEI(self)
def EndEI(self):
"""
EndEI(TUNGraph self) -> TUNGraph::TEdgeI
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TUNGraph self, int const & SrcNId, int const & DstNId) -> TUNGraph::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TUNGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TUNGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TUNGraph self) -> int
Parameters:
self: TUNGraph *
"""
return _snap.TUNGraph_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TUNGraph self, TRnd Rnd=Rnd) -> TUNGraph::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TUNGraph self) -> TUNGraph::TNodeI
Parameters:
self: TUNGraph *
"""
return _snap.TUNGraph_GetRndNI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TUNGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TUNGraph_GetNIdV(self, *args)
def Empty(self):
"""
Empty(TUNGraph self) -> bool
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_Empty(self)
def Clr(self):
"""
Clr(TUNGraph self)
Parameters:
self: TUNGraph *
"""
return _snap.TUNGraph_Clr(self)
def Reserve(self, *args):
"""
Reserve(TUNGraph self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TUNGraph_Reserve(self, *args)
def ReserveNIdDeg(self, *args):
"""
ReserveNIdDeg(TUNGraph self, int const & NId, int const & Deg)
Parameters:
NId: int const &
Deg: int const &
"""
return _snap.TUNGraph_ReserveNIdDeg(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TUNGraph self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TUNGraph self)
Parameters:
self: TUNGraph *
"""
return _snap.TUNGraph_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TUNGraph self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TUNGraph self) -> bool
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TUNGraph self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TUNGraph self)
Parameters:
self: TUNGraph const *
"""
return _snap.TUNGraph_Dump(self, *args)
def GetSmallGraph():
"""GetSmallGraph() -> PUNGraph"""
return _snap.TUNGraph_GetSmallGraph()
GetSmallGraph = staticmethod(GetSmallGraph)
__swig_destroy__ = _snap.delete_TUNGraph
TUNGraph.Save = new_instancemethod(_snap.TUNGraph_Save,None,TUNGraph)
TUNGraph.HasFlag = new_instancemethod(_snap.TUNGraph_HasFlag,None,TUNGraph)
TUNGraph.GetNodes = new_instancemethod(_snap.TUNGraph_GetNodes,None,TUNGraph)
TUNGraph.AddNode = new_instancemethod(_snap.TUNGraph_AddNode,None,TUNGraph)
TUNGraph.DelNode = new_instancemethod(_snap.TUNGraph_DelNode,None,TUNGraph)
TUNGraph.IsNode = new_instancemethod(_snap.TUNGraph_IsNode,None,TUNGraph)
TUNGraph.BegNI = new_instancemethod(_snap.TUNGraph_BegNI,None,TUNGraph)
TUNGraph.EndNI = new_instancemethod(_snap.TUNGraph_EndNI,None,TUNGraph)
TUNGraph.GetNI = new_instancemethod(_snap.TUNGraph_GetNI,None,TUNGraph)
TUNGraph.GetMxNId = new_instancemethod(_snap.TUNGraph_GetMxNId,None,TUNGraph)
TUNGraph.GetEdges = new_instancemethod(_snap.TUNGraph_GetEdges,None,TUNGraph)
TUNGraph.AddEdge = new_instancemethod(_snap.TUNGraph_AddEdge,None,TUNGraph)
TUNGraph.DelEdge = new_instancemethod(_snap.TUNGraph_DelEdge,None,TUNGraph)
TUNGraph.IsEdge = new_instancemethod(_snap.TUNGraph_IsEdge,None,TUNGraph)
TUNGraph.BegEI = new_instancemethod(_snap.TUNGraph_BegEI,None,TUNGraph)
TUNGraph.EndEI = new_instancemethod(_snap.TUNGraph_EndEI,None,TUNGraph)
TUNGraph.GetEI = new_instancemethod(_snap.TUNGraph_GetEI,None,TUNGraph)
TUNGraph.GetRndNId = new_instancemethod(_snap.TUNGraph_GetRndNId,None,TUNGraph)
TUNGraph.GetRndNI = new_instancemethod(_snap.TUNGraph_GetRndNI,None,TUNGraph)
TUNGraph.GetNIdV = new_instancemethod(_snap.TUNGraph_GetNIdV,None,TUNGraph)
TUNGraph.Empty = new_instancemethod(_snap.TUNGraph_Empty,None,TUNGraph)
TUNGraph.Clr = new_instancemethod(_snap.TUNGraph_Clr,None,TUNGraph)
TUNGraph.Reserve = new_instancemethod(_snap.TUNGraph_Reserve,None,TUNGraph)
TUNGraph.ReserveNIdDeg = new_instancemethod(_snap.TUNGraph_ReserveNIdDeg,None,TUNGraph)
TUNGraph.Defrag = new_instancemethod(_snap.TUNGraph_Defrag,None,TUNGraph)
TUNGraph.IsOk = new_instancemethod(_snap.TUNGraph_IsOk,None,TUNGraph)
TUNGraph.Dump = new_instancemethod(_snap.TUNGraph_Dump,None,TUNGraph)
TUNGraph_swigregister = _snap.TUNGraph_swigregister
TUNGraph_swigregister(TUNGraph)
def TUNGraph_New(*args):
"""
New() -> PUNGraph
TUNGraph_New(int const & Nodes, int const & Edges) -> PUNGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TUNGraph_New(*args)
def TUNGraph_Load(*args):
"""
TUNGraph_Load(TSIn SIn) -> PUNGraph
Parameters:
SIn: TSIn &
"""
return _snap.TUNGraph_Load(*args)
def TUNGraph_GetSmallGraph():
"""TUNGraph_GetSmallGraph() -> PUNGraph"""
return _snap.TUNGraph_GetSmallGraph()
class TNGraph(object):
"""Proxy of C++ TNGraph class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNGraph self) -> TNGraph
__init__(TNGraph self, int const & Nodes, int const & Edges) -> TNGraph
Parameters:
Nodes: int const &
Edges: int const &
__init__(TNGraph self, TNGraph Graph) -> TNGraph
Parameters:
Graph: TNGraph const &
__init__(TNGraph self, TSIn SIn) -> TNGraph
Parameters:
SIn: TSIn &
"""
_snap.TNGraph_swiginit(self,_snap.new_TNGraph(*args))
def Save(self, *args):
"""
Save(TNGraph self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TNGraph_Save(self, *args)
def New(*args):
"""
New() -> PNGraph
New(int const & Nodes, int const & Edges) -> PNGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNGraph_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PNGraph
Parameters:
SIn: TSIn &
"""
return _snap.TNGraph_Load(*args)
Load = staticmethod(Load)
def HasFlag(self, *args):
"""
HasFlag(TNGraph self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.TNGraph_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(TNGraph self) -> int
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(TNGraph self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TNGraph self) -> int
AddNode(TNGraph self, TNGraph::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNGraph::TNodeI const &
AddNode(TNGraph self, int const & NId, TIntV InNIdV, TIntV OutNIdV) -> int
Parameters:
NId: int const &
InNIdV: TIntV const &
OutNIdV: TIntV const &
AddNode(TNGraph self, int const & NId, TVecPool< TInt > const & Pool, int const & SrcVId, int const & DstVId) -> int
Parameters:
NId: int const &
Pool: TVecPool< TInt > const &
SrcVId: int const &
DstVId: int const &
"""
return _snap.TNGraph_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TNGraph self, int const & NId)
Parameters:
NId: int const &
DelNode(TNGraph self, TNGraph::TNode const & NodeI)
Parameters:
NodeI: TNGraph::TNode const &
"""
return _snap.TNGraph_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TNGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNGraph_IsNode(self, *args)
def BegNI(self):
"""
BegNI(TNGraph self) -> TNGraph::TNodeI
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_BegNI(self)
def EndNI(self):
"""
EndNI(TNGraph self) -> TNGraph::TNodeI
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_EndNI(self)
def GetNI(self, *args):
"""
GetNI(TNGraph self, int const & NId) -> TNGraph::TNodeI
Parameters:
NId: int const &
"""
return _snap.TNGraph_GetNI(self, *args)
def GetMxNId(self):
"""
GetMxNId(TNGraph self) -> int
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(TNGraph self) -> int
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TNGraph self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(TNGraph self, TNGraph::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TNGraph::TEdgeI const &
"""
return _snap.TNGraph_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TNGraph self, int const & SrcNId, int const & DstNId, bool const & IsDir=True)
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
DelEdge(TNGraph self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNGraph_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TNGraph self, int const & SrcNId, int const & DstNId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
IsEdge(TNGraph self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNGraph_IsEdge(self, *args)
def BegEI(self):
"""
BegEI(TNGraph self) -> TNGraph::TEdgeI
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_BegEI(self)
def EndEI(self):
"""
EndEI(TNGraph self) -> TNGraph::TEdgeI
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TNGraph self, int const & SrcNId, int const & DstNId) -> TNGraph::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TNGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TNGraph self) -> int
Parameters:
self: TNGraph *
"""
return _snap.TNGraph_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TNGraph self, TRnd Rnd=Rnd) -> TNGraph::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TNGraph self) -> TNGraph::TNodeI
Parameters:
self: TNGraph *
"""
return _snap.TNGraph_GetRndNI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TNGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TNGraph_GetNIdV(self, *args)
def Empty(self):
"""
Empty(TNGraph self) -> bool
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_Empty(self)
def Clr(self):
"""
Clr(TNGraph self)
Parameters:
self: TNGraph *
"""
return _snap.TNGraph_Clr(self)
def Reserve(self, *args):
"""
Reserve(TNGraph self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNGraph_Reserve(self, *args)
def ReserveNIdInDeg(self, *args):
"""
ReserveNIdInDeg(TNGraph self, int const & NId, int const & InDeg)
Parameters:
NId: int const &
InDeg: int const &
"""
return _snap.TNGraph_ReserveNIdInDeg(self, *args)
def ReserveNIdOutDeg(self, *args):
"""
ReserveNIdOutDeg(TNGraph self, int const & NId, int const & OutDeg)
Parameters:
NId: int const &
OutDeg: int const &
"""
return _snap.TNGraph_ReserveNIdOutDeg(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TNGraph self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TNGraph self)
Parameters:
self: TNGraph *
"""
return _snap.TNGraph_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TNGraph self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TNGraph self) -> bool
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TNGraph self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TNGraph self)
Parameters:
self: TNGraph const *
"""
return _snap.TNGraph_Dump(self, *args)
def GetSmallGraph():
"""GetSmallGraph() -> PNGraph"""
return _snap.TNGraph_GetSmallGraph()
GetSmallGraph = staticmethod(GetSmallGraph)
__swig_destroy__ = _snap.delete_TNGraph
TNGraph.Save = new_instancemethod(_snap.TNGraph_Save,None,TNGraph)
TNGraph.HasFlag = new_instancemethod(_snap.TNGraph_HasFlag,None,TNGraph)
TNGraph.GetNodes = new_instancemethod(_snap.TNGraph_GetNodes,None,TNGraph)
TNGraph.AddNode = new_instancemethod(_snap.TNGraph_AddNode,None,TNGraph)
TNGraph.DelNode = new_instancemethod(_snap.TNGraph_DelNode,None,TNGraph)
TNGraph.IsNode = new_instancemethod(_snap.TNGraph_IsNode,None,TNGraph)
TNGraph.BegNI = new_instancemethod(_snap.TNGraph_BegNI,None,TNGraph)
TNGraph.EndNI = new_instancemethod(_snap.TNGraph_EndNI,None,TNGraph)
TNGraph.GetNI = new_instancemethod(_snap.TNGraph_GetNI,None,TNGraph)
TNGraph.GetMxNId = new_instancemethod(_snap.TNGraph_GetMxNId,None,TNGraph)
TNGraph.GetEdges = new_instancemethod(_snap.TNGraph_GetEdges,None,TNGraph)
TNGraph.AddEdge = new_instancemethod(_snap.TNGraph_AddEdge,None,TNGraph)
TNGraph.DelEdge = new_instancemethod(_snap.TNGraph_DelEdge,None,TNGraph)
TNGraph.IsEdge = new_instancemethod(_snap.TNGraph_IsEdge,None,TNGraph)
TNGraph.BegEI = new_instancemethod(_snap.TNGraph_BegEI,None,TNGraph)
TNGraph.EndEI = new_instancemethod(_snap.TNGraph_EndEI,None,TNGraph)
TNGraph.GetEI = new_instancemethod(_snap.TNGraph_GetEI,None,TNGraph)
TNGraph.GetRndNId = new_instancemethod(_snap.TNGraph_GetRndNId,None,TNGraph)
TNGraph.GetRndNI = new_instancemethod(_snap.TNGraph_GetRndNI,None,TNGraph)
TNGraph.GetNIdV = new_instancemethod(_snap.TNGraph_GetNIdV,None,TNGraph)
TNGraph.Empty = new_instancemethod(_snap.TNGraph_Empty,None,TNGraph)
TNGraph.Clr = new_instancemethod(_snap.TNGraph_Clr,None,TNGraph)
TNGraph.Reserve = new_instancemethod(_snap.TNGraph_Reserve,None,TNGraph)
TNGraph.ReserveNIdInDeg = new_instancemethod(_snap.TNGraph_ReserveNIdInDeg,None,TNGraph)
TNGraph.ReserveNIdOutDeg = new_instancemethod(_snap.TNGraph_ReserveNIdOutDeg,None,TNGraph)
TNGraph.Defrag = new_instancemethod(_snap.TNGraph_Defrag,None,TNGraph)
TNGraph.IsOk = new_instancemethod(_snap.TNGraph_IsOk,None,TNGraph)
TNGraph.Dump = new_instancemethod(_snap.TNGraph_Dump,None,TNGraph)
TNGraph_swigregister = _snap.TNGraph_swigregister
TNGraph_swigregister(TNGraph)
def TNGraph_New(*args):
"""
New() -> PNGraph
TNGraph_New(int const & Nodes, int const & Edges) -> PNGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNGraph_New(*args)
def TNGraph_Load(*args):
"""
TNGraph_Load(TSIn SIn) -> PNGraph
Parameters:
SIn: TSIn &
"""
return _snap.TNGraph_Load(*args)
def TNGraph_GetSmallGraph():
"""TNGraph_GetSmallGraph() -> PNGraph"""
return _snap.TNGraph_GetSmallGraph()
class TNEGraph(object):
"""Proxy of C++ TNEGraph class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEGraph self) -> TNEGraph
__init__(TNEGraph self, int const & Nodes, int const & Edges) -> TNEGraph
Parameters:
Nodes: int const &
Edges: int const &
__init__(TNEGraph self, TNEGraph Graph) -> TNEGraph
Parameters:
Graph: TNEGraph const &
__init__(TNEGraph self, TSIn SIn) -> TNEGraph
Parameters:
SIn: TSIn &
"""
_snap.TNEGraph_swiginit(self,_snap.new_TNEGraph(*args))
def Save(self, *args):
"""
Save(TNEGraph self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TNEGraph_Save(self, *args)
def New(*args):
"""
New() -> PNEGraph
New(int const & Nodes, int const & Edges) -> PNEGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEGraph_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PNEGraph
Parameters:
SIn: TSIn &
"""
return _snap.TNEGraph_Load(*args)
Load = staticmethod(Load)
def HasFlag(self, *args):
"""
HasFlag(TNEGraph self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.TNEGraph_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(TNEGraph self) -> int
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(TNEGraph self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TNEGraph self) -> int
AddNode(TNEGraph self, TNEGraph::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNEGraph::TNodeI const &
"""
return _snap.TNEGraph_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TNEGraph self, int const & NId)
Parameters:
NId: int const &
DelNode(TNEGraph self, TNEGraph::TNode const & NodeI)
Parameters:
NodeI: TNEGraph::TNode const &
"""
return _snap.TNEGraph_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TNEGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEGraph_IsNode(self, *args)
def BegNI(self):
"""
BegNI(TNEGraph self) -> TNEGraph::TNodeI
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_BegNI(self)
def EndNI(self):
"""
EndNI(TNEGraph self) -> TNEGraph::TNodeI
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_EndNI(self)
def GetNI(self, *args):
"""
GetNI(TNEGraph self, int const & NId) -> TNEGraph::TNodeI
Parameters:
NId: int const &
"""
return _snap.TNEGraph_GetNI(self, *args)
def GetMxNId(self):
"""
GetMxNId(TNEGraph self) -> int
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(TNEGraph self) -> int
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TNEGraph self, int const & SrcNId, int const & DstNId, int EId=-1) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int
AddEdge(TNEGraph self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(TNEGraph self, TNEGraph::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TNEGraph::TEdgeI const &
"""
return _snap.TNEGraph_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TNEGraph self, int const & EId)
Parameters:
EId: int const &
DelEdge(TNEGraph self, int const & SrcNId, int const & DstNId, bool const & IsDir=True)
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
DelEdge(TNEGraph self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEGraph_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TNEGraph self, int const & EId) -> bool
Parameters:
EId: int const &
IsEdge(TNEGraph self, int const & SrcNId, int const & DstNId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
IsEdge(TNEGraph self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsEdge(TNEGraph self, int const & SrcNId, int const & DstNId, int & EId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
IsDir: bool const &
IsEdge(TNEGraph self, int const & SrcNId, int const & DstNId, int & EId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
"""
return _snap.TNEGraph_IsEdge(self, *args)
def GetEId(self, *args):
"""
GetEId(TNEGraph self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEGraph_GetEId(self, *args)
def BegEI(self):
"""
BegEI(TNEGraph self) -> TNEGraph::TEdgeI
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_BegEI(self)
def EndEI(self):
"""
EndEI(TNEGraph self) -> TNEGraph::TEdgeI
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TNEGraph self, int const & EId) -> TNEGraph::TEdgeI
Parameters:
EId: int const &
GetEI(TNEGraph self, int const & SrcNId, int const & DstNId) -> TNEGraph::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TNEGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TNEGraph self) -> int
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TNEGraph self, TRnd Rnd=Rnd) -> TNEGraph::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TNEGraph self) -> TNEGraph::TNodeI
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_GetRndNI(self, *args)
def GetRndEId(self, *args):
"""
GetRndEId(TNEGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndEId(TNEGraph self) -> int
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_GetRndEId(self, *args)
def GetRndEI(self, *args):
"""
GetRndEI(TNEGraph self, TRnd Rnd=Rnd) -> TNEGraph::TEdgeI
Parameters:
Rnd: TRnd &
GetRndEI(TNEGraph self) -> TNEGraph::TEdgeI
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_GetRndEI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TNEGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TNEGraph_GetNIdV(self, *args)
def GetEIdV(self, *args):
"""
GetEIdV(TNEGraph self, TIntV EIdV)
Parameters:
EIdV: TIntV &
"""
return _snap.TNEGraph_GetEIdV(self, *args)
def Empty(self):
"""
Empty(TNEGraph self) -> bool
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_Empty(self)
def Clr(self):
"""
Clr(TNEGraph self)
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_Clr(self)
def Reserve(self, *args):
"""
Reserve(TNEGraph self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEGraph_Reserve(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TNEGraph self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TNEGraph self)
Parameters:
self: TNEGraph *
"""
return _snap.TNEGraph_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TNEGraph self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TNEGraph self) -> bool
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TNEGraph self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TNEGraph self)
Parameters:
self: TNEGraph const *
"""
return _snap.TNEGraph_Dump(self, *args)
__swig_destroy__ = _snap.delete_TNEGraph
TNEGraph.Save = new_instancemethod(_snap.TNEGraph_Save,None,TNEGraph)
TNEGraph.HasFlag = new_instancemethod(_snap.TNEGraph_HasFlag,None,TNEGraph)
TNEGraph.GetNodes = new_instancemethod(_snap.TNEGraph_GetNodes,None,TNEGraph)
TNEGraph.AddNode = new_instancemethod(_snap.TNEGraph_AddNode,None,TNEGraph)
TNEGraph.DelNode = new_instancemethod(_snap.TNEGraph_DelNode,None,TNEGraph)
TNEGraph.IsNode = new_instancemethod(_snap.TNEGraph_IsNode,None,TNEGraph)
TNEGraph.BegNI = new_instancemethod(_snap.TNEGraph_BegNI,None,TNEGraph)
TNEGraph.EndNI = new_instancemethod(_snap.TNEGraph_EndNI,None,TNEGraph)
TNEGraph.GetNI = new_instancemethod(_snap.TNEGraph_GetNI,None,TNEGraph)
TNEGraph.GetMxNId = new_instancemethod(_snap.TNEGraph_GetMxNId,None,TNEGraph)
TNEGraph.GetEdges = new_instancemethod(_snap.TNEGraph_GetEdges,None,TNEGraph)
TNEGraph.AddEdge = new_instancemethod(_snap.TNEGraph_AddEdge,None,TNEGraph)
TNEGraph.DelEdge = new_instancemethod(_snap.TNEGraph_DelEdge,None,TNEGraph)
TNEGraph.IsEdge = new_instancemethod(_snap.TNEGraph_IsEdge,None,TNEGraph)
TNEGraph.GetEId = new_instancemethod(_snap.TNEGraph_GetEId,None,TNEGraph)
TNEGraph.BegEI = new_instancemethod(_snap.TNEGraph_BegEI,None,TNEGraph)
TNEGraph.EndEI = new_instancemethod(_snap.TNEGraph_EndEI,None,TNEGraph)
TNEGraph.GetEI = new_instancemethod(_snap.TNEGraph_GetEI,None,TNEGraph)
TNEGraph.GetRndNId = new_instancemethod(_snap.TNEGraph_GetRndNId,None,TNEGraph)
TNEGraph.GetRndNI = new_instancemethod(_snap.TNEGraph_GetRndNI,None,TNEGraph)
TNEGraph.GetRndEId = new_instancemethod(_snap.TNEGraph_GetRndEId,None,TNEGraph)
TNEGraph.GetRndEI = new_instancemethod(_snap.TNEGraph_GetRndEI,None,TNEGraph)
TNEGraph.GetNIdV = new_instancemethod(_snap.TNEGraph_GetNIdV,None,TNEGraph)
TNEGraph.GetEIdV = new_instancemethod(_snap.TNEGraph_GetEIdV,None,TNEGraph)
TNEGraph.Empty = new_instancemethod(_snap.TNEGraph_Empty,None,TNEGraph)
TNEGraph.Clr = new_instancemethod(_snap.TNEGraph_Clr,None,TNEGraph)
TNEGraph.Reserve = new_instancemethod(_snap.TNEGraph_Reserve,None,TNEGraph)
TNEGraph.Defrag = new_instancemethod(_snap.TNEGraph_Defrag,None,TNEGraph)
TNEGraph.IsOk = new_instancemethod(_snap.TNEGraph_IsOk,None,TNEGraph)
TNEGraph.Dump = new_instancemethod(_snap.TNEGraph_Dump,None,TNEGraph)
TNEGraph_swigregister = _snap.TNEGraph_swigregister
TNEGraph_swigregister(TNEGraph)
def TNEGraph_New(*args):
"""
New() -> PNEGraph
TNEGraph_New(int const & Nodes, int const & Edges) -> PNEGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEGraph_New(*args)
def TNEGraph_Load(*args):
"""
TNEGraph_Load(TSIn SIn) -> PNEGraph
Parameters:
SIn: TSIn &
"""
return _snap.TNEGraph_Load(*args)
class TBPGraph(object):
"""Proxy of C++ TBPGraph class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
bgsUndef = _snap.TBPGraph_bgsUndef
bgsLeft = _snap.TBPGraph_bgsLeft
bgsRight = _snap.TBPGraph_bgsRight
bgsBoth = _snap.TBPGraph_bgsBoth
def __init__(self, *args):
"""
__init__(TBPGraph self) -> TBPGraph
__init__(TBPGraph self, int const & Nodes, int const & Edges) -> TBPGraph
Parameters:
Nodes: int const &
Edges: int const &
__init__(TBPGraph self, TBPGraph BPGraph) -> TBPGraph
Parameters:
BPGraph: TBPGraph const &
__init__(TBPGraph self, TSIn SIn) -> TBPGraph
Parameters:
SIn: TSIn &
"""
_snap.TBPGraph_swiginit(self,_snap.new_TBPGraph(*args))
def Save(self, *args):
"""
Save(TBPGraph self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TBPGraph_Save(self, *args)
def New(*args):
"""
New() -> PBPGraph
New(int const & Nodes, int const & Edges) -> PBPGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TBPGraph_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PBPGraph
Parameters:
SIn: TSIn &
"""
return _snap.TBPGraph_Load(*args)
Load = staticmethod(Load)
def GetNodes(self):
"""
GetNodes(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetNodes(self)
def GetLNodes(self):
"""
GetLNodes(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetLNodes(self)
def GetRNodes(self):
"""
GetRNodes(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetRNodes(self)
def AddNode(self, *args):
"""
AddNode(TBPGraph self, int NId=-1, bool const & LeftNode=True) -> int
Parameters:
NId: int
LeftNode: bool const &
AddNode(TBPGraph self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TBPGraph self) -> int
AddNode(TBPGraph self, TBPGraph::TNodeI const & NodeI) -> int
Parameters:
NodeI: TBPGraph::TNodeI const &
"""
return _snap.TBPGraph_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TBPGraph self, int const & NId)
Parameters:
NId: int const &
DelNode(TBPGraph self, TBPGraph::TNode const & NodeI)
Parameters:
NodeI: TBPGraph::TNode const &
"""
return _snap.TBPGraph_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TBPGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TBPGraph_IsNode(self, *args)
def IsLNode(self, *args):
"""
IsLNode(TBPGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TBPGraph_IsLNode(self, *args)
def IsRNode(self, *args):
"""
IsRNode(TBPGraph self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TBPGraph_IsRNode(self, *args)
def GetMxNId(self):
"""
GetMxNId(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetMxNId(self)
def BegNI(self):
"""
BegNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_BegNI(self)
def EndNI(self):
"""
EndNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_EndNI(self)
def GetNI(self, *args):
"""
GetNI(TBPGraph self, int const & NId) -> TBPGraph::TNodeI
Parameters:
NId: int const &
"""
return _snap.TBPGraph_GetNI(self, *args)
def BegLNI(self):
"""
BegLNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_BegLNI(self)
def EndLNI(self):
"""
EndLNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_EndLNI(self)
def BegRNI(self):
"""
BegRNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_BegRNI(self)
def EndRNI(self):
"""
EndRNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_EndRNI(self)
def GetEdges(self):
"""
GetEdges(TBPGraph self) -> int
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TBPGraph self, int const & LeftNId, int const & RightNId) -> int
Parameters:
LeftNId: int const &
RightNId: int const &
AddEdge(TBPGraph self, TBPGraph::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TBPGraph::TEdgeI const &
"""
return _snap.TBPGraph_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TBPGraph self, int const & LeftNId, int const & RightNId)
Parameters:
LeftNId: int const &
RightNId: int const &
"""
return _snap.TBPGraph_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TBPGraph self, int const & LeftNId, int const & RightNId) -> bool
Parameters:
LeftNId: int const &
RightNId: int const &
"""
return _snap.TBPGraph_IsEdge(self, *args)
def BegEI(self):
"""
BegEI(TBPGraph self) -> TBPGraph::TEdgeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_BegEI(self)
def EndEI(self):
"""
EndEI(TBPGraph self) -> TBPGraph::TEdgeI
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_EndEI(self)
def GetEI(self, *args):
"""
GetEI(TBPGraph self, int const & LeftNId, int const & RightNId) -> TBPGraph::TEdgeI
Parameters:
LeftNId: int const &
RightNId: int const &
"""
return _snap.TBPGraph_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TBPGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TBPGraph self) -> int
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_GetRndNId(self, *args)
def GetRndLNId(self, *args):
"""
GetRndLNId(TBPGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndLNId(TBPGraph self) -> int
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_GetRndLNId(self, *args)
def GetRndRNId(self, *args):
"""
GetRndRNId(TBPGraph self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndRNId(TBPGraph self) -> int
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_GetRndRNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TBPGraph self, TRnd Rnd=Rnd) -> TBPGraph::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TBPGraph self) -> TBPGraph::TNodeI
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_GetRndNI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TBPGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TBPGraph_GetNIdV(self, *args)
def GetLNIdV(self, *args):
"""
GetLNIdV(TBPGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TBPGraph_GetLNIdV(self, *args)
def GetRNIdV(self, *args):
"""
GetRNIdV(TBPGraph self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TBPGraph_GetRNIdV(self, *args)
def Empty(self):
"""
Empty(TBPGraph self) -> bool
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_Empty(self)
def Clr(self):
"""
Clr(TBPGraph self)
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_Clr(self)
def Reserve(self, *args):
"""
Reserve(TBPGraph self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TBPGraph_Reserve(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TBPGraph self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TBPGraph self)
Parameters:
self: TBPGraph *
"""
return _snap.TBPGraph_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TBPGraph self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TBPGraph self) -> bool
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TBPGraph self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TBPGraph self)
Parameters:
self: TBPGraph const *
"""
return _snap.TBPGraph_Dump(self, *args)
def GetSmallGraph():
"""GetSmallGraph() -> PBPGraph"""
return _snap.TBPGraph_GetSmallGraph()
GetSmallGraph = staticmethod(GetSmallGraph)
__swig_destroy__ = _snap.delete_TBPGraph
TBPGraph.Save = new_instancemethod(_snap.TBPGraph_Save,None,TBPGraph)
TBPGraph.GetNodes = new_instancemethod(_snap.TBPGraph_GetNodes,None,TBPGraph)
TBPGraph.GetLNodes = new_instancemethod(_snap.TBPGraph_GetLNodes,None,TBPGraph)
TBPGraph.GetRNodes = new_instancemethod(_snap.TBPGraph_GetRNodes,None,TBPGraph)
TBPGraph.AddNode = new_instancemethod(_snap.TBPGraph_AddNode,None,TBPGraph)
TBPGraph.DelNode = new_instancemethod(_snap.TBPGraph_DelNode,None,TBPGraph)
TBPGraph.IsNode = new_instancemethod(_snap.TBPGraph_IsNode,None,TBPGraph)
TBPGraph.IsLNode = new_instancemethod(_snap.TBPGraph_IsLNode,None,TBPGraph)
TBPGraph.IsRNode = new_instancemethod(_snap.TBPGraph_IsRNode,None,TBPGraph)
TBPGraph.GetMxNId = new_instancemethod(_snap.TBPGraph_GetMxNId,None,TBPGraph)
TBPGraph.BegNI = new_instancemethod(_snap.TBPGraph_BegNI,None,TBPGraph)
TBPGraph.EndNI = new_instancemethod(_snap.TBPGraph_EndNI,None,TBPGraph)
TBPGraph.GetNI = new_instancemethod(_snap.TBPGraph_GetNI,None,TBPGraph)
TBPGraph.BegLNI = new_instancemethod(_snap.TBPGraph_BegLNI,None,TBPGraph)
TBPGraph.EndLNI = new_instancemethod(_snap.TBPGraph_EndLNI,None,TBPGraph)
TBPGraph.BegRNI = new_instancemethod(_snap.TBPGraph_BegRNI,None,TBPGraph)
TBPGraph.EndRNI = new_instancemethod(_snap.TBPGraph_EndRNI,None,TBPGraph)
TBPGraph.GetEdges = new_instancemethod(_snap.TBPGraph_GetEdges,None,TBPGraph)
TBPGraph.AddEdge = new_instancemethod(_snap.TBPGraph_AddEdge,None,TBPGraph)
TBPGraph.DelEdge = new_instancemethod(_snap.TBPGraph_DelEdge,None,TBPGraph)
TBPGraph.IsEdge = new_instancemethod(_snap.TBPGraph_IsEdge,None,TBPGraph)
TBPGraph.BegEI = new_instancemethod(_snap.TBPGraph_BegEI,None,TBPGraph)
TBPGraph.EndEI = new_instancemethod(_snap.TBPGraph_EndEI,None,TBPGraph)
TBPGraph.GetEI = new_instancemethod(_snap.TBPGraph_GetEI,None,TBPGraph)
TBPGraph.GetRndNId = new_instancemethod(_snap.TBPGraph_GetRndNId,None,TBPGraph)
TBPGraph.GetRndLNId = new_instancemethod(_snap.TBPGraph_GetRndLNId,None,TBPGraph)
TBPGraph.GetRndRNId = new_instancemethod(_snap.TBPGraph_GetRndRNId,None,TBPGraph)
TBPGraph.GetRndNI = new_instancemethod(_snap.TBPGraph_GetRndNI,None,TBPGraph)
TBPGraph.GetNIdV = new_instancemethod(_snap.TBPGraph_GetNIdV,None,TBPGraph)
TBPGraph.GetLNIdV = new_instancemethod(_snap.TBPGraph_GetLNIdV,None,TBPGraph)
TBPGraph.GetRNIdV = new_instancemethod(_snap.TBPGraph_GetRNIdV,None,TBPGraph)
TBPGraph.Empty = new_instancemethod(_snap.TBPGraph_Empty,None,TBPGraph)
TBPGraph.Clr = new_instancemethod(_snap.TBPGraph_Clr,None,TBPGraph)
TBPGraph.Reserve = new_instancemethod(_snap.TBPGraph_Reserve,None,TBPGraph)
TBPGraph.Defrag = new_instancemethod(_snap.TBPGraph_Defrag,None,TBPGraph)
TBPGraph.IsOk = new_instancemethod(_snap.TBPGraph_IsOk,None,TBPGraph)
TBPGraph.Dump = new_instancemethod(_snap.TBPGraph_Dump,None,TBPGraph)
TBPGraph_swigregister = _snap.TBPGraph_swigregister
TBPGraph_swigregister(TBPGraph)
def TBPGraph_New(*args):
"""
New() -> PBPGraph
TBPGraph_New(int const & Nodes, int const & Edges) -> PBPGraph
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TBPGraph_New(*args)
def TBPGraph_Load(*args):
"""
TBPGraph_Load(TSIn SIn) -> PBPGraph
Parameters:
SIn: TSIn &
"""
return _snap.TBPGraph_Load(*args)
def TBPGraph_GetSmallGraph():
"""TBPGraph_GetSmallGraph() -> PBPGraph"""
return _snap.TBPGraph_GetSmallGraph()
class TNGraphMtx(object):
"""Proxy of C++ TNGraphMtx class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNGraphMtx self, PNGraph const & GraphPt) -> TNGraphMtx
Parameters:
GraphPt: PNGraph const &
__init__(TNGraphMtx self, TNGraphMtx GraphMtx) -> TNGraphMtx
Parameters:
GraphMtx: TNGraphMtx const &
"""
_snap.TNGraphMtx_swiginit(self,_snap.new_TNGraphMtx(*args))
def PGetRows(self):
"""
PGetRows(TNGraphMtx self) -> int
Parameters:
self: TNGraphMtx const *
"""
return _snap.TNGraphMtx_PGetRows(self)
def PGetCols(self):
"""
PGetCols(TNGraphMtx self) -> int
Parameters:
self: TNGraphMtx const *
"""
return _snap.TNGraphMtx_PGetCols(self)
def PMultiply(self, *args):
"""
PMultiply(TNGraphMtx self, TFltVV const & B, int ColId, TFltV & Result)
Parameters:
B: TFltVV const &
ColId: int
Result: TFltV &
PMultiply(TNGraphMtx self, TFltV const & Vec, TFltV & Result)
Parameters:
Vec: TFltV const &
Result: TFltV &
"""
return _snap.TNGraphMtx_PMultiply(self, *args)
def PMultiplyT(self, *args):
"""
PMultiplyT(TNGraphMtx self, TFltVV const & B, int ColId, TFltV & Result)
Parameters:
B: TFltVV const &
ColId: int
Result: TFltV &
PMultiplyT(TNGraphMtx self, TFltV const & Vec, TFltV & Result)
Parameters:
Vec: TFltV const &
Result: TFltV &
"""
return _snap.TNGraphMtx_PMultiplyT(self, *args)
__swig_destroy__ = _snap.delete_TNGraphMtx
TNGraphMtx.PGetRows = new_instancemethod(_snap.TNGraphMtx_PGetRows,None,TNGraphMtx)
TNGraphMtx.PGetCols = new_instancemethod(_snap.TNGraphMtx_PGetCols,None,TNGraphMtx)
TNGraphMtx.PMultiply = new_instancemethod(_snap.TNGraphMtx_PMultiply,None,TNGraphMtx)
TNGraphMtx.PMultiplyT = new_instancemethod(_snap.TNGraphMtx_PMultiplyT,None,TNGraphMtx)
TNGraphMtx_swigregister = _snap.TNGraphMtx_swigregister
TNGraphMtx_swigregister(TNGraphMtx)
class TUNGraphMtx(object):
"""Proxy of C++ TUNGraphMtx class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TUNGraphMtx self, PUNGraph const & GraphPt) -> TUNGraphMtx
Parameters:
GraphPt: PUNGraph const &
__init__(TUNGraphMtx self, TUNGraphMtx GraphMtx) -> TUNGraphMtx
Parameters:
GraphMtx: TUNGraphMtx const &
"""
_snap.TUNGraphMtx_swiginit(self,_snap.new_TUNGraphMtx(*args))
def PGetRows(self):
"""
PGetRows(TUNGraphMtx self) -> int
Parameters:
self: TUNGraphMtx const *
"""
return _snap.TUNGraphMtx_PGetRows(self)
def PGetCols(self):
"""
PGetCols(TUNGraphMtx self) -> int
Parameters:
self: TUNGraphMtx const *
"""
return _snap.TUNGraphMtx_PGetCols(self)
def PMultiply(self, *args):
"""
PMultiply(TUNGraphMtx self, TFltVV const & B, int ColId, TFltV & Result)
Parameters:
B: TFltVV const &
ColId: int
Result: TFltV &
PMultiply(TUNGraphMtx self, TFltV const & Vec, TFltV & Result)
Parameters:
Vec: TFltV const &
Result: TFltV &
"""
return _snap.TUNGraphMtx_PMultiply(self, *args)
def PMultiplyT(self, *args):
"""
PMultiplyT(TUNGraphMtx self, TFltVV const & B, int ColId, TFltV & Result)
Parameters:
B: TFltVV const &
ColId: int
Result: TFltV &
PMultiplyT(TUNGraphMtx self, TFltV const & Vec, TFltV & Result)
Parameters:
Vec: TFltV const &
Result: TFltV &
"""
return _snap.TUNGraphMtx_PMultiplyT(self, *args)
__swig_destroy__ = _snap.delete_TUNGraphMtx
TUNGraphMtx.PGetRows = new_instancemethod(_snap.TUNGraphMtx_PGetRows,None,TUNGraphMtx)
TUNGraphMtx.PGetCols = new_instancemethod(_snap.TUNGraphMtx_PGetCols,None,TUNGraphMtx)
TUNGraphMtx.PMultiply = new_instancemethod(_snap.TUNGraphMtx_PMultiply,None,TUNGraphMtx)
TUNGraphMtx.PMultiplyT = new_instancemethod(_snap.TUNGraphMtx_PMultiplyT,None,TUNGraphMtx)
TUNGraphMtx_swigregister = _snap.TUNGraphMtx_swigregister
TUNGraphMtx_swigregister(TUNGraphMtx)
def GetSngVals(*args):
"""
GetSngVals(PNGraph const & Graph, int const & SngVals, TFltV & SngValV)
Parameters:
Graph: PNGraph const &
SngVals: int const &
SngValV: TFltV &
"""
return _snap.GetSngVals(*args)
def GetSngVec(*args):
"""
GetSngVec(PNGraph const & Graph, TFltV & LeftSV, TFltV & RightSV)
Parameters:
Graph: PNGraph const &
LeftSV: TFltV &
RightSV: TFltV &
GetSngVec(PNGraph const & Graph, int const & SngVecs, TFltV & SngValV, TVec< TFltV > & LeftSV,
TVec< TFltV > & RightSV)
Parameters:
Graph: PNGraph const &
SngVecs: int const &
SngValV: TFltV &
LeftSV: TVec< TFltV > &
RightSV: TVec< TFltV > &
"""
return _snap.GetSngVec(*args)
def GetEigVals(*args):
"""
GetEigVals(PUNGraph const & Graph, int const & EigVals, TFltV & EigValV)
Parameters:
Graph: PUNGraph const &
EigVals: int const &
EigValV: TFltV &
"""
return _snap.GetEigVals(*args)
def GetEigVec(*args):
"""
GetEigVec(PUNGraph const & Graph, TFltV & EigVecV)
Parameters:
Graph: PUNGraph const &
EigVecV: TFltV &
GetEigVec(PUNGraph const & Graph, int const & EigVecs, TFltV & EigValV, TVec< TFltV > & EigVecV)
Parameters:
Graph: PUNGraph const &
EigVecs: int const &
EigValV: TFltV &
EigVecV: TVec< TFltV > &
"""
return _snap.GetEigVec(*args)
def GetInvParticipRat(*args):
"""
GetInvParticipRat(PUNGraph const & Graph, int MaxEigVecs, int TimeLimit, TFltPrV & EigValIprV)
Parameters:
Graph: PUNGraph const &
MaxEigVecs: int
TimeLimit: int
EigValIprV: TFltPrV &
"""
return _snap.GetInvParticipRat(*args)
def GetInvParticipRatEig(*args):
"""
GetInvParticipRatEig(TFltV const & EigVec) -> double
Parameters:
EigVec: TFltV const &
"""
return _snap.GetInvParticipRatEig(*args)
def LoadDyNet(*args):
"""
LoadDyNet(TStr FNm) -> PNGraph
Parameters:
FNm: TStr const &
"""
return _snap.LoadDyNet(*args)
def LoadDyNetGraphV(*args):
"""
LoadDyNetGraphV(TStr FNm) -> TVec< PNGraph >
Parameters:
FNm: TStr const &
"""
return _snap.LoadDyNetGraphV(*args)
gvlDot = _snap.gvlDot
gvlNeato = _snap.gvlNeato
gvlTwopi = _snap.gvlTwopi
gvlCirco = _snap.gvlCirco
def GVizDoLayout(*args):
"""
GVizDoLayout(TStr GraphInFNm, TStr OutFNm, TGVizLayout const & Layout)
Parameters:
GraphInFNm: TStr const &
OutFNm: TStr
Layout: TGVizLayout const &
"""
return _snap.GVizDoLayout(*args)
def GVizGetLayoutStr(*args):
"""
GVizGetLayoutStr(TGVizLayout const & Layout) -> TStr
Parameters:
Layout: TGVizLayout const &
"""
return _snap.GVizGetLayoutStr(*args)
class TBigStrPool(object):
"""Proxy of C++ TBigStrPool class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TBigStrPool self, TSize MxBfLen=0, uint _GrowBy=16*1024*1024) -> TBigStrPool
Parameters:
MxBfLen: TSize
_GrowBy: uint
__init__(TBigStrPool self, TSize MxBfLen=0) -> TBigStrPool
Parameters:
MxBfLen: TSize
__init__(TBigStrPool self) -> TBigStrPool
__init__(TBigStrPool self, TSIn SIn, bool LoadCompact=True) -> TBigStrPool
Parameters:
SIn: TSIn &
LoadCompact: bool
__init__(TBigStrPool self, TSIn SIn) -> TBigStrPool
Parameters:
SIn: TSIn &
__init__(TBigStrPool self, TBigStrPool Pool) -> TBigStrPool
Parameters:
Pool: TBigStrPool const &
"""
_snap.TBigStrPool_swiginit(self,_snap.new_TBigStrPool(*args))
__swig_destroy__ = _snap.delete_TBigStrPool
def New(*args):
"""
New(TSize _MxBfLen=0, uint _GrowBy=16*1024*1024) -> PBigStrPool
Parameters:
_MxBfLen: TSize
_GrowBy: uint
New(TSize _MxBfLen=0) -> PBigStrPool
Parameters:
_MxBfLen: TSize
New() -> PBigStrPool
New(TSIn SIn) -> PBigStrPool
Parameters:
SIn: TSIn &
New(TStr fileName) -> PBigStrPool
Parameters:
fileName: TStr const &
"""
return _snap.TBigStrPool_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn, bool LoadCompacted=True) -> PBigStrPool
Parameters:
SIn: TSIn &
LoadCompacted: bool
Load(TSIn SIn) -> PBigStrPool
Parameters:
SIn: TSIn &
"""
return _snap.TBigStrPool_Load(*args)
Load = staticmethod(Load)
def Save(self, *args):
"""
Save(TBigStrPool self, TSOut SOut)
Parameters:
SOut: TSOut &
Save(TBigStrPool self, TStr fileName)
Parameters:
fileName: TStr const &
"""
return _snap.TBigStrPool_Save(self, *args)
def GetStrs(self):
"""
GetStrs(TBigStrPool self) -> int
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool_GetStrs(self)
def Len(self):
"""
Len(TBigStrPool self) -> TSize
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool_Len(self)
def Size(self):
"""
Size(TBigStrPool self) -> TSize
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool_Size(self)
def Empty(self):
"""
Empty(TBigStrPool self) -> bool
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool_Empty(self)
def __call__(self):
"""
__call__(TBigStrPool self) -> char *
Parameters:
self: TBigStrPool const *
"""
return _snap.TBigStrPool___call__(self)
def AddStr(self, *args):
"""
AddStr(TBigStrPool self, char const * Str, uint Len) -> int
Parameters:
Str: char const *
Len: uint
AddStr(TBigStrPool self, char const * Str) -> int
Parameters:
Str: char const *
AddStr(TBigStrPool self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TBigStrPool_AddStr(self, *args)
def GetCStr(self, *args):
"""
GetCStr(TBigStrPool self, int const & StrId) -> char const *
Parameters:
StrId: int const &
"""
return _snap.TBigStrPool_GetCStr(self, *args)
def GetStrFromOffset(self, *args):
"""
GetStrFromOffset(TBigStrPool self, TSize const & Offset) -> TStr
Parameters:
Offset: TSize const &
"""
return _snap.TBigStrPool_GetStrFromOffset(self, *args)
def GetCStrFromOffset(self, *args):
"""
GetCStrFromOffset(TBigStrPool self, TSize const & Offset) -> char const *
Parameters:
Offset: TSize const &
"""
return _snap.TBigStrPool_GetCStrFromOffset(self, *args)
def Clr(self, DoDel=False):
"""
Clr(TBigStrPool self, bool DoDel=False)
Parameters:
DoDel: bool
Clr(TBigStrPool self)
Parameters:
self: TBigStrPool *
"""
return _snap.TBigStrPool_Clr(self, DoDel)
def Cmp(self, *args):
"""
Cmp(TBigStrPool self, int const & StrId, char const * Str) -> int
Parameters:
StrId: int const &
Str: char const *
"""
return _snap.TBigStrPool_Cmp(self, *args)
def GetPrimHashCd(self, *args):
"""
GetPrimHashCd(TBigStrPool self, char const * CStr) -> int
Parameters:
CStr: char const *
GetPrimHashCd(TBigStrPool self, int const & StrId) -> int
Parameters:
StrId: int const &
"""
return _snap.TBigStrPool_GetPrimHashCd(self, *args)
def GetSecHashCd(self, *args):
"""
GetSecHashCd(TBigStrPool self, char const * CStr) -> int
Parameters:
CStr: char const *
GetSecHashCd(TBigStrPool self, int const & StrId) -> int
Parameters:
StrId: int const &
"""
return _snap.TBigStrPool_GetSecHashCd(self, *args)
TBigStrPool.Save = new_instancemethod(_snap.TBigStrPool_Save,None,TBigStrPool)
TBigStrPool.GetStrs = new_instancemethod(_snap.TBigStrPool_GetStrs,None,TBigStrPool)
TBigStrPool.Len = new_instancemethod(_snap.TBigStrPool_Len,None,TBigStrPool)
TBigStrPool.Size = new_instancemethod(_snap.TBigStrPool_Size,None,TBigStrPool)
TBigStrPool.Empty = new_instancemethod(_snap.TBigStrPool_Empty,None,TBigStrPool)
TBigStrPool.__call__ = new_instancemethod(_snap.TBigStrPool___call__,None,TBigStrPool)
TBigStrPool.AddStr = new_instancemethod(_snap.TBigStrPool_AddStr,None,TBigStrPool)
TBigStrPool.GetCStr = new_instancemethod(_snap.TBigStrPool_GetCStr,None,TBigStrPool)
TBigStrPool.GetStrFromOffset = new_instancemethod(_snap.TBigStrPool_GetStrFromOffset,None,TBigStrPool)
TBigStrPool.GetCStrFromOffset = new_instancemethod(_snap.TBigStrPool_GetCStrFromOffset,None,TBigStrPool)
TBigStrPool.Clr = new_instancemethod(_snap.TBigStrPool_Clr,None,TBigStrPool)
TBigStrPool.Cmp = new_instancemethod(_snap.TBigStrPool_Cmp,None,TBigStrPool)
TBigStrPool.GetPrimHashCd = new_instancemethod(_snap.TBigStrPool_GetPrimHashCd,None,TBigStrPool)
TBigStrPool.GetSecHashCd = new_instancemethod(_snap.TBigStrPool_GetSecHashCd,None,TBigStrPool)
TBigStrPool_swigregister = _snap.TBigStrPool_swigregister
TBigStrPool_swigregister(TBigStrPool)
def TBigStrPool_New(*args):
"""
New(TSize _MxBfLen=0, uint _GrowBy=16*1024*1024) -> PBigStrPool
Parameters:
_MxBfLen: TSize
_GrowBy: uint
New(TSize _MxBfLen=0) -> PBigStrPool
Parameters:
_MxBfLen: TSize
New() -> PBigStrPool
New(TSIn SIn) -> PBigStrPool
Parameters:
SIn: TSIn &
TBigStrPool_New(TStr fileName) -> PBigStrPool
Parameters:
fileName: TStr const &
"""
return _snap.TBigStrPool_New(*args)
def TBigStrPool_Load(*args):
"""
Load(TSIn SIn, bool LoadCompacted=True) -> PBigStrPool
Parameters:
SIn: TSIn &
LoadCompacted: bool
TBigStrPool_Load(TSIn SIn) -> PBigStrPool
Parameters:
SIn: TSIn &
"""
return _snap.TBigStrPool_Load(*args)
class TStrHashF_OldGLib(object):
"""Proxy of C++ TStrHashF_OldGLib class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetPrimHashCd(*args)
GetPrimHashCd = staticmethod(GetPrimHashCd)
def GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetSecHashCd(*args)
GetSecHashCd = staticmethod(GetSecHashCd)
def __init__(self):
"""__init__(TStrHashF_OldGLib self) -> TStrHashF_OldGLib"""
_snap.TStrHashF_OldGLib_swiginit(self,_snap.new_TStrHashF_OldGLib())
__swig_destroy__ = _snap.delete_TStrHashF_OldGLib
TStrHashF_OldGLib_swigregister = _snap.TStrHashF_OldGLib_swigregister
TStrHashF_OldGLib_swigregister(TStrHashF_OldGLib)
def TStrHashF_OldGLib_GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_OldGLib_GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetPrimHashCd(*args)
def TStrHashF_OldGLib_GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_OldGLib_GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_OldGLib_GetSecHashCd(*args)
class TStrHashF_Md5(object):
"""Proxy of C++ TStrHashF_Md5 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_Md5_GetPrimHashCd(*args)
GetPrimHashCd = staticmethod(GetPrimHashCd)
def GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_Md5_GetSecHashCd(*args)
GetSecHashCd = staticmethod(GetSecHashCd)
def __init__(self):
"""__init__(TStrHashF_Md5 self) -> TStrHashF_Md5"""
_snap.TStrHashF_Md5_swiginit(self,_snap.new_TStrHashF_Md5())
__swig_destroy__ = _snap.delete_TStrHashF_Md5
TStrHashF_Md5_swigregister = _snap.TStrHashF_Md5_swigregister
TStrHashF_Md5_swigregister(TStrHashF_Md5)
def TStrHashF_Md5_GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_Md5_GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_Md5_GetPrimHashCd(*args)
def TStrHashF_Md5_GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_Md5_GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_Md5_GetSecHashCd(*args)
class TStrHashF_DJB(object):
"""Proxy of C++ TStrHashF_DJB class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_DJB_GetPrimHashCd(*args)
GetPrimHashCd = staticmethod(GetPrimHashCd)
def GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_DJB_GetSecHashCd(*args)
GetSecHashCd = staticmethod(GetSecHashCd)
def __init__(self):
"""__init__(TStrHashF_DJB self) -> TStrHashF_DJB"""
_snap.TStrHashF_DJB_swiginit(self,_snap.new_TStrHashF_DJB())
__swig_destroy__ = _snap.delete_TStrHashF_DJB
TStrHashF_DJB_swigregister = _snap.TStrHashF_DJB_swigregister
TStrHashF_DJB_swigregister(TStrHashF_DJB)
def TStrHashF_DJB_GetPrimHashCd(*args):
"""
GetPrimHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_DJB_GetPrimHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_DJB_GetPrimHashCd(*args)
def TStrHashF_DJB_GetSecHashCd(*args):
"""
GetSecHashCd(char const * p) -> int
Parameters:
p: char const *
TStrHashF_DJB_GetSecHashCd(TStr s) -> int
Parameters:
s: TStr const &
"""
return _snap.TStrHashF_DJB_GetSecHashCd(*args)
def GenRndBipart(*args):
"""
GenRndBipart(int const & LeftNodes, int const & RightNodes, int const & Edges, TRnd Rnd=Rnd) -> PBPGraph
Parameters:
LeftNodes: int const &
RightNodes: int const &
Edges: int const &
Rnd: TRnd &
GenRndBipart(int const & LeftNodes, int const & RightNodes, int const & Edges) -> PBPGraph
Parameters:
LeftNodes: int const &
RightNodes: int const &
Edges: int const &
"""
return _snap.GenRndBipart(*args)
def GenRndDegK(*args):
"""
GenRndDegK(int const & Nodes, int const & NodeDeg, int const & NSwitch=100, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
NodeDeg: int const &
NSwitch: int const &
Rnd: TRnd &
GenRndDegK(int const & Nodes, int const & NodeDeg, int const & NSwitch=100) -> PUNGraph
Parameters:
Nodes: int const &
NodeDeg: int const &
NSwitch: int const &
GenRndDegK(int const & Nodes, int const & NodeDeg) -> PUNGraph
Parameters:
Nodes: int const &
NodeDeg: int const &
"""
return _snap.GenRndDegK(*args)
def GenRndPowerLaw(*args):
"""
GenRndPowerLaw(int const & Nodes, double const & PowerExp, bool const & ConfModel=True, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
PowerExp: double const &
ConfModel: bool const &
Rnd: TRnd &
GenRndPowerLaw(int const & Nodes, double const & PowerExp, bool const & ConfModel=True) -> PUNGraph
Parameters:
Nodes: int const &
PowerExp: double const &
ConfModel: bool const &
GenRndPowerLaw(int const & Nodes, double const & PowerExp) -> PUNGraph
Parameters:
Nodes: int const &
PowerExp: double const &
"""
return _snap.GenRndPowerLaw(*args)
def GenDegSeq(*args):
"""
GenDegSeq(TIntV DegSeqV, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
DegSeqV: TIntV const &
Rnd: TRnd &
GenDegSeq(TIntV DegSeqV) -> PUNGraph
Parameters:
DegSeqV: TIntV const &
"""
return _snap.GenDegSeq(*args)
def GenPrefAttach(*args):
"""
GenPrefAttach(int const & Nodes, int const & NodeOutDeg, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
NodeOutDeg: int const &
Rnd: TRnd &
GenPrefAttach(int const & Nodes, int const & NodeOutDeg) -> PUNGraph
Parameters:
Nodes: int const &
NodeOutDeg: int const &
"""
return _snap.GenPrefAttach(*args)
def GenGeoPrefAttach(*args):
"""
GenGeoPrefAttach(int const & Nodes, int const & OutDeg, double const & Beta, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
OutDeg: int const &
Beta: double const &
Rnd: TRnd &
GenGeoPrefAttach(int const & Nodes, int const & OutDeg, double const & Beta) -> PUNGraph
Parameters:
Nodes: int const &
OutDeg: int const &
Beta: double const &
"""
return _snap.GenGeoPrefAttach(*args)
def GenSmallWorld(*args):
"""
GenSmallWorld(int const & Nodes, int const & NodeOutDeg, double const & RewireProb, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Nodes: int const &
NodeOutDeg: int const &
RewireProb: double const &
Rnd: TRnd &
GenSmallWorld(int const & Nodes, int const & NodeOutDeg, double const & RewireProb) -> PUNGraph
Parameters:
Nodes: int const &
NodeOutDeg: int const &
RewireProb: double const &
"""
return _snap.GenSmallWorld(*args)
def GenForestFire(*args):
"""
GenForestFire(int const & Nodes, double const & FwdProb, double const & BckProb) -> PNGraph
Parameters:
Nodes: int const &
FwdProb: double const &
BckProb: double const &
"""
return _snap.GenForestFire(*args)
def GenCopyModel(*args):
"""
GenCopyModel(int const & Nodes, double const & Beta, TRnd Rnd=Rnd) -> PNGraph
Parameters:
Nodes: int const &
Beta: double const &
Rnd: TRnd &
GenCopyModel(int const & Nodes, double const & Beta) -> PNGraph
Parameters:
Nodes: int const &
Beta: double const &
"""
return _snap.GenCopyModel(*args)
def GenRMat(*args):
"""
GenRMat(int const & Nodes, int const & Edges, double const & A, double const & B, double const & C,
TRnd Rnd=Rnd) -> PNGraph
Parameters:
Nodes: int const &
Edges: int const &
A: double const &
B: double const &
C: double const &
Rnd: TRnd &
GenRMat(int const & Nodes, int const & Edges, double const & A, double const & B, double const & C) -> PNGraph
Parameters:
Nodes: int const &
Edges: int const &
A: double const &
B: double const &
C: double const &
"""
return _snap.GenRMat(*args)
def GenRMatEpinions():
"""GenRMatEpinions() -> PNGraph"""
return _snap.GenRMatEpinions()
def GenRewire(*args):
"""
GenRewire(PUNGraph const & Graph, int const & NSwitch=100, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
Graph: PUNGraph const &
NSwitch: int const &
Rnd: TRnd &
GenRewire(PUNGraph const & Graph, int const & NSwitch=100) -> PUNGraph
Parameters:
Graph: PUNGraph const &
NSwitch: int const &
GenRewire(PUNGraph const & Graph) -> PUNGraph
Parameters:
Graph: PUNGraph const &
GenRewire(PNGraph const & Graph, int const & NSwitch=100, TRnd Rnd=Rnd) -> PNGraph
Parameters:
Graph: PNGraph const &
NSwitch: int const &
Rnd: TRnd &
GenRewire(PNGraph const & Graph, int const & NSwitch=100) -> PNGraph
Parameters:
Graph: PNGraph const &
NSwitch: int const &
GenRewire(PNGraph const & Graph) -> PNGraph
Parameters:
Graph: PNGraph const &
GenRewire(PBPGraph const & Graph, int const & NSwitch=100, TRnd Rnd=Rnd) -> PBPGraph
Parameters:
Graph: PBPGraph const &
NSwitch: int const &
Rnd: TRnd &
GenRewire(PBPGraph const & Graph, int const & NSwitch=100) -> PBPGraph
Parameters:
Graph: PBPGraph const &
NSwitch: int const &
GenRewire(PBPGraph const & Graph) -> PBPGraph
Parameters:
Graph: PBPGraph const &
"""
return _snap.GenRewire(*args)
def GenConfModel(*args):
"""
GenConfModel(TIntV DegSeqV, TRnd Rnd=Rnd) -> PUNGraph
Parameters:
DegSeqV: TIntV const &
Rnd: TRnd &
GenConfModel(TIntV DegSeqV) -> PUNGraph
Parameters:
DegSeqV: TIntV const &
GenConfModel(PUNGraph const & G) -> PUNGraph
Parameters:
G: PUNGraph const &
"""
return _snap.GenConfModel(*args)
def GetSubGraph(*args):
"""
GetSubGraph(PUNGraph const & Graph, TIntV NIdV, bool const & RenumberNodes=False) -> PUNGraph
Parameters:
Graph: PUNGraph const &
NIdV: TIntV const &
RenumberNodes: bool const &
GetSubGraph(PUNGraph const & Graph, TIntV NIdV) -> PUNGraph
Parameters:
Graph: PUNGraph const &
NIdV: TIntV const &
GetSubGraph(PNGraph const & Graph, TIntV NIdV, bool const & RenumberNodes=False) -> PNGraph
Parameters:
Graph: PNGraph const &
NIdV: TIntV const &
RenumberNodes: bool const &
GetSubGraph(PNGraph const & Graph, TIntV NIdV) -> PNGraph
Parameters:
Graph: PNGraph const &
NIdV: TIntV const &
"""
return _snap.GetSubGraph(*args)
class TGUtil(object):
"""Proxy of C++ TGUtil class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetCdf(*args):
"""
GetCdf(TIntPrV const & PdfV, TIntPrV & CdfV)
Parameters:
PdfV: TIntPrV const &
CdfV: TIntPrV &
GetCdf(TFltPrV const & PdfV, TFltPrV & CdfV)
Parameters:
PdfV: TFltPrV const &
CdfV: TFltPrV &
GetCdf(TIntFltKdV const & PdfV, TIntFltKdV & CdfV)
Parameters:
PdfV: TIntFltKdV const &
CdfV: TIntFltKdV &
GetCdf(TIntPrV const & PdfV) -> TIntPrV
Parameters:
PdfV: TIntPrV const &
GetCdf(TFltPrV const & PdfV) -> TFltPrV
Parameters:
PdfV: TFltPrV const &
"""
return _snap.TGUtil_GetCdf(*args)
GetCdf = staticmethod(GetCdf)
def GetCCdf(*args):
"""
GetCCdf(TIntPrV const & PdfV, TIntPrV & CCdfV)
Parameters:
PdfV: TIntPrV const &
CCdfV: TIntPrV &
GetCCdf(TFltPrV const & PdfV, TFltPrV & CCdfV)
Parameters:
PdfV: TFltPrV const &
CCdfV: TFltPrV &
GetCCdf(TIntFltKdV const & PdfV, TIntFltKdV & CCdfV)
Parameters:
PdfV: TIntFltKdV const &
CCdfV: TIntFltKdV &
GetCCdf(TIntPrV const & PdfV) -> TIntPrV
Parameters:
PdfV: TIntPrV const &
GetCCdf(TFltPrV const & PdfV) -> TFltPrV
Parameters:
PdfV: TFltPrV const &
"""
return _snap.TGUtil_GetCCdf(*args)
GetCCdf = staticmethod(GetCCdf)
def GetPdf(*args):
"""
GetPdf(TIntPrV const & CdfV, TIntPrV & PdfV)
Parameters:
CdfV: TIntPrV const &
PdfV: TIntPrV &
GetPdf(TFltPrV const & CdfV, TFltPrV & PdfV)
Parameters:
CdfV: TFltPrV const &
PdfV: TFltPrV &
GetPdf(TIntFltKdV const & CdfV, TIntFltKdV & PdfV)
Parameters:
CdfV: TIntFltKdV const &
PdfV: TIntFltKdV &
"""
return _snap.TGUtil_GetPdf(*args)
GetPdf = staticmethod(GetPdf)
def Normalize(*args):
"""
Normalize(TFltPrV & PdfV)
Parameters:
PdfV: TFltPrV &
Normalize(TIntFltKdV & PdfV)
Parameters:
PdfV: TIntFltKdV &
"""
return _snap.TGUtil_Normalize(*args)
Normalize = staticmethod(Normalize)
def MakeExpBins(*args):
"""
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV, double const & BinFactor=2, double const & MinYVal=1)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
BinFactor: double const &
MinYVal: double const &
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV, double const & BinFactor=2)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
BinFactor: double const &
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV, double const & BinFactor=2, double const & MinYVal=1)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
BinFactor: double const &
MinYVal: double const &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV, double const & BinFactor=2)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
BinFactor: double const &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
MakeExpBins(TFltV const & YValV, TFltV & ExpYValV, double const & BinFactor=1.01)
Parameters:
YValV: TFltV const &
ExpYValV: TFltV &
BinFactor: double const &
MakeExpBins(TFltV const & YValV, TFltV & ExpYValV)
Parameters:
YValV: TFltV const &
ExpYValV: TFltV &
MakeExpBins(TIntV YValV, TIntV ExpYValV, double const & BinFactor=1.01)
Parameters:
YValV: TIntV const &
ExpYValV: TIntV &
BinFactor: double const &
MakeExpBins(TIntV YValV, TIntV ExpYValV)
Parameters:
YValV: TIntV const &
ExpYValV: TIntV &
"""
return _snap.TGUtil_MakeExpBins(*args)
MakeExpBins = staticmethod(MakeExpBins)
def __init__(self):
"""__init__(TGUtil self) -> TGUtil"""
_snap.TGUtil_swiginit(self,_snap.new_TGUtil())
__swig_destroy__ = _snap.delete_TGUtil
TGUtil_swigregister = _snap.TGUtil_swigregister
TGUtil_swigregister(TGUtil)
def TGUtil_GetCdf(*args):
"""
GetCdf(TIntPrV const & PdfV, TIntPrV & CdfV)
Parameters:
PdfV: TIntPrV const &
CdfV: TIntPrV &
GetCdf(TFltPrV const & PdfV, TFltPrV & CdfV)
Parameters:
PdfV: TFltPrV const &
CdfV: TFltPrV &
GetCdf(TIntFltKdV const & PdfV, TIntFltKdV & CdfV)
Parameters:
PdfV: TIntFltKdV const &
CdfV: TIntFltKdV &
GetCdf(TIntPrV const & PdfV) -> TIntPrV
Parameters:
PdfV: TIntPrV const &
TGUtil_GetCdf(TFltPrV const & PdfV) -> TFltPrV
Parameters:
PdfV: TFltPrV const &
"""
return _snap.TGUtil_GetCdf(*args)
def TGUtil_GetCCdf(*args):
"""
GetCCdf(TIntPrV const & PdfV, TIntPrV & CCdfV)
Parameters:
PdfV: TIntPrV const &
CCdfV: TIntPrV &
GetCCdf(TFltPrV const & PdfV, TFltPrV & CCdfV)
Parameters:
PdfV: TFltPrV const &
CCdfV: TFltPrV &
GetCCdf(TIntFltKdV const & PdfV, TIntFltKdV & CCdfV)
Parameters:
PdfV: TIntFltKdV const &
CCdfV: TIntFltKdV &
GetCCdf(TIntPrV const & PdfV) -> TIntPrV
Parameters:
PdfV: TIntPrV const &
TGUtil_GetCCdf(TFltPrV const & PdfV) -> TFltPrV
Parameters:
PdfV: TFltPrV const &
"""
return _snap.TGUtil_GetCCdf(*args)
def TGUtil_GetPdf(*args):
"""
GetPdf(TIntPrV const & CdfV, TIntPrV & PdfV)
Parameters:
CdfV: TIntPrV const &
PdfV: TIntPrV &
GetPdf(TFltPrV const & CdfV, TFltPrV & PdfV)
Parameters:
CdfV: TFltPrV const &
PdfV: TFltPrV &
TGUtil_GetPdf(TIntFltKdV const & CdfV, TIntFltKdV & PdfV)
Parameters:
CdfV: TIntFltKdV const &
PdfV: TIntFltKdV &
"""
return _snap.TGUtil_GetPdf(*args)
def TGUtil_Normalize(*args):
"""
Normalize(TFltPrV & PdfV)
Parameters:
PdfV: TFltPrV &
TGUtil_Normalize(TIntFltKdV & PdfV)
Parameters:
PdfV: TIntFltKdV &
"""
return _snap.TGUtil_Normalize(*args)
def TGUtil_MakeExpBins(*args):
"""
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV, double const & BinFactor=2, double const & MinYVal=1)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
BinFactor: double const &
MinYVal: double const &
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV, double const & BinFactor=2)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
BinFactor: double const &
MakeExpBins(TFltPrV const & XYValV, TFltPrV & ExpXYValV)
Parameters:
XYValV: TFltPrV const &
ExpXYValV: TFltPrV &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV, double const & BinFactor=2, double const & MinYVal=1)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
BinFactor: double const &
MinYVal: double const &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV, double const & BinFactor=2)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
BinFactor: double const &
MakeExpBins(TFltKdV const & XYValV, TFltKdV & ExpXYValV)
Parameters:
XYValV: TFltKdV const &
ExpXYValV: TFltKdV &
MakeExpBins(TFltV const & YValV, TFltV & ExpYValV, double const & BinFactor=1.01)
Parameters:
YValV: TFltV const &
ExpYValV: TFltV &
BinFactor: double const &
MakeExpBins(TFltV const & YValV, TFltV & ExpYValV)
Parameters:
YValV: TFltV const &
ExpYValV: TFltV &
MakeExpBins(TIntV YValV, TIntV ExpYValV, double const & BinFactor=1.01)
Parameters:
YValV: TIntV const &
ExpYValV: TIntV &
BinFactor: double const &
TGUtil_MakeExpBins(TIntV YValV, TIntV ExpYValV)
Parameters:
YValV: TIntV const &
ExpYValV: TIntV &
"""
return _snap.TGUtil_MakeExpBins(*args)
class TStrUtil(object):
"""Proxy of C++ TStrUtil class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def GetXmlTagVal(*args):
"""
GetXmlTagVal(TXmlLx & XmlLx, TChA TagNm) -> TChA
Parameters:
XmlLx: TXmlLx &
TagNm: TChA const &
"""
return _snap.TStrUtil_GetXmlTagVal(*args)
GetXmlTagVal = staticmethod(GetXmlTagVal)
def GetXmlTagNmVal(*args):
"""
GetXmlTagNmVal(TXmlLx & XmlLx, TChA TagNm, TChA TagVal)
Parameters:
XmlLx: TXmlLx &
TagNm: TChA &
TagVal: TChA &
"""
return _snap.TStrUtil_GetXmlTagNmVal(*args)
GetXmlTagNmVal = staticmethod(GetXmlTagNmVal)
def GetXmlTagNmVal2(*args):
"""
GetXmlTagNmVal2(TXmlLx & XmlLx, TChA TagNm, TChA TagVal, bool const & TakeTagNms) -> bool
Parameters:
XmlLx: TXmlLx &
TagNm: TChA &
TagVal: TChA &
TakeTagNms: bool const &
"""
return _snap.TStrUtil_GetXmlTagNmVal2(*args)
GetXmlTagNmVal2 = staticmethod(GetXmlTagNmVal2)
def GetDomNm(*args):
"""
GetDomNm(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetDomNm(*args)
GetDomNm = staticmethod(GetDomNm)
def GetDomNm2(*args):
"""
GetDomNm2(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetDomNm2(*args)
GetDomNm2 = staticmethod(GetDomNm2)
def GetWebsiteNm(*args):
"""
GetWebsiteNm(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetWebsiteNm(*args)
GetWebsiteNm = staticmethod(GetWebsiteNm)
def GetNormalizedUrl(*args):
"""
GetNormalizedUrl(TChA UrlIn, TChA BaseUrl, TChA UrlOut) -> bool
Parameters:
UrlIn: TChA const &
BaseUrl: TChA const &
UrlOut: TChA &
"""
return _snap.TStrUtil_GetNormalizedUrl(*args)
GetNormalizedUrl = staticmethod(GetNormalizedUrl)
def StripEnd(*args):
"""
StripEnd(TChA Str, TChA SearchStr, TChA NewStr) -> bool
Parameters:
Str: TChA const &
SearchStr: TChA const &
NewStr: TChA &
"""
return _snap.TStrUtil_StripEnd(*args)
StripEnd = staticmethod(StripEnd)
def GetShorStr(*args):
"""
GetShorStr(TChA LongStr, int const MaxLen=50) -> TChA
Parameters:
LongStr: TChA const &
MaxLen: int const
GetShorStr(TChA LongStr) -> TChA
Parameters:
LongStr: TChA const &
"""
return _snap.TStrUtil_GetShorStr(*args)
GetShorStr = staticmethod(GetShorStr)
def GetCleanStr(*args):
"""
GetCleanStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanStr(*args)
GetCleanStr = staticmethod(GetCleanStr)
def GetCleanWrdStr(*args):
"""
GetCleanWrdStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanWrdStr(*args)
GetCleanWrdStr = staticmethod(GetCleanWrdStr)
def CountWords(*args):
"""
CountWords(char const * CStr) -> int
Parameters:
CStr: char const *
CountWords(TChA ChA) -> int
Parameters:
ChA: TChA const &
CountWords(TChA ChA, TStrHash< TInt > const & StopWordH) -> int
Parameters:
ChA: TChA const &
StopWordH: TStrHash< TInt > const &
"""
return _snap.TStrUtil_CountWords(*args)
CountWords = staticmethod(CountWords)
def SplitWords(*args):
"""
SplitWords(TChA ChA, TVec< char * > & WrdV, bool const & SplitOnWs=True) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
SplitOnWs: bool const &
SplitWords(TChA ChA, TVec< char * > & WrdV) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
"""
return _snap.TStrUtil_SplitWords(*args)
SplitWords = staticmethod(SplitWords)
def SplitOnCh(*args):
"""
SplitOnCh(TChA ChA, TVec< char * > & WrdV, char const & Ch, bool const & SkipEmpty=False) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
Ch: char const &
SkipEmpty: bool const &
SplitOnCh(TChA ChA, TVec< char * > & WrdV, char const & Ch) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
Ch: char const &
"""
return _snap.TStrUtil_SplitOnCh(*args)
SplitOnCh = staticmethod(SplitOnCh)
def SplitLines(*args):
"""
SplitLines(TChA ChA, TVec< char * > & LineV, bool const & SkipEmpty=False) -> int
Parameters:
ChA: TChA &
LineV: TVec< char * > &
SkipEmpty: bool const &
SplitLines(TChA ChA, TVec< char * > & LineV) -> int
Parameters:
ChA: TChA &
LineV: TVec< char * > &
"""
return _snap.TStrUtil_SplitLines(*args)
SplitLines = staticmethod(SplitLines)
def SplitSentences(*args):
"""
SplitSentences(TChA ChA, TVec< char * > & SentenceV) -> int
Parameters:
ChA: TChA &
SentenceV: TVec< char * > &
"""
return _snap.TStrUtil_SplitSentences(*args)
SplitSentences = staticmethod(SplitSentences)
def RemoveHtmlTags(*args):
"""
RemoveHtmlTags(TChA HtmlStr, TChA TextStr)
Parameters:
HtmlStr: TChA const &
TextStr: TChA &
"""
return _snap.TStrUtil_RemoveHtmlTags(*args)
RemoveHtmlTags = staticmethod(RemoveHtmlTags)
def IsLatinStr(*args):
"""
IsLatinStr(TChA Str, double const & MinAlFrac) -> bool
Parameters:
Str: TChA const &
MinAlFrac: double const &
"""
return _snap.TStrUtil_IsLatinStr(*args)
IsLatinStr = staticmethod(IsLatinStr)
def GetWIdV(*args):
"""
GetWIdV(TStrHash< TInt > const & StrH, char const * CStr, TIntV WIdV)
Parameters:
StrH: TStrHash< TInt > const &
CStr: char const *
WIdV: TIntV &
"""
return _snap.TStrUtil_GetWIdV(*args)
GetWIdV = staticmethod(GetWIdV)
def GetAddWIdV(*args):
"""
GetAddWIdV(TStrHash< TInt > & StrH, char const * CStr, TIntV WIdV)
Parameters:
StrH: TStrHash< TInt > &
CStr: char const *
WIdV: TIntV &
"""
return _snap.TStrUtil_GetAddWIdV(*args)
GetAddWIdV = staticmethod(GetAddWIdV)
def GetTmFromStr(*args):
"""
GetTmFromStr(char const * TmStr, TSecTm & Tm) -> bool
Parameters:
TmStr: char const *
Tm: TSecTm &
"""
return _snap.TStrUtil_GetTmFromStr(*args)
GetTmFromStr = staticmethod(GetTmFromStr)
def GetStdName(*args):
"""
GetStdName(TStr AuthorName) -> TStr
Parameters:
AuthorName: TStr
"""
return _snap.TStrUtil_GetStdName(*args)
GetStdName = staticmethod(GetStdName)
def GetStdNameV(*args):
"""
GetStdNameV(TStr AuthorNames, TStrV StdNameV)
Parameters:
AuthorNames: TStr
StdNameV: TStrV &
"""
return _snap.TStrUtil_GetStdNameV(*args)
GetStdNameV = staticmethod(GetStdNameV)
def __init__(self):
"""__init__(TStrUtil self) -> TStrUtil"""
_snap.TStrUtil_swiginit(self,_snap.new_TStrUtil())
__swig_destroy__ = _snap.delete_TStrUtil
TStrUtil_swigregister = _snap.TStrUtil_swigregister
TStrUtil_swigregister(TStrUtil)
def TStrUtil_GetXmlTagVal(*args):
"""
TStrUtil_GetXmlTagVal(TXmlLx & XmlLx, TChA TagNm) -> TChA
Parameters:
XmlLx: TXmlLx &
TagNm: TChA const &
"""
return _snap.TStrUtil_GetXmlTagVal(*args)
def TStrUtil_GetXmlTagNmVal(*args):
"""
TStrUtil_GetXmlTagNmVal(TXmlLx & XmlLx, TChA TagNm, TChA TagVal)
Parameters:
XmlLx: TXmlLx &
TagNm: TChA &
TagVal: TChA &
"""
return _snap.TStrUtil_GetXmlTagNmVal(*args)
def TStrUtil_GetXmlTagNmVal2(*args):
"""
TStrUtil_GetXmlTagNmVal2(TXmlLx & XmlLx, TChA TagNm, TChA TagVal, bool const & TakeTagNms) -> bool
Parameters:
XmlLx: TXmlLx &
TagNm: TChA &
TagVal: TChA &
TakeTagNms: bool const &
"""
return _snap.TStrUtil_GetXmlTagNmVal2(*args)
def TStrUtil_GetDomNm(*args):
"""
TStrUtil_GetDomNm(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetDomNm(*args)
def TStrUtil_GetDomNm2(*args):
"""
TStrUtil_GetDomNm2(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetDomNm2(*args)
def TStrUtil_GetWebsiteNm(*args):
"""
TStrUtil_GetWebsiteNm(TChA UrlChA) -> TChA
Parameters:
UrlChA: TChA const &
"""
return _snap.TStrUtil_GetWebsiteNm(*args)
def TStrUtil_GetNormalizedUrl(*args):
"""
TStrUtil_GetNormalizedUrl(TChA UrlIn, TChA BaseUrl, TChA UrlOut) -> bool
Parameters:
UrlIn: TChA const &
BaseUrl: TChA const &
UrlOut: TChA &
"""
return _snap.TStrUtil_GetNormalizedUrl(*args)
def TStrUtil_StripEnd(*args):
"""
TStrUtil_StripEnd(TChA Str, TChA SearchStr, TChA NewStr) -> bool
Parameters:
Str: TChA const &
SearchStr: TChA const &
NewStr: TChA &
"""
return _snap.TStrUtil_StripEnd(*args)
def TStrUtil_GetShorStr(*args):
"""
GetShorStr(TChA LongStr, int const MaxLen=50) -> TChA
Parameters:
LongStr: TChA const &
MaxLen: int const
TStrUtil_GetShorStr(TChA LongStr) -> TChA
Parameters:
LongStr: TChA const &
"""
return _snap.TStrUtil_GetShorStr(*args)
def TStrUtil_GetCleanStr(*args):
"""
TStrUtil_GetCleanStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanStr(*args)
def TStrUtil_GetCleanWrdStr(*args):
"""
TStrUtil_GetCleanWrdStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanWrdStr(*args)
def TStrUtil_CountWords(*args):
"""
CountWords(char const * CStr) -> int
Parameters:
CStr: char const *
CountWords(TChA ChA) -> int
Parameters:
ChA: TChA const &
TStrUtil_CountWords(TChA ChA, TStrHash< TInt > const & StopWordH) -> int
Parameters:
ChA: TChA const &
StopWordH: TStrHash< TInt > const &
"""
return _snap.TStrUtil_CountWords(*args)
def TStrUtil_SplitWords(*args):
"""
SplitWords(TChA ChA, TVec< char * > & WrdV, bool const & SplitOnWs=True) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
SplitOnWs: bool const &
TStrUtil_SplitWords(TChA ChA, TVec< char * > & WrdV) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
"""
return _snap.TStrUtil_SplitWords(*args)
def TStrUtil_SplitOnCh(*args):
"""
SplitOnCh(TChA ChA, TVec< char * > & WrdV, char const & Ch, bool const & SkipEmpty=False) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
Ch: char const &
SkipEmpty: bool const &
TStrUtil_SplitOnCh(TChA ChA, TVec< char * > & WrdV, char const & Ch) -> int
Parameters:
ChA: TChA &
WrdV: TVec< char * > &
Ch: char const &
"""
return _snap.TStrUtil_SplitOnCh(*args)
def TStrUtil_SplitLines(*args):
"""
SplitLines(TChA ChA, TVec< char * > & LineV, bool const & SkipEmpty=False) -> int
Parameters:
ChA: TChA &
LineV: TVec< char * > &
SkipEmpty: bool const &
TStrUtil_SplitLines(TChA ChA, TVec< char * > & LineV) -> int
Parameters:
ChA: TChA &
LineV: TVec< char * > &
"""
return _snap.TStrUtil_SplitLines(*args)
def TStrUtil_SplitSentences(*args):
"""
TStrUtil_SplitSentences(TChA ChA, TVec< char * > & SentenceV) -> int
Parameters:
ChA: TChA &
SentenceV: TVec< char * > &
"""
return _snap.TStrUtil_SplitSentences(*args)
def TStrUtil_RemoveHtmlTags(*args):
"""
TStrUtil_RemoveHtmlTags(TChA HtmlStr, TChA TextStr)
Parameters:
HtmlStr: TChA const &
TextStr: TChA &
"""
return _snap.TStrUtil_RemoveHtmlTags(*args)
def TStrUtil_IsLatinStr(*args):
"""
TStrUtil_IsLatinStr(TChA Str, double const & MinAlFrac) -> bool
Parameters:
Str: TChA const &
MinAlFrac: double const &
"""
return _snap.TStrUtil_IsLatinStr(*args)
def TStrUtil_GetWIdV(*args):
"""
TStrUtil_GetWIdV(TStrHash< TInt > const & StrH, char const * CStr, TIntV WIdV)
Parameters:
StrH: TStrHash< TInt > const &
CStr: char const *
WIdV: TIntV &
"""
return _snap.TStrUtil_GetWIdV(*args)
def TStrUtil_GetAddWIdV(*args):
"""
TStrUtil_GetAddWIdV(TStrHash< TInt > & StrH, char const * CStr, TIntV WIdV)
Parameters:
StrH: TStrHash< TInt > &
CStr: char const *
WIdV: TIntV &
"""
return _snap.TStrUtil_GetAddWIdV(*args)
def TStrUtil_GetTmFromStr(*args):
"""
TStrUtil_GetTmFromStr(char const * TmStr, TSecTm & Tm) -> bool
Parameters:
TmStr: char const *
Tm: TSecTm &
"""
return _snap.TStrUtil_GetTmFromStr(*args)
def TStrUtil_GetStdName(*args):
"""
TStrUtil_GetStdName(TStr AuthorName) -> TStr
Parameters:
AuthorName: TStr
"""
return _snap.TStrUtil_GetStdName(*args)
def TStrUtil_GetStdNameV(*args):
"""
TStrUtil_GetStdNameV(TStr AuthorNames, TStrV StdNameV)
Parameters:
AuthorNames: TStr
StdNameV: TStrV &
"""
return _snap.TStrUtil_GetStdNameV(*args)
class TRnd(object):
"""Proxy of C++ TRnd class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TRnd self, int const & _Seed=1, int const & Steps=0) -> TRnd
Parameters:
_Seed: int const &
Steps: int const &
__init__(TRnd self, int const & _Seed=1) -> TRnd
Parameters:
_Seed: int const &
__init__(TRnd self) -> TRnd
__init__(TRnd self, TSIn SIn) -> TRnd
Parameters:
SIn: TSIn &
"""
_snap.TRnd_swiginit(self,_snap.new_TRnd(*args))
def Save(self, *args):
"""
Save(TRnd self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TRnd_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TRnd self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TRnd_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TRnd self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TRnd_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TRnd self, TRnd arg2) -> bool
Parameters:
arg2: TRnd const &
"""
return _snap.TRnd___eq__(self, *args)
def GetUniDev(self):
"""
GetUniDev(TRnd self) -> double
Parameters:
self: TRnd *
"""
return _snap.TRnd_GetUniDev(self)
def GetUniDevInt(self, *args):
"""
GetUniDevInt(TRnd self, int const & Range=0) -> int
Parameters:
Range: int const &
GetUniDevInt(TRnd self) -> int
GetUniDevInt(TRnd self, int const & MnVal, int const & MxVal) -> int
Parameters:
MnVal: int const &
MxVal: int const &
"""
return _snap.TRnd_GetUniDevInt(self, *args)
def GetUniDevUInt(self, Range=0):
"""
GetUniDevUInt(TRnd self, uint const & Range=0) -> uint
Parameters:
Range: uint const &
GetUniDevUInt(TRnd self) -> uint
Parameters:
self: TRnd *
"""
return _snap.TRnd_GetUniDevUInt(self, Range)
def GetUniDevInt64(self, Range=0):
"""
GetUniDevInt64(TRnd self, int64 const & Range=0) -> int64
Parameters:
Range: int64 const &
GetUniDevInt64(TRnd self) -> int64
Parameters:
self: TRnd *
"""
return _snap.TRnd_GetUniDevInt64(self, Range)
def GetUniDevUInt64(self, Range=0):
"""
GetUniDevUInt64(TRnd self, uint64 const & Range=0) -> uint64
Parameters:
Range: uint64 const &
GetUniDevUInt64(TRnd self) -> uint64
Parameters:
self: TRnd *
"""
return _snap.TRnd_GetUniDevUInt64(self, Range)
def GetNrmDev(self, *args):
"""
GetNrmDev(TRnd self) -> double
GetNrmDev(TRnd self, double const & Mean, double const & SDev, double const & Mn, double const & Mx) -> double
Parameters:
Mean: double const &
SDev: double const &
Mn: double const &
Mx: double const &
"""
return _snap.TRnd_GetNrmDev(self, *args)
def GetExpDev(self, *args):
"""
GetExpDev(TRnd self) -> double
GetExpDev(TRnd self, double const & Lambda) -> double
Parameters:
Lambda: double const &
"""
return _snap.TRnd_GetExpDev(self, *args)
def GetGammaDev(self, *args):
"""
GetGammaDev(TRnd self, int const & Order) -> double
Parameters:
Order: int const &
"""
return _snap.TRnd_GetGammaDev(self, *args)
def GetPoissonDev(self, *args):
"""
GetPoissonDev(TRnd self, double const & Mean) -> double
Parameters:
Mean: double const &
"""
return _snap.TRnd_GetPoissonDev(self, *args)
def GetBinomialDev(self, *args):
"""
GetBinomialDev(TRnd self, double const & Prb, int const & Trials) -> double
Parameters:
Prb: double const &
Trials: int const &
"""
return _snap.TRnd_GetBinomialDev(self, *args)
def GetGeoDev(self, *args):
"""
GetGeoDev(TRnd self, double const & Prb) -> int
Parameters:
Prb: double const &
"""
return _snap.TRnd_GetGeoDev(self, *args)
def GetPowerDev(self, *args):
"""
GetPowerDev(TRnd self, double const & AlphaSlope) -> double
Parameters:
AlphaSlope: double const &
"""
return _snap.TRnd_GetPowerDev(self, *args)
def GetRayleigh(self, *args):
"""
GetRayleigh(TRnd self, double const & Sigma) -> double
Parameters:
Sigma: double const &
"""
return _snap.TRnd_GetRayleigh(self, *args)
def GetWeibull(self, *args):
"""
GetWeibull(TRnd self, double const & K, double const & Lambda) -> double
Parameters:
K: double const &
Lambda: double const &
"""
return _snap.TRnd_GetWeibull(self, *args)
def PutSeed(self, *args):
"""
PutSeed(TRnd self, int const & _Seed)
Parameters:
_Seed: int const &
"""
return _snap.TRnd_PutSeed(self, *args)
def GetSeed(self):
"""
GetSeed(TRnd self) -> int
Parameters:
self: TRnd const *
"""
return _snap.TRnd_GetSeed(self)
def Randomize(self):
"""
Randomize(TRnd self)
Parameters:
self: TRnd *
"""
return _snap.TRnd_Randomize(self)
def Move(self, *args):
"""
Move(TRnd self, int const & Steps)
Parameters:
Steps: int const &
"""
return _snap.TRnd_Move(self, *args)
def Check(self):
"""
Check(TRnd self) -> bool
Parameters:
self: TRnd *
"""
return _snap.TRnd_Check(self)
def GetUniDevStep(*args):
"""
GetUniDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetUniDevStep(*args)
GetUniDevStep = staticmethod(GetUniDevStep)
def GetNrmDevStep(*args):
"""
GetNrmDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetNrmDevStep(*args)
GetNrmDevStep = staticmethod(GetNrmDevStep)
def GetExpDevStep(*args):
"""
GetExpDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetExpDevStep(*args)
GetExpDevStep = staticmethod(GetExpDevStep)
def LoadTxt(*args):
"""
LoadTxt(TILx & Lx) -> TRnd
Parameters:
Lx: TILx &
"""
return _snap.TRnd_LoadTxt(*args)
LoadTxt = staticmethod(LoadTxt)
def SaveTxt(self, *args):
"""
SaveTxt(TRnd self, TOLx & Lx)
Parameters:
Lx: TOLx &
"""
return _snap.TRnd_SaveTxt(self, *args)
__swig_destroy__ = _snap.delete_TRnd
TRnd.Save = new_instancemethod(_snap.TRnd_Save,None,TRnd)
TRnd.LoadXml = new_instancemethod(_snap.TRnd_LoadXml,None,TRnd)
TRnd.SaveXml = new_instancemethod(_snap.TRnd_SaveXml,None,TRnd)
TRnd.__eq__ = new_instancemethod(_snap.TRnd___eq__,None,TRnd)
TRnd.GetUniDev = new_instancemethod(_snap.TRnd_GetUniDev,None,TRnd)
TRnd.GetUniDevInt = new_instancemethod(_snap.TRnd_GetUniDevInt,None,TRnd)
TRnd.GetUniDevUInt = new_instancemethod(_snap.TRnd_GetUniDevUInt,None,TRnd)
TRnd.GetUniDevInt64 = new_instancemethod(_snap.TRnd_GetUniDevInt64,None,TRnd)
TRnd.GetUniDevUInt64 = new_instancemethod(_snap.TRnd_GetUniDevUInt64,None,TRnd)
TRnd.GetNrmDev = new_instancemethod(_snap.TRnd_GetNrmDev,None,TRnd)
TRnd.GetExpDev = new_instancemethod(_snap.TRnd_GetExpDev,None,TRnd)
TRnd.GetGammaDev = new_instancemethod(_snap.TRnd_GetGammaDev,None,TRnd)
TRnd.GetPoissonDev = new_instancemethod(_snap.TRnd_GetPoissonDev,None,TRnd)
TRnd.GetBinomialDev = new_instancemethod(_snap.TRnd_GetBinomialDev,None,TRnd)
TRnd.GetGeoDev = new_instancemethod(_snap.TRnd_GetGeoDev,None,TRnd)
TRnd.GetPowerDev = new_instancemethod(_snap.TRnd_GetPowerDev,None,TRnd)
TRnd.GetRayleigh = new_instancemethod(_snap.TRnd_GetRayleigh,None,TRnd)
TRnd.GetWeibull = new_instancemethod(_snap.TRnd_GetWeibull,None,TRnd)
TRnd.PutSeed = new_instancemethod(_snap.TRnd_PutSeed,None,TRnd)
TRnd.GetSeed = new_instancemethod(_snap.TRnd_GetSeed,None,TRnd)
TRnd.Randomize = new_instancemethod(_snap.TRnd_Randomize,None,TRnd)
TRnd.Move = new_instancemethod(_snap.TRnd_Move,None,TRnd)
TRnd.Check = new_instancemethod(_snap.TRnd_Check,None,TRnd)
TRnd.SaveTxt = new_instancemethod(_snap.TRnd_SaveTxt,None,TRnd)
TRnd_swigregister = _snap.TRnd_swigregister
TRnd_swigregister(TRnd)
TRnd.RndSeed = _snap.cvar.TRnd_RndSeed
def TRnd_GetUniDevStep(*args):
"""
TRnd_GetUniDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetUniDevStep(*args)
def TRnd_GetNrmDevStep(*args):
"""
TRnd_GetNrmDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetNrmDevStep(*args)
def TRnd_GetExpDevStep(*args):
"""
TRnd_GetExpDevStep(int const & Seed, int const & Steps) -> double
Parameters:
Seed: int const &
Steps: int const &
"""
return _snap.TRnd_GetExpDevStep(*args)
def TRnd_LoadTxt(*args):
"""
TRnd_LoadTxt(TILx & Lx) -> TRnd
Parameters:
Lx: TILx &
"""
return _snap.TRnd_LoadTxt(*args)
class TMem(object):
"""Proxy of C++ TMem class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def New(*args):
"""
New(int const & MxBfL=0) -> PMem
Parameters:
MxBfL: int const &
New() -> PMem
New(void const * Bf, int const & BfL) -> PMem
Parameters:
Bf: void const *
BfL: int const &
New(TMem Mem) -> PMem
Parameters:
Mem: TMem const &
New(PMem const & Mem) -> PMem
Parameters:
Mem: PMem const &
New(TStr Str) -> PMem
Parameters:
Str: TStr const &
"""
return _snap.TMem_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TMem
def __init__(self, *args):
"""
__init__(TMem self, int const & _MxBfL=0) -> TMem
Parameters:
_MxBfL: int const &
__init__(TMem self) -> TMem
__init__(TMem self, void const * _Bf, int const & _BfL) -> TMem
Parameters:
_Bf: void const *
_BfL: int const &
__init__(TMem self, TMem Mem) -> TMem
Parameters:
Mem: TMem const &
__init__(TMem self, TStr Str) -> TMem
Parameters:
Str: TStr const &
__init__(TMem self, TSIn SIn) -> TMem
Parameters:
SIn: TSIn &
"""
_snap.TMem_swiginit(self,_snap.new_TMem(*args))
def Save(self, *args):
"""
Save(TMem self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TMem_Save(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TMem self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TMem_SaveXml(self, *args)
def __call__(self):
"""
__call__(TMem self) -> char *
Parameters:
self: TMem const *
"""
return _snap.TMem___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TMem self, char const & Ch) -> TMem
Parameters:
Ch: char const &
__iadd__(TMem self, TMem Mem) -> TMem
Parameters:
Mem: TMem const &
__iadd__(TMem self, TStr Str) -> TMem
Parameters:
Str: TStr const &
__iadd__(TMem self, PSIn const & SIn) -> TMem
Parameters:
SIn: PSIn const &
"""
return _snap.TMem___iadd__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TMem self) -> int
Parameters:
self: TMem const *
"""
return _snap.TMem_GetMemUsed(self)
def Gen(self, *args):
"""
Gen(TMem self, int const & _BfL)
Parameters:
_BfL: int const &
"""
return _snap.TMem_Gen(self, *args)
def GenZeros(self, *args):
"""
GenZeros(TMem self, int const & _BfL)
Parameters:
_BfL: int const &
"""
return _snap.TMem_GenZeros(self, *args)
def Reserve(self, *args):
"""
Reserve(TMem self, int const & _MxBfL, bool const & DoClr=True)
Parameters:
_MxBfL: int const &
DoClr: bool const &
Reserve(TMem self, int const & _MxBfL)
Parameters:
_MxBfL: int const &
"""
return _snap.TMem_Reserve(self, *args)
def Del(self, *args):
"""
Del(TMem self, int const & BChN, int const & EChN)
Parameters:
BChN: int const &
EChN: int const &
"""
return _snap.TMem_Del(self, *args)
def Clr(self, DoDel=True):
"""
Clr(TMem self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TMem self)
Parameters:
self: TMem *
"""
return _snap.TMem_Clr(self, DoDel)
def Len(self):
"""
Len(TMem self) -> int
Parameters:
self: TMem const *
"""
return _snap.TMem_Len(self)
def Empty(self):
"""
Empty(TMem self) -> bool
Parameters:
self: TMem const *
"""
return _snap.TMem_Empty(self)
def Trunc(self, *args):
"""
Trunc(TMem self, int const & _BfL)
Parameters:
_BfL: int const &
"""
return _snap.TMem_Trunc(self, *args)
def Push(self, *args):
"""
Push(TMem self, char const & Ch)
Parameters:
Ch: char const &
"""
return _snap.TMem_Push(self, *args)
def Pop(self):
"""
Pop(TMem self) -> char
Parameters:
self: TMem *
"""
return _snap.TMem_Pop(self)
def DoFitStr(self, *args):
"""
DoFitStr(TMem self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TMem_DoFitStr(self, *args)
def AddBf(self, *args):
"""
AddBf(TMem self, void const * Bf, int const & BfL)
Parameters:
Bf: void const *
BfL: int const &
"""
return _snap.TMem_AddBf(self, *args)
def GetBf(self):
"""
GetBf(TMem self) -> char *
Parameters:
self: TMem const *
"""
return _snap.TMem_GetBf(self)
def GetAsStr(self, NewNullCh='\0'):
"""
GetAsStr(TMem self, char const & NewNullCh='\0') -> TStr
Parameters:
NewNullCh: char const &
GetAsStr(TMem self) -> TStr
Parameters:
self: TMem const *
"""
return _snap.TMem_GetAsStr(self, NewNullCh)
def GetSIn(self):
"""
GetSIn(TMem self) -> PSIn
Parameters:
self: TMem const *
"""
return _snap.TMem_GetSIn(self)
def LoadMem(*args):
"""
LoadMem(PSIn const & SIn, TMem Mem)
Parameters:
SIn: PSIn const &
Mem: TMem &
LoadMem(PSIn const & SIn, PMem const & Mem)
Parameters:
SIn: PSIn const &
Mem: PMem const &
"""
return _snap.TMem_LoadMem(*args)
LoadMem = staticmethod(LoadMem)
def SaveMem(self, *args):
"""
SaveMem(TMem self, PSOut const & SOut)
Parameters:
SOut: PSOut const &
"""
return _snap.TMem_SaveMem(self, *args)
TMem.Save = new_instancemethod(_snap.TMem_Save,None,TMem)
TMem.SaveXml = new_instancemethod(_snap.TMem_SaveXml,None,TMem)
TMem.__call__ = new_instancemethod(_snap.TMem___call__,None,TMem)
TMem.__iadd__ = new_instancemethod(_snap.TMem___iadd__,None,TMem)
TMem.GetMemUsed = new_instancemethod(_snap.TMem_GetMemUsed,None,TMem)
TMem.Gen = new_instancemethod(_snap.TMem_Gen,None,TMem)
TMem.GenZeros = new_instancemethod(_snap.TMem_GenZeros,None,TMem)
TMem.Reserve = new_instancemethod(_snap.TMem_Reserve,None,TMem)
TMem.Del = new_instancemethod(_snap.TMem_Del,None,TMem)
TMem.Clr = new_instancemethod(_snap.TMem_Clr,None,TMem)
TMem.Len = new_instancemethod(_snap.TMem_Len,None,TMem)
TMem.Empty = new_instancemethod(_snap.TMem_Empty,None,TMem)
TMem.Trunc = new_instancemethod(_snap.TMem_Trunc,None,TMem)
TMem.Push = new_instancemethod(_snap.TMem_Push,None,TMem)
TMem.Pop = new_instancemethod(_snap.TMem_Pop,None,TMem)
TMem.DoFitStr = new_instancemethod(_snap.TMem_DoFitStr,None,TMem)
TMem.AddBf = new_instancemethod(_snap.TMem_AddBf,None,TMem)
TMem.GetBf = new_instancemethod(_snap.TMem_GetBf,None,TMem)
TMem.GetAsStr = new_instancemethod(_snap.TMem_GetAsStr,None,TMem)
TMem.GetSIn = new_instancemethod(_snap.TMem_GetSIn,None,TMem)
TMem.SaveMem = new_instancemethod(_snap.TMem_SaveMem,None,TMem)
TMem_swigregister = _snap.TMem_swigregister
TMem_swigregister(TMem)
def TMem_New(*args):
"""
New(int const & MxBfL=0) -> PMem
Parameters:
MxBfL: int const &
New() -> PMem
New(void const * Bf, int const & BfL) -> PMem
Parameters:
Bf: void const *
BfL: int const &
New(TMem Mem) -> PMem
Parameters:
Mem: TMem const &
New(PMem const & Mem) -> PMem
Parameters:
Mem: PMem const &
TMem_New(TStr Str) -> PMem
Parameters:
Str: TStr const &
"""
return _snap.TMem_New(*args)
def TMem_LoadMem(*args):
"""
LoadMem(PSIn const & SIn, TMem Mem)
Parameters:
SIn: PSIn const &
Mem: TMem &
TMem_LoadMem(PSIn const & SIn, PMem const & Mem)
Parameters:
SIn: PSIn const &
Mem: PMem const &
"""
return _snap.TMem_LoadMem(*args)
class TMemIn(TSIn):
"""Proxy of C++ TMemIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TMemIn self, TMem _Mem, int const & _BfC=0) -> TMemIn
Parameters:
_Mem: TMem const &
_BfC: int const &
__init__(TMemIn self, TMem _Mem) -> TMemIn
Parameters:
_Mem: TMem const &
"""
_snap.TMemIn_swiginit(self,_snap.new_TMemIn(*args))
def New(*args):
"""
New(TMem Mem) -> PSIn
Parameters:
Mem: TMem const &
New(PMem const & Mem) -> PSIn
Parameters:
Mem: PMem const &
"""
return _snap.TMemIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TMemIn
TMemIn_swigregister = _snap.TMemIn_swigregister
TMemIn_swigregister(TMemIn)
def TMemIn_New(*args):
"""
New(TMem Mem) -> PSIn
Parameters:
Mem: TMem const &
TMemIn_New(PMem const & Mem) -> PSIn
Parameters:
Mem: PMem const &
"""
return _snap.TMemIn_New(*args)
class TMemOut(TSOut):
"""Proxy of C++ TMemOut class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TMemOut self, PMem const & _Mem) -> TMemOut
Parameters:
_Mem: PMem const &
"""
_snap.TMemOut_swiginit(self,_snap.new_TMemOut(*args))
def New(*args):
"""
New(PMem const & Mem) -> PSOut
Parameters:
Mem: PMem const &
"""
return _snap.TMemOut_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TMemOut
TMemOut_swigregister = _snap.TMemOut_swigregister
TMemOut_swigregister(TMemOut)
def TMemOut_New(*args):
"""
TMemOut_New(PMem const & Mem) -> PSOut
Parameters:
Mem: PMem const &
"""
return _snap.TMemOut_New(*args)
class TChA(object):
"""Proxy of C++ TChA class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TChA
def __init__(self, *args):
"""
__init__(TChA self, int const & _MxBfL=256) -> TChA
Parameters:
_MxBfL: int const &
__init__(TChA self) -> TChA
__init__(TChA self, char const * CStr) -> TChA
Parameters:
CStr: char const *
__init__(TChA self, char const * CStr, int const & StrLen) -> TChA
Parameters:
CStr: char const *
StrLen: int const &
__init__(TChA self, TChA ChA) -> TChA
Parameters:
ChA: TChA const &
__init__(TChA self, TStr Str) -> TChA
Parameters:
Str: TStr const &
__init__(TChA self, TMem Mem) -> TChA
Parameters:
Mem: TMem const &
__init__(TChA self, TSIn SIn) -> TChA
Parameters:
SIn: TSIn &
"""
_snap.TChA_swiginit(self,_snap.new_TChA(*args))
def Load(self, *args):
"""
Load(TChA self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TChA_Load(self, *args)
def Save(self, *args):
"""
Save(TChA self, TSOut SOut, bool const & SaveCompact=True)
Parameters:
SOut: TSOut &
SaveCompact: bool const &
Save(TChA self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TChA_Save(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TChA self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TChA_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TChA self, TChA ChA) -> bool
Parameters:
ChA: TChA const &
__eq__(TChA self, char const * _CStr) -> bool
Parameters:
_CStr: char const *
__eq__(TChA self, char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TChA___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TChA self, TChA ChA) -> bool
Parameters:
ChA: TChA const &
__ne__(TChA self, char const * _CStr) -> bool
Parameters:
_CStr: char const *
__ne__(TChA self, char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TChA___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TChA self, TChA ChA) -> bool
Parameters:
ChA: TChA const &
"""
return _snap.TChA___lt__(self, *args)
def __iadd__(self, *args):
"""
__iadd__(TChA self, TMem Mem) -> TChA
Parameters:
Mem: TMem const &
__iadd__(TChA self, TChA ChA) -> TChA
Parameters:
ChA: TChA const &
__iadd__(TChA self, TStr Str) -> TChA
Parameters:
Str: TStr const &
__iadd__(TChA self, char const * CStr) -> TChA
Parameters:
CStr: char const *
__iadd__(TChA self, char const & Ch) -> TChA
Parameters:
Ch: char const &
"""
return _snap.TChA___iadd__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TChA self) -> int
Parameters:
self: TChA const *
"""
return _snap.TChA_GetMemUsed(self)
def __call__(self, *args):
"""
__call__(TChA self) -> char
__call__(TChA self) -> char const *
Parameters:
self: TChA const *
"""
return _snap.TChA___call__(self, *args)
def CStr(self, *args):
"""
CStr(TChA self) -> char
CStr(TChA self) -> char const *
Parameters:
self: TChA const *
"""
return _snap.TChA_CStr(self, *args)
def Clr(self):
"""
Clr(TChA self)
Parameters:
self: TChA *
"""
return _snap.TChA_Clr(self)
def Len(self):
"""
Len(TChA self) -> int
Parameters:
self: TChA const *
"""
return _snap.TChA_Len(self)
def Empty(self):
"""
Empty(TChA self) -> bool
Parameters:
self: TChA const *
"""
return _snap.TChA_Empty(self)
def Ins(self, *args):
"""
Ins(TChA self, int const & BChN, char const * CStr)
Parameters:
BChN: int const &
CStr: char const *
"""
return _snap.TChA_Ins(self, *args)
def Del(self, *args):
"""
Del(TChA self, int const & ChN)
Parameters:
ChN: int const &
"""
return _snap.TChA_Del(self, *args)
def DelLastCh(self):
"""
DelLastCh(TChA self)
Parameters:
self: TChA *
"""
return _snap.TChA_DelLastCh(self)
def Push(self, *args):
"""
Push(TChA self, char const & Ch)
Parameters:
Ch: char const &
"""
return _snap.TChA_Push(self, *args)
def Pop(self):
"""
Pop(TChA self) -> char
Parameters:
self: TChA *
"""
return _snap.TChA_Pop(self)
def Trunc(self, *args):
"""
Trunc(TChA self)
Trunc(TChA self, int const & _BfL)
Parameters:
_BfL: int const &
"""
return _snap.TChA_Trunc(self, *args)
def Reverse(self):
"""
Reverse(TChA self)
Parameters:
self: TChA *
"""
return _snap.TChA_Reverse(self)
def AddCh(self, *args):
"""
AddCh(TChA self, char const & Ch, int const & MxLen=-1)
Parameters:
Ch: char const &
MxLen: int const &
AddCh(TChA self, char const & Ch)
Parameters:
Ch: char const &
"""
return _snap.TChA_AddCh(self, *args)
def AddChTo(self, *args):
"""
AddChTo(TChA self, char const & Ch, int const & ToChN)
Parameters:
Ch: char const &
ToChN: int const &
"""
return _snap.TChA_AddChTo(self, *args)
def AddBf(self, *args):
"""
AddBf(TChA self, char * NewBf, int const & BfS)
Parameters:
NewBf: char *
BfS: int const &
"""
return _snap.TChA_AddBf(self, *args)
def PutCh(self, *args):
"""
PutCh(TChA self, int const & ChN, char const & Ch)
Parameters:
ChN: int const &
Ch: char const &
"""
return _snap.TChA_PutCh(self, *args)
def GetCh(self, *args):
"""
GetCh(TChA self, int const & ChN) -> char
Parameters:
ChN: int const &
"""
return _snap.TChA_GetCh(self, *args)
def LastCh(self):
"""
LastCh(TChA self) -> char
Parameters:
self: TChA const *
"""
return _snap.TChA_LastCh(self)
def LastLastCh(self):
"""
LastLastCh(TChA self) -> char
Parameters:
self: TChA const *
"""
return _snap.TChA_LastLastCh(self)
def GetSubStr(self, *args):
"""
GetSubStr(TChA self, int const & BChN, int const & EChN) -> TChA
Parameters:
BChN: int const &
EChN: int const &
"""
return _snap.TChA_GetSubStr(self, *args)
def CountCh(self, *args):
"""
CountCh(TChA self, char const & Ch, int const & BChN=0) -> int
Parameters:
Ch: char const &
BChN: int const &
CountCh(TChA self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TChA_CountCh(self, *args)
def SearchCh(self, *args):
"""
SearchCh(TChA self, char const & Ch, int const & BChN=0) -> int
Parameters:
Ch: char const &
BChN: int const &
SearchCh(TChA self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TChA_SearchCh(self, *args)
def SearchChBack(self, *args):
"""
SearchChBack(TChA self, char const & Ch, int BChN=-1) -> int
Parameters:
Ch: char const &
BChN: int
SearchChBack(TChA self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TChA_SearchChBack(self, *args)
def SearchStr(self, *args):
"""
SearchStr(TChA self, TChA Str, int const & BChN=0) -> int
Parameters:
Str: TChA const &
BChN: int const &
SearchStr(TChA self, TChA Str) -> int
Parameters:
Str: TChA const &
SearchStr(TChA self, TStr Str, int const & BChN=0) -> int
Parameters:
Str: TStr const &
BChN: int const &
SearchStr(TChA self, TStr Str) -> int
Parameters:
Str: TStr const &
SearchStr(TChA self, char const * CStr, int const & BChN=0) -> int
Parameters:
CStr: char const *
BChN: int const &
SearchStr(TChA self, char const * CStr) -> int
Parameters:
CStr: char const *
"""
return _snap.TChA_SearchStr(self, *args)
def IsStrIn(self, *args):
"""
IsStrIn(TChA self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TChA_IsStrIn(self, *args)
def IsPrefix(self, *args):
"""
IsPrefix(TChA self, char const * CStr, int const & BChN=0) -> bool
Parameters:
CStr: char const *
BChN: int const &
IsPrefix(TChA self, char const * CStr) -> bool
Parameters:
CStr: char const *
IsPrefix(TChA self, TStr Str) -> bool
Parameters:
Str: TStr const &
IsPrefix(TChA self, TChA Str) -> bool
Parameters:
Str: TChA const &
"""
return _snap.TChA_IsPrefix(self, *args)
def IsSuffix(self, *args):
"""
IsSuffix(TChA self, char const * CStr) -> bool
Parameters:
CStr: char const *
IsSuffix(TChA self, TStr Str) -> bool
Parameters:
Str: TStr const &
IsSuffix(TChA self, TChA Str) -> bool
Parameters:
Str: TChA const &
"""
return _snap.TChA_IsSuffix(self, *args)
def IsChIn(self, *args):
"""
IsChIn(TChA self, char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TChA_IsChIn(self, *args)
def ChangeCh(self, *args):
"""
ChangeCh(TChA self, char const & SrcCh, char const & DstCh)
Parameters:
SrcCh: char const &
DstCh: char const &
"""
return _snap.TChA_ChangeCh(self, *args)
def ToUc(self):
"""
ToUc(TChA self) -> TChA
Parameters:
self: TChA *
"""
return _snap.TChA_ToUc(self)
def ToLc(self):
"""
ToLc(TChA self) -> TChA
Parameters:
self: TChA *
"""
return _snap.TChA_ToLc(self)
def ToTrunc(self):
"""
ToTrunc(TChA self) -> TChA
Parameters:
self: TChA *
"""
return _snap.TChA_ToTrunc(self)
def CompressWs(self):
"""
CompressWs(TChA self)
Parameters:
self: TChA *
"""
return _snap.TChA_CompressWs(self)
def Swap(self, *args):
"""
Swap(TChA self, int const & ChN1, int const & ChN2)
Parameters:
ChN1: int const &
ChN2: int const &
Swap(TChA self, TChA ChA)
Parameters:
ChA: TChA &
"""
return _snap.TChA_Swap(self, *args)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TChA self) -> int
Parameters:
self: TChA const *
"""
return _snap.TChA_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TChA self) -> int
Parameters:
self: TChA const *
"""
return _snap.TChA_GetSecHashCd(self)
def LoadTxt(*args):
"""
LoadTxt(PSIn const & SIn, TChA ChA)
Parameters:
SIn: PSIn const &
ChA: TChA &
"""
return _snap.TChA_LoadTxt(*args)
LoadTxt = staticmethod(LoadTxt)
def SaveTxt(self, *args):
"""
SaveTxt(TChA self, PSOut const & SOut)
Parameters:
SOut: PSOut const &
"""
return _snap.TChA_SaveTxt(self, *args)
TChA.Load = new_instancemethod(_snap.TChA_Load,None,TChA)
TChA.Save = new_instancemethod(_snap.TChA_Save,None,TChA)
TChA.SaveXml = new_instancemethod(_snap.TChA_SaveXml,None,TChA)
TChA.__eq__ = new_instancemethod(_snap.TChA___eq__,None,TChA)
TChA.__ne__ = new_instancemethod(_snap.TChA___ne__,None,TChA)
TChA.__lt__ = new_instancemethod(_snap.TChA___lt__,None,TChA)
TChA.__iadd__ = new_instancemethod(_snap.TChA___iadd__,None,TChA)
TChA.GetMemUsed = new_instancemethod(_snap.TChA_GetMemUsed,None,TChA)
TChA.__call__ = new_instancemethod(_snap.TChA___call__,None,TChA)
TChA.CStr = new_instancemethod(_snap.TChA_CStr,None,TChA)
TChA.Clr = new_instancemethod(_snap.TChA_Clr,None,TChA)
TChA.Len = new_instancemethod(_snap.TChA_Len,None,TChA)
TChA.Empty = new_instancemethod(_snap.TChA_Empty,None,TChA)
TChA.Ins = new_instancemethod(_snap.TChA_Ins,None,TChA)
TChA.Del = new_instancemethod(_snap.TChA_Del,None,TChA)
TChA.DelLastCh = new_instancemethod(_snap.TChA_DelLastCh,None,TChA)
TChA.Push = new_instancemethod(_snap.TChA_Push,None,TChA)
TChA.Pop = new_instancemethod(_snap.TChA_Pop,None,TChA)
TChA.Trunc = new_instancemethod(_snap.TChA_Trunc,None,TChA)
TChA.Reverse = new_instancemethod(_snap.TChA_Reverse,None,TChA)
TChA.AddCh = new_instancemethod(_snap.TChA_AddCh,None,TChA)
TChA.AddChTo = new_instancemethod(_snap.TChA_AddChTo,None,TChA)
TChA.AddBf = new_instancemethod(_snap.TChA_AddBf,None,TChA)
TChA.PutCh = new_instancemethod(_snap.TChA_PutCh,None,TChA)
TChA.GetCh = new_instancemethod(_snap.TChA_GetCh,None,TChA)
TChA.LastCh = new_instancemethod(_snap.TChA_LastCh,None,TChA)
TChA.LastLastCh = new_instancemethod(_snap.TChA_LastLastCh,None,TChA)
TChA.GetSubStr = new_instancemethod(_snap.TChA_GetSubStr,None,TChA)
TChA.CountCh = new_instancemethod(_snap.TChA_CountCh,None,TChA)
TChA.SearchCh = new_instancemethod(_snap.TChA_SearchCh,None,TChA)
TChA.SearchChBack = new_instancemethod(_snap.TChA_SearchChBack,None,TChA)
TChA.SearchStr = new_instancemethod(_snap.TChA_SearchStr,None,TChA)
TChA.IsStrIn = new_instancemethod(_snap.TChA_IsStrIn,None,TChA)
TChA.IsPrefix = new_instancemethod(_snap.TChA_IsPrefix,None,TChA)
TChA.IsSuffix = new_instancemethod(_snap.TChA_IsSuffix,None,TChA)
TChA.IsChIn = new_instancemethod(_snap.TChA_IsChIn,None,TChA)
TChA.ChangeCh = new_instancemethod(_snap.TChA_ChangeCh,None,TChA)
TChA.ToUc = new_instancemethod(_snap.TChA_ToUc,None,TChA)
TChA.ToLc = new_instancemethod(_snap.TChA_ToLc,None,TChA)
TChA.ToTrunc = new_instancemethod(_snap.TChA_ToTrunc,None,TChA)
TChA.CompressWs = new_instancemethod(_snap.TChA_CompressWs,None,TChA)
TChA.Swap = new_instancemethod(_snap.TChA_Swap,None,TChA)
TChA.GetPrimHashCd = new_instancemethod(_snap.TChA_GetPrimHashCd,None,TChA)
TChA.GetSecHashCd = new_instancemethod(_snap.TChA_GetSecHashCd,None,TChA)
TChA.SaveTxt = new_instancemethod(_snap.TChA_SaveTxt,None,TChA)
TChA_swigregister = _snap.TChA_swigregister
TChA_swigregister(TChA)
def TChA_LoadTxt(*args):
"""
TChA_LoadTxt(PSIn const & SIn, TChA ChA)
Parameters:
SIn: PSIn const &
ChA: TChA &
"""
return _snap.TChA_LoadTxt(*args)
class TChAIn(TSIn):
"""Proxy of C++ TChAIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TChAIn self, TChA ChA, int const & _BfC=0) -> TChAIn
Parameters:
ChA: TChA const &
_BfC: int const &
__init__(TChAIn self, TChA ChA) -> TChAIn
Parameters:
ChA: TChA const &
"""
_snap.TChAIn_swiginit(self,_snap.new_TChAIn(*args))
def New(*args):
"""
New(TChA ChA) -> PSIn
Parameters:
ChA: TChA const &
"""
return _snap.TChAIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TChAIn
TChAIn_swigregister = _snap.TChAIn_swigregister
TChAIn_swigregister(TChAIn)
def TChAIn_New(*args):
"""
TChAIn_New(TChA ChA) -> PSIn
Parameters:
ChA: TChA const &
"""
return _snap.TChAIn_New(*args)
class TRStr(object):
"""Proxy of C++ TRStr class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Bf = _swig_property(_snap.TRStr_Bf_get, _snap.TRStr_Bf_set)
Refs = _swig_property(_snap.TRStr_Refs_get, _snap.TRStr_Refs_set)
__swig_destroy__ = _snap.delete_TRStr
def __init__(self, *args):
"""
__init__(TRStr self) -> TRStr
__init__(TRStr self, int const & Len) -> TRStr
Parameters:
Len: int const &
__init__(TRStr self, char const * CStr) -> TRStr
Parameters:
CStr: char const *
__init__(TRStr self, char const * CStr, int const & MxLen) -> TRStr
Parameters:
CStr: char const *
MxLen: int const &
__init__(TRStr self, char const * CStr1, char const * CStr2) -> TRStr
Parameters:
CStr1: char const *
CStr2: char const *
__init__(TRStr self, char const & Ch) -> TRStr
Parameters:
Ch: char const &
__init__(TRStr self, char const & Ch1, char const & Ch2) -> TRStr
Parameters:
Ch1: char const &
Ch2: char const &
__init__(TRStr self, TSIn SIn, bool const & IsSmall) -> TRStr
Parameters:
SIn: TSIn &
IsSmall: bool const &
"""
_snap.TRStr_swiginit(self,_snap.new_TRStr(*args))
def Save(self, *args):
"""
Save(TRStr self, TSOut SOut, bool const & IsSmall)
Parameters:
SOut: TSOut &
IsSmall: bool const &
"""
return _snap.TRStr_Save(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TRStr self) -> int
Parameters:
self: TRStr const *
"""
return _snap.TRStr_GetMemUsed(self)
def MkRef(self):
"""
MkRef(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_MkRef(self)
def UnRef(self):
"""
UnRef(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_UnRef(self)
def CStr(self, *args):
"""
CStr(TRStr self) -> char const
CStr(TRStr self) -> char *
Parameters:
self: TRStr *
"""
return _snap.TRStr_CStr(self, *args)
def Empty(self):
"""
Empty(TRStr self) -> bool
Parameters:
self: TRStr const *
"""
return _snap.TRStr_Empty(self)
def Len(self):
"""
Len(TRStr self) -> int
Parameters:
self: TRStr const *
"""
return _snap.TRStr_Len(self)
def PutCh(self, *args):
"""
PutCh(TRStr self, int const & ChN, char const & Ch)
Parameters:
ChN: int const &
Ch: char const &
"""
return _snap.TRStr_PutCh(self, *args)
def GetCh(self, *args):
"""
GetCh(TRStr self, int const & ChN) -> char
Parameters:
ChN: int const &
"""
return _snap.TRStr_GetCh(self, *args)
def IsUc(self):
"""
IsUc(TRStr self) -> bool
Parameters:
self: TRStr const *
"""
return _snap.TRStr_IsUc(self)
def ToUc(self):
"""
ToUc(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_ToUc(self)
def IsLc(self):
"""
IsLc(TRStr self) -> bool
Parameters:
self: TRStr const *
"""
return _snap.TRStr_IsLc(self)
def ToLc(self):
"""
ToLc(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_ToLc(self)
def ToCap(self):
"""
ToCap(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_ToCap(self)
def ConvUsFromYuAscii(self):
"""
ConvUsFromYuAscii(TRStr self)
Parameters:
self: TRStr *
"""
return _snap.TRStr_ConvUsFromYuAscii(self)
def CmpI(*args):
"""
CmpI(char const * CStr1, char const * CStr2) -> int
Parameters:
CStr1: char const *
CStr2: char const *
"""
return _snap.TRStr_CmpI(*args)
CmpI = staticmethod(CmpI)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TRStr self) -> int
Parameters:
self: TRStr const *
"""
return _snap.TRStr_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TRStr self) -> int
Parameters:
self: TRStr const *
"""
return _snap.TRStr_GetSecHashCd(self)
def GetNullRStr():
"""GetNullRStr() -> TRStr"""
return _snap.TRStr_GetNullRStr()
GetNullRStr = staticmethod(GetNullRStr)
TRStr.Save = new_instancemethod(_snap.TRStr_Save,None,TRStr)
TRStr.GetMemUsed = new_instancemethod(_snap.TRStr_GetMemUsed,None,TRStr)
TRStr.MkRef = new_instancemethod(_snap.TRStr_MkRef,None,TRStr)
TRStr.UnRef = new_instancemethod(_snap.TRStr_UnRef,None,TRStr)
TRStr.CStr = new_instancemethod(_snap.TRStr_CStr,None,TRStr)
TRStr.Empty = new_instancemethod(_snap.TRStr_Empty,None,TRStr)
TRStr.Len = new_instancemethod(_snap.TRStr_Len,None,TRStr)
TRStr.PutCh = new_instancemethod(_snap.TRStr_PutCh,None,TRStr)
TRStr.GetCh = new_instancemethod(_snap.TRStr_GetCh,None,TRStr)
TRStr.IsUc = new_instancemethod(_snap.TRStr_IsUc,None,TRStr)
TRStr.ToUc = new_instancemethod(_snap.TRStr_ToUc,None,TRStr)
TRStr.IsLc = new_instancemethod(_snap.TRStr_IsLc,None,TRStr)
TRStr.ToLc = new_instancemethod(_snap.TRStr_ToLc,None,TRStr)
TRStr.ToCap = new_instancemethod(_snap.TRStr_ToCap,None,TRStr)
TRStr.ConvUsFromYuAscii = new_instancemethod(_snap.TRStr_ConvUsFromYuAscii,None,TRStr)
TRStr.GetPrimHashCd = new_instancemethod(_snap.TRStr_GetPrimHashCd,None,TRStr)
TRStr.GetSecHashCd = new_instancemethod(_snap.TRStr_GetSecHashCd,None,TRStr)
TRStr_swigregister = _snap.TRStr_swigregister
TRStr_swigregister(TRStr)
def TRStr_CmpI(*args):
"""
TRStr_CmpI(char const * CStr1, char const * CStr2) -> int
Parameters:
CStr1: char const *
CStr2: char const *
"""
return _snap.TRStr_CmpI(*args)
def TRStr_GetNullRStr():
"""TRStr_GetNullRStr() -> TRStr"""
return _snap.TRStr_GetNullRStr()
class TStr(object):
"""Proxy of C++ TStr class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TStr
def __init__(self, *args):
"""
__init__(TStr self) -> TStr
__init__(TStr self, TStr Str) -> TStr
Parameters:
Str: TStr const &
__init__(TStr self, TChA ChA) -> TStr
Parameters:
ChA: TChA const &
__init__(TStr self, TSStr SStr) -> TStr
Parameters:
SStr: TSStr const &
__init__(TStr self, char const * CStr) -> TStr
Parameters:
CStr: char const *
__init__(TStr self, char const & Ch) -> TStr
Parameters:
Ch: char const &
__init__(TStr self, TMem Mem) -> TStr
Parameters:
Mem: TMem const &
__init__(TStr self, PSIn const & SIn) -> TStr
Parameters:
SIn: PSIn const &
__init__(TStr self, TSIn SIn, bool const & IsSmall=False) -> TStr
Parameters:
SIn: TSIn &
IsSmall: bool const &
__init__(TStr self, TSIn SIn) -> TStr
Parameters:
SIn: TSIn &
"""
_snap.TStr_swiginit(self,_snap.new_TStr(*args))
def Load(self, *args):
"""
Load(TStr self, TSIn SIn, bool const & IsSmall=False)
Parameters:
SIn: TSIn &
IsSmall: bool const &
Load(TStr self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TStr_Load(self, *args)
def Save(self, *args):
"""
Save(TStr self, TSOut SOut, bool const & IsSmall=False)
Parameters:
SOut: TSOut &
IsSmall: bool const &
Save(TStr self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TStr_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TStr self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TStr_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TStr self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TStr_SaveXml(self, *args)
def __iadd__(self, *args):
"""
__iadd__(TStr self, TStr Str) -> TStr
Parameters:
Str: TStr const &
__iadd__(TStr self, char const * CStr) -> TStr
Parameters:
CStr: char const *
"""
return _snap.TStr___iadd__(self, *args)
def __eq__(self, *args):
"""
__eq__(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
__eq__(TStr self, char const * CStr) -> bool
Parameters:
CStr: char const *
"""
return _snap.TStr___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TStr self, char const * CStr) -> bool
Parameters:
CStr: char const *
"""
return _snap.TStr___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TStr self) -> int
Parameters:
self: TStr const *
"""
return _snap.TStr_GetMemUsed(self)
def CStr(self, *args):
"""
CStr(TStr self) -> char
CStr(TStr self) -> char const *
Parameters:
self: TStr const *
"""
return _snap.TStr_CStr(self, *args)
def PutCh(self, *args):
"""
PutCh(TStr self, int const & ChN, char const & Ch)
Parameters:
ChN: int const &
Ch: char const &
"""
return _snap.TStr_PutCh(self, *args)
def GetCh(self, *args):
"""
GetCh(TStr self, int const & ChN) -> char
Parameters:
ChN: int const &
"""
return _snap.TStr_GetCh(self, *args)
def LastCh(self):
"""
LastCh(TStr self) -> char
Parameters:
self: TStr const *
"""
return _snap.TStr_LastCh(self)
def Clr(self):
"""
Clr(TStr self)
Parameters:
self: TStr *
"""
return _snap.TStr_Clr(self)
def Len(self):
"""
Len(TStr self) -> int
Parameters:
self: TStr const *
"""
return _snap.TStr_Len(self)
def Empty(self):
"""
Empty(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_Empty(self)
def IsUc(self):
"""
IsUc(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsUc(self)
def ToUc(self):
"""
ToUc(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToUc(self)
def GetUc(self):
"""
GetUc(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetUc(self)
def CmpI(self, *args):
"""
CmpI(TStr self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TStr_CmpI(self, *args)
def EqI(self, *args):
"""
EqI(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_EqI(self, *args)
def IsLc(self):
"""
IsLc(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsLc(self)
def ToLc(self):
"""
ToLc(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToLc(self)
def GetLc(self):
"""
GetLc(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetLc(self)
def ToCap(self):
"""
ToCap(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToCap(self)
def GetCap(self):
"""
GetCap(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetCap(self)
def ToTrunc(self):
"""
ToTrunc(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToTrunc(self)
def GetTrunc(self):
"""
GetTrunc(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetTrunc(self)
def ConvUsFromYuAscii(self):
"""
ConvUsFromYuAscii(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ConvUsFromYuAscii(self)
def GetUsFromYuAscii(self):
"""
GetUsFromYuAscii(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetUsFromYuAscii(self)
def ToHex(self):
"""
ToHex(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_ToHex(self)
def GetHex(self):
"""
GetHex(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetHex(self)
def FromHex(self):
"""
FromHex(TStr self) -> TStr
Parameters:
self: TStr *
"""
return _snap.TStr_FromHex(self)
def GetFromHex(self):
"""
GetFromHex(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFromHex(self)
def GetSubStr(self, *args):
"""
GetSubStr(TStr self, int const & BChN, int const & EChN) -> TStr
Parameters:
BChN: int const &
EChN: int const &
GetSubStr(TStr self, int const & BChN) -> TStr
Parameters:
BChN: int const &
"""
return _snap.TStr_GetSubStr(self, *args)
def InsStr(self, *args):
"""
InsStr(TStr self, int const & BChN, TStr Str)
Parameters:
BChN: int const &
Str: TStr const &
"""
return _snap.TStr_InsStr(self, *args)
def DelChAll(self, *args):
"""
DelChAll(TStr self, char const & Ch)
Parameters:
Ch: char const &
"""
return _snap.TStr_DelChAll(self, *args)
def DelSubStr(self, *args):
"""
DelSubStr(TStr self, int const & BChN, int const & EChN)
Parameters:
BChN: int const &
EChN: int const &
"""
return _snap.TStr_DelSubStr(self, *args)
def DelStr(self, *args):
"""
DelStr(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_DelStr(self, *args)
def LeftOf(self, *args):
"""
LeftOf(TStr self, char const & SplitCh) -> TStr
Parameters:
SplitCh: char const &
"""
return _snap.TStr_LeftOf(self, *args)
def LeftOfLast(self, *args):
"""
LeftOfLast(TStr self, char const & SplitCh) -> TStr
Parameters:
SplitCh: char const &
"""
return _snap.TStr_LeftOfLast(self, *args)
def RightOf(self, *args):
"""
RightOf(TStr self, char const & SplitCh) -> TStr
Parameters:
SplitCh: char const &
"""
return _snap.TStr_RightOf(self, *args)
def RightOfLast(self, *args):
"""
RightOfLast(TStr self, char const & SplitCh) -> TStr
Parameters:
SplitCh: char const &
"""
return _snap.TStr_RightOfLast(self, *args)
def SplitOnCh(self, *args):
"""
SplitOnCh(TStr self, TStr LStr, char const & SplitCh, TStr RStr)
Parameters:
LStr: TStr &
SplitCh: char const &
RStr: TStr &
"""
return _snap.TStr_SplitOnCh(self, *args)
def SplitOnLastCh(self, *args):
"""
SplitOnLastCh(TStr self, TStr LStr, char const & SplitCh, TStr RStr)
Parameters:
LStr: TStr &
SplitCh: char const &
RStr: TStr &
"""
return _snap.TStr_SplitOnLastCh(self, *args)
def SplitOnAllCh(self, *args):
"""
SplitOnAllCh(TStr self, char const & SplitCh, TStrV StrV, bool const & SkipEmpty=True)
Parameters:
SplitCh: char const &
StrV: TStrV &
SkipEmpty: bool const &
SplitOnAllCh(TStr self, char const & SplitCh, TStrV StrV)
Parameters:
SplitCh: char const &
StrV: TStrV &
"""
return _snap.TStr_SplitOnAllCh(self, *args)
def SplitOnAllAnyCh(self, *args):
"""
SplitOnAllAnyCh(TStr self, TStr SplitChStr, TStrV StrV, bool const & SkipEmpty=True)
Parameters:
SplitChStr: TStr const &
StrV: TStrV &
SkipEmpty: bool const &
SplitOnAllAnyCh(TStr self, TStr SplitChStr, TStrV StrV)
Parameters:
SplitChStr: TStr const &
StrV: TStrV &
"""
return _snap.TStr_SplitOnAllAnyCh(self, *args)
def SplitOnWs(self, *args):
"""
SplitOnWs(TStr self, TStrV StrV)
Parameters:
StrV: TStrV &
"""
return _snap.TStr_SplitOnWs(self, *args)
def SplitOnNonAlNum(self, *args):
"""
SplitOnNonAlNum(TStr self, TStrV StrV)
Parameters:
StrV: TStrV &
"""
return _snap.TStr_SplitOnNonAlNum(self, *args)
def SplitOnStr(self, *args):
"""
SplitOnStr(TStr self, TStr SplitStr, TStrV StrV)
Parameters:
SplitStr: TStr const &
StrV: TStrV &
SplitOnStr(TStr self, TStr LeftStr, TStr MidStr, TStr RightStr)
Parameters:
LeftStr: TStr &
MidStr: TStr const &
RightStr: TStr &
"""
return _snap.TStr_SplitOnStr(self, *args)
def Mid(self, *args):
"""
Mid(TStr self, int const & BChN, int const & Chs) -> TStr
Parameters:
BChN: int const &
Chs: int const &
Mid(TStr self, int const & BChN) -> TStr
Parameters:
BChN: int const &
"""
return _snap.TStr_Mid(self, *args)
def Left(self, *args):
"""
Left(TStr self, int const & EChN) -> TStr
Parameters:
EChN: int const &
"""
return _snap.TStr_Left(self, *args)
def Right(self, *args):
"""
Right(TStr self, int const & BChN) -> TStr
Parameters:
BChN: int const &
"""
return _snap.TStr_Right(self, *args)
def Slice(self, *args):
"""
Slice(TStr self, int BChN, int EChNP1) -> TStr
Parameters:
BChN: int
EChNP1: int
"""
return _snap.TStr_Slice(self, *args)
def __call__(self, *args):
"""
__call__(TStr self) -> char
__call__(TStr self) -> char const
__call__(TStr self, int const & BChN, int const & EChNP1) -> TStr
Parameters:
BChN: int const &
EChNP1: int const &
"""
return _snap.TStr___call__(self, *args)
def CountCh(self, *args):
"""
CountCh(TStr self, char const & Ch, int const & BChN=0) -> int
Parameters:
Ch: char const &
BChN: int const &
CountCh(TStr self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TStr_CountCh(self, *args)
def SearchCh(self, *args):
"""
SearchCh(TStr self, char const & Ch, int const & BChN=0) -> int
Parameters:
Ch: char const &
BChN: int const &
SearchCh(TStr self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TStr_SearchCh(self, *args)
def SearchChBack(self, *args):
"""
SearchChBack(TStr self, char const & Ch, int BChN=-1) -> int
Parameters:
Ch: char const &
BChN: int
SearchChBack(TStr self, char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TStr_SearchChBack(self, *args)
def SearchStr(self, *args):
"""
SearchStr(TStr self, TStr Str, int const & BChN=0) -> int
Parameters:
Str: TStr const &
BChN: int const &
SearchStr(TStr self, TStr Str) -> int
Parameters:
Str: TStr const &
"""
return _snap.TStr_SearchStr(self, *args)
def IsChIn(self, *args):
"""
IsChIn(TStr self, char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TStr_IsChIn(self, *args)
def IsStrIn(self, *args):
"""
IsStrIn(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_IsStrIn(self, *args)
def IsPrefix(self, *args):
"""
IsPrefix(TStr self, char const * Str) -> bool
Parameters:
Str: char const *
IsPrefix(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_IsPrefix(self, *args)
def IsSuffix(self, *args):
"""
IsSuffix(TStr self, char const * Str) -> bool
Parameters:
Str: char const *
IsSuffix(TStr self, TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TStr_IsSuffix(self, *args)
def ChangeCh(self, *args):
"""
ChangeCh(TStr self, char const & SrcCh, char const & DstCh, int const & BChN=0) -> int
Parameters:
SrcCh: char const &
DstCh: char const &
BChN: int const &
ChangeCh(TStr self, char const & SrcCh, char const & DstCh) -> int
Parameters:
SrcCh: char const &
DstCh: char const &
"""
return _snap.TStr_ChangeCh(self, *args)
def ChangeChAll(self, *args):
"""
ChangeChAll(TStr self, char const & SrcCh, char const & DstCh) -> int
Parameters:
SrcCh: char const &
DstCh: char const &
"""
return _snap.TStr_ChangeChAll(self, *args)
def ChangeStr(self, *args):
"""
ChangeStr(TStr self, TStr SrcStr, TStr DstStr, int const & BChN=0) -> int
Parameters:
SrcStr: TStr const &
DstStr: TStr const &
BChN: int const &
ChangeStr(TStr self, TStr SrcStr, TStr DstStr) -> int
Parameters:
SrcStr: TStr const &
DstStr: TStr const &
"""
return _snap.TStr_ChangeStr(self, *args)
def ChangeStrAll(self, *args):
"""
ChangeStrAll(TStr self, TStr SrcStr, TStr DstStr, bool const & FromStartP=False) -> int
Parameters:
SrcStr: TStr const &
DstStr: TStr const &
FromStartP: bool const &
ChangeStrAll(TStr self, TStr SrcStr, TStr DstStr) -> int
Parameters:
SrcStr: TStr const &
DstStr: TStr const &
"""
return _snap.TStr_ChangeStrAll(self, *args)
def Reverse(self):
"""
Reverse(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_Reverse(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TStr self) -> int
Parameters:
self: TStr const *
"""
return _snap.TStr_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TStr self) -> int
Parameters:
self: TStr const *
"""
return _snap.TStr_GetSecHashCd(self)
def IsBool(self, *args):
"""
IsBool(TStr self, bool & Val) -> bool
Parameters:
Val: bool &
"""
return _snap.TStr_IsBool(self, *args)
def IsInt(self, *args):
"""
IsInt(TStr self, bool const & Check, int const & MnVal, int const & MxVal, int & Val) -> bool
Parameters:
Check: bool const &
MnVal: int const &
MxVal: int const &
Val: int &
IsInt(TStr self, int & Val) -> bool
Parameters:
Val: int &
IsInt(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsInt(self, *args)
def GetInt(self, *args):
"""
GetInt(TStr self) -> int
GetInt(TStr self, int const & DfVal) -> int
Parameters:
DfVal: int const &
"""
return _snap.TStr_GetInt(self, *args)
def IsUInt(self, *args):
"""
IsUInt(TStr self, bool const & Check, uint const & MnVal, uint const & MxVal, uint & Val) -> bool
Parameters:
Check: bool const &
MnVal: uint const &
MxVal: uint const &
Val: uint &
IsUInt(TStr self, uint & Val) -> bool
Parameters:
Val: uint &
IsUInt(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsUInt(self, *args)
def GetUInt(self, *args):
"""
GetUInt(TStr self) -> uint
GetUInt(TStr self, uint const & DfVal) -> uint
Parameters:
DfVal: uint const &
"""
return _snap.TStr_GetUInt(self, *args)
def IsInt64(self, *args):
"""
IsInt64(TStr self, bool const & Check, int64 const & MnVal, int64 const & MxVal, int64 & Val) -> bool
Parameters:
Check: bool const &
MnVal: int64 const &
MxVal: int64 const &
Val: int64 &
IsInt64(TStr self, int64 & Val) -> bool
Parameters:
Val: int64 &
IsInt64(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsInt64(self, *args)
def GetInt64(self, *args):
"""
GetInt64(TStr self) -> int64
GetInt64(TStr self, int64 const & DfVal) -> int64
Parameters:
DfVal: int64 const &
"""
return _snap.TStr_GetInt64(self, *args)
def IsUInt64(self, *args):
"""
IsUInt64(TStr self, bool const & Check, uint64 const & MnVal, uint64 const & MxVal, uint64 & Val) -> bool
Parameters:
Check: bool const &
MnVal: uint64 const &
MxVal: uint64 const &
Val: uint64 &
IsUInt64(TStr self, uint64 & Val) -> bool
Parameters:
Val: uint64 &
IsUInt64(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsUInt64(self, *args)
def GetUInt64(self, *args):
"""
GetUInt64(TStr self) -> uint64
GetUInt64(TStr self, uint64 const & DfVal) -> uint64
Parameters:
DfVal: uint64 const &
"""
return _snap.TStr_GetUInt64(self, *args)
def IsHexInt(self, *args):
"""
IsHexInt(TStr self, bool const & Check, int const & MnVal, int const & MxVal, int & Val) -> bool
Parameters:
Check: bool const &
MnVal: int const &
MxVal: int const &
Val: int &
IsHexInt(TStr self, int & Val) -> bool
Parameters:
Val: int &
IsHexInt(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsHexInt(self, *args)
def GetHexInt(self, *args):
"""
GetHexInt(TStr self) -> int
GetHexInt(TStr self, int const & DfVal) -> int
Parameters:
DfVal: int const &
"""
return _snap.TStr_GetHexInt(self, *args)
def IsHexInt64(self, *args):
"""
IsHexInt64(TStr self, bool const & Check, int64 const & MnVal, int64 const & MxVal, int64 & Val) -> bool
Parameters:
Check: bool const &
MnVal: int64 const &
MxVal: int64 const &
Val: int64 &
IsHexInt64(TStr self, int64 & Val) -> bool
Parameters:
Val: int64 &
IsHexInt64(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsHexInt64(self, *args)
def GetHexInt64(self, *args):
"""
GetHexInt64(TStr self) -> int64
GetHexInt64(TStr self, int64 const & DfVal) -> int64
Parameters:
DfVal: int64 const &
"""
return _snap.TStr_GetHexInt64(self, *args)
def IsFlt(self, *args):
"""
IsFlt(TStr self, bool const & Check, double const & MnVal, double const & MxVal, double & Val, char const & DecDelimCh='.') -> bool
Parameters:
Check: bool const &
MnVal: double const &
MxVal: double const &
Val: double &
DecDelimCh: char const &
IsFlt(TStr self, bool const & Check, double const & MnVal, double const & MxVal, double & Val) -> bool
Parameters:
Check: bool const &
MnVal: double const &
MxVal: double const &
Val: double &
IsFlt(TStr self, double & Val) -> bool
Parameters:
Val: double &
IsFlt(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsFlt(self, *args)
def GetFlt(self, *args):
"""
GetFlt(TStr self) -> double
GetFlt(TStr self, double const & DfVal) -> double
Parameters:
DfVal: double const &
"""
return _snap.TStr_GetFlt(self, *args)
def IsWord(self, WsPrefixP=True, FirstUcAllowedP=True):
"""
IsWord(TStr self, bool const & WsPrefixP=True, bool const & FirstUcAllowedP=True) -> bool
Parameters:
WsPrefixP: bool const &
FirstUcAllowedP: bool const &
IsWord(TStr self, bool const & WsPrefixP=True) -> bool
Parameters:
WsPrefixP: bool const &
IsWord(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsWord(self, WsPrefixP, FirstUcAllowedP)
def IsWs(self):
"""
IsWs(TStr self) -> bool
Parameters:
self: TStr const *
"""
return _snap.TStr_IsWs(self)
def IsWcMatch(self, *args):
"""
IsWcMatch(TStr self, int const & StrBChN, TStr WcStr, int const & WcStrBChN, TStrV StarStrV, char const & StarCh='*',
char const & QuestCh='?') -> bool
Parameters:
StrBChN: int const &
WcStr: TStr const &
WcStrBChN: int const &
StarStrV: TStrV &
StarCh: char const &
QuestCh: char const &
IsWcMatch(TStr self, int const & StrBChN, TStr WcStr, int const & WcStrBChN, TStrV StarStrV, char const & StarCh='*') -> bool
Parameters:
StrBChN: int const &
WcStr: TStr const &
WcStrBChN: int const &
StarStrV: TStrV &
StarCh: char const &
IsWcMatch(TStr self, int const & StrBChN, TStr WcStr, int const & WcStrBChN, TStrV StarStrV) -> bool
Parameters:
StrBChN: int const &
WcStr: TStr const &
WcStrBChN: int const &
StarStrV: TStrV &
IsWcMatch(TStr self, TStr WcStr, TStrV StarStrV, char const & StarCh='*', char const & QuestCh='?') -> bool
Parameters:
WcStr: TStr const &
StarStrV: TStrV &
StarCh: char const &
QuestCh: char const &
IsWcMatch(TStr self, TStr WcStr, TStrV StarStrV, char const & StarCh='*') -> bool
Parameters:
WcStr: TStr const &
StarStrV: TStrV &
StarCh: char const &
IsWcMatch(TStr self, TStr WcStr, TStrV StarStrV) -> bool
Parameters:
WcStr: TStr const &
StarStrV: TStrV &
IsWcMatch(TStr self, TStr WcStr, char const & StarCh, char const & QuestCh) -> bool
Parameters:
WcStr: TStr const &
StarCh: char const &
QuestCh: char const &
IsWcMatch(TStr self, TStr WcStr, int const & StarStrN, TStr StarStr) -> bool
Parameters:
WcStr: TStr const &
StarStrN: int const &
StarStr: TStr &
IsWcMatch(TStr self, TStr WcStr) -> bool
Parameters:
WcStr: TStr const &
"""
return _snap.TStr_IsWcMatch(self, *args)
def GetWcMatch(self, *args):
"""
GetWcMatch(TStr self, TStr WcStr, int const & StarStrN=0) -> TStr
Parameters:
WcStr: TStr const &
StarStrN: int const &
GetWcMatch(TStr self, TStr WcStr) -> TStr
Parameters:
WcStr: TStr const &
"""
return _snap.TStr_GetWcMatch(self, *args)
def GetFPath(self):
"""
GetFPath(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFPath(self)
def GetFBase(self):
"""
GetFBase(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFBase(self)
def GetFMid(self):
"""
GetFMid(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFMid(self)
def GetFExt(self):
"""
GetFExt(TStr self) -> TStr
Parameters:
self: TStr const *
"""
return _snap.TStr_GetFExt(self)
def GetNrFPath(*args):
"""
GetNrFPath(TStr FPath) -> TStr
Parameters:
FPath: TStr const &
"""
return _snap.TStr_GetNrFPath(*args)
GetNrFPath = staticmethod(GetNrFPath)
def GetNrFMid(*args):
"""
GetNrFMid(TStr FMid) -> TStr
Parameters:
FMid: TStr const &
"""
return _snap.TStr_GetNrFMid(*args)
GetNrFMid = staticmethod(GetNrFMid)
def GetNrFExt(*args):
"""
GetNrFExt(TStr FExt) -> TStr
Parameters:
FExt: TStr const &
"""
return _snap.TStr_GetNrFExt(*args)
GetNrFExt = staticmethod(GetNrFExt)
def GetNrNumFExt(*args):
"""
GetNrNumFExt(int const & FExtN) -> TStr
Parameters:
FExtN: int const &
"""
return _snap.TStr_GetNrNumFExt(*args)
GetNrNumFExt = staticmethod(GetNrNumFExt)
def GetNrFNm(*args):
"""
GetNrFNm(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TStr_GetNrFNm(*args)
GetNrFNm = staticmethod(GetNrFNm)
def GetNrAbsFPath(*args):
"""
GetNrAbsFPath(TStr FPath, TStr BaseFPath=TStr()) -> TStr
Parameters:
FPath: TStr const &
BaseFPath: TStr const &
GetNrAbsFPath(TStr FPath) -> TStr
Parameters:
FPath: TStr const &
"""
return _snap.TStr_GetNrAbsFPath(*args)
GetNrAbsFPath = staticmethod(GetNrAbsFPath)
def IsAbsFPath(*args):
"""
IsAbsFPath(TStr FPath) -> bool
Parameters:
FPath: TStr const &
"""
return _snap.TStr_IsAbsFPath(*args)
IsAbsFPath = staticmethod(IsAbsFPath)
def PutFExt(*args):
"""
PutFExt(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExt(*args)
PutFExt = staticmethod(PutFExt)
def PutFExtIfEmpty(*args):
"""
PutFExtIfEmpty(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExtIfEmpty(*args)
PutFExtIfEmpty = staticmethod(PutFExtIfEmpty)
def PutFBase(*args):
"""
PutFBase(TStr FNm, TStr FBase) -> TStr
Parameters:
FNm: TStr const &
FBase: TStr const &
"""
return _snap.TStr_PutFBase(*args)
PutFBase = staticmethod(PutFBase)
def PutFBaseIfEmpty(*args):
"""
PutFBaseIfEmpty(TStr FNm, TStr FBase) -> TStr
Parameters:
FNm: TStr const &
FBase: TStr const &
"""
return _snap.TStr_PutFBaseIfEmpty(*args)
PutFBaseIfEmpty = staticmethod(PutFBaseIfEmpty)
def AddToFMid(*args):
"""
AddToFMid(TStr FNm, TStr ExtFMid) -> TStr
Parameters:
FNm: TStr const &
ExtFMid: TStr const &
"""
return _snap.TStr_AddToFMid(*args)
AddToFMid = staticmethod(AddToFMid)
def GetNumFNm(*args):
"""
GetNumFNm(TStr FNm, int const & Num) -> TStr
Parameters:
FNm: TStr const &
Num: int const &
"""
return _snap.TStr_GetNumFNm(*args)
GetNumFNm = staticmethod(GetNumFNm)
def GetFNmStr(*args):
"""
GetFNmStr(TStr Str, bool const & AlNumOnlyP=True) -> TStr
Parameters:
Str: TStr const &
AlNumOnlyP: bool const &
GetFNmStr(TStr Str) -> TStr
Parameters:
Str: TStr const &
"""
return _snap.TStr_GetFNmStr(*args)
GetFNmStr = staticmethod(GetFNmStr)
def LoadTxt(*args):
"""
LoadTxt(PSIn const & SIn) -> TStr
Parameters:
SIn: PSIn const &
LoadTxt(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TStr_LoadTxt(*args)
LoadTxt = staticmethod(LoadTxt)
def SaveTxt(self, *args):
"""
SaveTxt(TStr self, PSOut const & SOut)
Parameters:
SOut: PSOut const &
SaveTxt(TStr self, TStr FNm)
Parameters:
FNm: TStr const &
"""
return _snap.TStr_SaveTxt(self, *args)
def GetChStr(*args):
"""
GetChStr(char const & Ch) -> TStr
Parameters:
Ch: char const &
"""
return _snap.TStr_GetChStr(*args)
GetChStr = staticmethod(GetChStr)
def GetDChStr(*args):
"""
GetDChStr(char const & Ch1, char const & Ch2) -> TStr
Parameters:
Ch1: char const &
Ch2: char const &
"""
return _snap.TStr_GetDChStr(*args)
GetDChStr = staticmethod(GetDChStr)
def Fmt(*args):
"""
Fmt(char const * FmtStr) -> TStr
Parameters:
FmtStr: char const *
"""
return _snap.TStr_Fmt(*args)
Fmt = staticmethod(Fmt)
def GetSpaceStr(*args):
"""
GetSpaceStr(int const & Spaces) -> TStr
Parameters:
Spaces: int const &
"""
return _snap.TStr_GetSpaceStr(*args)
GetSpaceStr = staticmethod(GetSpaceStr)
def GetCStr(self):
"""
GetCStr(TStr self) -> char *
Parameters:
self: TStr const *
"""
return _snap.TStr_GetCStr(self)
def MkClone(*args):
"""
MkClone(TStr Str) -> TStr
Parameters:
Str: TStr const &
"""
return _snap.TStr_MkClone(*args)
MkClone = staticmethod(MkClone)
def GetNullStr():
"""GetNullStr() -> TStr"""
return _snap.TStr_GetNullStr()
GetNullStr = staticmethod(GetNullStr)
TStr.Load = new_instancemethod(_snap.TStr_Load,None,TStr)
TStr.Save = new_instancemethod(_snap.TStr_Save,None,TStr)
TStr.LoadXml = new_instancemethod(_snap.TStr_LoadXml,None,TStr)
TStr.SaveXml = new_instancemethod(_snap.TStr_SaveXml,None,TStr)
TStr.__iadd__ = new_instancemethod(_snap.TStr___iadd__,None,TStr)
TStr.__eq__ = new_instancemethod(_snap.TStr___eq__,None,TStr)
TStr.__ne__ = new_instancemethod(_snap.TStr___ne__,None,TStr)
TStr.__lt__ = new_instancemethod(_snap.TStr___lt__,None,TStr)
TStr.GetMemUsed = new_instancemethod(_snap.TStr_GetMemUsed,None,TStr)
TStr.CStr = new_instancemethod(_snap.TStr_CStr,None,TStr)
TStr.PutCh = new_instancemethod(_snap.TStr_PutCh,None,TStr)
TStr.GetCh = new_instancemethod(_snap.TStr_GetCh,None,TStr)
TStr.LastCh = new_instancemethod(_snap.TStr_LastCh,None,TStr)
TStr.Clr = new_instancemethod(_snap.TStr_Clr,None,TStr)
TStr.Len = new_instancemethod(_snap.TStr_Len,None,TStr)
TStr.Empty = new_instancemethod(_snap.TStr_Empty,None,TStr)
TStr.IsUc = new_instancemethod(_snap.TStr_IsUc,None,TStr)
TStr.ToUc = new_instancemethod(_snap.TStr_ToUc,None,TStr)
TStr.GetUc = new_instancemethod(_snap.TStr_GetUc,None,TStr)
TStr.CmpI = new_instancemethod(_snap.TStr_CmpI,None,TStr)
TStr.EqI = new_instancemethod(_snap.TStr_EqI,None,TStr)
TStr.IsLc = new_instancemethod(_snap.TStr_IsLc,None,TStr)
TStr.ToLc = new_instancemethod(_snap.TStr_ToLc,None,TStr)
TStr.GetLc = new_instancemethod(_snap.TStr_GetLc,None,TStr)
TStr.ToCap = new_instancemethod(_snap.TStr_ToCap,None,TStr)
TStr.GetCap = new_instancemethod(_snap.TStr_GetCap,None,TStr)
TStr.ToTrunc = new_instancemethod(_snap.TStr_ToTrunc,None,TStr)
TStr.GetTrunc = new_instancemethod(_snap.TStr_GetTrunc,None,TStr)
TStr.ConvUsFromYuAscii = new_instancemethod(_snap.TStr_ConvUsFromYuAscii,None,TStr)
TStr.GetUsFromYuAscii = new_instancemethod(_snap.TStr_GetUsFromYuAscii,None,TStr)
TStr.ToHex = new_instancemethod(_snap.TStr_ToHex,None,TStr)
TStr.GetHex = new_instancemethod(_snap.TStr_GetHex,None,TStr)
TStr.FromHex = new_instancemethod(_snap.TStr_FromHex,None,TStr)
TStr.GetFromHex = new_instancemethod(_snap.TStr_GetFromHex,None,TStr)
TStr.GetSubStr = new_instancemethod(_snap.TStr_GetSubStr,None,TStr)
TStr.InsStr = new_instancemethod(_snap.TStr_InsStr,None,TStr)
TStr.DelChAll = new_instancemethod(_snap.TStr_DelChAll,None,TStr)
TStr.DelSubStr = new_instancemethod(_snap.TStr_DelSubStr,None,TStr)
TStr.DelStr = new_instancemethod(_snap.TStr_DelStr,None,TStr)
TStr.LeftOf = new_instancemethod(_snap.TStr_LeftOf,None,TStr)
TStr.LeftOfLast = new_instancemethod(_snap.TStr_LeftOfLast,None,TStr)
TStr.RightOf = new_instancemethod(_snap.TStr_RightOf,None,TStr)
TStr.RightOfLast = new_instancemethod(_snap.TStr_RightOfLast,None,TStr)
TStr.SplitOnCh = new_instancemethod(_snap.TStr_SplitOnCh,None,TStr)
TStr.SplitOnLastCh = new_instancemethod(_snap.TStr_SplitOnLastCh,None,TStr)
TStr.SplitOnAllCh = new_instancemethod(_snap.TStr_SplitOnAllCh,None,TStr)
TStr.SplitOnAllAnyCh = new_instancemethod(_snap.TStr_SplitOnAllAnyCh,None,TStr)
TStr.SplitOnWs = new_instancemethod(_snap.TStr_SplitOnWs,None,TStr)
TStr.SplitOnNonAlNum = new_instancemethod(_snap.TStr_SplitOnNonAlNum,None,TStr)
TStr.SplitOnStr = new_instancemethod(_snap.TStr_SplitOnStr,None,TStr)
TStr.Mid = new_instancemethod(_snap.TStr_Mid,None,TStr)
TStr.Left = new_instancemethod(_snap.TStr_Left,None,TStr)
TStr.Right = new_instancemethod(_snap.TStr_Right,None,TStr)
TStr.Slice = new_instancemethod(_snap.TStr_Slice,None,TStr)
TStr.__call__ = new_instancemethod(_snap.TStr___call__,None,TStr)
TStr.CountCh = new_instancemethod(_snap.TStr_CountCh,None,TStr)
TStr.SearchCh = new_instancemethod(_snap.TStr_SearchCh,None,TStr)
TStr.SearchChBack = new_instancemethod(_snap.TStr_SearchChBack,None,TStr)
TStr.SearchStr = new_instancemethod(_snap.TStr_SearchStr,None,TStr)
TStr.IsChIn = new_instancemethod(_snap.TStr_IsChIn,None,TStr)
TStr.IsStrIn = new_instancemethod(_snap.TStr_IsStrIn,None,TStr)
TStr.IsPrefix = new_instancemethod(_snap.TStr_IsPrefix,None,TStr)
TStr.IsSuffix = new_instancemethod(_snap.TStr_IsSuffix,None,TStr)
TStr.ChangeCh = new_instancemethod(_snap.TStr_ChangeCh,None,TStr)
TStr.ChangeChAll = new_instancemethod(_snap.TStr_ChangeChAll,None,TStr)
TStr.ChangeStr = new_instancemethod(_snap.TStr_ChangeStr,None,TStr)
TStr.ChangeStrAll = new_instancemethod(_snap.TStr_ChangeStrAll,None,TStr)
TStr.Reverse = new_instancemethod(_snap.TStr_Reverse,None,TStr)
TStr.GetPrimHashCd = new_instancemethod(_snap.TStr_GetPrimHashCd,None,TStr)
TStr.GetSecHashCd = new_instancemethod(_snap.TStr_GetSecHashCd,None,TStr)
TStr.IsBool = new_instancemethod(_snap.TStr_IsBool,None,TStr)
TStr.IsInt = new_instancemethod(_snap.TStr_IsInt,None,TStr)
TStr.GetInt = new_instancemethod(_snap.TStr_GetInt,None,TStr)
TStr.IsUInt = new_instancemethod(_snap.TStr_IsUInt,None,TStr)
TStr.GetUInt = new_instancemethod(_snap.TStr_GetUInt,None,TStr)
TStr.IsInt64 = new_instancemethod(_snap.TStr_IsInt64,None,TStr)
TStr.GetInt64 = new_instancemethod(_snap.TStr_GetInt64,None,TStr)
TStr.IsUInt64 = new_instancemethod(_snap.TStr_IsUInt64,None,TStr)
TStr.GetUInt64 = new_instancemethod(_snap.TStr_GetUInt64,None,TStr)
TStr.IsHexInt = new_instancemethod(_snap.TStr_IsHexInt,None,TStr)
TStr.GetHexInt = new_instancemethod(_snap.TStr_GetHexInt,None,TStr)
TStr.IsHexInt64 = new_instancemethod(_snap.TStr_IsHexInt64,None,TStr)
TStr.GetHexInt64 = new_instancemethod(_snap.TStr_GetHexInt64,None,TStr)
TStr.IsFlt = new_instancemethod(_snap.TStr_IsFlt,None,TStr)
TStr.GetFlt = new_instancemethod(_snap.TStr_GetFlt,None,TStr)
TStr.IsWord = new_instancemethod(_snap.TStr_IsWord,None,TStr)
TStr.IsWs = new_instancemethod(_snap.TStr_IsWs,None,TStr)
TStr.IsWcMatch = new_instancemethod(_snap.TStr_IsWcMatch,None,TStr)
TStr.GetWcMatch = new_instancemethod(_snap.TStr_GetWcMatch,None,TStr)
TStr.GetFPath = new_instancemethod(_snap.TStr_GetFPath,None,TStr)
TStr.GetFBase = new_instancemethod(_snap.TStr_GetFBase,None,TStr)
TStr.GetFMid = new_instancemethod(_snap.TStr_GetFMid,None,TStr)
TStr.GetFExt = new_instancemethod(_snap.TStr_GetFExt,None,TStr)
TStr.SaveTxt = new_instancemethod(_snap.TStr_SaveTxt,None,TStr)
TStr.GetCStr = new_instancemethod(_snap.TStr_GetCStr,None,TStr)
TStr_swigregister = _snap.TStr_swigregister
TStr_swigregister(TStr)
def TStr_GetNrFPath(*args):
"""
TStr_GetNrFPath(TStr FPath) -> TStr
Parameters:
FPath: TStr const &
"""
return _snap.TStr_GetNrFPath(*args)
def TStr_GetNrFMid(*args):
"""
TStr_GetNrFMid(TStr FMid) -> TStr
Parameters:
FMid: TStr const &
"""
return _snap.TStr_GetNrFMid(*args)
def TStr_GetNrFExt(*args):
"""
TStr_GetNrFExt(TStr FExt) -> TStr
Parameters:
FExt: TStr const &
"""
return _snap.TStr_GetNrFExt(*args)
def TStr_GetNrNumFExt(*args):
"""
TStr_GetNrNumFExt(int const & FExtN) -> TStr
Parameters:
FExtN: int const &
"""
return _snap.TStr_GetNrNumFExt(*args)
def TStr_GetNrFNm(*args):
"""
TStr_GetNrFNm(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TStr_GetNrFNm(*args)
def TStr_GetNrAbsFPath(*args):
"""
GetNrAbsFPath(TStr FPath, TStr BaseFPath=TStr()) -> TStr
Parameters:
FPath: TStr const &
BaseFPath: TStr const &
TStr_GetNrAbsFPath(TStr FPath) -> TStr
Parameters:
FPath: TStr const &
"""
return _snap.TStr_GetNrAbsFPath(*args)
def TStr_IsAbsFPath(*args):
"""
TStr_IsAbsFPath(TStr FPath) -> bool
Parameters:
FPath: TStr const &
"""
return _snap.TStr_IsAbsFPath(*args)
def TStr_PutFExt(*args):
"""
TStr_PutFExt(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExt(*args)
def TStr_PutFExtIfEmpty(*args):
"""
TStr_PutFExtIfEmpty(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExtIfEmpty(*args)
def TStr_PutFBase(*args):
"""
TStr_PutFBase(TStr FNm, TStr FBase) -> TStr
Parameters:
FNm: TStr const &
FBase: TStr const &
"""
return _snap.TStr_PutFBase(*args)
def TStr_PutFBaseIfEmpty(*args):
"""
TStr_PutFBaseIfEmpty(TStr FNm, TStr FBase) -> TStr
Parameters:
FNm: TStr const &
FBase: TStr const &
"""
return _snap.TStr_PutFBaseIfEmpty(*args)
def TStr_AddToFMid(*args):
"""
TStr_AddToFMid(TStr FNm, TStr ExtFMid) -> TStr
Parameters:
FNm: TStr const &
ExtFMid: TStr const &
"""
return _snap.TStr_AddToFMid(*args)
def TStr_GetNumFNm(*args):
"""
TStr_GetNumFNm(TStr FNm, int const & Num) -> TStr
Parameters:
FNm: TStr const &
Num: int const &
"""
return _snap.TStr_GetNumFNm(*args)
def TStr_GetFNmStr(*args):
"""
GetFNmStr(TStr Str, bool const & AlNumOnlyP=True) -> TStr
Parameters:
Str: TStr const &
AlNumOnlyP: bool const &
TStr_GetFNmStr(TStr Str) -> TStr
Parameters:
Str: TStr const &
"""
return _snap.TStr_GetFNmStr(*args)
def TStr_LoadTxt(*args):
"""
LoadTxt(PSIn const & SIn) -> TStr
Parameters:
SIn: PSIn const &
TStr_LoadTxt(TStr FNm) -> TStr
Parameters:
FNm: TStr const &
"""
return _snap.TStr_LoadTxt(*args)
def TStr_GetChStr(*args):
"""
TStr_GetChStr(char const & Ch) -> TStr
Parameters:
Ch: char const &
"""
return _snap.TStr_GetChStr(*args)
def TStr_GetDChStr(*args):
"""
TStr_GetDChStr(char const & Ch1, char const & Ch2) -> TStr
Parameters:
Ch1: char const &
Ch2: char const &
"""
return _snap.TStr_GetDChStr(*args)
def TStr_Fmt(*args):
"""
TStr_Fmt(char const * FmtStr) -> TStr
Parameters:
FmtStr: char const *
"""
return _snap.TStr_Fmt(*args)
def TStr_GetSpaceStr(*args):
"""
TStr_GetSpaceStr(int const & Spaces) -> TStr
Parameters:
Spaces: int const &
"""
return _snap.TStr_GetSpaceStr(*args)
def TStr_MkClone(*args):
"""
TStr_MkClone(TStr Str) -> TStr
Parameters:
Str: TStr const &
"""
return _snap.TStr_MkClone(*args)
def TStr_GetNullStr():
"""TStr_GetNullStr() -> TStr"""
return _snap.TStr_GetNullStr()
class TStrIn(TSIn):
"""Proxy of C++ TStrIn class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TStrIn self, TStr _Str) -> TStrIn
Parameters:
_Str: TStr const &
"""
_snap.TStrIn_swiginit(self,_snap.new_TStrIn(*args))
def New(*args):
"""
New(TStr Str) -> PSIn
Parameters:
Str: TStr const &
"""
return _snap.TStrIn_New(*args)
New = staticmethod(New)
__swig_destroy__ = _snap.delete_TStrIn
TStrIn_swigregister = _snap.TStrIn_swigregister
TStrIn_swigregister(TStrIn)
def TStrIn_New(*args):
"""
TStrIn_New(TStr Str) -> PSIn
Parameters:
Str: TStr const &
"""
return _snap.TStrIn_New(*args)
class TDbStr(object):
"""Proxy of C++ TDbStr class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Str1 = _swig_property(_snap.TDbStr_Str1_get, _snap.TDbStr_Str1_set)
Str2 = _swig_property(_snap.TDbStr_Str2_get, _snap.TDbStr_Str2_set)
def __init__(self, *args):
"""
__init__(TDbStr self) -> TDbStr
__init__(TDbStr self, TDbStr DbStr) -> TDbStr
Parameters:
DbStr: TDbStr const &
__init__(TDbStr self, TStr _Str1) -> TDbStr
Parameters:
_Str1: TStr const &
__init__(TDbStr self, TStr _Str1, TStr _Str2) -> TDbStr
Parameters:
_Str1: TStr const &
_Str2: TStr const &
__init__(TDbStr self, TSIn SIn) -> TDbStr
Parameters:
SIn: TSIn &
"""
_snap.TDbStr_swiginit(self,_snap.new_TDbStr(*args))
def Save(self, *args):
"""
Save(TDbStr self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TDbStr_Save(self, *args)
def __eq__(self, *args):
"""
__eq__(TDbStr self, TDbStr DbStr) -> bool
Parameters:
DbStr: TDbStr const &
"""
return _snap.TDbStr___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TDbStr self, TDbStr DbStr) -> bool
Parameters:
DbStr: TDbStr const &
"""
return _snap.TDbStr___lt__(self, *args)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TDbStr self) -> int
Parameters:
self: TDbStr const *
"""
return _snap.TDbStr_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TDbStr self) -> int
Parameters:
self: TDbStr const *
"""
return _snap.TDbStr_GetSecHashCd(self)
def Empty(self):
"""
Empty(TDbStr self) -> bool
Parameters:
self: TDbStr const *
"""
return _snap.TDbStr_Empty(self)
def Filled(self):
"""
Filled(TDbStr self) -> bool
Parameters:
self: TDbStr const *
"""
return _snap.TDbStr_Filled(self)
__swig_destroy__ = _snap.delete_TDbStr
TDbStr.Save = new_instancemethod(_snap.TDbStr_Save,None,TDbStr)
TDbStr.__eq__ = new_instancemethod(_snap.TDbStr___eq__,None,TDbStr)
TDbStr.__lt__ = new_instancemethod(_snap.TDbStr___lt__,None,TDbStr)
TDbStr.GetPrimHashCd = new_instancemethod(_snap.TDbStr_GetPrimHashCd,None,TDbStr)
TDbStr.GetSecHashCd = new_instancemethod(_snap.TDbStr_GetSecHashCd,None,TDbStr)
TDbStr.Empty = new_instancemethod(_snap.TDbStr_Empty,None,TDbStr)
TDbStr.Filled = new_instancemethod(_snap.TDbStr_Filled,None,TDbStr)
TDbStr_swigregister = _snap.TDbStr_swigregister
TDbStr_swigregister(TDbStr)
class TStrPool(object):
"""Proxy of C++ TStrPool class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TStrPool self, uint const & MxBfLen=0, uint const & _GrowBy=16*1024*1024) -> TStrPool
Parameters:
MxBfLen: uint const &
_GrowBy: uint const &
__init__(TStrPool self, uint const & MxBfLen=0) -> TStrPool
Parameters:
MxBfLen: uint const &
__init__(TStrPool self) -> TStrPool
__init__(TStrPool self, TSIn SIn, bool LoadCompact=True) -> TStrPool
Parameters:
SIn: TSIn &
LoadCompact: bool
__init__(TStrPool self, TSIn SIn) -> TStrPool
Parameters:
SIn: TSIn &
__init__(TStrPool self, TStrPool Pool) -> TStrPool
Parameters:
Pool: TStrPool const &
"""
_snap.TStrPool_swiginit(self,_snap.new_TStrPool(*args))
__swig_destroy__ = _snap.delete_TStrPool
def New(*args):
"""
New(uint const & _MxBfLen=0, uint const & _GrowBy=16*1024*1024) -> PStrPool
Parameters:
_MxBfLen: uint const &
_GrowBy: uint const &
New(uint const & _MxBfLen=0) -> PStrPool
Parameters:
_MxBfLen: uint const &
New() -> PStrPool
New(TSIn SIn) -> PStrPool
Parameters:
SIn: TSIn &
New(TStr fileName) -> PStrPool
Parameters:
fileName: TStr const &
"""
return _snap.TStrPool_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn, bool LoadCompacted=True) -> PStrPool
Parameters:
SIn: TSIn &
LoadCompacted: bool
Load(TSIn SIn) -> PStrPool
Parameters:
SIn: TSIn &
"""
return _snap.TStrPool_Load(*args)
Load = staticmethod(Load)
def Save(self, *args):
"""
Save(TStrPool self, TSOut SOut)
Parameters:
SOut: TSOut &
Save(TStrPool self, TStr FNm)
Parameters:
FNm: TStr const &
"""
return _snap.TStrPool_Save(self, *args)
def Len(self):
"""
Len(TStrPool self) -> uint
Parameters:
self: TStrPool const *
"""
return _snap.TStrPool_Len(self)
def Size(self):
"""
Size(TStrPool self) -> uint
Parameters:
self: TStrPool const *
"""
return _snap.TStrPool_Size(self)
def Empty(self):
"""
Empty(TStrPool self) -> bool
Parameters:
self: TStrPool const *
"""
return _snap.TStrPool_Empty(self)
def __call__(self):
"""
__call__(TStrPool self) -> char *
Parameters:
self: TStrPool const *
"""
return _snap.TStrPool___call__(self)
def AddStr(self, *args):
"""
AddStr(TStrPool self, char const * Str, uint const & Len) -> uint
Parameters:
Str: char const *
Len: uint const &
AddStr(TStrPool self, char const * Str) -> uint
Parameters:
Str: char const *
AddStr(TStrPool self, TStr Str) -> uint
Parameters:
Str: TStr const &
"""
return _snap.TStrPool_AddStr(self, *args)
def GetCStr(self, *args):
"""
GetCStr(TStrPool self, uint const & Offset) -> char const *
Parameters:
Offset: uint const &
"""
return _snap.TStrPool_GetCStr(self, *args)
def Clr(self, DoDel=False):
"""
Clr(TStrPool self, bool DoDel=False)
Parameters:
DoDel: bool
Clr(TStrPool self)
Parameters:
self: TStrPool *
"""
return _snap.TStrPool_Clr(self, DoDel)
def Cmp(self, *args):
"""
Cmp(TStrPool self, uint const & Offset, char const * Str) -> int
Parameters:
Offset: uint const &
Str: char const *
"""
return _snap.TStrPool_Cmp(self, *args)
def GetPrimHashCd(self, *args):
"""
GetPrimHashCd(TStrPool self, char const * CStr) -> int
Parameters:
CStr: char const *
GetPrimHashCd(TStrPool self, uint const & Offset) -> int
Parameters:
Offset: uint const &
"""
return _snap.TStrPool_GetPrimHashCd(self, *args)
def GetSecHashCd(self, *args):
"""
GetSecHashCd(TStrPool self, char const * CStr) -> int
Parameters:
CStr: char const *
GetSecHashCd(TStrPool self, uint const & Offset) -> int
Parameters:
Offset: uint const &
"""
return _snap.TStrPool_GetSecHashCd(self, *args)
TStrPool.Save = new_instancemethod(_snap.TStrPool_Save,None,TStrPool)
TStrPool.Len = new_instancemethod(_snap.TStrPool_Len,None,TStrPool)
TStrPool.Size = new_instancemethod(_snap.TStrPool_Size,None,TStrPool)
TStrPool.Empty = new_instancemethod(_snap.TStrPool_Empty,None,TStrPool)
TStrPool.__call__ = new_instancemethod(_snap.TStrPool___call__,None,TStrPool)
TStrPool.AddStr = new_instancemethod(_snap.TStrPool_AddStr,None,TStrPool)
TStrPool.GetCStr = new_instancemethod(_snap.TStrPool_GetCStr,None,TStrPool)
TStrPool.Clr = new_instancemethod(_snap.TStrPool_Clr,None,TStrPool)
TStrPool.Cmp = new_instancemethod(_snap.TStrPool_Cmp,None,TStrPool)
TStrPool.GetPrimHashCd = new_instancemethod(_snap.TStrPool_GetPrimHashCd,None,TStrPool)
TStrPool.GetSecHashCd = new_instancemethod(_snap.TStrPool_GetSecHashCd,None,TStrPool)
TStrPool_swigregister = _snap.TStrPool_swigregister
TStrPool_swigregister(TStrPool)
def TStrPool_New(*args):
"""
New(uint const & _MxBfLen=0, uint const & _GrowBy=16*1024*1024) -> PStrPool
Parameters:
_MxBfLen: uint const &
_GrowBy: uint const &
New(uint const & _MxBfLen=0) -> PStrPool
Parameters:
_MxBfLen: uint const &
New() -> PStrPool
New(TSIn SIn) -> PStrPool
Parameters:
SIn: TSIn &
TStrPool_New(TStr fileName) -> PStrPool
Parameters:
fileName: TStr const &
"""
return _snap.TStrPool_New(*args)
def TStrPool_Load(*args):
"""
Load(TSIn SIn, bool LoadCompacted=True) -> PStrPool
Parameters:
SIn: TSIn &
LoadCompacted: bool
TStrPool_Load(TSIn SIn) -> PStrPool
Parameters:
SIn: TSIn &
"""
return _snap.TStrPool_Load(*args)
class TStrPool64(object):
"""Proxy of C++ TStrPool64 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TStrPool64 self, ::TSize _MxBfL=0, ::TSize _GrowBy=16*1024*1024) -> TStrPool64
Parameters:
_MxBfL: ::TSize
_GrowBy: ::TSize
__init__(TStrPool64 self, ::TSize _MxBfL=0) -> TStrPool64
Parameters:
_MxBfL: ::TSize
__init__(TStrPool64 self) -> TStrPool64
__init__(TStrPool64 self, TStrPool64 StrPool) -> TStrPool64
Parameters:
StrPool: TStrPool64 const &
__init__(TStrPool64 self, TSIn SIn, bool LoadCompact=True) -> TStrPool64
Parameters:
SIn: TSIn &
LoadCompact: bool
__init__(TStrPool64 self, TSIn SIn) -> TStrPool64
Parameters:
SIn: TSIn &
"""
_snap.TStrPool64_swiginit(self,_snap.new_TStrPool64(*args))
__swig_destroy__ = _snap.delete_TStrPool64
def Save(self, *args):
"""
Save(TStrPool64 self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TStrPool64_Save(self, *args)
def New(MxBfL=0, GrowBy=16*1024*1024):
"""
New(::TSize MxBfL=0, ::TSize GrowBy=16*1024*1024) -> PStrPool64
Parameters:
MxBfL: ::TSize
GrowBy: ::TSize
New(::TSize MxBfL=0) -> PStrPool64
Parameters:
MxBfL: ::TSize
New() -> PStrPool64
"""
return _snap.TStrPool64_New(MxBfL, GrowBy)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn, bool LoadCompact=True) -> PStrPool64
Parameters:
SIn: TSIn &
LoadCompact: bool
Load(TSIn SIn) -> PStrPool64
Parameters:
SIn: TSIn &
"""
return _snap.TStrPool64_Load(*args)
Load = staticmethod(Load)
def GetMemUsed(self):
"""
GetMemUsed(TStrPool64 self) -> uint64
Parameters:
self: TStrPool64 const *
"""
return _snap.TStrPool64_GetMemUsed(self)
def Empty(self):
"""
Empty(TStrPool64 self) -> bool
Parameters:
self: TStrPool64 const *
"""
return _snap.TStrPool64_Empty(self)
def Len(self):
"""
Len(TStrPool64 self) -> uint64
Parameters:
self: TStrPool64 const *
"""
return _snap.TStrPool64_Len(self)
def Reserved(self):
"""
Reserved(TStrPool64 self) -> uint64
Parameters:
self: TStrPool64 const *
"""
return _snap.TStrPool64_Reserved(self)
def Clr(self, DoDel=False):
"""
Clr(TStrPool64 self, bool DoDel=False)
Parameters:
DoDel: bool
Clr(TStrPool64 self)
Parameters:
self: TStrPool64 *
"""
return _snap.TStrPool64_Clr(self, DoDel)
def Cmp(self, *args):
"""
Cmp(TStrPool64 self, uint64 Offset, char const * Str) -> int
Parameters:
Offset: uint64
Str: char const *
"""
return _snap.TStrPool64_Cmp(self, *args)
def AddStr(self, *args):
"""
AddStr(TStrPool64 self, TStr Str) -> uint64
Parameters:
Str: TStr const &
"""
return _snap.TStrPool64_AddStr(self, *args)
TStrPool64.Save = new_instancemethod(_snap.TStrPool64_Save,None,TStrPool64)
TStrPool64.GetMemUsed = new_instancemethod(_snap.TStrPool64_GetMemUsed,None,TStrPool64)
TStrPool64.Empty = new_instancemethod(_snap.TStrPool64_Empty,None,TStrPool64)
TStrPool64.Len = new_instancemethod(_snap.TStrPool64_Len,None,TStrPool64)
TStrPool64.Reserved = new_instancemethod(_snap.TStrPool64_Reserved,None,TStrPool64)
TStrPool64.Clr = new_instancemethod(_snap.TStrPool64_Clr,None,TStrPool64)
TStrPool64.Cmp = new_instancemethod(_snap.TStrPool64_Cmp,None,TStrPool64)
TStrPool64.AddStr = new_instancemethod(_snap.TStrPool64_AddStr,None,TStrPool64)
TStrPool64_swigregister = _snap.TStrPool64_swigregister
TStrPool64_swigregister(TStrPool64)
def TStrPool64_New(MxBfL=0, GrowBy=16*1024*1024):
"""
New(::TSize MxBfL=0, ::TSize GrowBy=16*1024*1024) -> PStrPool64
Parameters:
MxBfL: ::TSize
GrowBy: ::TSize
New(::TSize MxBfL=0) -> PStrPool64
Parameters:
MxBfL: ::TSize
TStrPool64_New() -> PStrPool64
"""
return _snap.TStrPool64_New(MxBfL, GrowBy)
def TStrPool64_Load(*args):
"""
Load(TSIn SIn, bool LoadCompact=True) -> PStrPool64
Parameters:
SIn: TSIn &
LoadCompact: bool
TStrPool64_Load(TSIn SIn) -> PStrPool64
Parameters:
SIn: TSIn &
"""
return _snap.TStrPool64_Load(*args)
class TVoid(object):
"""Proxy of C++ TVoid class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TVoid self) -> TVoid
__init__(TVoid self, TSIn arg2) -> TVoid
Parameters:
arg2: TSIn &
"""
_snap.TVoid_swiginit(self,_snap.new_TVoid(*args))
def Save(self, *args):
"""
Save(TVoid self, TSOut arg2)
Parameters:
arg2: TSOut &
"""
return _snap.TVoid_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TVoid self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TVoid_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TVoid self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TVoid_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TVoid self, TVoid arg2) -> bool
Parameters:
arg2: TVoid const &
"""
return _snap.TVoid___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TVoid self, TVoid arg2) -> bool
Parameters:
arg2: TVoid const &
"""
return _snap.TVoid___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TVoid self) -> int
Parameters:
self: TVoid const *
"""
return _snap.TVoid_GetMemUsed(self)
__swig_destroy__ = _snap.delete_TVoid
TVoid.Save = new_instancemethod(_snap.TVoid_Save,None,TVoid)
TVoid.LoadXml = new_instancemethod(_snap.TVoid_LoadXml,None,TVoid)
TVoid.SaveXml = new_instancemethod(_snap.TVoid_SaveXml,None,TVoid)
TVoid.__eq__ = new_instancemethod(_snap.TVoid___eq__,None,TVoid)
TVoid.__lt__ = new_instancemethod(_snap.TVoid___lt__,None,TVoid)
TVoid.GetMemUsed = new_instancemethod(_snap.TVoid_GetMemUsed,None,TVoid)
TVoid_swigregister = _snap.TVoid_swigregister
TVoid_swigregister(TVoid)
class TBool(object):
"""Proxy of C++ TBool class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TBool_Val_get, _snap.TBool_Val_set)
Rnd = _swig_property(_snap.TBool_Rnd_get, _snap.TBool_Rnd_set)
def __nonzero__(self):
return _snap.TBool___nonzero__(self)
__bool__ = __nonzero__
def __init__(self, *args):
"""
__init__(TBool self) -> TBool
__init__(TBool self, bool const & _Val) -> TBool
Parameters:
_Val: bool const &
__init__(TBool self, TSIn SIn) -> TBool
Parameters:
SIn: TSIn &
"""
_snap.TBool_swiginit(self,_snap.new_TBool(*args))
def Load(self, *args):
"""
Load(TBool self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TBool_Load(self, *args)
def Save(self, *args):
"""
Save(TBool self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TBool_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TBool self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TBool_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TBool self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TBool_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TBool self, TBool Bool) -> bool
Parameters:
Bool: TBool const &
"""
return _snap.TBool___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TBool self, TBool Bool) -> bool
Parameters:
Bool: TBool const &
"""
return _snap.TBool___lt__(self, *args)
def __call__(self):
"""
__call__(TBool self) -> bool
Parameters:
self: TBool const *
"""
return _snap.TBool___call__(self)
def GetMemUsed(self):
"""
GetMemUsed(TBool self) -> int
Parameters:
self: TBool const *
"""
return _snap.TBool_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TBool self) -> int
Parameters:
self: TBool const *
"""
return _snap.TBool_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TBool self) -> int
Parameters:
self: TBool const *
"""
return _snap.TBool_GetSecHashCd(self)
def GetRnd():
"""GetRnd() -> bool"""
return _snap.TBool_GetRnd()
GetRnd = staticmethod(GetRnd)
def GetYNStr(*args):
"""
GetYNStr(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_GetYNStr(*args)
GetYNStr = staticmethod(GetYNStr)
def GetYesNoStr(*args):
"""
GetYesNoStr(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_GetYesNoStr(*args)
GetYesNoStr = staticmethod(GetYesNoStr)
def Get01Str(*args):
"""
Get01Str(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_Get01Str(*args)
Get01Str = staticmethod(Get01Str)
def IsValStr(*args):
"""
IsValStr(TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TBool_IsValStr(*args)
IsValStr = staticmethod(IsValStr)
def GetValFromStr(*args):
"""
GetValFromStr(TStr Str) -> bool
Parameters:
Str: TStr const &
GetValFromStr(TStr Str, bool const & DfVal) -> bool
Parameters:
Str: TStr const &
DfVal: bool const &
"""
return _snap.TBool_GetValFromStr(*args)
GetValFromStr = staticmethod(GetValFromStr)
__swig_destroy__ = _snap.delete_TBool
TBool.Load = new_instancemethod(_snap.TBool_Load,None,TBool)
TBool.Save = new_instancemethod(_snap.TBool_Save,None,TBool)
TBool.LoadXml = new_instancemethod(_snap.TBool_LoadXml,None,TBool)
TBool.SaveXml = new_instancemethod(_snap.TBool_SaveXml,None,TBool)
TBool.__eq__ = new_instancemethod(_snap.TBool___eq__,None,TBool)
TBool.__lt__ = new_instancemethod(_snap.TBool___lt__,None,TBool)
TBool.__call__ = new_instancemethod(_snap.TBool___call__,None,TBool)
TBool.GetMemUsed = new_instancemethod(_snap.TBool_GetMemUsed,None,TBool)
TBool.GetPrimHashCd = new_instancemethod(_snap.TBool_GetPrimHashCd,None,TBool)
TBool.GetSecHashCd = new_instancemethod(_snap.TBool_GetSecHashCd,None,TBool)
TBool_swigregister = _snap.TBool_swigregister
TBool_swigregister(TBool)
TBool.Mn = _snap.cvar.TBool_Mn
TBool.Mx = _snap.cvar.TBool_Mx
TBool.Vals = _snap.cvar.TBool_Vals
TBool.FalseStr = _snap.cvar.TBool_FalseStr
TBool.TrueStr = _snap.cvar.TBool_TrueStr
TBool.NStr = _snap.cvar.TBool_NStr
TBool.YStr = _snap.cvar.TBool_YStr
TBool.NoStr = _snap.cvar.TBool_NoStr
TBool.YesStr = _snap.cvar.TBool_YesStr
def TBool_GetRnd():
"""TBool_GetRnd() -> bool"""
return _snap.TBool_GetRnd()
def TBool_GetYNStr(*args):
"""
TBool_GetYNStr(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_GetYNStr(*args)
def TBool_GetYesNoStr(*args):
"""
TBool_GetYesNoStr(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_GetYesNoStr(*args)
def TBool_Get01Str(*args):
"""
TBool_Get01Str(bool const & Val) -> TStr
Parameters:
Val: bool const &
"""
return _snap.TBool_Get01Str(*args)
def TBool_IsValStr(*args):
"""
TBool_IsValStr(TStr Str) -> bool
Parameters:
Str: TStr const &
"""
return _snap.TBool_IsValStr(*args)
def TBool_GetValFromStr(*args):
"""
GetValFromStr(TStr Str) -> bool
Parameters:
Str: TStr const &
TBool_GetValFromStr(TStr Str, bool const & DfVal) -> bool
Parameters:
Str: TStr const &
DfVal: bool const &
"""
return _snap.TBool_GetValFromStr(*args)
class TCh(object):
"""Proxy of C++ TCh class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TCh_Val_get, _snap.TCh_Val_set)
def __init__(self, *args):
"""
__init__(TCh self) -> TCh
__init__(TCh self, char const & _Val) -> TCh
Parameters:
_Val: char const &
__init__(TCh self, TSIn SIn) -> TCh
Parameters:
SIn: TSIn &
"""
_snap.TCh_swiginit(self,_snap.new_TCh(*args))
def Save(self, *args):
"""
Save(TCh self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TCh_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TCh self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TCh_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TCh self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TCh_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TCh self, TCh Ch) -> bool
Parameters:
Ch: TCh const &
"""
return _snap.TCh___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TCh self, TCh Ch) -> bool
Parameters:
Ch: TCh const &
"""
return _snap.TCh___lt__(self, *args)
def __call__(self):
"""
__call__(TCh self) -> char
Parameters:
self: TCh const *
"""
return _snap.TCh___call__(self)
def GetMemUsed(self):
"""
GetMemUsed(TCh self) -> int
Parameters:
self: TCh const *
"""
return _snap.TCh_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TCh self) -> int
Parameters:
self: TCh const *
"""
return _snap.TCh_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TCh self) -> int
Parameters:
self: TCh const *
"""
return _snap.TCh_GetSecHashCd(self)
def IsWs(*args):
"""
IsWs(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsWs(*args)
IsWs = staticmethod(IsWs)
def IsAlpha(*args):
"""
IsAlpha(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsAlpha(*args)
IsAlpha = staticmethod(IsAlpha)
def IsNum(*args):
"""
IsNum(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsNum(*args)
IsNum = staticmethod(IsNum)
def IsAlNum(*args):
"""
IsAlNum(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsAlNum(*args)
IsAlNum = staticmethod(IsAlNum)
def GetNum(*args):
"""
GetNum(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetNum(*args)
GetNum = staticmethod(GetNum)
def IsHex(*args):
"""
IsHex(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsHex(*args)
IsHex = staticmethod(IsHex)
def GetHex(*args):
"""
GetHex(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetHex(*args)
GetHex = staticmethod(GetHex)
def GetHexCh(*args):
"""
GetHexCh(int const & Val) -> char
Parameters:
Val: int const &
"""
return _snap.TCh_GetHexCh(*args)
GetHexCh = staticmethod(GetHexCh)
def IsUc(*args):
"""
IsUc(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_IsUc(*args)
IsUc = staticmethod(IsUc)
def GetUc(*args):
"""
GetUc(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_GetUc(*args)
GetUc = staticmethod(GetUc)
def GetUsFromYuAscii(*args):
"""
GetUsFromYuAscii(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_GetUsFromYuAscii(*args)
GetUsFromYuAscii = staticmethod(GetUsFromYuAscii)
__swig_destroy__ = _snap.delete_TCh
TCh.Save = new_instancemethod(_snap.TCh_Save,None,TCh)
TCh.LoadXml = new_instancemethod(_snap.TCh_LoadXml,None,TCh)
TCh.SaveXml = new_instancemethod(_snap.TCh_SaveXml,None,TCh)
TCh.__eq__ = new_instancemethod(_snap.TCh___eq__,None,TCh)
TCh.__lt__ = new_instancemethod(_snap.TCh___lt__,None,TCh)
TCh.__call__ = new_instancemethod(_snap.TCh___call__,None,TCh)
TCh.GetMemUsed = new_instancemethod(_snap.TCh_GetMemUsed,None,TCh)
TCh.GetPrimHashCd = new_instancemethod(_snap.TCh_GetPrimHashCd,None,TCh)
TCh.GetSecHashCd = new_instancemethod(_snap.TCh_GetSecHashCd,None,TCh)
TCh_swigregister = _snap.TCh_swigregister
TCh_swigregister(TCh)
TCh.Mn = _snap.cvar.TCh_Mn
TCh.Mx = _snap.cvar.TCh_Mx
TCh.Vals = _snap.cvar.TCh_Vals
TCh.NullCh = _snap.cvar.TCh_NullCh
TCh.TabCh = _snap.cvar.TCh_TabCh
TCh.LfCh = _snap.cvar.TCh_LfCh
TCh.CrCh = _snap.cvar.TCh_CrCh
TCh.EofCh = _snap.cvar.TCh_EofCh
TCh.HashCh = _snap.cvar.TCh_HashCh
def TCh_IsWs(*args):
"""
TCh_IsWs(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsWs(*args)
def TCh_IsAlpha(*args):
"""
TCh_IsAlpha(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsAlpha(*args)
def TCh_IsNum(*args):
"""
TCh_IsNum(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsNum(*args)
def TCh_IsAlNum(*args):
"""
TCh_IsAlNum(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsAlNum(*args)
def TCh_GetNum(*args):
"""
TCh_GetNum(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetNum(*args)
def TCh_IsHex(*args):
"""
TCh_IsHex(char const & Ch) -> bool
Parameters:
Ch: char const &
"""
return _snap.TCh_IsHex(*args)
def TCh_GetHex(*args):
"""
TCh_GetHex(char const & Ch) -> int
Parameters:
Ch: char const &
"""
return _snap.TCh_GetHex(*args)
def TCh_GetHexCh(*args):
"""
TCh_GetHexCh(int const & Val) -> char
Parameters:
Val: int const &
"""
return _snap.TCh_GetHexCh(*args)
def TCh_IsUc(*args):
"""
TCh_IsUc(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_IsUc(*args)
def TCh_GetUc(*args):
"""
TCh_GetUc(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_GetUc(*args)
def TCh_GetUsFromYuAscii(*args):
"""
TCh_GetUsFromYuAscii(char const & Ch) -> char
Parameters:
Ch: char const &
"""
return _snap.TCh_GetUsFromYuAscii(*args)
class TUCh(object):
"""Proxy of C++ TUCh class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TUCh_Val_get, _snap.TUCh_Val_set)
def __init__(self, *args):
"""
__init__(TUCh self) -> TUCh
__init__(TUCh self, uchar const & _Val) -> TUCh
Parameters:
_Val: uchar const &
__init__(TUCh self, TSIn SIn) -> TUCh
Parameters:
SIn: TSIn &
"""
_snap.TUCh_swiginit(self,_snap.new_TUCh(*args))
def Save(self, *args):
"""
Save(TUCh self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TUCh_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TUCh self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TUCh_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TUCh self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TUCh_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TUCh self, TUCh UCh) -> bool
Parameters:
UCh: TUCh const &
"""
return _snap.TUCh___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TUCh self, TUCh UCh) -> bool
Parameters:
UCh: TUCh const &
"""
return _snap.TUCh___lt__(self, *args)
def __call__(self):
"""
__call__(TUCh self) -> uchar
Parameters:
self: TUCh const *
"""
return _snap.TUCh___call__(self)
def GetMemUsed(self):
"""
GetMemUsed(TUCh self) -> int
Parameters:
self: TUCh const *
"""
return _snap.TUCh_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TUCh self) -> int
Parameters:
self: TUCh const *
"""
return _snap.TUCh_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TUCh self) -> int
Parameters:
self: TUCh const *
"""
return _snap.TUCh_GetSecHashCd(self)
__swig_destroy__ = _snap.delete_TUCh
TUCh.Save = new_instancemethod(_snap.TUCh_Save,None,TUCh)
TUCh.LoadXml = new_instancemethod(_snap.TUCh_LoadXml,None,TUCh)
TUCh.SaveXml = new_instancemethod(_snap.TUCh_SaveXml,None,TUCh)
TUCh.__eq__ = new_instancemethod(_snap.TUCh___eq__,None,TUCh)
TUCh.__lt__ = new_instancemethod(_snap.TUCh___lt__,None,TUCh)
TUCh.__call__ = new_instancemethod(_snap.TUCh___call__,None,TUCh)
TUCh.GetMemUsed = new_instancemethod(_snap.TUCh_GetMemUsed,None,TUCh)
TUCh.GetPrimHashCd = new_instancemethod(_snap.TUCh_GetPrimHashCd,None,TUCh)
TUCh.GetSecHashCd = new_instancemethod(_snap.TUCh_GetSecHashCd,None,TUCh)
TUCh_swigregister = _snap.TUCh_swigregister
TUCh_swigregister(TUCh)
TUCh.Mn = _snap.cvar.TUCh_Mn
TUCh.Mx = _snap.cvar.TUCh_Mx
TUCh.Vals = _snap.cvar.TUCh_Vals
class TSInt(object):
"""Proxy of C++ TSInt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TSInt_Val_get, _snap.TSInt_Val_set)
def __init__(self, *args):
"""
__init__(TSInt self) -> TSInt
__init__(TSInt self, int16 const & _Val) -> TSInt
Parameters:
_Val: int16 const &
__init__(TSInt self, TSIn SIn) -> TSInt
Parameters:
SIn: TSIn &
"""
_snap.TSInt_swiginit(self,_snap.new_TSInt(*args))
def Load(self, *args):
"""
Load(TSInt self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TSInt_Load(self, *args)
def Save(self, *args):
"""
Save(TSInt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TSInt_Save(self, *args)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TSInt self) -> int
Parameters:
self: TSInt const *
"""
return _snap.TSInt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TSInt self) -> int
Parameters:
self: TSInt const *
"""
return _snap.TSInt_GetSecHashCd(self)
__swig_destroy__ = _snap.delete_TSInt
TSInt.Load = new_instancemethod(_snap.TSInt_Load,None,TSInt)
TSInt.Save = new_instancemethod(_snap.TSInt_Save,None,TSInt)
TSInt.GetPrimHashCd = new_instancemethod(_snap.TSInt_GetPrimHashCd,None,TSInt)
TSInt.GetSecHashCd = new_instancemethod(_snap.TSInt_GetSecHashCd,None,TSInt)
TSInt_swigregister = _snap.TSInt_swigregister
TSInt_swigregister(TSInt)
class TInt(object):
"""Proxy of C++ TInt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TInt_Val_get, _snap.TInt_Val_set)
Rnd = _swig_property(_snap.TInt_Rnd_get, _snap.TInt_Rnd_set)
def __init__(self, *args):
"""
__init__(TInt self) -> TInt
__init__(TInt self, int const & _Val) -> TInt
Parameters:
_Val: int const &
__init__(TInt self, TSIn SIn) -> TInt
Parameters:
SIn: TSIn &
"""
_snap.TInt_swiginit(self,_snap.new_TInt(*args))
def Load(self, *args):
"""
Load(TInt self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TInt_Load(self, *args)
def Save(self, *args):
"""
Save(TInt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TInt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TInt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TInt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TInt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TInt_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TInt self, TInt Int) -> bool
Parameters:
Int: TInt const &
__eq__(TInt self, int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TInt self, int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TInt self, TInt Int) -> bool
Parameters:
Int: TInt const &
__lt__(TInt self, int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt___lt__(self, *args)
def __call__(self):
"""
__call__(TInt self) -> int
Parameters:
self: TInt const *
"""
return _snap.TInt___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TInt self, int const & Int) -> TInt
Parameters:
Int: int const &
"""
return _snap.TInt___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TInt self, int const & Int) -> TInt
Parameters:
Int: int const &
"""
return _snap.TInt___isub__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TInt self) -> int
Parameters:
self: TInt const *
"""
return _snap.TInt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TInt self) -> int
Parameters:
self: TInt const *
"""
return _snap.TInt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TInt self) -> int
Parameters:
self: TInt const *
"""
return _snap.TInt_GetSecHashCd(self)
def Abs(*args):
"""
Abs(int const & Int) -> int
Parameters:
Int: int const &
"""
return _snap.TInt_Abs(*args)
Abs = staticmethod(Abs)
def Sign(*args):
"""
Sign(int const & Int) -> int
Parameters:
Int: int const &
"""
return _snap.TInt_Sign(*args)
Sign = staticmethod(Sign)
def Swap(*args):
"""
Swap(int & Int1, int & Int2)
Parameters:
Int1: int &
Int2: int &
"""
return _snap.TInt_Swap(*args)
Swap = staticmethod(Swap)
def GetRnd(Range=0):
"""
GetRnd(int const & Range=0) -> int
Parameters:
Range: int const &
GetRnd() -> int
"""
return _snap.TInt_GetRnd(Range)
GetRnd = staticmethod(GetRnd)
def IsOdd(*args):
"""
IsOdd(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsOdd(*args)
IsOdd = staticmethod(IsOdd)
def IsEven(*args):
"""
IsEven(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsEven(*args)
IsEven = staticmethod(IsEven)
def GetMn(*args):
"""
GetMn(int const & Int1, int const & Int2) -> int
Parameters:
Int1: int const &
Int2: int const &
GetMn(int const & Int1, int const & Int2, int const & Int3) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
GetMn(int const & Int1, int const & Int2, int const & Int3, int const & Int4) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
Int4: int const &
"""
return _snap.TInt_GetMn(*args)
GetMn = staticmethod(GetMn)
def GetMx(*args):
"""
GetMx(int const & Int1, int const & Int2) -> int
Parameters:
Int1: int const &
Int2: int const &
GetMx(int const & Int1, int const & Int2, int const & Int3) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
GetMx(int const & Int1, int const & Int2, int const & Int3, int const & Int4) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
Int4: int const &
"""
return _snap.TInt_GetMx(*args)
GetMx = staticmethod(GetMx)
def GetInRng(*args):
"""
GetInRng(int const & Val, int const & Mn, int const & Mx) -> int
Parameters:
Val: int const &
Mn: int const &
Mx: int const &
"""
return _snap.TInt_GetInRng(*args)
GetInRng = staticmethod(GetInRng)
def GetHexStr(*args):
"""
GetHexStr(int const & Val) -> TStr
Parameters:
Val: int const &
GetHexStr(TInt Int) -> TStr
Parameters:
Int: TInt const &
"""
return _snap.TInt_GetHexStr(*args)
GetHexStr = staticmethod(GetHexStr)
def GetKiloStr(*args):
"""
GetKiloStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetKiloStr(*args)
GetKiloStr = staticmethod(GetKiloStr)
def GetMegaStr(*args):
"""
GetMegaStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetMegaStr(*args)
GetMegaStr = staticmethod(GetMegaStr)
def SaveFrugalInt(*args):
"""
SaveFrugalInt(char * pDest, int i) -> char *
Parameters:
pDest: char *
i: int
"""
return _snap.TInt_SaveFrugalInt(*args)
SaveFrugalInt = staticmethod(SaveFrugalInt)
def LoadFrugalInt(*args):
"""
LoadFrugalInt(char * pSrc, int & i) -> char *
Parameters:
pSrc: char *
i: int &
"""
return _snap.TInt_LoadFrugalInt(*args)
LoadFrugalInt = staticmethod(LoadFrugalInt)
def TestFrugalInt():
"""TestFrugalInt()"""
return _snap.TInt_TestFrugalInt()
TestFrugalInt = staticmethod(TestFrugalInt)
def SaveFrugalIntV(*args):
"""
SaveFrugalIntV(TSOut SOut, TIntV IntV)
Parameters:
SOut: TSOut &
IntV: TVec< TInt,int > const &
"""
return _snap.TInt_SaveFrugalIntV(*args)
SaveFrugalIntV = staticmethod(SaveFrugalIntV)
def LoadFrugalIntV(*args):
"""
LoadFrugalIntV(TSIn SIn, TIntV IntV, bool ClrP=True)
Parameters:
SIn: TSIn &
IntV: TVec< TInt,int > &
ClrP: bool
LoadFrugalIntV(TSIn SIn, TIntV IntV)
Parameters:
SIn: TSIn &
IntV: TVec< TInt,int > &
"""
return _snap.TInt_LoadFrugalIntV(*args)
LoadFrugalIntV = staticmethod(LoadFrugalIntV)
__swig_destroy__ = _snap.delete_TInt
TInt.Load = new_instancemethod(_snap.TInt_Load,None,TInt)
TInt.Save = new_instancemethod(_snap.TInt_Save,None,TInt)
TInt.LoadXml = new_instancemethod(_snap.TInt_LoadXml,None,TInt)
TInt.SaveXml = new_instancemethod(_snap.TInt_SaveXml,None,TInt)
TInt.__eq__ = new_instancemethod(_snap.TInt___eq__,None,TInt)
TInt.__ne__ = new_instancemethod(_snap.TInt___ne__,None,TInt)
TInt.__lt__ = new_instancemethod(_snap.TInt___lt__,None,TInt)
TInt.__call__ = new_instancemethod(_snap.TInt___call__,None,TInt)
TInt.__iadd__ = new_instancemethod(_snap.TInt___iadd__,None,TInt)
TInt.__isub__ = new_instancemethod(_snap.TInt___isub__,None,TInt)
TInt.GetMemUsed = new_instancemethod(_snap.TInt_GetMemUsed,None,TInt)
TInt.GetPrimHashCd = new_instancemethod(_snap.TInt_GetPrimHashCd,None,TInt)
TInt.GetSecHashCd = new_instancemethod(_snap.TInt_GetSecHashCd,None,TInt)
TInt_swigregister = _snap.TInt_swigregister
TInt_swigregister(TInt)
TInt.Mn = _snap.cvar.TInt_Mn
TInt.Mx = _snap.cvar.TInt_Mx
TInt.Kilo = _snap.cvar.TInt_Kilo
TInt.Mega = _snap.cvar.TInt_Mega
TInt.Giga = _snap.cvar.TInt_Giga
def TInt_Abs(*args):
"""
TInt_Abs(int const & Int) -> int
Parameters:
Int: int const &
"""
return _snap.TInt_Abs(*args)
def TInt_Sign(*args):
"""
TInt_Sign(int const & Int) -> int
Parameters:
Int: int const &
"""
return _snap.TInt_Sign(*args)
def TInt_Swap(*args):
"""
TInt_Swap(int & Int1, int & Int2)
Parameters:
Int1: int &
Int2: int &
"""
return _snap.TInt_Swap(*args)
def TInt_GetRnd(Range=0):
"""
GetRnd(int const & Range=0) -> int
Parameters:
Range: int const &
TInt_GetRnd() -> int
"""
return _snap.TInt_GetRnd(Range)
def TInt_IsOdd(*args):
"""
TInt_IsOdd(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsOdd(*args)
def TInt_IsEven(*args):
"""
TInt_IsEven(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsEven(*args)
def TInt_GetMn(*args):
"""
GetMn(int const & Int1, int const & Int2) -> int
Parameters:
Int1: int const &
Int2: int const &
GetMn(int const & Int1, int const & Int2, int const & Int3) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
TInt_GetMn(int const & Int1, int const & Int2, int const & Int3, int const & Int4) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
Int4: int const &
"""
return _snap.TInt_GetMn(*args)
def TInt_GetMx(*args):
"""
GetMx(int const & Int1, int const & Int2) -> int
Parameters:
Int1: int const &
Int2: int const &
GetMx(int const & Int1, int const & Int2, int const & Int3) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
TInt_GetMx(int const & Int1, int const & Int2, int const & Int3, int const & Int4) -> int
Parameters:
Int1: int const &
Int2: int const &
Int3: int const &
Int4: int const &
"""
return _snap.TInt_GetMx(*args)
def TInt_GetInRng(*args):
"""
TInt_GetInRng(int const & Val, int const & Mn, int const & Mx) -> int
Parameters:
Val: int const &
Mn: int const &
Mx: int const &
"""
return _snap.TInt_GetInRng(*args)
def TInt_GetHexStr(*args):
"""
GetHexStr(int const & Val) -> TStr
Parameters:
Val: int const &
TInt_GetHexStr(TInt Int) -> TStr
Parameters:
Int: TInt const &
"""
return _snap.TInt_GetHexStr(*args)
def TInt_GetKiloStr(*args):
"""
TInt_GetKiloStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetKiloStr(*args)
def TInt_GetMegaStr(*args):
"""
TInt_GetMegaStr(int const & Val) -> TStr
Parameters:
Val: int const &
"""
return _snap.TInt_GetMegaStr(*args)
def TInt_SaveFrugalInt(*args):
"""
TInt_SaveFrugalInt(char * pDest, int i) -> char *
Parameters:
pDest: char *
i: int
"""
return _snap.TInt_SaveFrugalInt(*args)
def TInt_LoadFrugalInt(*args):
"""
TInt_LoadFrugalInt(char * pSrc, int & i) -> char *
Parameters:
pSrc: char *
i: int &
"""
return _snap.TInt_LoadFrugalInt(*args)
def TInt_TestFrugalInt():
"""TInt_TestFrugalInt()"""
return _snap.TInt_TestFrugalInt()
def TInt_SaveFrugalIntV(*args):
"""
TInt_SaveFrugalIntV(TSOut SOut, TIntV IntV)
Parameters:
SOut: TSOut &
IntV: TVec< TInt,int > const &
"""
return _snap.TInt_SaveFrugalIntV(*args)
def TInt_LoadFrugalIntV(*args):
"""
LoadFrugalIntV(TSIn SIn, TIntV IntV, bool ClrP=True)
Parameters:
SIn: TSIn &
IntV: TVec< TInt,int > &
ClrP: bool
TInt_LoadFrugalIntV(TSIn SIn, TIntV IntV)
Parameters:
SIn: TSIn &
IntV: TVec< TInt,int > &
"""
return _snap.TInt_LoadFrugalIntV(*args)
class TUInt(object):
"""Proxy of C++ TUInt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TUInt_Val_get, _snap.TUInt_Val_set)
Rnd = _swig_property(_snap.TUInt_Rnd_get, _snap.TUInt_Rnd_set)
def __init__(self, *args):
"""
__init__(TUInt self) -> TUInt
__init__(TUInt self, uint const & _Val) -> TUInt
Parameters:
_Val: uint const &
__init__(TUInt self, TSIn SIn) -> TUInt
Parameters:
SIn: TSIn &
"""
_snap.TUInt_swiginit(self,_snap.new_TUInt(*args))
def Load(self, *args):
"""
Load(TUInt self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TUInt_Load(self, *args)
def Save(self, *args):
"""
Save(TUInt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TUInt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TUInt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TUInt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TUInt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TUInt_SaveXml(self, *args)
def __call__(self, *args):
"""
__call__(TUInt self) -> uint
__call__(TUInt self) -> uint &
Parameters:
self: TUInt *
"""
return _snap.TUInt___call__(self, *args)
def __invert__(self):
"""
__invert__(TUInt self) -> TUInt
Parameters:
self: TUInt *
"""
return _snap.TUInt___invert__(self)
def __iand__(self, *args):
"""
__iand__(TUInt self, TUInt UInt) -> TUInt
Parameters:
UInt: TUInt const &
"""
return _snap.TUInt___iand__(self, *args)
def __ior__(self, *args):
"""
__ior__(TUInt self, TUInt UInt) -> TUInt
Parameters:
UInt: TUInt const &
"""
return _snap.TUInt___ior__(self, *args)
def __ixor__(self, *args):
"""
__ixor__(TUInt self, TUInt UInt) -> TUInt
Parameters:
UInt: TUInt const &
"""
return _snap.TUInt___ixor__(self, *args)
def __irshift__(self, *args):
"""
__irshift__(TUInt self, int const & ShiftBits) -> TUInt
Parameters:
ShiftBits: int const &
"""
return _snap.TUInt___irshift__(self, *args)
def __ilshift__(self, *args):
"""
__ilshift__(TUInt self, int const & ShiftBits) -> TUInt
Parameters:
ShiftBits: int const &
"""
return _snap.TUInt___ilshift__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TUInt self) -> int
Parameters:
self: TUInt const *
"""
return _snap.TUInt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TUInt self) -> int
Parameters:
self: TUInt const *
"""
return _snap.TUInt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TUInt self) -> int
Parameters:
self: TUInt const *
"""
return _snap.TUInt_GetSecHashCd(self)
def GetRnd(Range=0):
"""
GetRnd(uint const & Range=0) -> uint
Parameters:
Range: uint const &
GetRnd() -> uint
"""
return _snap.TUInt_GetRnd(Range)
GetRnd = staticmethod(GetRnd)
def GetKiloStr(*args):
"""
GetKiloStr(uint const & Val) -> TStr
Parameters:
Val: uint const &
"""
return _snap.TUInt_GetKiloStr(*args)
GetKiloStr = staticmethod(GetKiloStr)
def GetMegaStr(*args):
"""
GetMegaStr(uint const & Val) -> TStr
Parameters:
Val: uint const &
"""
return _snap.TUInt_GetMegaStr(*args)
GetMegaStr = staticmethod(GetMegaStr)
def JavaUIntToCppUInt(*args):
"""
JavaUIntToCppUInt(uint const & JavaUInt) -> uint
Parameters:
JavaUInt: uint const &
"""
return _snap.TUInt_JavaUIntToCppUInt(*args)
JavaUIntToCppUInt = staticmethod(JavaUIntToCppUInt)
def IsIpStr(*args):
"""
IsIpStr(TStr IpStr, uint & Ip, char const & SplitCh='.') -> bool
Parameters:
IpStr: TStr const &
Ip: uint &
SplitCh: char const &
IsIpStr(TStr IpStr, uint & Ip) -> bool
Parameters:
IpStr: TStr const &
Ip: uint &
IsIpStr(TStr IpStr, char const & SplitCh='.') -> bool
Parameters:
IpStr: TStr const &
SplitCh: char const &
IsIpStr(TStr IpStr) -> bool
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_IsIpStr(*args)
IsIpStr = staticmethod(IsIpStr)
def GetUIntFromIpStr(*args):
"""
GetUIntFromIpStr(TStr IpStr, char const & SplitCh='.') -> uint
Parameters:
IpStr: TStr const &
SplitCh: char const &
GetUIntFromIpStr(TStr IpStr) -> uint
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_GetUIntFromIpStr(*args)
GetUIntFromIpStr = staticmethod(GetUIntFromIpStr)
def GetStrFromIpUInt(*args):
"""
GetStrFromIpUInt(uint const & Ip) -> TStr
Parameters:
Ip: uint const &
"""
return _snap.TUInt_GetStrFromIpUInt(*args)
GetStrFromIpUInt = staticmethod(GetStrFromIpUInt)
def IsIpv6Str(*args):
"""
IsIpv6Str(TStr IpStr, char const & SplitCh=':') -> bool
Parameters:
IpStr: TStr const &
SplitCh: char const &
IsIpv6Str(TStr IpStr) -> bool
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_IsIpv6Str(*args)
IsIpv6Str = staticmethod(IsIpv6Str)
__swig_destroy__ = _snap.delete_TUInt
TUInt.Load = new_instancemethod(_snap.TUInt_Load,None,TUInt)
TUInt.Save = new_instancemethod(_snap.TUInt_Save,None,TUInt)
TUInt.LoadXml = new_instancemethod(_snap.TUInt_LoadXml,None,TUInt)
TUInt.SaveXml = new_instancemethod(_snap.TUInt_SaveXml,None,TUInt)
TUInt.__call__ = new_instancemethod(_snap.TUInt___call__,None,TUInt)
TUInt.__invert__ = new_instancemethod(_snap.TUInt___invert__,None,TUInt)
TUInt.__iand__ = new_instancemethod(_snap.TUInt___iand__,None,TUInt)
TUInt.__ior__ = new_instancemethod(_snap.TUInt___ior__,None,TUInt)
TUInt.__ixor__ = new_instancemethod(_snap.TUInt___ixor__,None,TUInt)
TUInt.__irshift__ = new_instancemethod(_snap.TUInt___irshift__,None,TUInt)
TUInt.__ilshift__ = new_instancemethod(_snap.TUInt___ilshift__,None,TUInt)
TUInt.GetMemUsed = new_instancemethod(_snap.TUInt_GetMemUsed,None,TUInt)
TUInt.GetPrimHashCd = new_instancemethod(_snap.TUInt_GetPrimHashCd,None,TUInt)
TUInt.GetSecHashCd = new_instancemethod(_snap.TUInt_GetSecHashCd,None,TUInt)
TUInt_swigregister = _snap.TUInt_swigregister
TUInt_swigregister(TUInt)
TUInt.Mn = _snap.cvar.TUInt_Mn
TUInt.Mx = _snap.cvar.TUInt_Mx
def TUInt_GetRnd(Range=0):
"""
GetRnd(uint const & Range=0) -> uint
Parameters:
Range: uint const &
TUInt_GetRnd() -> uint
"""
return _snap.TUInt_GetRnd(Range)
def TUInt_GetKiloStr(*args):
"""
TUInt_GetKiloStr(uint const & Val) -> TStr
Parameters:
Val: uint const &
"""
return _snap.TUInt_GetKiloStr(*args)
def TUInt_GetMegaStr(*args):
"""
TUInt_GetMegaStr(uint const & Val) -> TStr
Parameters:
Val: uint const &
"""
return _snap.TUInt_GetMegaStr(*args)
def TUInt_JavaUIntToCppUInt(*args):
"""
TUInt_JavaUIntToCppUInt(uint const & JavaUInt) -> uint
Parameters:
JavaUInt: uint const &
"""
return _snap.TUInt_JavaUIntToCppUInt(*args)
def TUInt_IsIpStr(*args):
"""
IsIpStr(TStr IpStr, uint & Ip, char const & SplitCh='.') -> bool
Parameters:
IpStr: TStr const &
Ip: uint &
SplitCh: char const &
IsIpStr(TStr IpStr, uint & Ip) -> bool
Parameters:
IpStr: TStr const &
Ip: uint &
IsIpStr(TStr IpStr, char const & SplitCh='.') -> bool
Parameters:
IpStr: TStr const &
SplitCh: char const &
TUInt_IsIpStr(TStr IpStr) -> bool
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_IsIpStr(*args)
def TUInt_GetUIntFromIpStr(*args):
"""
GetUIntFromIpStr(TStr IpStr, char const & SplitCh='.') -> uint
Parameters:
IpStr: TStr const &
SplitCh: char const &
TUInt_GetUIntFromIpStr(TStr IpStr) -> uint
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_GetUIntFromIpStr(*args)
def TUInt_GetStrFromIpUInt(*args):
"""
TUInt_GetStrFromIpUInt(uint const & Ip) -> TStr
Parameters:
Ip: uint const &
"""
return _snap.TUInt_GetStrFromIpUInt(*args)
def TUInt_IsIpv6Str(*args):
"""
IsIpv6Str(TStr IpStr, char const & SplitCh=':') -> bool
Parameters:
IpStr: TStr const &
SplitCh: char const &
TUInt_IsIpv6Str(TStr IpStr) -> bool
Parameters:
IpStr: TStr const &
"""
return _snap.TUInt_IsIpv6Str(*args)
class TUInt64(object):
"""Proxy of C++ TUInt64 class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TUInt64_Val_get, _snap.TUInt64_Val_set)
def __init__(self, *args):
"""
__init__(TUInt64 self) -> TUInt64
__init__(TUInt64 self, TUInt64 Int) -> TUInt64
Parameters:
Int: TUInt64 const &
__init__(TUInt64 self, uint64 const & Int) -> TUInt64
Parameters:
Int: uint64 const &
__init__(TUInt64 self, uint const & MsVal, uint const & LsVal) -> TUInt64
Parameters:
MsVal: uint const &
LsVal: uint const &
__init__(TUInt64 self, void * Pt) -> TUInt64
Parameters:
Pt: void *
__init__(TUInt64 self, TSIn SIn) -> TUInt64
Parameters:
SIn: TSIn &
"""
_snap.TUInt64_swiginit(self,_snap.new_TUInt64(*args))
def Load(self, *args):
"""
Load(TUInt64 self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TUInt64_Load(self, *args)
def Save(self, *args):
"""
Save(TUInt64 self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TUInt64_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TUInt64 self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TUInt64_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TUInt64 self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TUInt64_SaveXml(self, *args)
def __iadd__(self, *args):
"""
__iadd__(TUInt64 self, TUInt64 Int) -> TUInt64
Parameters:
Int: TUInt64 const &
"""
return _snap.TUInt64___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TUInt64 self, TUInt64 Int) -> TUInt64
Parameters:
Int: TUInt64 const &
"""
return _snap.TUInt64___isub__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TUInt64 self) -> int
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TUInt64 self) -> int
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TUInt64 self) -> int
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetSecHashCd(self)
def GetMsVal(self):
"""
GetMsVal(TUInt64 self) -> uint
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetMsVal(self)
def GetLsVal(self):
"""
GetLsVal(TUInt64 self) -> uint
Parameters:
self: TUInt64 const *
"""
return _snap.TUInt64_GetLsVal(self)
def GetHexStr(*args):
"""
GetHexStr(TUInt64 Int) -> TStr
Parameters:
Int: TUInt64 const &
"""
return _snap.TUInt64_GetHexStr(*args)
GetHexStr = staticmethod(GetHexStr)
def GetKiloStr(*args):
"""
GetKiloStr(uint64 const & Val) -> TStr
Parameters:
Val: uint64 const &
"""
return _snap.TUInt64_GetKiloStr(*args)
GetKiloStr = staticmethod(GetKiloStr)
def GetMegaStr(*args):
"""
GetMegaStr(uint64 const & Val) -> TStr
Parameters:
Val: uint64 const &
"""
return _snap.TUInt64_GetMegaStr(*args)
GetMegaStr = staticmethod(GetMegaStr)
__swig_destroy__ = _snap.delete_TUInt64
TUInt64.Load = new_instancemethod(_snap.TUInt64_Load,None,TUInt64)
TUInt64.Save = new_instancemethod(_snap.TUInt64_Save,None,TUInt64)
TUInt64.LoadXml = new_instancemethod(_snap.TUInt64_LoadXml,None,TUInt64)
TUInt64.SaveXml = new_instancemethod(_snap.TUInt64_SaveXml,None,TUInt64)
TUInt64.__iadd__ = new_instancemethod(_snap.TUInt64___iadd__,None,TUInt64)
TUInt64.__isub__ = new_instancemethod(_snap.TUInt64___isub__,None,TUInt64)
TUInt64.GetMemUsed = new_instancemethod(_snap.TUInt64_GetMemUsed,None,TUInt64)
TUInt64.GetPrimHashCd = new_instancemethod(_snap.TUInt64_GetPrimHashCd,None,TUInt64)
TUInt64.GetSecHashCd = new_instancemethod(_snap.TUInt64_GetSecHashCd,None,TUInt64)
TUInt64.GetMsVal = new_instancemethod(_snap.TUInt64_GetMsVal,None,TUInt64)
TUInt64.GetLsVal = new_instancemethod(_snap.TUInt64_GetLsVal,None,TUInt64)
TUInt64_swigregister = _snap.TUInt64_swigregister
TUInt64_swigregister(TUInt64)
TUInt64.Mn = _snap.cvar.TUInt64_Mn
TUInt64.Mx = _snap.cvar.TUInt64_Mx
def TUInt64_GetHexStr(*args):
"""
TUInt64_GetHexStr(TUInt64 Int) -> TStr
Parameters:
Int: TUInt64 const &
"""
return _snap.TUInt64_GetHexStr(*args)
def TUInt64_GetKiloStr(*args):
"""
TUInt64_GetKiloStr(uint64 const & Val) -> TStr
Parameters:
Val: uint64 const &
"""
return _snap.TUInt64_GetKiloStr(*args)
def TUInt64_GetMegaStr(*args):
"""
TUInt64_GetMegaStr(uint64 const & Val) -> TStr
Parameters:
Val: uint64 const &
"""
return _snap.TUInt64_GetMegaStr(*args)
class TFlt(object):
"""Proxy of C++ TFlt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TFlt_Val_get, _snap.TFlt_Val_set)
Rnd = _swig_property(_snap.TFlt_Rnd_get, _snap.TFlt_Rnd_set)
def __init__(self, *args):
"""
__init__(TFlt self) -> TFlt
__init__(TFlt self, double const & _Val) -> TFlt
Parameters:
_Val: double const &
__init__(TFlt self, TSIn SIn) -> TFlt
Parameters:
SIn: TSIn &
__init__(TFlt self, TSIn SIn, bool const & IsTxt) -> TFlt
Parameters:
SIn: TSIn &
IsTxt: bool const &
"""
_snap.TFlt_swiginit(self,_snap.new_TFlt(*args))
def Load(self, *args):
"""
Load(TFlt self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TFlt_Load(self, *args)
def Save(self, *args):
"""
Save(TFlt self, TSOut SOut)
Parameters:
SOut: TSOut &
Save(TFlt self, TSOut SOut, bool const & IsTxt)
Parameters:
SOut: TSOut &
IsTxt: bool const &
"""
return _snap.TFlt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TFlt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TFlt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TFlt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TFlt_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TFlt self, TFlt Flt) -> bool
Parameters:
Flt: TFlt const &
__eq__(TFlt self, double const & Flt) -> bool
Parameters:
Flt: double const &
"""
return _snap.TFlt___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TFlt self, double const & Flt) -> bool
Parameters:
Flt: double const &
"""
return _snap.TFlt___ne__(self, *args)
def __call__(self):
"""
__call__(TFlt self) -> double
Parameters:
self: TFlt const *
"""
return _snap.TFlt___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TFlt self, double const & Flt) -> TFlt
Parameters:
Flt: double const &
"""
return _snap.TFlt___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TFlt self, double const & Flt) -> TFlt
Parameters:
Flt: double const &
"""
return _snap.TFlt___isub__(self, *args)
def __imul__(self, *args):
"""
__imul__(TFlt self, double const & Flt) -> TFlt
Parameters:
Flt: double const &
"""
return _snap.TFlt___imul__(self, *args)
def __idiv__(self, *args):
"""
__idiv__(TFlt self, double const & Flt) -> TFlt
Parameters:
Flt: double const &
"""
return _snap.TFlt___idiv__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TFlt self) -> int
Parameters:
self: TFlt const *
"""
return _snap.TFlt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TFlt self) -> int
Parameters:
self: TFlt const *
"""
return _snap.TFlt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TFlt self) -> int
Parameters:
self: TFlt const *
"""
return _snap.TFlt_GetSecHashCd(self)
def Abs(*args):
"""
Abs(double const & Flt) -> double
Parameters:
Flt: double const &
"""
return _snap.TFlt_Abs(*args)
Abs = staticmethod(Abs)
def Sign(*args):
"""
Sign(double const & Flt) -> int
Parameters:
Flt: double const &
"""
return _snap.TFlt_Sign(*args)
Sign = staticmethod(Sign)
def Round(*args):
"""
Round(double const & Flt) -> int
Parameters:
Flt: double const &
"""
return _snap.TFlt_Round(*args)
Round = staticmethod(Round)
def GetRnd():
"""GetRnd() -> double"""
return _snap.TFlt_GetRnd()
GetRnd = staticmethod(GetRnd)
def Eq6(*args):
"""
Eq6(double const & LFlt, double const & RFlt) -> bool
Parameters:
LFlt: double const &
RFlt: double const &
"""
return _snap.TFlt_Eq6(*args)
Eq6 = staticmethod(Eq6)
def GetMn(*args):
"""
GetMn(double const & Flt1, double const & Flt2) -> double
Parameters:
Flt1: double const &
Flt2: double const &
GetMn(double const & Flt1, double const & Flt2, double const & Flt3) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const &
GetMn(double const & Flt1, double const & Flt2, double const & Flt3, double const & Flt4) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const &
Flt4: double const &
"""
return _snap.TFlt_GetMn(*args)
GetMn = staticmethod(GetMn)
def GetMx(*args):
"""
GetMx(double const & Flt1, double const & Flt2) -> double
Parameters:
Flt1: double const &
Flt2: double const &
GetMx(double const & Flt1, double const & Flt2, double const Flt3) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const
GetMx(double const & Flt1, double const & Flt2, double const Flt3, double const & Flt4) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const
Flt4: double const &
"""
return _snap.TFlt_GetMx(*args)
GetMx = staticmethod(GetMx)
def GetInRng(*args):
"""
GetInRng(double const & Val, double const & Mn, double const & Mx) -> double
Parameters:
Val: double const &
Mn: double const &
Mx: double const &
"""
return _snap.TFlt_GetInRng(*args)
GetInRng = staticmethod(GetInRng)
def IsNum(self, *args):
"""
IsNum(TFlt self, double const & Val) -> bool
Parameters:
Val: double const &
IsNum(TFlt self) -> bool
Parameters:
self: TFlt const *
"""
return _snap.TFlt_IsNum(self, *args)
def IsNan(self, *args):
"""
IsNan(TFlt self, double const & Val) -> bool
Parameters:
Val: double const &
IsNan(TFlt self) -> bool
Parameters:
self: TFlt const *
"""
return _snap.TFlt_IsNan(self, *args)
def GetPrcStr(*args):
"""
GetPrcStr(double const & RelVal, double const & FullVal) -> TStr
Parameters:
RelVal: double const &
FullVal: double const &
"""
return _snap.TFlt_GetPrcStr(*args)
GetPrcStr = staticmethod(GetPrcStr)
def GetKiloStr(*args):
"""
GetKiloStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetKiloStr(*args)
GetKiloStr = staticmethod(GetKiloStr)
def GetMegaStr(*args):
"""
GetMegaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetMegaStr(*args)
GetMegaStr = staticmethod(GetMegaStr)
def GetGigaStr(*args):
"""
GetGigaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetGigaStr(*args)
GetGigaStr = staticmethod(GetGigaStr)
__swig_destroy__ = _snap.delete_TFlt
TFlt.Load = new_instancemethod(_snap.TFlt_Load,None,TFlt)
TFlt.Save = new_instancemethod(_snap.TFlt_Save,None,TFlt)
TFlt.LoadXml = new_instancemethod(_snap.TFlt_LoadXml,None,TFlt)
TFlt.SaveXml = new_instancemethod(_snap.TFlt_SaveXml,None,TFlt)
TFlt.__eq__ = new_instancemethod(_snap.TFlt___eq__,None,TFlt)
TFlt.__ne__ = new_instancemethod(_snap.TFlt___ne__,None,TFlt)
TFlt.__call__ = new_instancemethod(_snap.TFlt___call__,None,TFlt)
TFlt.__iadd__ = new_instancemethod(_snap.TFlt___iadd__,None,TFlt)
TFlt.__isub__ = new_instancemethod(_snap.TFlt___isub__,None,TFlt)
TFlt.__imul__ = new_instancemethod(_snap.TFlt___imul__,None,TFlt)
TFlt.__idiv__ = new_instancemethod(_snap.TFlt___idiv__,None,TFlt)
TFlt.GetMemUsed = new_instancemethod(_snap.TFlt_GetMemUsed,None,TFlt)
TFlt.GetPrimHashCd = new_instancemethod(_snap.TFlt_GetPrimHashCd,None,TFlt)
TFlt.GetSecHashCd = new_instancemethod(_snap.TFlt_GetSecHashCd,None,TFlt)
TFlt.IsNum = new_instancemethod(_snap.TFlt_IsNum,None,TFlt)
TFlt.IsNan = new_instancemethod(_snap.TFlt_IsNan,None,TFlt)
TFlt_swigregister = _snap.TFlt_swigregister
TFlt_swigregister(TFlt)
TFlt.Mn = _snap.cvar.TFlt_Mn
TFlt.Mx = _snap.cvar.TFlt_Mx
TFlt.NInf = _snap.cvar.TFlt_NInf
TFlt.PInf = _snap.cvar.TFlt_PInf
TFlt.Eps = _snap.cvar.TFlt_Eps
TFlt.EpsHalf = _snap.cvar.TFlt_EpsHalf
def TFlt_Abs(*args):
"""
TFlt_Abs(double const & Flt) -> double
Parameters:
Flt: double const &
"""
return _snap.TFlt_Abs(*args)
def TFlt_Sign(*args):
"""
TFlt_Sign(double const & Flt) -> int
Parameters:
Flt: double const &
"""
return _snap.TFlt_Sign(*args)
def TFlt_Round(*args):
"""
TFlt_Round(double const & Flt) -> int
Parameters:
Flt: double const &
"""
return _snap.TFlt_Round(*args)
def TFlt_GetRnd():
"""TFlt_GetRnd() -> double"""
return _snap.TFlt_GetRnd()
def TFlt_Eq6(*args):
"""
TFlt_Eq6(double const & LFlt, double const & RFlt) -> bool
Parameters:
LFlt: double const &
RFlt: double const &
"""
return _snap.TFlt_Eq6(*args)
def TFlt_GetMn(*args):
"""
GetMn(double const & Flt1, double const & Flt2) -> double
Parameters:
Flt1: double const &
Flt2: double const &
GetMn(double const & Flt1, double const & Flt2, double const & Flt3) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const &
TFlt_GetMn(double const & Flt1, double const & Flt2, double const & Flt3, double const & Flt4) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const &
Flt4: double const &
"""
return _snap.TFlt_GetMn(*args)
def TFlt_GetMx(*args):
"""
GetMx(double const & Flt1, double const & Flt2) -> double
Parameters:
Flt1: double const &
Flt2: double const &
GetMx(double const & Flt1, double const & Flt2, double const Flt3) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const
TFlt_GetMx(double const & Flt1, double const & Flt2, double const Flt3, double const & Flt4) -> double
Parameters:
Flt1: double const &
Flt2: double const &
Flt3: double const
Flt4: double const &
"""
return _snap.TFlt_GetMx(*args)
def TFlt_GetInRng(*args):
"""
TFlt_GetInRng(double const & Val, double const & Mn, double const & Mx) -> double
Parameters:
Val: double const &
Mn: double const &
Mx: double const &
"""
return _snap.TFlt_GetInRng(*args)
def TFlt_GetPrcStr(*args):
"""
TFlt_GetPrcStr(double const & RelVal, double const & FullVal) -> TStr
Parameters:
RelVal: double const &
FullVal: double const &
"""
return _snap.TFlt_GetPrcStr(*args)
def TFlt_GetKiloStr(*args):
"""
TFlt_GetKiloStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetKiloStr(*args)
def TFlt_GetMegaStr(*args):
"""
TFlt_GetMegaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetMegaStr(*args)
def TFlt_GetGigaStr(*args):
"""
TFlt_GetGigaStr(double const & Val) -> TStr
Parameters:
Val: double const &
"""
return _snap.TFlt_GetGigaStr(*args)
class TAscFlt(TFlt):
"""Proxy of C++ TAscFlt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TAscFlt self) -> TAscFlt
__init__(TAscFlt self, double const & Val) -> TAscFlt
Parameters:
Val: double const &
__init__(TAscFlt self, TSIn SIn) -> TAscFlt
Parameters:
SIn: TSIn &
"""
_snap.TAscFlt_swiginit(self,_snap.new_TAscFlt(*args))
def Save(self, *args):
"""
Save(TAscFlt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TAscFlt_Save(self, *args)
__swig_destroy__ = _snap.delete_TAscFlt
TAscFlt.Save = new_instancemethod(_snap.TAscFlt_Save,None,TAscFlt)
TAscFlt_swigregister = _snap.TAscFlt_swigregister
TAscFlt_swigregister(TAscFlt)
class TSFlt(object):
"""Proxy of C++ TSFlt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TSFlt_Val_get, _snap.TSFlt_Val_set)
def __init__(self, *args):
"""
__init__(TSFlt self) -> TSFlt
__init__(TSFlt self, sdouble const & _Val) -> TSFlt
Parameters:
_Val: sdouble const &
__init__(TSFlt self, TSIn SIn) -> TSFlt
Parameters:
SIn: TSIn &
"""
_snap.TSFlt_swiginit(self,_snap.new_TSFlt(*args))
def Save(self, *args):
"""
Save(TSFlt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TSFlt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TSFlt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TSFlt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TSFlt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TSFlt_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TSFlt self, TSFlt SFlt) -> bool
Parameters:
SFlt: TSFlt const &
__eq__(TSFlt self, double const & Flt) -> bool
Parameters:
Flt: double const &
"""
return _snap.TSFlt___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TSFlt self, double const & Flt) -> bool
Parameters:
Flt: double const &
"""
return _snap.TSFlt___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TSFlt self, TSFlt SFlt) -> bool
Parameters:
SFlt: TSFlt const &
"""
return _snap.TSFlt___lt__(self, *args)
def __call__(self):
"""
__call__(TSFlt self) -> sdouble
Parameters:
self: TSFlt const *
"""
return _snap.TSFlt___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TSFlt self, double const & SFlt) -> TSFlt
Parameters:
SFlt: double const &
"""
return _snap.TSFlt___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TSFlt self, double const & SFlt) -> TSFlt
Parameters:
SFlt: double const &
"""
return _snap.TSFlt___isub__(self, *args)
def __imul__(self, *args):
"""
__imul__(TSFlt self, double const & SFlt) -> TSFlt
Parameters:
SFlt: double const &
"""
return _snap.TSFlt___imul__(self, *args)
def __idiv__(self, *args):
"""
__idiv__(TSFlt self, double const & SFlt) -> TSFlt
Parameters:
SFlt: double const &
"""
return _snap.TSFlt___idiv__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TSFlt self) -> int
Parameters:
self: TSFlt const *
"""
return _snap.TSFlt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TSFlt self) -> int
Parameters:
self: TSFlt const *
"""
return _snap.TSFlt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TSFlt self) -> int
Parameters:
self: TSFlt const *
"""
return _snap.TSFlt_GetSecHashCd(self)
__swig_destroy__ = _snap.delete_TSFlt
TSFlt.Save = new_instancemethod(_snap.TSFlt_Save,None,TSFlt)
TSFlt.LoadXml = new_instancemethod(_snap.TSFlt_LoadXml,None,TSFlt)
TSFlt.SaveXml = new_instancemethod(_snap.TSFlt_SaveXml,None,TSFlt)
TSFlt.__eq__ = new_instancemethod(_snap.TSFlt___eq__,None,TSFlt)
TSFlt.__ne__ = new_instancemethod(_snap.TSFlt___ne__,None,TSFlt)
TSFlt.__lt__ = new_instancemethod(_snap.TSFlt___lt__,None,TSFlt)
TSFlt.__call__ = new_instancemethod(_snap.TSFlt___call__,None,TSFlt)
TSFlt.__iadd__ = new_instancemethod(_snap.TSFlt___iadd__,None,TSFlt)
TSFlt.__isub__ = new_instancemethod(_snap.TSFlt___isub__,None,TSFlt)
TSFlt.__imul__ = new_instancemethod(_snap.TSFlt___imul__,None,TSFlt)
TSFlt.__idiv__ = new_instancemethod(_snap.TSFlt___idiv__,None,TSFlt)
TSFlt.GetMemUsed = new_instancemethod(_snap.TSFlt_GetMemUsed,None,TSFlt)
TSFlt.GetPrimHashCd = new_instancemethod(_snap.TSFlt_GetPrimHashCd,None,TSFlt)
TSFlt.GetSecHashCd = new_instancemethod(_snap.TSFlt_GetSecHashCd,None,TSFlt)
TSFlt_swigregister = _snap.TSFlt_swigregister
TSFlt_swigregister(TSFlt)
TSFlt.Mn = _snap.cvar.TSFlt_Mn
TSFlt.Mx = _snap.cvar.TSFlt_Mx
class TLFlt(object):
"""Proxy of C++ TLFlt class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TLFlt_Val_get, _snap.TLFlt_Val_set)
def __init__(self, *args):
"""
__init__(TLFlt self) -> TLFlt
__init__(TLFlt self, ldouble const & _Val) -> TLFlt
Parameters:
_Val: ldouble const &
__init__(TLFlt self, TSIn SIn) -> TLFlt
Parameters:
SIn: TSIn &
"""
_snap.TLFlt_swiginit(self,_snap.new_TLFlt(*args))
def Save(self, *args):
"""
Save(TLFlt self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TLFlt_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TLFlt self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TLFlt_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TLFlt self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TLFlt_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TLFlt self, TLFlt LFlt) -> bool
Parameters:
LFlt: TLFlt const &
__eq__(TLFlt self, ldouble const & LFlt) -> bool
Parameters:
LFlt: ldouble const &
"""
return _snap.TLFlt___eq__(self, *args)
def __ne__(self, *args):
"""
__ne__(TLFlt self, ldouble const & LFlt) -> bool
Parameters:
LFlt: ldouble const &
"""
return _snap.TLFlt___ne__(self, *args)
def __lt__(self, *args):
"""
__lt__(TLFlt self, TLFlt LFlt) -> bool
Parameters:
LFlt: TLFlt const &
"""
return _snap.TLFlt___lt__(self, *args)
def __call__(self):
"""
__call__(TLFlt self) -> ldouble
Parameters:
self: TLFlt const *
"""
return _snap.TLFlt___call__(self)
def __iadd__(self, *args):
"""
__iadd__(TLFlt self, ldouble const & LFlt) -> TLFlt
Parameters:
LFlt: ldouble const &
"""
return _snap.TLFlt___iadd__(self, *args)
def __isub__(self, *args):
"""
__isub__(TLFlt self, ldouble const & LFlt) -> TLFlt
Parameters:
LFlt: ldouble const &
"""
return _snap.TLFlt___isub__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TLFlt self) -> int
Parameters:
self: TLFlt const *
"""
return _snap.TLFlt_GetMemUsed(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TLFlt self) -> int
Parameters:
self: TLFlt const *
"""
return _snap.TLFlt_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TLFlt self) -> int
Parameters:
self: TLFlt const *
"""
return _snap.TLFlt_GetSecHashCd(self)
__swig_destroy__ = _snap.delete_TLFlt
TLFlt.Save = new_instancemethod(_snap.TLFlt_Save,None,TLFlt)
TLFlt.LoadXml = new_instancemethod(_snap.TLFlt_LoadXml,None,TLFlt)
TLFlt.SaveXml = new_instancemethod(_snap.TLFlt_SaveXml,None,TLFlt)
TLFlt.__eq__ = new_instancemethod(_snap.TLFlt___eq__,None,TLFlt)
TLFlt.__ne__ = new_instancemethod(_snap.TLFlt___ne__,None,TLFlt)
TLFlt.__lt__ = new_instancemethod(_snap.TLFlt___lt__,None,TLFlt)
TLFlt.__call__ = new_instancemethod(_snap.TLFlt___call__,None,TLFlt)
TLFlt.__iadd__ = new_instancemethod(_snap.TLFlt___iadd__,None,TLFlt)
TLFlt.__isub__ = new_instancemethod(_snap.TLFlt___isub__,None,TLFlt)
TLFlt.GetMemUsed = new_instancemethod(_snap.TLFlt_GetMemUsed,None,TLFlt)
TLFlt.GetPrimHashCd = new_instancemethod(_snap.TLFlt_GetPrimHashCd,None,TLFlt)
TLFlt.GetSecHashCd = new_instancemethod(_snap.TLFlt_GetSecHashCd,None,TLFlt)
TLFlt_swigregister = _snap.TLFlt_swigregister
TLFlt_swigregister(TLFlt)
TLFlt.Mn = _snap.cvar.TLFlt_Mn
TLFlt.Mx = _snap.cvar.TLFlt_Mx
class TFltRect(object):
"""Proxy of C++ TFltRect class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
MnX = _swig_property(_snap.TFltRect_MnX_get, _snap.TFltRect_MnX_set)
MnY = _swig_property(_snap.TFltRect_MnY_get, _snap.TFltRect_MnY_set)
MxX = _swig_property(_snap.TFltRect_MxX_get, _snap.TFltRect_MxX_set)
MxY = _swig_property(_snap.TFltRect_MxY_get, _snap.TFltRect_MxY_set)
def __init__(self, *args):
"""
__init__(TFltRect self) -> TFltRect
__init__(TFltRect self, TFltRect FltRect) -> TFltRect
Parameters:
FltRect: TFltRect const &
__init__(TFltRect self, double const & _MnX, double const & _MnY, double const & _MxX, double const & _MxY) -> TFltRect
Parameters:
_MnX: double const &
_MnY: double const &
_MxX: double const &
_MxY: double const &
__init__(TFltRect self, TSIn SIn) -> TFltRect
Parameters:
SIn: TSIn &
"""
_snap.TFltRect_swiginit(self,_snap.new_TFltRect(*args))
def Save(self, *args):
"""
Save(TFltRect self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TFltRect_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TFltRect self, PXmlTok const & XmlTok, TStr Nm)
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
"""
return _snap.TFltRect_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TFltRect self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TFltRect_SaveXml(self, *args)
def GetMnX(self):
"""
GetMnX(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetMnX(self)
def GetMnY(self):
"""
GetMnY(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetMnY(self)
def GetMxX(self):
"""
GetMxX(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetMxX(self)
def GetMxY(self):
"""
GetMxY(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetMxY(self)
def GetXLen(self):
"""
GetXLen(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetXLen(self)
def GetYLen(self):
"""
GetYLen(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetYLen(self)
def GetXCenter(self):
"""
GetXCenter(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetXCenter(self)
def GetYCenter(self):
"""
GetYCenter(TFltRect self) -> double
Parameters:
self: TFltRect const *
"""
return _snap.TFltRect_GetYCenter(self)
def IsXYIn(self, *args):
"""
IsXYIn(TFltRect self, double const & X, double const & Y) -> bool
Parameters:
X: double const &
Y: double const &
"""
return _snap.TFltRect_IsXYIn(self, *args)
def Intersection(*args):
"""
Intersection(TFltRect Rect1, TFltRect Rect2) -> bool
Parameters:
Rect1: TFltRect const &
Rect2: TFltRect const &
"""
return _snap.TFltRect_Intersection(*args)
Intersection = staticmethod(Intersection)
__swig_destroy__ = _snap.delete_TFltRect
TFltRect.Save = new_instancemethod(_snap.TFltRect_Save,None,TFltRect)
TFltRect.LoadXml = new_instancemethod(_snap.TFltRect_LoadXml,None,TFltRect)
TFltRect.SaveXml = new_instancemethod(_snap.TFltRect_SaveXml,None,TFltRect)
TFltRect.GetMnX = new_instancemethod(_snap.TFltRect_GetMnX,None,TFltRect)
TFltRect.GetMnY = new_instancemethod(_snap.TFltRect_GetMnY,None,TFltRect)
TFltRect.GetMxX = new_instancemethod(_snap.TFltRect_GetMxX,None,TFltRect)
TFltRect.GetMxY = new_instancemethod(_snap.TFltRect_GetMxY,None,TFltRect)
TFltRect.GetXLen = new_instancemethod(_snap.TFltRect_GetXLen,None,TFltRect)
TFltRect.GetYLen = new_instancemethod(_snap.TFltRect_GetYLen,None,TFltRect)
TFltRect.GetXCenter = new_instancemethod(_snap.TFltRect_GetXCenter,None,TFltRect)
TFltRect.GetYCenter = new_instancemethod(_snap.TFltRect_GetYCenter,None,TFltRect)
TFltRect.IsXYIn = new_instancemethod(_snap.TFltRect_IsXYIn,None,TFltRect)
TFltRect_swigregister = _snap.TFltRect_swigregister
TFltRect_swigregister(TFltRect)
def TFltRect_Intersection(*args):
"""
TFltRect_Intersection(TFltRect Rect1, TFltRect Rect2) -> bool
Parameters:
Rect1: TFltRect const &
Rect2: TFltRect const &
"""
return _snap.TFltRect_Intersection(*args)
class TIntV(object):
"""Proxy of C++ TVec<(TInt,int)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TIntV
def __init__(self, *args):
"""
__init__(TVec<(TInt,int)> self) -> TIntV
__init__(TVec<(TInt,int)> self, TIntV Vec) -> TIntV
Parameters:
Vec: TVec< TInt,int > const &
__init__(TVec<(TInt,int)> self, int const & _Vals) -> TIntV
Parameters:
_Vals: int const &
__init__(TVec<(TInt,int)> self, int const & _MxVals, int const & _Vals) -> TIntV
Parameters:
_MxVals: int const &
_Vals: int const &
__init__(TVec<(TInt,int)> self, TInt _ValT, int const & _Vals) -> TIntV
Parameters:
_ValT: TInt *
_Vals: int const &
__init__(TVec<(TInt,int)> self, TSIn SIn) -> TIntV
Parameters:
SIn: TSIn &
"""
_snap.TIntV_swiginit(self,_snap.new_TIntV(*args))
def Load(self, *args):
"""
Load(TIntV self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TIntV_Load(self, *args)
def Save(self, *args):
"""
Save(TIntV self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TIntV_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TIntV self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TIntV self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TIntV_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TIntV self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TIntV_SaveXml(self, *args)
def __add__(self, *args):
"""
__add__(TIntV self, TInt Val) -> TIntV
Parameters:
Val: TInt const &
"""
return _snap.TIntV___add__(self, *args)
def __eq__(self, *args):
"""
__eq__(TIntV self, TIntV Vec) -> bool
Parameters:
Vec: TVec< TInt,int > const &
"""
return _snap.TIntV___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntV self, TIntV Vec) -> bool
Parameters:
Vec: TVec< TInt,int > const &
"""
return _snap.TIntV___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetMemUsed(self)
def GetMemSize(self):
"""
GetMemSize(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetMemSize(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetSecHashCd(self)
def Gen(self, *args):
"""
Gen(TIntV self, int const & _Vals)
Parameters:
_Vals: int const &
Gen(TIntV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TIntV_Gen(self, *args)
def GenExt(self, *args):
"""
GenExt(TIntV self, TInt _ValT, int const & _Vals)
Parameters:
_ValT: TInt *
_Vals: int const &
"""
return _snap.TIntV_GenExt(self, *args)
def IsExt(self):
"""
IsExt(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_IsExt(self)
def Reserve(self, *args):
"""
Reserve(TIntV self, int const & _MxVals)
Parameters:
_MxVals: int const &
Reserve(TIntV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TIntV_Reserve(self, *args)
def Clr(self, *args):
"""
Clr(TIntV self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TIntV self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Clr(self, *args)
def Trunc(self, *args):
"""
Trunc(TIntV self, int const & _Vals=-1)
Parameters:
_Vals: int const &
Trunc(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Trunc(self, *args)
def Pack(self):
"""
Pack(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Pack(self)
def MoveFrom(self, *args):
"""
MoveFrom(TIntV self, TIntV Vec)
Parameters:
Vec: TVec< TInt,int > &
"""
return _snap.TIntV_MoveFrom(self, *args)
def Empty(self):
"""
Empty(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_Empty(self)
def Len(self):
"""
Len(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_Len(self)
def Reserved(self):
"""
Reserved(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_Reserved(self)
def Last(self, *args):
"""
Last(TIntV self) -> TInt
Last(TIntV self) -> TInt
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Last(self, *args)
def LastValN(self):
"""
LastValN(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_LastValN(self)
def LastLast(self, *args):
"""
LastLast(TIntV self) -> TInt
LastLast(TIntV self) -> TInt
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_LastLast(self, *args)
def BegI(self):
"""
BegI(TIntV self) -> TInt
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_BegI(self)
def EndI(self):
"""
EndI(TIntV self) -> TInt
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_EndI(self)
def GetI(self, *args):
"""
GetI(TIntV self, int const & ValN) -> TInt
Parameters:
ValN: int const &
"""
return _snap.TIntV_GetI(self, *args)
def AddV(self, *args):
"""
AddV(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_AddV(self, *args)
def AddSorted(self, *args):
"""
AddSorted(TIntV self, TInt Val, bool const & Asc=True, int const & _MxVals=-1) -> int
Parameters:
Val: TInt const &
Asc: bool const &
_MxVals: int const &
AddSorted(TIntV self, TInt Val, bool const & Asc=True) -> int
Parameters:
Val: TInt const &
Asc: bool const &
AddSorted(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_AddSorted(self, *args)
def AddBackSorted(self, *args):
"""
AddBackSorted(TIntV self, TInt Val, bool const & Asc) -> int
Parameters:
Val: TInt const &
Asc: bool const &
"""
return _snap.TIntV_AddBackSorted(self, *args)
def AddVMerged(self, *args):
"""
AddVMerged(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_AddVMerged(self, *args)
def AddUnique(self, *args):
"""
AddUnique(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_AddUnique(self, *args)
def GetVal(self, *args):
"""
GetVal(TIntV self, int const & ValN) -> TInt
Parameters:
ValN: int const &
GetVal(TIntV self, int const & ValN) -> TInt
Parameters:
ValN: int const &
"""
return _snap.TIntV_GetVal(self, *args)
def GetSubValV(self, *args):
"""
GetSubValV(TIntV self, int const & BValN, int const & EValN, TIntV ValV)
Parameters:
BValN: int const &
EValN: int const &
ValV: TVec< TInt,int > &
"""
return _snap.TIntV_GetSubValV(self, *args)
def Ins(self, *args):
"""
Ins(TIntV self, int const & ValN, TInt Val)
Parameters:
ValN: int const &
Val: TInt const &
"""
return _snap.TIntV_Ins(self, *args)
def Del(self, *args):
"""
Del(TIntV self, int const & ValN)
Parameters:
ValN: int const &
Del(TIntV self, int const & MnValN, int const & MxValN)
Parameters:
MnValN: int const &
MxValN: int const &
"""
return _snap.TIntV_Del(self, *args)
def DelLast(self):
"""
DelLast(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_DelLast(self)
def DelIfIn(self, *args):
"""
DelIfIn(TIntV self, TInt Val) -> bool
Parameters:
Val: TInt const &
"""
return _snap.TIntV_DelIfIn(self, *args)
def DelAll(self, *args):
"""
DelAll(TIntV self, TInt Val)
Parameters:
Val: TInt const &
"""
return _snap.TIntV_DelAll(self, *args)
def PutAll(self, *args):
"""
PutAll(TIntV self, TInt Val)
Parameters:
Val: TInt const &
"""
return _snap.TIntV_PutAll(self, *args)
def Swap(self, *args):
"""
Swap(TIntV self, TIntV Vec)
Parameters:
Vec: TVec< TInt,int > &
Swap(TIntV self, int const & ValN1, int const & ValN2)
Parameters:
ValN1: int const &
ValN2: int const &
"""
return _snap.TIntV_Swap(self, *args)
def SwapI(*args):
"""
SwapI(TInt LVal, TInt RVal)
Parameters:
LVal: TVec< TInt,int >::TIter
RVal: TVec< TInt,int >::TIter
"""
return _snap.TIntV_SwapI(*args)
SwapI = staticmethod(SwapI)
def NextPerm(self):
"""
NextPerm(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_NextPerm(self)
def PrevPerm(self):
"""
PrevPerm(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_PrevPerm(self)
def GetPivotValN(self, *args):
"""
GetPivotValN(TIntV self, int const & LValN, int const & RValN) -> int
Parameters:
LValN: int const &
RValN: int const &
"""
return _snap.TIntV_GetPivotValN(self, *args)
def BSort(self, *args):
"""
BSort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntV_BSort(self, *args)
def ISort(self, *args):
"""
ISort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntV_ISort(self, *args)
def Partition(self, *args):
"""
Partition(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc) -> int
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntV_Partition(self, *args)
def QSort(self, *args):
"""
QSort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntV_QSort(self, *args)
def Sort(self, Asc=True):
"""
Sort(TIntV self, bool const & Asc=True)
Parameters:
Asc: bool const &
Sort(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Sort(self, Asc)
def IsSorted(self, Asc=True):
"""
IsSorted(TIntV self, bool const & Asc=True) -> bool
Parameters:
Asc: bool const &
IsSorted(TIntV self) -> bool
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_IsSorted(self, Asc)
def Shuffle(self, *args):
"""
Shuffle(TIntV self, TRnd Rnd)
Parameters:
Rnd: TRnd &
"""
return _snap.TIntV_Shuffle(self, *args)
def Reverse(self, *args):
"""
Reverse(TIntV self)
Reverse(TIntV self, int LValN, int RValN)
Parameters:
LValN: int
RValN: int
"""
return _snap.TIntV_Reverse(self, *args)
def Merge(self):
"""
Merge(TIntV self)
Parameters:
self: TVec< TInt,int > *
"""
return _snap.TIntV_Merge(self)
def Intrs(self, *args):
"""
Intrs(TIntV self, TIntV ValV)
Parameters:
ValV: TVec< TInt,int > const &
Intrs(TIntV self, TIntV ValV, TIntV DstValV)
Parameters:
ValV: TVec< TInt,int > const &
DstValV: TVec< TInt,int > &
"""
return _snap.TIntV_Intrs(self, *args)
def Union(self, *args):
"""
Union(TIntV self, TIntV ValV)
Parameters:
ValV: TVec< TInt,int > const &
Union(TIntV self, TIntV ValV, TIntV DstValV)
Parameters:
ValV: TVec< TInt,int > const &
DstValV: TVec< TInt,int > &
"""
return _snap.TIntV_Union(self, *args)
def Diff(self, *args):
"""
Diff(TIntV self, TIntV ValV)
Parameters:
ValV: TVec< TInt,int > const &
Diff(TIntV self, TIntV ValV, TIntV DstValV)
Parameters:
ValV: TVec< TInt,int > const &
DstValV: TVec< TInt,int > &
"""
return _snap.TIntV_Diff(self, *args)
def IntrsLen(self, *args):
"""
IntrsLen(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_IntrsLen(self, *args)
def UnionLen(self, *args):
"""
UnionLen(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_UnionLen(self, *args)
def Count(self, *args):
"""
Count(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_Count(self, *args)
def SearchBin(self, *args):
"""
SearchBin(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
SearchBin(TIntV self, TInt Val, int & InsValN) -> int
Parameters:
Val: TInt const &
InsValN: int &
"""
return _snap.TIntV_SearchBin(self, *args)
def SearchForw(self, *args):
"""
SearchForw(TIntV self, TInt Val, int const & BValN=0) -> int
Parameters:
Val: TInt const &
BValN: int const &
SearchForw(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_SearchForw(self, *args)
def SearchBack(self, *args):
"""
SearchBack(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
"""
return _snap.TIntV_SearchBack(self, *args)
def SearchVForw(self, *args):
"""
SearchVForw(TIntV self, TIntV ValV, int const & BValN=0) -> int
Parameters:
ValV: TVec< TInt,int > const &
BValN: int const &
SearchVForw(TIntV self, TIntV ValV) -> int
Parameters:
ValV: TVec< TInt,int > const &
"""
return _snap.TIntV_SearchVForw(self, *args)
def IsIn(self, *args):
"""
IsIn(TIntV self, TInt Val) -> bool
Parameters:
Val: TInt const &
IsIn(TIntV self, TInt Val, int & ValN) -> bool
Parameters:
Val: TInt const &
ValN: int &
"""
return _snap.TIntV_IsIn(self, *args)
def IsInBin(self, *args):
"""
IsInBin(TIntV self, TInt Val) -> bool
Parameters:
Val: TInt const &
"""
return _snap.TIntV_IsInBin(self, *args)
def GetDat(self, *args):
"""
GetDat(TIntV self, TInt Val) -> TInt
Parameters:
Val: TInt const &
"""
return _snap.TIntV_GetDat(self, *args)
def GetAddDat(self, *args):
"""
GetAddDat(TIntV self, TInt Val) -> TInt
Parameters:
Val: TInt const &
"""
return _snap.TIntV_GetAddDat(self, *args)
def GetMxValN(self):
"""
GetMxValN(TIntV self) -> int
Parameters:
self: TVec< TInt,int > const *
"""
return _snap.TIntV_GetMxValN(self)
def GetV(*args):
"""
GetV(TInt Val1) -> TIntV
Parameters:
Val1: TInt const &
GetV(TInt Val1, TInt Val2) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7, TInt Val8) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
Val8: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7, TInt Val8,
TInt Val9) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
Val8: TInt const &
Val9: TInt const &
"""
return _snap.TIntV_GetV(*args)
GetV = staticmethod(GetV)
def Add(self, *args):
"""
Add(TIntV self) -> int
Add(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
Add(TIntV self, TInt Val, int const & ResizeLen) -> int
Parameters:
Val: TInt const &
ResizeLen: int const &
Add(TIntV self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntV_Add(self, *args)
def AddMerged(self, *args):
"""
AddMerged(TIntV self, TInt Val) -> int
Parameters:
Val: TInt const &
AddMerged(TIntV self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntV_AddMerged(self, *args)
TIntV.Load = new_instancemethod(_snap.TIntV_Load,None,TIntV)
TIntV.Save = new_instancemethod(_snap.TIntV_Save,None,TIntV)
TIntV.LoadXml = new_instancemethod(_snap.TIntV_LoadXml,None,TIntV)
TIntV.SaveXml = new_instancemethod(_snap.TIntV_SaveXml,None,TIntV)
TIntV.__add__ = new_instancemethod(_snap.TIntV___add__,None,TIntV)
TIntV.__eq__ = new_instancemethod(_snap.TIntV___eq__,None,TIntV)
TIntV.__lt__ = new_instancemethod(_snap.TIntV___lt__,None,TIntV)
TIntV.GetMemUsed = new_instancemethod(_snap.TIntV_GetMemUsed,None,TIntV)
TIntV.GetMemSize = new_instancemethod(_snap.TIntV_GetMemSize,None,TIntV)
TIntV.GetPrimHashCd = new_instancemethod(_snap.TIntV_GetPrimHashCd,None,TIntV)
TIntV.GetSecHashCd = new_instancemethod(_snap.TIntV_GetSecHashCd,None,TIntV)
TIntV.Gen = new_instancemethod(_snap.TIntV_Gen,None,TIntV)
TIntV.GenExt = new_instancemethod(_snap.TIntV_GenExt,None,TIntV)
TIntV.IsExt = new_instancemethod(_snap.TIntV_IsExt,None,TIntV)
TIntV.Reserve = new_instancemethod(_snap.TIntV_Reserve,None,TIntV)
TIntV.Clr = new_instancemethod(_snap.TIntV_Clr,None,TIntV)
TIntV.Trunc = new_instancemethod(_snap.TIntV_Trunc,None,TIntV)
TIntV.Pack = new_instancemethod(_snap.TIntV_Pack,None,TIntV)
TIntV.MoveFrom = new_instancemethod(_snap.TIntV_MoveFrom,None,TIntV)
TIntV.Empty = new_instancemethod(_snap.TIntV_Empty,None,TIntV)
TIntV.Len = new_instancemethod(_snap.TIntV_Len,None,TIntV)
TIntV.Reserved = new_instancemethod(_snap.TIntV_Reserved,None,TIntV)
TIntV.Last = new_instancemethod(_snap.TIntV_Last,None,TIntV)
TIntV.LastValN = new_instancemethod(_snap.TIntV_LastValN,None,TIntV)
TIntV.LastLast = new_instancemethod(_snap.TIntV_LastLast,None,TIntV)
TIntV.BegI = new_instancemethod(_snap.TIntV_BegI,None,TIntV)
TIntV.EndI = new_instancemethod(_snap.TIntV_EndI,None,TIntV)
TIntV.GetI = new_instancemethod(_snap.TIntV_GetI,None,TIntV)
TIntV.AddV = new_instancemethod(_snap.TIntV_AddV,None,TIntV)
TIntV.AddSorted = new_instancemethod(_snap.TIntV_AddSorted,None,TIntV)
TIntV.AddBackSorted = new_instancemethod(_snap.TIntV_AddBackSorted,None,TIntV)
TIntV.AddVMerged = new_instancemethod(_snap.TIntV_AddVMerged,None,TIntV)
TIntV.AddUnique = new_instancemethod(_snap.TIntV_AddUnique,None,TIntV)
TIntV.GetVal = new_instancemethod(_snap.TIntV_GetVal,None,TIntV)
TIntV.GetSubValV = new_instancemethod(_snap.TIntV_GetSubValV,None,TIntV)
TIntV.Ins = new_instancemethod(_snap.TIntV_Ins,None,TIntV)
TIntV.Del = new_instancemethod(_snap.TIntV_Del,None,TIntV)
TIntV.DelLast = new_instancemethod(_snap.TIntV_DelLast,None,TIntV)
TIntV.DelIfIn = new_instancemethod(_snap.TIntV_DelIfIn,None,TIntV)
TIntV.DelAll = new_instancemethod(_snap.TIntV_DelAll,None,TIntV)
TIntV.PutAll = new_instancemethod(_snap.TIntV_PutAll,None,TIntV)
TIntV.Swap = new_instancemethod(_snap.TIntV_Swap,None,TIntV)
TIntV.NextPerm = new_instancemethod(_snap.TIntV_NextPerm,None,TIntV)
TIntV.PrevPerm = new_instancemethod(_snap.TIntV_PrevPerm,None,TIntV)
TIntV.GetPivotValN = new_instancemethod(_snap.TIntV_GetPivotValN,None,TIntV)
TIntV.BSort = new_instancemethod(_snap.TIntV_BSort,None,TIntV)
TIntV.ISort = new_instancemethod(_snap.TIntV_ISort,None,TIntV)
TIntV.Partition = new_instancemethod(_snap.TIntV_Partition,None,TIntV)
TIntV.QSort = new_instancemethod(_snap.TIntV_QSort,None,TIntV)
TIntV.Sort = new_instancemethod(_snap.TIntV_Sort,None,TIntV)
TIntV.IsSorted = new_instancemethod(_snap.TIntV_IsSorted,None,TIntV)
TIntV.Shuffle = new_instancemethod(_snap.TIntV_Shuffle,None,TIntV)
TIntV.Reverse = new_instancemethod(_snap.TIntV_Reverse,None,TIntV)
TIntV.Merge = new_instancemethod(_snap.TIntV_Merge,None,TIntV)
TIntV.Intrs = new_instancemethod(_snap.TIntV_Intrs,None,TIntV)
TIntV.Union = new_instancemethod(_snap.TIntV_Union,None,TIntV)
TIntV.Diff = new_instancemethod(_snap.TIntV_Diff,None,TIntV)
TIntV.IntrsLen = new_instancemethod(_snap.TIntV_IntrsLen,None,TIntV)
TIntV.UnionLen = new_instancemethod(_snap.TIntV_UnionLen,None,TIntV)
TIntV.Count = new_instancemethod(_snap.TIntV_Count,None,TIntV)
TIntV.SearchBin = new_instancemethod(_snap.TIntV_SearchBin,None,TIntV)
TIntV.SearchForw = new_instancemethod(_snap.TIntV_SearchForw,None,TIntV)
TIntV.SearchBack = new_instancemethod(_snap.TIntV_SearchBack,None,TIntV)
TIntV.SearchVForw = new_instancemethod(_snap.TIntV_SearchVForw,None,TIntV)
TIntV.IsIn = new_instancemethod(_snap.TIntV_IsIn,None,TIntV)
TIntV.IsInBin = new_instancemethod(_snap.TIntV_IsInBin,None,TIntV)
TIntV.GetDat = new_instancemethod(_snap.TIntV_GetDat,None,TIntV)
TIntV.GetAddDat = new_instancemethod(_snap.TIntV_GetAddDat,None,TIntV)
TIntV.GetMxValN = new_instancemethod(_snap.TIntV_GetMxValN,None,TIntV)
TIntV.Add = new_instancemethod(_snap.TIntV_Add,None,TIntV)
TIntV.AddMerged = new_instancemethod(_snap.TIntV_AddMerged,None,TIntV)
TIntV_swigregister = _snap.TIntV_swigregister
TIntV_swigregister(TIntV)
def TIntV_SwapI(*args):
"""
TIntV_SwapI(TInt LVal, TInt RVal)
Parameters:
LVal: TVec< TInt,int >::TIter
RVal: TVec< TInt,int >::TIter
"""
return _snap.TIntV_SwapI(*args)
def TIntV_GetV(*args):
"""
GetV(TInt Val1) -> TIntV
Parameters:
Val1: TInt const &
GetV(TInt Val1, TInt Val2) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7, TInt Val8) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
Val8: TInt const &
TIntV_GetV(TInt Val1, TInt Val2, TInt Val3, TInt Val4, TInt Val5, TInt Val6, TInt Val7, TInt Val8,
TInt Val9) -> TIntV
Parameters:
Val1: TInt const &
Val2: TInt const &
Val3: TInt const &
Val4: TInt const &
Val5: TInt const &
Val6: TInt const &
Val7: TInt const &
Val8: TInt const &
Val9: TInt const &
"""
return _snap.TIntV_GetV(*args)
class TIntIntVV(object):
"""Proxy of C++ TVec<(TVec<(TInt,int)>,int)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TIntIntVV
def __init__(self, *args):
"""
__init__(TVec<(TVec<(TInt,int)>,int)> self) -> TIntIntVV
__init__(TVec<(TVec<(TInt,int)>,int)> self, TIntIntVV Vec) -> TIntIntVV
Parameters:
Vec: TVec< TVec< TInt,int >,int > const &
__init__(TVec<(TVec<(TInt,int)>,int)> self, int const & _Vals) -> TIntIntVV
Parameters:
_Vals: int const &
__init__(TVec<(TVec<(TInt,int)>,int)> self, int const & _MxVals, int const & _Vals) -> TIntIntVV
Parameters:
_MxVals: int const &
_Vals: int const &
__init__(TVec<(TVec<(TInt,int)>,int)> self, TIntV _ValT, int const & _Vals) -> TIntIntVV
Parameters:
_ValT: TVec< TInt,int > *
_Vals: int const &
__init__(TVec<(TVec<(TInt,int)>,int)> self, TSIn SIn) -> TIntIntVV
Parameters:
SIn: TSIn &
"""
_snap.TIntIntVV_swiginit(self,_snap.new_TIntIntVV(*args))
def Load(self, *args):
"""
Load(TIntIntVV self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TIntIntVV_Load(self, *args)
def Save(self, *args):
"""
Save(TIntIntVV self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TIntIntVV_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TIntIntVV self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TIntIntVV self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TIntIntVV_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TIntIntVV self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TIntIntVV_SaveXml(self, *args)
def __add__(self, *args):
"""
__add__(TIntIntVV self, TIntV Val) -> TIntIntVV
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV___add__(self, *args)
def __eq__(self, *args):
"""
__eq__(TIntIntVV self, TIntIntVV Vec) -> bool
Parameters:
Vec: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntIntVV self, TIntIntVV Vec) -> bool
Parameters:
Vec: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetMemUsed(self)
def GetMemSize(self):
"""
GetMemSize(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetMemSize(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetSecHashCd(self)
def Gen(self, *args):
"""
Gen(TIntIntVV self, int const & _Vals)
Parameters:
_Vals: int const &
Gen(TIntIntVV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TIntIntVV_Gen(self, *args)
def GenExt(self, *args):
"""
GenExt(TIntIntVV self, TIntV _ValT, int const & _Vals)
Parameters:
_ValT: TVec< TInt,int > *
_Vals: int const &
"""
return _snap.TIntIntVV_GenExt(self, *args)
def IsExt(self):
"""
IsExt(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_IsExt(self)
def Reserve(self, *args):
"""
Reserve(TIntIntVV self, int const & _MxVals)
Parameters:
_MxVals: int const &
Reserve(TIntIntVV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TIntIntVV_Reserve(self, *args)
def Clr(self, *args):
"""
Clr(TIntIntVV self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TIntIntVV self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Clr(self, *args)
def Trunc(self, *args):
"""
Trunc(TIntIntVV self, int const & _Vals=-1)
Parameters:
_Vals: int const &
Trunc(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Trunc(self, *args)
def Pack(self):
"""
Pack(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Pack(self)
def MoveFrom(self, *args):
"""
MoveFrom(TIntIntVV self, TIntIntVV Vec)
Parameters:
Vec: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_MoveFrom(self, *args)
def Empty(self):
"""
Empty(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_Empty(self)
def Len(self):
"""
Len(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_Len(self)
def Reserved(self):
"""
Reserved(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_Reserved(self)
def Last(self, *args):
"""
Last(TIntIntVV self) -> TIntV
Last(TIntIntVV self) -> TIntV
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Last(self, *args)
def LastValN(self):
"""
LastValN(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_LastValN(self)
def LastLast(self, *args):
"""
LastLast(TIntIntVV self) -> TIntV
LastLast(TIntIntVV self) -> TIntV
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_LastLast(self, *args)
def BegI(self):
"""
BegI(TIntIntVV self) -> TIntV
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_BegI(self)
def EndI(self):
"""
EndI(TIntIntVV self) -> TIntV
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_EndI(self)
def GetI(self, *args):
"""
GetI(TIntIntVV self, int const & ValN) -> TIntV
Parameters:
ValN: int const &
"""
return _snap.TIntIntVV_GetI(self, *args)
def AddV(self, *args):
"""
AddV(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_AddV(self, *args)
def AddSorted(self, *args):
"""
AddSorted(TIntIntVV self, TIntV Val, bool const & Asc=True, int const & _MxVals=-1) -> int
Parameters:
Val: TVec< TInt,int > const &
Asc: bool const &
_MxVals: int const &
AddSorted(TIntIntVV self, TIntV Val, bool const & Asc=True) -> int
Parameters:
Val: TVec< TInt,int > const &
Asc: bool const &
AddSorted(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_AddSorted(self, *args)
def AddBackSorted(self, *args):
"""
AddBackSorted(TIntIntVV self, TIntV Val, bool const & Asc) -> int
Parameters:
Val: TVec< TInt,int > const &
Asc: bool const &
"""
return _snap.TIntIntVV_AddBackSorted(self, *args)
def AddVMerged(self, *args):
"""
AddVMerged(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_AddVMerged(self, *args)
def AddUnique(self, *args):
"""
AddUnique(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_AddUnique(self, *args)
def GetVal(self, *args):
"""
GetVal(TIntIntVV self, int const & ValN) -> TIntV
Parameters:
ValN: int const &
GetVal(TIntIntVV self, int const & ValN) -> TIntV
Parameters:
ValN: int const &
"""
return _snap.TIntIntVV_GetVal(self, *args)
def GetSubValV(self, *args):
"""
GetSubValV(TIntIntVV self, int const & BValN, int const & EValN, TIntIntVV ValV)
Parameters:
BValN: int const &
EValN: int const &
ValV: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_GetSubValV(self, *args)
def Ins(self, *args):
"""
Ins(TIntIntVV self, int const & ValN, TIntV Val)
Parameters:
ValN: int const &
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_Ins(self, *args)
def Del(self, *args):
"""
Del(TIntIntVV self, int const & ValN)
Parameters:
ValN: int const &
Del(TIntIntVV self, int const & MnValN, int const & MxValN)
Parameters:
MnValN: int const &
MxValN: int const &
"""
return _snap.TIntIntVV_Del(self, *args)
def DelLast(self):
"""
DelLast(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_DelLast(self)
def DelIfIn(self, *args):
"""
DelIfIn(TIntIntVV self, TIntV Val) -> bool
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_DelIfIn(self, *args)
def DelAll(self, *args):
"""
DelAll(TIntIntVV self, TIntV Val)
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_DelAll(self, *args)
def PutAll(self, *args):
"""
PutAll(TIntIntVV self, TIntV Val)
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_PutAll(self, *args)
def Swap(self, *args):
"""
Swap(TIntIntVV self, TIntIntVV Vec)
Parameters:
Vec: TVec< TVec< TInt,int >,int > &
Swap(TIntIntVV self, int const & ValN1, int const & ValN2)
Parameters:
ValN1: int const &
ValN2: int const &
"""
return _snap.TIntIntVV_Swap(self, *args)
def SwapI(*args):
"""
SwapI(TIntV LVal, TIntV RVal)
Parameters:
LVal: TVec< TVec< TInt,int >,int >::TIter
RVal: TVec< TVec< TInt,int >,int >::TIter
"""
return _snap.TIntIntVV_SwapI(*args)
SwapI = staticmethod(SwapI)
def NextPerm(self):
"""
NextPerm(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_NextPerm(self)
def PrevPerm(self):
"""
PrevPerm(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_PrevPerm(self)
def GetPivotValN(self, *args):
"""
GetPivotValN(TIntIntVV self, int const & LValN, int const & RValN) -> int
Parameters:
LValN: int const &
RValN: int const &
"""
return _snap.TIntIntVV_GetPivotValN(self, *args)
def BSort(self, *args):
"""
BSort(TIntIntVV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntIntVV_BSort(self, *args)
def ISort(self, *args):
"""
ISort(TIntIntVV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntIntVV_ISort(self, *args)
def Partition(self, *args):
"""
Partition(TIntIntVV self, int const & MnLValN, int const & MxRValN, bool const & Asc) -> int
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntIntVV_Partition(self, *args)
def QSort(self, *args):
"""
QSort(TIntIntVV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TIntIntVV_QSort(self, *args)
def Sort(self, Asc=True):
"""
Sort(TIntIntVV self, bool const & Asc=True)
Parameters:
Asc: bool const &
Sort(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Sort(self, Asc)
def IsSorted(self, Asc=True):
"""
IsSorted(TIntIntVV self, bool const & Asc=True) -> bool
Parameters:
Asc: bool const &
IsSorted(TIntIntVV self) -> bool
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_IsSorted(self, Asc)
def Shuffle(self, *args):
"""
Shuffle(TIntIntVV self, TRnd Rnd)
Parameters:
Rnd: TRnd &
"""
return _snap.TIntIntVV_Shuffle(self, *args)
def Reverse(self, *args):
"""
Reverse(TIntIntVV self)
Reverse(TIntIntVV self, int LValN, int RValN)
Parameters:
LValN: int
RValN: int
"""
return _snap.TIntIntVV_Reverse(self, *args)
def Merge(self):
"""
Merge(TIntIntVV self)
Parameters:
self: TVec< TVec< TInt,int >,int > *
"""
return _snap.TIntIntVV_Merge(self)
def Intrs(self, *args):
"""
Intrs(TIntIntVV self, TIntIntVV ValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
Intrs(TIntIntVV self, TIntIntVV ValV, TIntIntVV DstValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
DstValV: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_Intrs(self, *args)
def Union(self, *args):
"""
Union(TIntIntVV self, TIntIntVV ValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
Union(TIntIntVV self, TIntIntVV ValV, TIntIntVV DstValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
DstValV: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_Union(self, *args)
def Diff(self, *args):
"""
Diff(TIntIntVV self, TIntIntVV ValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
Diff(TIntIntVV self, TIntIntVV ValV, TIntIntVV DstValV)
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
DstValV: TVec< TVec< TInt,int >,int > &
"""
return _snap.TIntIntVV_Diff(self, *args)
def IntrsLen(self, *args):
"""
IntrsLen(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_IntrsLen(self, *args)
def UnionLen(self, *args):
"""
UnionLen(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_UnionLen(self, *args)
def Count(self, *args):
"""
Count(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_Count(self, *args)
def SearchBin(self, *args):
"""
SearchBin(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
SearchBin(TIntIntVV self, TIntV Val, int & InsValN) -> int
Parameters:
Val: TVec< TInt,int > const &
InsValN: int &
"""
return _snap.TIntIntVV_SearchBin(self, *args)
def SearchForw(self, *args):
"""
SearchForw(TIntIntVV self, TIntV Val, int const & BValN=0) -> int
Parameters:
Val: TVec< TInt,int > const &
BValN: int const &
SearchForw(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_SearchForw(self, *args)
def SearchBack(self, *args):
"""
SearchBack(TIntIntVV self, TIntV Val) -> int
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_SearchBack(self, *args)
def SearchVForw(self, *args):
"""
SearchVForw(TIntIntVV self, TIntIntVV ValV, int const & BValN=0) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
BValN: int const &
SearchVForw(TIntIntVV self, TIntIntVV ValV) -> int
Parameters:
ValV: TVec< TVec< TInt,int >,int > const &
"""
return _snap.TIntIntVV_SearchVForw(self, *args)
def IsIn(self, *args):
"""
IsIn(TIntIntVV self, TIntV Val) -> bool
Parameters:
Val: TVec< TInt,int > const &
IsIn(TIntIntVV self, TIntV Val, int & ValN) -> bool
Parameters:
Val: TVec< TInt,int > const &
ValN: int &
"""
return _snap.TIntIntVV_IsIn(self, *args)
def IsInBin(self, *args):
"""
IsInBin(TIntIntVV self, TIntV Val) -> bool
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_IsInBin(self, *args)
def GetDat(self, *args):
"""
GetDat(TIntIntVV self, TIntV Val) -> TIntV
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetDat(self, *args)
def GetAddDat(self, *args):
"""
GetAddDat(TIntIntVV self, TIntV Val) -> TIntV
Parameters:
Val: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetAddDat(self, *args)
def GetMxValN(self):
"""
GetMxValN(TIntIntVV self) -> int
Parameters:
self: TVec< TVec< TInt,int >,int > const *
"""
return _snap.TIntIntVV_GetMxValN(self)
def GetV(*args):
"""
GetV(TIntV Val1) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7,
TIntV Val8) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
Val8: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7,
TIntV Val8, TIntV Val9) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
Val8: TVec< TInt,int > const &
Val9: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetV(*args)
GetV = staticmethod(GetV)
TIntIntVV.Load = new_instancemethod(_snap.TIntIntVV_Load,None,TIntIntVV)
TIntIntVV.Save = new_instancemethod(_snap.TIntIntVV_Save,None,TIntIntVV)
TIntIntVV.LoadXml = new_instancemethod(_snap.TIntIntVV_LoadXml,None,TIntIntVV)
TIntIntVV.SaveXml = new_instancemethod(_snap.TIntIntVV_SaveXml,None,TIntIntVV)
TIntIntVV.__add__ = new_instancemethod(_snap.TIntIntVV___add__,None,TIntIntVV)
TIntIntVV.__eq__ = new_instancemethod(_snap.TIntIntVV___eq__,None,TIntIntVV)
TIntIntVV.__lt__ = new_instancemethod(_snap.TIntIntVV___lt__,None,TIntIntVV)
TIntIntVV.GetMemUsed = new_instancemethod(_snap.TIntIntVV_GetMemUsed,None,TIntIntVV)
TIntIntVV.GetMemSize = new_instancemethod(_snap.TIntIntVV_GetMemSize,None,TIntIntVV)
TIntIntVV.GetPrimHashCd = new_instancemethod(_snap.TIntIntVV_GetPrimHashCd,None,TIntIntVV)
TIntIntVV.GetSecHashCd = new_instancemethod(_snap.TIntIntVV_GetSecHashCd,None,TIntIntVV)
TIntIntVV.Gen = new_instancemethod(_snap.TIntIntVV_Gen,None,TIntIntVV)
TIntIntVV.GenExt = new_instancemethod(_snap.TIntIntVV_GenExt,None,TIntIntVV)
TIntIntVV.IsExt = new_instancemethod(_snap.TIntIntVV_IsExt,None,TIntIntVV)
TIntIntVV.Reserve = new_instancemethod(_snap.TIntIntVV_Reserve,None,TIntIntVV)
TIntIntVV.Clr = new_instancemethod(_snap.TIntIntVV_Clr,None,TIntIntVV)
TIntIntVV.Trunc = new_instancemethod(_snap.TIntIntVV_Trunc,None,TIntIntVV)
TIntIntVV.Pack = new_instancemethod(_snap.TIntIntVV_Pack,None,TIntIntVV)
TIntIntVV.MoveFrom = new_instancemethod(_snap.TIntIntVV_MoveFrom,None,TIntIntVV)
TIntIntVV.Empty = new_instancemethod(_snap.TIntIntVV_Empty,None,TIntIntVV)
TIntIntVV.Len = new_instancemethod(_snap.TIntIntVV_Len,None,TIntIntVV)
TIntIntVV.Reserved = new_instancemethod(_snap.TIntIntVV_Reserved,None,TIntIntVV)
TIntIntVV.Last = new_instancemethod(_snap.TIntIntVV_Last,None,TIntIntVV)
TIntIntVV.LastValN = new_instancemethod(_snap.TIntIntVV_LastValN,None,TIntIntVV)
TIntIntVV.LastLast = new_instancemethod(_snap.TIntIntVV_LastLast,None,TIntIntVV)
TIntIntVV.BegI = new_instancemethod(_snap.TIntIntVV_BegI,None,TIntIntVV)
TIntIntVV.EndI = new_instancemethod(_snap.TIntIntVV_EndI,None,TIntIntVV)
TIntIntVV.GetI = new_instancemethod(_snap.TIntIntVV_GetI,None,TIntIntVV)
TIntIntVV.AddV = new_instancemethod(_snap.TIntIntVV_AddV,None,TIntIntVV)
TIntIntVV.AddSorted = new_instancemethod(_snap.TIntIntVV_AddSorted,None,TIntIntVV)
TIntIntVV.AddBackSorted = new_instancemethod(_snap.TIntIntVV_AddBackSorted,None,TIntIntVV)
TIntIntVV.AddVMerged = new_instancemethod(_snap.TIntIntVV_AddVMerged,None,TIntIntVV)
TIntIntVV.AddUnique = new_instancemethod(_snap.TIntIntVV_AddUnique,None,TIntIntVV)
TIntIntVV.GetVal = new_instancemethod(_snap.TIntIntVV_GetVal,None,TIntIntVV)
TIntIntVV.GetSubValV = new_instancemethod(_snap.TIntIntVV_GetSubValV,None,TIntIntVV)
TIntIntVV.Ins = new_instancemethod(_snap.TIntIntVV_Ins,None,TIntIntVV)
TIntIntVV.Del = new_instancemethod(_snap.TIntIntVV_Del,None,TIntIntVV)
TIntIntVV.DelLast = new_instancemethod(_snap.TIntIntVV_DelLast,None,TIntIntVV)
TIntIntVV.DelIfIn = new_instancemethod(_snap.TIntIntVV_DelIfIn,None,TIntIntVV)
TIntIntVV.DelAll = new_instancemethod(_snap.TIntIntVV_DelAll,None,TIntIntVV)
TIntIntVV.PutAll = new_instancemethod(_snap.TIntIntVV_PutAll,None,TIntIntVV)
TIntIntVV.Swap = new_instancemethod(_snap.TIntIntVV_Swap,None,TIntIntVV)
TIntIntVV.NextPerm = new_instancemethod(_snap.TIntIntVV_NextPerm,None,TIntIntVV)
TIntIntVV.PrevPerm = new_instancemethod(_snap.TIntIntVV_PrevPerm,None,TIntIntVV)
TIntIntVV.GetPivotValN = new_instancemethod(_snap.TIntIntVV_GetPivotValN,None,TIntIntVV)
TIntIntVV.BSort = new_instancemethod(_snap.TIntIntVV_BSort,None,TIntIntVV)
TIntIntVV.ISort = new_instancemethod(_snap.TIntIntVV_ISort,None,TIntIntVV)
TIntIntVV.Partition = new_instancemethod(_snap.TIntIntVV_Partition,None,TIntIntVV)
TIntIntVV.QSort = new_instancemethod(_snap.TIntIntVV_QSort,None,TIntIntVV)
TIntIntVV.Sort = new_instancemethod(_snap.TIntIntVV_Sort,None,TIntIntVV)
TIntIntVV.IsSorted = new_instancemethod(_snap.TIntIntVV_IsSorted,None,TIntIntVV)
TIntIntVV.Shuffle = new_instancemethod(_snap.TIntIntVV_Shuffle,None,TIntIntVV)
TIntIntVV.Reverse = new_instancemethod(_snap.TIntIntVV_Reverse,None,TIntIntVV)
TIntIntVV.Merge = new_instancemethod(_snap.TIntIntVV_Merge,None,TIntIntVV)
TIntIntVV.Intrs = new_instancemethod(_snap.TIntIntVV_Intrs,None,TIntIntVV)
TIntIntVV.Union = new_instancemethod(_snap.TIntIntVV_Union,None,TIntIntVV)
TIntIntVV.Diff = new_instancemethod(_snap.TIntIntVV_Diff,None,TIntIntVV)
TIntIntVV.IntrsLen = new_instancemethod(_snap.TIntIntVV_IntrsLen,None,TIntIntVV)
TIntIntVV.UnionLen = new_instancemethod(_snap.TIntIntVV_UnionLen,None,TIntIntVV)
TIntIntVV.Count = new_instancemethod(_snap.TIntIntVV_Count,None,TIntIntVV)
TIntIntVV.SearchBin = new_instancemethod(_snap.TIntIntVV_SearchBin,None,TIntIntVV)
TIntIntVV.SearchForw = new_instancemethod(_snap.TIntIntVV_SearchForw,None,TIntIntVV)
TIntIntVV.SearchBack = new_instancemethod(_snap.TIntIntVV_SearchBack,None,TIntIntVV)
TIntIntVV.SearchVForw = new_instancemethod(_snap.TIntIntVV_SearchVForw,None,TIntIntVV)
TIntIntVV.IsIn = new_instancemethod(_snap.TIntIntVV_IsIn,None,TIntIntVV)
TIntIntVV.IsInBin = new_instancemethod(_snap.TIntIntVV_IsInBin,None,TIntIntVV)
TIntIntVV.GetDat = new_instancemethod(_snap.TIntIntVV_GetDat,None,TIntIntVV)
TIntIntVV.GetAddDat = new_instancemethod(_snap.TIntIntVV_GetAddDat,None,TIntIntVV)
TIntIntVV.GetMxValN = new_instancemethod(_snap.TIntIntVV_GetMxValN,None,TIntIntVV)
TIntIntVV_swigregister = _snap.TIntIntVV_swigregister
TIntIntVV_swigregister(TIntIntVV)
def TIntIntVV_SwapI(*args):
"""
TIntIntVV_SwapI(TIntV LVal, TIntV RVal)
Parameters:
LVal: TVec< TVec< TInt,int >,int >::TIter
RVal: TVec< TVec< TInt,int >,int >::TIter
"""
return _snap.TIntIntVV_SwapI(*args)
def TIntIntVV_GetV(*args):
"""
GetV(TIntV Val1) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7,
TIntV Val8) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
Val8: TVec< TInt,int > const &
TIntIntVV_GetV(TIntV Val1, TIntV Val2, TIntV Val3, TIntV Val4, TIntV Val5, TIntV Val6, TIntV Val7,
TIntV Val8, TIntV Val9) -> TIntIntVV
Parameters:
Val1: TVec< TInt,int > const &
Val2: TVec< TInt,int > const &
Val3: TVec< TInt,int > const &
Val4: TVec< TInt,int > const &
Val5: TVec< TInt,int > const &
Val6: TVec< TInt,int > const &
Val7: TVec< TInt,int > const &
Val8: TVec< TInt,int > const &
Val9: TVec< TInt,int > const &
"""
return _snap.TIntIntVV_GetV(*args)
class TIntIntVH(object):
"""Proxy of C++ THash<(TInt,TVec<(TInt,int)>)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
HashPrimes = _snap.TIntIntVH_HashPrimes
def __init__(self, *args):
"""
__init__(THash<(TInt,TVec<(TInt,int)>)> self) -> TIntIntVH
__init__(THash<(TInt,TVec<(TInt,int)>)> self, TIntIntVH Hash) -> TIntIntVH
Parameters:
Hash: THash< TInt,TVec< TInt,int > > const &
__init__(THash<(TInt,TVec<(TInt,int)>)> self, int const & ExpectVals, bool const & _AutoSizeP=False) -> TIntIntVH
Parameters:
ExpectVals: int const &
_AutoSizeP: bool const &
__init__(THash<(TInt,TVec<(TInt,int)>)> self, int const & ExpectVals) -> TIntIntVH
Parameters:
ExpectVals: int const &
__init__(THash<(TInt,TVec<(TInt,int)>)> self, TSIn SIn) -> TIntIntVH
Parameters:
SIn: TSIn &
"""
_snap.TIntIntVH_swiginit(self,_snap.new_TIntIntVH(*args))
def Load(self, *args):
"""
Load(TIntIntVH self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TIntIntVH_Load(self, *args)
def Save(self, *args):
"""
Save(TIntIntVH self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TIntIntVH_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TIntIntVH self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TIntIntVH self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TIntIntVH_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TIntIntVH self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TIntIntVH_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TIntIntVH self, TIntIntVH Hash) -> bool
Parameters:
Hash: THash< TInt,TVec< TInt,int > > const &
"""
return _snap.TIntIntVH___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntIntVH self, TIntIntVH Hash) -> bool
Parameters:
Hash: THash< TInt,TVec< TInt,int > > const &
"""
return _snap.TIntIntVH___lt__(self, *args)
def __call__(self, *args):
"""
__call__(TIntIntVH self, TInt Key) -> TIntV
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH___call__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TIntIntVH self) -> ::TSize
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_GetMemUsed(self)
def BegI(self):
"""
BegI(TIntIntVH self) -> THash< TInt,TVec< TInt,int > >::TIter
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_BegI(self)
def EndI(self):
"""
EndI(TIntIntVH self) -> THash< TInt,TVec< TInt,int > >::TIter
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_EndI(self)
def GetI(self, *args):
"""
GetI(TIntIntVH self, TInt Key) -> THash< TInt,TVec< TInt,int > >::TIter
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_GetI(self, *args)
def Gen(self, *args):
"""
Gen(TIntIntVH self, int const & ExpectVals)
Parameters:
ExpectVals: int const &
"""
return _snap.TIntIntVH_Gen(self, *args)
def Clr(self, *args):
"""
Clr(TIntIntVH self, bool const & DoDel=True, int const & NoDelLim=-1, bool const & ResetDat=True)
Parameters:
DoDel: bool const &
NoDelLim: int const &
ResetDat: bool const &
Clr(TIntIntVH self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TIntIntVH self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_Clr(self, *args)
def Empty(self):
"""
Empty(TIntIntVH self) -> bool
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_Empty(self)
def Len(self):
"""
Len(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_Len(self)
def GetPorts(self):
"""
GetPorts(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_GetPorts(self)
def IsAutoSize(self):
"""
IsAutoSize(TIntIntVH self) -> bool
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_IsAutoSize(self)
def GetMxKeyIds(self):
"""
GetMxKeyIds(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_GetMxKeyIds(self)
def GetReservedKeyIds(self):
"""
GetReservedKeyIds(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_GetReservedKeyIds(self)
def IsKeyIdEqKeyN(self):
"""
IsKeyIdEqKeyN(TIntIntVH self) -> bool
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_IsKeyIdEqKeyN(self)
def DelKey(self, *args):
"""
DelKey(TIntIntVH self, TInt Key)
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_DelKey(self, *args)
def DelIfKey(self, *args):
"""
DelIfKey(TIntIntVH self, TInt Key) -> bool
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_DelIfKey(self, *args)
def DelKeyId(self, *args):
"""
DelKeyId(TIntIntVH self, int const & KeyId)
Parameters:
KeyId: int const &
"""
return _snap.TIntIntVH_DelKeyId(self, *args)
def DelKeyIdV(self, *args):
"""
DelKeyIdV(TIntIntVH self, TIntV KeyIdV)
Parameters:
KeyIdV: TIntV const &
"""
return _snap.TIntIntVH_DelKeyIdV(self, *args)
def MarkDelKey(self, *args):
"""
MarkDelKey(TIntIntVH self, TInt Key)
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_MarkDelKey(self, *args)
def MarkDelKeyId(self, *args):
"""
MarkDelKeyId(TIntIntVH self, int const & KeyId)
Parameters:
KeyId: int const &
"""
return _snap.TIntIntVH_MarkDelKeyId(self, *args)
def GetKey(self, *args):
"""
GetKey(TIntIntVH self, int const & KeyId) -> TInt
Parameters:
KeyId: int const &
"""
return _snap.TIntIntVH_GetKey(self, *args)
def GetKeyId(self, *args):
"""
GetKeyId(TIntIntVH self, TInt Key) -> int
Parameters:
Key: TInt const &
"""
return _snap.TIntIntVH_GetKeyId(self, *args)
def GetRndKeyId(self, *args):
"""
GetRndKeyId(TIntIntVH self, TRnd Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndKeyId(TIntIntVH self, TRnd Rnd, double const & EmptyFrac) -> int
Parameters:
Rnd: TRnd &
EmptyFrac: double const &
"""
return _snap.TIntIntVH_GetRndKeyId(self, *args)
def IsKeyId(self, *args):
"""
IsKeyId(TIntIntVH self, int const & KeyId) -> bool
Parameters:
KeyId: int const &
"""
return _snap.TIntIntVH_IsKeyId(self, *args)
def GetKeyDat(self, *args):
"""
GetKeyDat(TIntIntVH self, int const & KeyId, TInt Key, TIntV Dat)
Parameters:
KeyId: int const &
Key: TInt &
Dat: TVec< TInt,int > &
"""
return _snap.TIntIntVH_GetKeyDat(self, *args)
def IsKeyGetDat(self, *args):
"""
IsKeyGetDat(TIntIntVH self, TInt Key, TIntV Dat) -> bool
Parameters:
Key: TInt const &
Dat: TVec< TInt,int > &
"""
return _snap.TIntIntVH_IsKeyGetDat(self, *args)
def FFirstKeyId(self):
"""
FFirstKeyId(TIntIntVH self) -> int
Parameters:
self: THash< TInt,TVec< TInt,int > > const *
"""
return _snap.TIntIntVH_FFirstKeyId(self)
def FNextKeyId(self, *args):
"""
FNextKeyId(TIntIntVH self, int & KeyId) -> bool
Parameters:
KeyId: int &
"""
return _snap.TIntIntVH_FNextKeyId(self, *args)
def GetKeyV(self, *args):
"""
GetKeyV(TIntIntVH self, TIntV KeyV)
Parameters:
KeyV: TVec< TInt > &
"""
return _snap.TIntIntVH_GetKeyV(self, *args)
def GetDatV(self, *args):
"""
GetDatV(TIntIntVH self, TIntIntVV DatV)
Parameters:
DatV: TVec< TVec< TInt,int > > &
"""
return _snap.TIntIntVH_GetDatV(self, *args)
def GetKeyDatPrV(self, *args):
"""
GetKeyDatPrV(TIntIntVH self, TVec< TPair< TInt,TVec< TInt,int > > > & KeyDatPrV)
Parameters:
KeyDatPrV: TVec< TPair< TInt,TVec< TInt,int > > > &
"""
return _snap.TIntIntVH_GetKeyDatPrV(self, *args)
def GetDatKeyPrV(self, *args):
"""
GetDatKeyPrV(TIntIntVH self, TVec< TPair< TVec< TInt,int >,TInt > > & DatKeyPrV)
Parameters:
DatKeyPrV: TVec< TPair< TVec< TInt,int >,TInt > > &
"""
return _snap.TIntIntVH_GetDatKeyPrV(self, *args)
def GetKeyDatKdV(self, *args):
"""
GetKeyDatKdV(TIntIntVH self, TVec< TKeyDat< TInt,TVec< TInt,int > > > & KeyDatKdV)
Parameters:
KeyDatKdV: TVec< TKeyDat< TInt,TVec< TInt,int > > > &
"""
return _snap.TIntIntVH_GetKeyDatKdV(self, *args)
def GetDatKeyKdV(self, *args):
"""
GetDatKeyKdV(TIntIntVH self, TVec< TKeyDat< TVec< TInt,int >,TInt > > & DatKeyKdV)
Parameters:
DatKeyKdV: TVec< TKeyDat< TVec< TInt,int >,TInt > > &
"""
return _snap.TIntIntVH_GetDatKeyKdV(self, *args)
def Swap(self, *args):
"""
Swap(TIntIntVH self, TIntIntVH Hash)
Parameters:
Hash: THash< TInt,TVec< TInt,int > > &
"""
return _snap.TIntIntVH_Swap(self, *args)
def Defrag(self):
"""
Defrag(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_Defrag(self)
def Pack(self):
"""
Pack(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_Pack(self)
def Sort(self, *args):
"""
Sort(TIntIntVH self, bool const & CmpKey, bool const & Asc)
Parameters:
CmpKey: bool const &
Asc: bool const &
"""
return _snap.TIntIntVH_Sort(self, *args)
def SortByKey(self, Asc=True):
"""
SortByKey(TIntIntVH self, bool const & Asc=True)
Parameters:
Asc: bool const &
SortByKey(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_SortByKey(self, Asc)
def SortByDat(self, Asc=True):
"""
SortByDat(TIntIntVH self, bool const & Asc=True)
Parameters:
Asc: bool const &
SortByDat(TIntIntVH self)
Parameters:
self: THash< TInt,TVec< TInt,int > > *
"""
return _snap.TIntIntVH_SortByDat(self, Asc)
def AddKey(self, *args):
"""
AddKey(TIntIntVH self, TInt Key) -> int
Parameters:
Key: TInt const &
AddKey(TIntIntVH self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntIntVH_AddKey(self, *args)
def IsKey(self, *args):
"""
IsKey(TIntIntVH self, TInt Key) -> bool
Parameters:
Key: TInt const &
IsKey(TIntIntVH self, TInt Key, int & KeyId) -> bool
Parameters:
Key: TInt const &
KeyId: int &
IsKey(TIntIntVH self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntIntVH_IsKey(self, *args)
def GetDat(self, *args):
"""
GetDat(TIntIntVH self, TInt Key) -> TIntV
Parameters:
Key: TInt const &
GetDat(TIntIntVH self, TInt Key) -> TIntV
Parameters:
Key: TInt const &
GetDat(TIntIntVH self, int Val) -> TIntV
Parameters:
Val: int
"""
return _snap.TIntIntVH_GetDat(self, *args)
__swig_destroy__ = _snap.delete_TIntIntVH
TIntIntVH.Load = new_instancemethod(_snap.TIntIntVH_Load,None,TIntIntVH)
TIntIntVH.Save = new_instancemethod(_snap.TIntIntVH_Save,None,TIntIntVH)
TIntIntVH.LoadXml = new_instancemethod(_snap.TIntIntVH_LoadXml,None,TIntIntVH)
TIntIntVH.SaveXml = new_instancemethod(_snap.TIntIntVH_SaveXml,None,TIntIntVH)
TIntIntVH.__eq__ = new_instancemethod(_snap.TIntIntVH___eq__,None,TIntIntVH)
TIntIntVH.__lt__ = new_instancemethod(_snap.TIntIntVH___lt__,None,TIntIntVH)
TIntIntVH.__call__ = new_instancemethod(_snap.TIntIntVH___call__,None,TIntIntVH)
TIntIntVH.GetMemUsed = new_instancemethod(_snap.TIntIntVH_GetMemUsed,None,TIntIntVH)
TIntIntVH.BegI = new_instancemethod(_snap.TIntIntVH_BegI,None,TIntIntVH)
TIntIntVH.EndI = new_instancemethod(_snap.TIntIntVH_EndI,None,TIntIntVH)
TIntIntVH.GetI = new_instancemethod(_snap.TIntIntVH_GetI,None,TIntIntVH)
TIntIntVH.Gen = new_instancemethod(_snap.TIntIntVH_Gen,None,TIntIntVH)
TIntIntVH.Clr = new_instancemethod(_snap.TIntIntVH_Clr,None,TIntIntVH)
TIntIntVH.Empty = new_instancemethod(_snap.TIntIntVH_Empty,None,TIntIntVH)
TIntIntVH.Len = new_instancemethod(_snap.TIntIntVH_Len,None,TIntIntVH)
TIntIntVH.GetPorts = new_instancemethod(_snap.TIntIntVH_GetPorts,None,TIntIntVH)
TIntIntVH.IsAutoSize = new_instancemethod(_snap.TIntIntVH_IsAutoSize,None,TIntIntVH)
TIntIntVH.GetMxKeyIds = new_instancemethod(_snap.TIntIntVH_GetMxKeyIds,None,TIntIntVH)
TIntIntVH.GetReservedKeyIds = new_instancemethod(_snap.TIntIntVH_GetReservedKeyIds,None,TIntIntVH)
TIntIntVH.IsKeyIdEqKeyN = new_instancemethod(_snap.TIntIntVH_IsKeyIdEqKeyN,None,TIntIntVH)
TIntIntVH.DelKey = new_instancemethod(_snap.TIntIntVH_DelKey,None,TIntIntVH)
TIntIntVH.DelIfKey = new_instancemethod(_snap.TIntIntVH_DelIfKey,None,TIntIntVH)
TIntIntVH.DelKeyId = new_instancemethod(_snap.TIntIntVH_DelKeyId,None,TIntIntVH)
TIntIntVH.DelKeyIdV = new_instancemethod(_snap.TIntIntVH_DelKeyIdV,None,TIntIntVH)
TIntIntVH.MarkDelKey = new_instancemethod(_snap.TIntIntVH_MarkDelKey,None,TIntIntVH)
TIntIntVH.MarkDelKeyId = new_instancemethod(_snap.TIntIntVH_MarkDelKeyId,None,TIntIntVH)
TIntIntVH.GetKey = new_instancemethod(_snap.TIntIntVH_GetKey,None,TIntIntVH)
TIntIntVH.GetKeyId = new_instancemethod(_snap.TIntIntVH_GetKeyId,None,TIntIntVH)
TIntIntVH.GetRndKeyId = new_instancemethod(_snap.TIntIntVH_GetRndKeyId,None,TIntIntVH)
TIntIntVH.IsKeyId = new_instancemethod(_snap.TIntIntVH_IsKeyId,None,TIntIntVH)
TIntIntVH.GetKeyDat = new_instancemethod(_snap.TIntIntVH_GetKeyDat,None,TIntIntVH)
TIntIntVH.IsKeyGetDat = new_instancemethod(_snap.TIntIntVH_IsKeyGetDat,None,TIntIntVH)
TIntIntVH.FFirstKeyId = new_instancemethod(_snap.TIntIntVH_FFirstKeyId,None,TIntIntVH)
TIntIntVH.FNextKeyId = new_instancemethod(_snap.TIntIntVH_FNextKeyId,None,TIntIntVH)
TIntIntVH.GetKeyV = new_instancemethod(_snap.TIntIntVH_GetKeyV,None,TIntIntVH)
TIntIntVH.GetDatV = new_instancemethod(_snap.TIntIntVH_GetDatV,None,TIntIntVH)
TIntIntVH.GetKeyDatPrV = new_instancemethod(_snap.TIntIntVH_GetKeyDatPrV,None,TIntIntVH)
TIntIntVH.GetDatKeyPrV = new_instancemethod(_snap.TIntIntVH_GetDatKeyPrV,None,TIntIntVH)
TIntIntVH.GetKeyDatKdV = new_instancemethod(_snap.TIntIntVH_GetKeyDatKdV,None,TIntIntVH)
TIntIntVH.GetDatKeyKdV = new_instancemethod(_snap.TIntIntVH_GetDatKeyKdV,None,TIntIntVH)
TIntIntVH.Swap = new_instancemethod(_snap.TIntIntVH_Swap,None,TIntIntVH)
TIntIntVH.Defrag = new_instancemethod(_snap.TIntIntVH_Defrag,None,TIntIntVH)
TIntIntVH.Pack = new_instancemethod(_snap.TIntIntVH_Pack,None,TIntIntVH)
TIntIntVH.Sort = new_instancemethod(_snap.TIntIntVH_Sort,None,TIntIntVH)
TIntIntVH.SortByKey = new_instancemethod(_snap.TIntIntVH_SortByKey,None,TIntIntVH)
TIntIntVH.SortByDat = new_instancemethod(_snap.TIntIntVH_SortByDat,None,TIntIntVH)
TIntIntVH.AddKey = new_instancemethod(_snap.TIntIntVH_AddKey,None,TIntIntVH)
TIntIntVH.IsKey = new_instancemethod(_snap.TIntIntVH_IsKey,None,TIntIntVH)
TIntIntVH.GetDat = new_instancemethod(_snap.TIntIntVH_GetDat,None,TIntIntVH)
TIntIntVH_swigregister = _snap.TIntIntVH_swigregister
TIntIntVH_swigregister(TIntIntVH)
class TIntH(object):
"""Proxy of C++ THash<(TInt,TInt)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
HashPrimes = _snap.TIntH_HashPrimes
def __init__(self, *args):
"""
__init__(THash<(TInt,TInt)> self) -> TIntH
__init__(THash<(TInt,TInt)> self, TIntH Hash) -> TIntH
Parameters:
Hash: THash< TInt,TInt > const &
__init__(THash<(TInt,TInt)> self, int const & ExpectVals, bool const & _AutoSizeP=False) -> TIntH
Parameters:
ExpectVals: int const &
_AutoSizeP: bool const &
__init__(THash<(TInt,TInt)> self, int const & ExpectVals) -> TIntH
Parameters:
ExpectVals: int const &
__init__(THash<(TInt,TInt)> self, TSIn SIn) -> TIntH
Parameters:
SIn: TSIn &
"""
_snap.TIntH_swiginit(self,_snap.new_TIntH(*args))
def Load(self, *args):
"""
Load(TIntH self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TIntH_Load(self, *args)
def Save(self, *args):
"""
Save(TIntH self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TIntH_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TIntH self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TIntH self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TIntH_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TIntH self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TIntH_SaveXml(self, *args)
def __eq__(self, *args):
"""
__eq__(TIntH self, TIntH Hash) -> bool
Parameters:
Hash: THash< TInt,TInt > const &
"""
return _snap.TIntH___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntH self, TIntH Hash) -> bool
Parameters:
Hash: THash< TInt,TInt > const &
"""
return _snap.TIntH___lt__(self, *args)
def __call__(self, *args):
"""
__call__(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
"""
return _snap.TIntH___call__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TIntH self) -> ::TSize
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_GetMemUsed(self)
def BegI(self):
"""
BegI(TIntH self) -> TIntHI
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_BegI(self)
def EndI(self):
"""
EndI(TIntH self) -> TIntHI
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_EndI(self)
def GetI(self, *args):
"""
GetI(TIntH self, TInt Key) -> TIntHI
Parameters:
Key: TInt const &
"""
return _snap.TIntH_GetI(self, *args)
def Gen(self, *args):
"""
Gen(TIntH self, int const & ExpectVals)
Parameters:
ExpectVals: int const &
"""
return _snap.TIntH_Gen(self, *args)
def Clr(self, *args):
"""
Clr(TIntH self, bool const & DoDel=True, int const & NoDelLim=-1, bool const & ResetDat=True)
Parameters:
DoDel: bool const &
NoDelLim: int const &
ResetDat: bool const &
Clr(TIntH self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TIntH self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_Clr(self, *args)
def Empty(self):
"""
Empty(TIntH self) -> bool
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_Empty(self)
def Len(self):
"""
Len(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_Len(self)
def GetPorts(self):
"""
GetPorts(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_GetPorts(self)
def IsAutoSize(self):
"""
IsAutoSize(TIntH self) -> bool
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_IsAutoSize(self)
def GetMxKeyIds(self):
"""
GetMxKeyIds(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_GetMxKeyIds(self)
def GetReservedKeyIds(self):
"""
GetReservedKeyIds(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_GetReservedKeyIds(self)
def IsKeyIdEqKeyN(self):
"""
IsKeyIdEqKeyN(TIntH self) -> bool
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_IsKeyIdEqKeyN(self)
def AddDatId(self, *args):
"""
AddDatId(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
"""
return _snap.TIntH_AddDatId(self, *args)
def DelKey(self, *args):
"""
DelKey(TIntH self, TInt Key)
Parameters:
Key: TInt const &
"""
return _snap.TIntH_DelKey(self, *args)
def DelIfKey(self, *args):
"""
DelIfKey(TIntH self, TInt Key) -> bool
Parameters:
Key: TInt const &
"""
return _snap.TIntH_DelIfKey(self, *args)
def DelKeyId(self, *args):
"""
DelKeyId(TIntH self, int const & KeyId)
Parameters:
KeyId: int const &
"""
return _snap.TIntH_DelKeyId(self, *args)
def DelKeyIdV(self, *args):
"""
DelKeyIdV(TIntH self, TIntV KeyIdV)
Parameters:
KeyIdV: TIntV const &
"""
return _snap.TIntH_DelKeyIdV(self, *args)
def MarkDelKey(self, *args):
"""
MarkDelKey(TIntH self, TInt Key)
Parameters:
Key: TInt const &
"""
return _snap.TIntH_MarkDelKey(self, *args)
def MarkDelKeyId(self, *args):
"""
MarkDelKeyId(TIntH self, int const & KeyId)
Parameters:
KeyId: int const &
"""
return _snap.TIntH_MarkDelKeyId(self, *args)
def GetKey(self, *args):
"""
GetKey(TIntH self, int const & KeyId) -> TInt
Parameters:
KeyId: int const &
"""
return _snap.TIntH_GetKey(self, *args)
def GetKeyId(self, *args):
"""
GetKeyId(TIntH self, TInt Key) -> int
Parameters:
Key: TInt const &
"""
return _snap.TIntH_GetKeyId(self, *args)
def GetRndKeyId(self, *args):
"""
GetRndKeyId(TIntH self, TRnd Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndKeyId(TIntH self, TRnd Rnd, double const & EmptyFrac) -> int
Parameters:
Rnd: TRnd &
EmptyFrac: double const &
"""
return _snap.TIntH_GetRndKeyId(self, *args)
def IsKeyId(self, *args):
"""
IsKeyId(TIntH self, int const & KeyId) -> bool
Parameters:
KeyId: int const &
"""
return _snap.TIntH_IsKeyId(self, *args)
def GetKeyDat(self, *args):
"""
GetKeyDat(TIntH self, int const & KeyId, TInt Key, TInt Dat)
Parameters:
KeyId: int const &
Key: TInt &
Dat: TInt &
"""
return _snap.TIntH_GetKeyDat(self, *args)
def IsKeyGetDat(self, *args):
"""
IsKeyGetDat(TIntH self, TInt Key, TInt Dat) -> bool
Parameters:
Key: TInt const &
Dat: TInt &
"""
return _snap.TIntH_IsKeyGetDat(self, *args)
def FFirstKeyId(self):
"""
FFirstKeyId(TIntH self) -> int
Parameters:
self: THash< TInt,TInt > const *
"""
return _snap.TIntH_FFirstKeyId(self)
def FNextKeyId(self, *args):
"""
FNextKeyId(TIntH self, int & KeyId) -> bool
Parameters:
KeyId: int &
"""
return _snap.TIntH_FNextKeyId(self, *args)
def GetKeyV(self, *args):
"""
GetKeyV(TIntH self, TIntV KeyV)
Parameters:
KeyV: TVec< TInt > &
"""
return _snap.TIntH_GetKeyV(self, *args)
def GetDatV(self, *args):
"""
GetDatV(TIntH self, TIntV DatV)
Parameters:
DatV: TVec< TInt > &
"""
return _snap.TIntH_GetDatV(self, *args)
def GetKeyDatPrV(self, *args):
"""
GetKeyDatPrV(TIntH self, TVec< TPair< TInt,TInt > > & KeyDatPrV)
Parameters:
KeyDatPrV: TVec< TPair< TInt,TInt > > &
"""
return _snap.TIntH_GetKeyDatPrV(self, *args)
def GetDatKeyPrV(self, *args):
"""
GetDatKeyPrV(TIntH self, TVec< TPair< TInt,TInt > > & DatKeyPrV)
Parameters:
DatKeyPrV: TVec< TPair< TInt,TInt > > &
"""
return _snap.TIntH_GetDatKeyPrV(self, *args)
def GetKeyDatKdV(self, *args):
"""
GetKeyDatKdV(TIntH self, TVec< TKeyDat< TInt,TInt > > & KeyDatKdV)
Parameters:
KeyDatKdV: TVec< TKeyDat< TInt,TInt > > &
"""
return _snap.TIntH_GetKeyDatKdV(self, *args)
def GetDatKeyKdV(self, *args):
"""
GetDatKeyKdV(TIntH self, TVec< TKeyDat< TInt,TInt > > & DatKeyKdV)
Parameters:
DatKeyKdV: TVec< TKeyDat< TInt,TInt > > &
"""
return _snap.TIntH_GetDatKeyKdV(self, *args)
def Swap(self, *args):
"""
Swap(TIntH self, TIntH Hash)
Parameters:
Hash: THash< TInt,TInt > &
"""
return _snap.TIntH_Swap(self, *args)
def Defrag(self):
"""
Defrag(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_Defrag(self)
def Pack(self):
"""
Pack(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_Pack(self)
def Sort(self, *args):
"""
Sort(TIntH self, bool const & CmpKey, bool const & Asc)
Parameters:
CmpKey: bool const &
Asc: bool const &
"""
return _snap.TIntH_Sort(self, *args)
def SortByKey(self, Asc=True):
"""
SortByKey(TIntH self, bool const & Asc=True)
Parameters:
Asc: bool const &
SortByKey(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_SortByKey(self, Asc)
def SortByDat(self, Asc=True):
"""
SortByDat(TIntH self, bool const & Asc=True)
Parameters:
Asc: bool const &
SortByDat(TIntH self)
Parameters:
self: THash< TInt,TInt > *
"""
return _snap.TIntH_SortByDat(self, Asc)
def AddKey(self, *args):
"""
AddKey(TIntH self, TInt Key) -> int
Parameters:
Key: TInt const &
AddKey(TIntH self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntH_AddKey(self, *args)
def IsKey(self, *args):
"""
IsKey(TIntH self, TInt Key) -> bool
Parameters:
Key: TInt const &
IsKey(TIntH self, TInt Key, int & KeyId) -> bool
Parameters:
Key: TInt const &
KeyId: int &
IsKey(TIntH self, int Val) -> int
Parameters:
Val: int
"""
return _snap.TIntH_IsKey(self, *args)
def GetDat(self, *args):
"""
GetDat(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
GetDat(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
GetDat(TIntH self, int Val) -> TInt
Parameters:
Val: int
"""
return _snap.TIntH_GetDat(self, *args)
def AddDat(self, *args):
"""
AddDat(TIntH self, TInt Key) -> TInt
Parameters:
Key: TInt const &
AddDat(TIntH self, TInt Key, TInt Dat) -> TInt
Parameters:
Key: TInt const &
Dat: TInt const &
AddDat(TIntH self, int Key, int Val) -> TInt
Parameters:
Key: int
Val: int
"""
return _snap.TIntH_AddDat(self, *args)
__swig_destroy__ = _snap.delete_TIntH
TIntH.Load = new_instancemethod(_snap.TIntH_Load,None,TIntH)
TIntH.Save = new_instancemethod(_snap.TIntH_Save,None,TIntH)
TIntH.LoadXml = new_instancemethod(_snap.TIntH_LoadXml,None,TIntH)
TIntH.SaveXml = new_instancemethod(_snap.TIntH_SaveXml,None,TIntH)
TIntH.__eq__ = new_instancemethod(_snap.TIntH___eq__,None,TIntH)
TIntH.__lt__ = new_instancemethod(_snap.TIntH___lt__,None,TIntH)
TIntH.__call__ = new_instancemethod(_snap.TIntH___call__,None,TIntH)
TIntH.GetMemUsed = new_instancemethod(_snap.TIntH_GetMemUsed,None,TIntH)
TIntH.BegI = new_instancemethod(_snap.TIntH_BegI,None,TIntH)
TIntH.EndI = new_instancemethod(_snap.TIntH_EndI,None,TIntH)
TIntH.GetI = new_instancemethod(_snap.TIntH_GetI,None,TIntH)
TIntH.Gen = new_instancemethod(_snap.TIntH_Gen,None,TIntH)
TIntH.Clr = new_instancemethod(_snap.TIntH_Clr,None,TIntH)
TIntH.Empty = new_instancemethod(_snap.TIntH_Empty,None,TIntH)
TIntH.Len = new_instancemethod(_snap.TIntH_Len,None,TIntH)
TIntH.GetPorts = new_instancemethod(_snap.TIntH_GetPorts,None,TIntH)
TIntH.IsAutoSize = new_instancemethod(_snap.TIntH_IsAutoSize,None,TIntH)
TIntH.GetMxKeyIds = new_instancemethod(_snap.TIntH_GetMxKeyIds,None,TIntH)
TIntH.GetReservedKeyIds = new_instancemethod(_snap.TIntH_GetReservedKeyIds,None,TIntH)
TIntH.IsKeyIdEqKeyN = new_instancemethod(_snap.TIntH_IsKeyIdEqKeyN,None,TIntH)
TIntH.AddDatId = new_instancemethod(_snap.TIntH_AddDatId,None,TIntH)
TIntH.DelKey = new_instancemethod(_snap.TIntH_DelKey,None,TIntH)
TIntH.DelIfKey = new_instancemethod(_snap.TIntH_DelIfKey,None,TIntH)
TIntH.DelKeyId = new_instancemethod(_snap.TIntH_DelKeyId,None,TIntH)
TIntH.DelKeyIdV = new_instancemethod(_snap.TIntH_DelKeyIdV,None,TIntH)
TIntH.MarkDelKey = new_instancemethod(_snap.TIntH_MarkDelKey,None,TIntH)
TIntH.MarkDelKeyId = new_instancemethod(_snap.TIntH_MarkDelKeyId,None,TIntH)
TIntH.GetKey = new_instancemethod(_snap.TIntH_GetKey,None,TIntH)
TIntH.GetKeyId = new_instancemethod(_snap.TIntH_GetKeyId,None,TIntH)
TIntH.GetRndKeyId = new_instancemethod(_snap.TIntH_GetRndKeyId,None,TIntH)
TIntH.IsKeyId = new_instancemethod(_snap.TIntH_IsKeyId,None,TIntH)
TIntH.GetKeyDat = new_instancemethod(_snap.TIntH_GetKeyDat,None,TIntH)
TIntH.IsKeyGetDat = new_instancemethod(_snap.TIntH_IsKeyGetDat,None,TIntH)
TIntH.FFirstKeyId = new_instancemethod(_snap.TIntH_FFirstKeyId,None,TIntH)
TIntH.FNextKeyId = new_instancemethod(_snap.TIntH_FNextKeyId,None,TIntH)
TIntH.GetKeyV = new_instancemethod(_snap.TIntH_GetKeyV,None,TIntH)
TIntH.GetDatV = new_instancemethod(_snap.TIntH_GetDatV,None,TIntH)
TIntH.GetKeyDatPrV = new_instancemethod(_snap.TIntH_GetKeyDatPrV,None,TIntH)
TIntH.GetDatKeyPrV = new_instancemethod(_snap.TIntH_GetDatKeyPrV,None,TIntH)
TIntH.GetKeyDatKdV = new_instancemethod(_snap.TIntH_GetKeyDatKdV,None,TIntH)
TIntH.GetDatKeyKdV = new_instancemethod(_snap.TIntH_GetDatKeyKdV,None,TIntH)
TIntH.Swap = new_instancemethod(_snap.TIntH_Swap,None,TIntH)
TIntH.Defrag = new_instancemethod(_snap.TIntH_Defrag,None,TIntH)
TIntH.Pack = new_instancemethod(_snap.TIntH_Pack,None,TIntH)
TIntH.Sort = new_instancemethod(_snap.TIntH_Sort,None,TIntH)
TIntH.SortByKey = new_instancemethod(_snap.TIntH_SortByKey,None,TIntH)
TIntH.SortByDat = new_instancemethod(_snap.TIntH_SortByDat,None,TIntH)
TIntH.AddKey = new_instancemethod(_snap.TIntH_AddKey,None,TIntH)
TIntH.IsKey = new_instancemethod(_snap.TIntH_IsKey,None,TIntH)
TIntH.GetDat = new_instancemethod(_snap.TIntH_GetDat,None,TIntH)
TIntH.AddDat = new_instancemethod(_snap.TIntH_AddDat,None,TIntH)
TIntH_swigregister = _snap.TIntH_swigregister
TIntH_swigregister(TIntH)
class TIntHI(object):
"""Proxy of C++ THashKeyDatI<(TInt,TInt)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(THashKeyDatI<(TInt,TInt)> self) -> TIntHI
__init__(THashKeyDatI<(TInt,TInt)> self, TIntHI _HashKeyDatI) -> TIntHI
Parameters:
_HashKeyDatI: THashKeyDatI< TInt,TInt > const &
__init__(THashKeyDatI<(TInt,TInt)> self, THashKeyDatI< TInt,TInt >::THKeyDat const * _KeyDatI, THashKeyDatI< TInt,TInt >::THKeyDat const * _EndI) -> TIntHI
Parameters:
_KeyDatI: THashKeyDatI< TInt,TInt >::THKeyDat const *
_EndI: THashKeyDatI< TInt,TInt >::THKeyDat const *
"""
_snap.TIntHI_swiginit(self,_snap.new_TIntHI(*args))
def __eq__(self, *args):
"""
__eq__(TIntHI self, TIntHI HashKeyDatI) -> bool
Parameters:
HashKeyDatI: THashKeyDatI< TInt,TInt > const &
"""
return _snap.TIntHI___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TIntHI self, TIntHI HashKeyDatI) -> bool
Parameters:
HashKeyDatI: THashKeyDatI< TInt,TInt > const &
"""
return _snap.TIntHI___lt__(self, *args)
def __ref__(self):
"""
__ref__(TIntHI self) -> THashKeyDatI< TInt,TInt >::THKeyDat &
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI___ref__(self)
def __call__(self):
"""
__call__(TIntHI self) -> THashKeyDatI< TInt,TInt >::THKeyDat &
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI___call__(self)
def __deref__(self):
"""
__deref__(TIntHI self) -> THashKeyDatI< TInt,TInt >::THKeyDat *
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI___deref__(self)
def Next(self):
"""
Next(TIntHI self) -> TIntHI
Parameters:
self: THashKeyDatI< TInt,TInt > *
"""
return _snap.TIntHI_Next(self)
def IsEmpty(self):
"""
IsEmpty(TIntHI self) -> bool
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI_IsEmpty(self)
def IsEnd(self):
"""
IsEnd(TIntHI self) -> bool
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI_IsEnd(self)
def GetKey(self):
"""
GetKey(TIntHI self) -> TInt
Parameters:
self: THashKeyDatI< TInt,TInt > const *
"""
return _snap.TIntHI_GetKey(self)
def GetDat(self, *args):
"""
GetDat(TIntHI self) -> TInt
GetDat(TIntHI self) -> TInt
Parameters:
self: THashKeyDatI< TInt,TInt > *
"""
return _snap.TIntHI_GetDat(self, *args)
__swig_destroy__ = _snap.delete_TIntHI
TIntHI.__eq__ = new_instancemethod(_snap.TIntHI___eq__,None,TIntHI)
TIntHI.__lt__ = new_instancemethod(_snap.TIntHI___lt__,None,TIntHI)
TIntHI.__ref__ = new_instancemethod(_snap.TIntHI___ref__,None,TIntHI)
TIntHI.__call__ = new_instancemethod(_snap.TIntHI___call__,None,TIntHI)
TIntHI.__deref__ = new_instancemethod(_snap.TIntHI___deref__,None,TIntHI)
TIntHI.Next = new_instancemethod(_snap.TIntHI_Next,None,TIntHI)
TIntHI.IsEmpty = new_instancemethod(_snap.TIntHI_IsEmpty,None,TIntHI)
TIntHI.IsEnd = new_instancemethod(_snap.TIntHI_IsEnd,None,TIntHI)
TIntHI.GetKey = new_instancemethod(_snap.TIntHI_GetKey,None,TIntHI)
TIntHI.GetDat = new_instancemethod(_snap.TIntHI_GetDat,None,TIntHI)
TIntHI_swigregister = _snap.TIntHI_swigregister
TIntHI_swigregister(TIntHI)
class TStrV(object):
"""Proxy of C++ TVec<(TStr,int)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
__swig_destroy__ = _snap.delete_TStrV
def __init__(self, *args):
"""
__init__(TVec<(TStr,int)> self) -> TStrV
__init__(TVec<(TStr,int)> self, TStrV Vec) -> TStrV
Parameters:
Vec: TVec< TStr,int > const &
__init__(TVec<(TStr,int)> self, int const & _Vals) -> TStrV
Parameters:
_Vals: int const &
__init__(TVec<(TStr,int)> self, int const & _MxVals, int const & _Vals) -> TStrV
Parameters:
_MxVals: int const &
_Vals: int const &
__init__(TVec<(TStr,int)> self, TStr _ValT, int const & _Vals) -> TStrV
Parameters:
_ValT: TStr *
_Vals: int const &
__init__(TVec<(TStr,int)> self, TSIn SIn) -> TStrV
Parameters:
SIn: TSIn &
"""
_snap.TStrV_swiginit(self,_snap.new_TStrV(*args))
def Load(self, *args):
"""
Load(TStrV self, TSIn SIn)
Parameters:
SIn: TSIn &
"""
return _snap.TStrV_Load(self, *args)
def Save(self, *args):
"""
Save(TStrV self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TStrV_Save(self, *args)
def LoadXml(self, *args):
"""
LoadXml(TStrV self, PXmlTok const & XmlTok, TStr Nm="")
Parameters:
XmlTok: PXmlTok const &
Nm: TStr const &
LoadXml(TStrV self, PXmlTok const & XmlTok)
Parameters:
XmlTok: PXmlTok const &
"""
return _snap.TStrV_LoadXml(self, *args)
def SaveXml(self, *args):
"""
SaveXml(TStrV self, TSOut SOut, TStr Nm)
Parameters:
SOut: TSOut &
Nm: TStr const &
"""
return _snap.TStrV_SaveXml(self, *args)
def __add__(self, *args):
"""
__add__(TStrV self, TStr Val) -> TStrV
Parameters:
Val: TStr const &
"""
return _snap.TStrV___add__(self, *args)
def __eq__(self, *args):
"""
__eq__(TStrV self, TStrV Vec) -> bool
Parameters:
Vec: TVec< TStr,int > const &
"""
return _snap.TStrV___eq__(self, *args)
def __lt__(self, *args):
"""
__lt__(TStrV self, TStrV Vec) -> bool
Parameters:
Vec: TVec< TStr,int > const &
"""
return _snap.TStrV___lt__(self, *args)
def GetMemUsed(self):
"""
GetMemUsed(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetMemUsed(self)
def GetMemSize(self):
"""
GetMemSize(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetMemSize(self)
def GetPrimHashCd(self):
"""
GetPrimHashCd(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetPrimHashCd(self)
def GetSecHashCd(self):
"""
GetSecHashCd(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetSecHashCd(self)
def Gen(self, *args):
"""
Gen(TStrV self, int const & _Vals)
Parameters:
_Vals: int const &
Gen(TStrV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TStrV_Gen(self, *args)
def GenExt(self, *args):
"""
GenExt(TStrV self, TStr _ValT, int const & _Vals)
Parameters:
_ValT: TStr *
_Vals: int const &
"""
return _snap.TStrV_GenExt(self, *args)
def IsExt(self):
"""
IsExt(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_IsExt(self)
def Reserve(self, *args):
"""
Reserve(TStrV self, int const & _MxVals)
Parameters:
_MxVals: int const &
Reserve(TStrV self, int const & _MxVals, int const & _Vals)
Parameters:
_MxVals: int const &
_Vals: int const &
"""
return _snap.TStrV_Reserve(self, *args)
def Clr(self, *args):
"""
Clr(TStrV self, bool const & DoDel=True, int const & NoDelLim=-1)
Parameters:
DoDel: bool const &
NoDelLim: int const &
Clr(TStrV self, bool const & DoDel=True)
Parameters:
DoDel: bool const &
Clr(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Clr(self, *args)
def Trunc(self, *args):
"""
Trunc(TStrV self, int const & _Vals=-1)
Parameters:
_Vals: int const &
Trunc(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Trunc(self, *args)
def Pack(self):
"""
Pack(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Pack(self)
def MoveFrom(self, *args):
"""
MoveFrom(TStrV self, TStrV Vec)
Parameters:
Vec: TVec< TStr,int > &
"""
return _snap.TStrV_MoveFrom(self, *args)
def Empty(self):
"""
Empty(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_Empty(self)
def Len(self):
"""
Len(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_Len(self)
def Reserved(self):
"""
Reserved(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_Reserved(self)
def Last(self, *args):
"""
Last(TStrV self) -> TStr
Last(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Last(self, *args)
def LastValN(self):
"""
LastValN(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_LastValN(self)
def LastLast(self, *args):
"""
LastLast(TStrV self) -> TStr
LastLast(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_LastLast(self, *args)
def BegI(self):
"""
BegI(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_BegI(self)
def EndI(self):
"""
EndI(TStrV self) -> TStr
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_EndI(self)
def GetI(self, *args):
"""
GetI(TStrV self, int const & ValN) -> TStr
Parameters:
ValN: int const &
"""
return _snap.TStrV_GetI(self, *args)
def AddV(self, *args):
"""
AddV(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_AddV(self, *args)
def AddSorted(self, *args):
"""
AddSorted(TStrV self, TStr Val, bool const & Asc=True, int const & _MxVals=-1) -> int
Parameters:
Val: TStr const &
Asc: bool const &
_MxVals: int const &
AddSorted(TStrV self, TStr Val, bool const & Asc=True) -> int
Parameters:
Val: TStr const &
Asc: bool const &
AddSorted(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_AddSorted(self, *args)
def AddBackSorted(self, *args):
"""
AddBackSorted(TStrV self, TStr Val, bool const & Asc) -> int
Parameters:
Val: TStr const &
Asc: bool const &
"""
return _snap.TStrV_AddBackSorted(self, *args)
def AddVMerged(self, *args):
"""
AddVMerged(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_AddVMerged(self, *args)
def AddUnique(self, *args):
"""
AddUnique(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_AddUnique(self, *args)
def GetVal(self, *args):
"""
GetVal(TStrV self, int const & ValN) -> TStr
Parameters:
ValN: int const &
GetVal(TStrV self, int const & ValN) -> TStr
Parameters:
ValN: int const &
"""
return _snap.TStrV_GetVal(self, *args)
def GetSubValV(self, *args):
"""
GetSubValV(TStrV self, int const & BValN, int const & EValN, TStrV ValV)
Parameters:
BValN: int const &
EValN: int const &
ValV: TVec< TStr,int > &
"""
return _snap.TStrV_GetSubValV(self, *args)
def Ins(self, *args):
"""
Ins(TStrV self, int const & ValN, TStr Val)
Parameters:
ValN: int const &
Val: TStr const &
"""
return _snap.TStrV_Ins(self, *args)
def Del(self, *args):
"""
Del(TStrV self, int const & ValN)
Parameters:
ValN: int const &
Del(TStrV self, int const & MnValN, int const & MxValN)
Parameters:
MnValN: int const &
MxValN: int const &
"""
return _snap.TStrV_Del(self, *args)
def DelLast(self):
"""
DelLast(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_DelLast(self)
def DelIfIn(self, *args):
"""
DelIfIn(TStrV self, TStr Val) -> bool
Parameters:
Val: TStr const &
"""
return _snap.TStrV_DelIfIn(self, *args)
def DelAll(self, *args):
"""
DelAll(TStrV self, TStr Val)
Parameters:
Val: TStr const &
"""
return _snap.TStrV_DelAll(self, *args)
def PutAll(self, *args):
"""
PutAll(TStrV self, TStr Val)
Parameters:
Val: TStr const &
"""
return _snap.TStrV_PutAll(self, *args)
def Swap(self, *args):
"""
Swap(TStrV self, TStrV Vec)
Parameters:
Vec: TVec< TStr,int > &
Swap(TStrV self, int const & ValN1, int const & ValN2)
Parameters:
ValN1: int const &
ValN2: int const &
"""
return _snap.TStrV_Swap(self, *args)
def SwapI(*args):
"""
SwapI(TStr LVal, TStr RVal)
Parameters:
LVal: TVec< TStr,int >::TIter
RVal: TVec< TStr,int >::TIter
"""
return _snap.TStrV_SwapI(*args)
SwapI = staticmethod(SwapI)
def NextPerm(self):
"""
NextPerm(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_NextPerm(self)
def PrevPerm(self):
"""
PrevPerm(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_PrevPerm(self)
def GetPivotValN(self, *args):
"""
GetPivotValN(TStrV self, int const & LValN, int const & RValN) -> int
Parameters:
LValN: int const &
RValN: int const &
"""
return _snap.TStrV_GetPivotValN(self, *args)
def BSort(self, *args):
"""
BSort(TStrV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TStrV_BSort(self, *args)
def ISort(self, *args):
"""
ISort(TStrV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TStrV_ISort(self, *args)
def Partition(self, *args):
"""
Partition(TStrV self, int const & MnLValN, int const & MxRValN, bool const & Asc) -> int
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TStrV_Partition(self, *args)
def QSort(self, *args):
"""
QSort(TStrV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
Parameters:
MnLValN: int const &
MxRValN: int const &
Asc: bool const &
"""
return _snap.TStrV_QSort(self, *args)
def Sort(self, Asc=True):
"""
Sort(TStrV self, bool const & Asc=True)
Parameters:
Asc: bool const &
Sort(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Sort(self, Asc)
def IsSorted(self, Asc=True):
"""
IsSorted(TStrV self, bool const & Asc=True) -> bool
Parameters:
Asc: bool const &
IsSorted(TStrV self) -> bool
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_IsSorted(self, Asc)
def Shuffle(self, *args):
"""
Shuffle(TStrV self, TRnd Rnd)
Parameters:
Rnd: TRnd &
"""
return _snap.TStrV_Shuffle(self, *args)
def Reverse(self, *args):
"""
Reverse(TStrV self)
Reverse(TStrV self, int LValN, int RValN)
Parameters:
LValN: int
RValN: int
"""
return _snap.TStrV_Reverse(self, *args)
def Merge(self):
"""
Merge(TStrV self)
Parameters:
self: TVec< TStr,int > *
"""
return _snap.TStrV_Merge(self)
def Intrs(self, *args):
"""
Intrs(TStrV self, TStrV ValV)
Parameters:
ValV: TVec< TStr,int > const &
Intrs(TStrV self, TStrV ValV, TStrV DstValV)
Parameters:
ValV: TVec< TStr,int > const &
DstValV: TVec< TStr,int > &
"""
return _snap.TStrV_Intrs(self, *args)
def Union(self, *args):
"""
Union(TStrV self, TStrV ValV)
Parameters:
ValV: TVec< TStr,int > const &
Union(TStrV self, TStrV ValV, TStrV DstValV)
Parameters:
ValV: TVec< TStr,int > const &
DstValV: TVec< TStr,int > &
"""
return _snap.TStrV_Union(self, *args)
def Diff(self, *args):
"""
Diff(TStrV self, TStrV ValV)
Parameters:
ValV: TVec< TStr,int > const &
Diff(TStrV self, TStrV ValV, TStrV DstValV)
Parameters:
ValV: TVec< TStr,int > const &
DstValV: TVec< TStr,int > &
"""
return _snap.TStrV_Diff(self, *args)
def IntrsLen(self, *args):
"""
IntrsLen(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_IntrsLen(self, *args)
def UnionLen(self, *args):
"""
UnionLen(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_UnionLen(self, *args)
def Count(self, *args):
"""
Count(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_Count(self, *args)
def SearchBin(self, *args):
"""
SearchBin(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
SearchBin(TStrV self, TStr Val, int & InsValN) -> int
Parameters:
Val: TStr const &
InsValN: int &
"""
return _snap.TStrV_SearchBin(self, *args)
def SearchForw(self, *args):
"""
SearchForw(TStrV self, TStr Val, int const & BValN=0) -> int
Parameters:
Val: TStr const &
BValN: int const &
SearchForw(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_SearchForw(self, *args)
def SearchBack(self, *args):
"""
SearchBack(TStrV self, TStr Val) -> int
Parameters:
Val: TStr const &
"""
return _snap.TStrV_SearchBack(self, *args)
def SearchVForw(self, *args):
"""
SearchVForw(TStrV self, TStrV ValV, int const & BValN=0) -> int
Parameters:
ValV: TVec< TStr,int > const &
BValN: int const &
SearchVForw(TStrV self, TStrV ValV) -> int
Parameters:
ValV: TVec< TStr,int > const &
"""
return _snap.TStrV_SearchVForw(self, *args)
def IsIn(self, *args):
"""
IsIn(TStrV self, TStr Val) -> bool
Parameters:
Val: TStr const &
IsIn(TStrV self, TStr Val, int & ValN) -> bool
Parameters:
Val: TStr const &
ValN: int &
"""
return _snap.TStrV_IsIn(self, *args)
def IsInBin(self, *args):
"""
IsInBin(TStrV self, TStr Val) -> bool
Parameters:
Val: TStr const &
"""
return _snap.TStrV_IsInBin(self, *args)
def GetDat(self, *args):
"""
GetDat(TStrV self, TStr Val) -> TStr
Parameters:
Val: TStr const &
"""
return _snap.TStrV_GetDat(self, *args)
def GetAddDat(self, *args):
"""
GetAddDat(TStrV self, TStr Val) -> TStr
Parameters:
Val: TStr const &
"""
return _snap.TStrV_GetAddDat(self, *args)
def GetMxValN(self):
"""
GetMxValN(TStrV self) -> int
Parameters:
self: TVec< TStr,int > const *
"""
return _snap.TStrV_GetMxValN(self)
def GetV(*args):
"""
GetV(TStr Val1) -> TStrV
Parameters:
Val1: TStr const &
GetV(TStr Val1, TStr Val2) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7, TStr Val8) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
Val8: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7, TStr Val8,
TStr Val9) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
Val8: TStr const &
Val9: TStr const &
"""
return _snap.TStrV_GetV(*args)
GetV = staticmethod(GetV)
TStrV.Load = new_instancemethod(_snap.TStrV_Load,None,TStrV)
TStrV.Save = new_instancemethod(_snap.TStrV_Save,None,TStrV)
TStrV.LoadXml = new_instancemethod(_snap.TStrV_LoadXml,None,TStrV)
TStrV.SaveXml = new_instancemethod(_snap.TStrV_SaveXml,None,TStrV)
TStrV.__add__ = new_instancemethod(_snap.TStrV___add__,None,TStrV)
TStrV.__eq__ = new_instancemethod(_snap.TStrV___eq__,None,TStrV)
TStrV.__lt__ = new_instancemethod(_snap.TStrV___lt__,None,TStrV)
TStrV.GetMemUsed = new_instancemethod(_snap.TStrV_GetMemUsed,None,TStrV)
TStrV.GetMemSize = new_instancemethod(_snap.TStrV_GetMemSize,None,TStrV)
TStrV.GetPrimHashCd = new_instancemethod(_snap.TStrV_GetPrimHashCd,None,TStrV)
TStrV.GetSecHashCd = new_instancemethod(_snap.TStrV_GetSecHashCd,None,TStrV)
TStrV.Gen = new_instancemethod(_snap.TStrV_Gen,None,TStrV)
TStrV.GenExt = new_instancemethod(_snap.TStrV_GenExt,None,TStrV)
TStrV.IsExt = new_instancemethod(_snap.TStrV_IsExt,None,TStrV)
TStrV.Reserve = new_instancemethod(_snap.TStrV_Reserve,None,TStrV)
TStrV.Clr = new_instancemethod(_snap.TStrV_Clr,None,TStrV)
TStrV.Trunc = new_instancemethod(_snap.TStrV_Trunc,None,TStrV)
TStrV.Pack = new_instancemethod(_snap.TStrV_Pack,None,TStrV)
TStrV.MoveFrom = new_instancemethod(_snap.TStrV_MoveFrom,None,TStrV)
TStrV.Empty = new_instancemethod(_snap.TStrV_Empty,None,TStrV)
TStrV.Len = new_instancemethod(_snap.TStrV_Len,None,TStrV)
TStrV.Reserved = new_instancemethod(_snap.TStrV_Reserved,None,TStrV)
TStrV.Last = new_instancemethod(_snap.TStrV_Last,None,TStrV)
TStrV.LastValN = new_instancemethod(_snap.TStrV_LastValN,None,TStrV)
TStrV.LastLast = new_instancemethod(_snap.TStrV_LastLast,None,TStrV)
TStrV.BegI = new_instancemethod(_snap.TStrV_BegI,None,TStrV)
TStrV.EndI = new_instancemethod(_snap.TStrV_EndI,None,TStrV)
TStrV.GetI = new_instancemethod(_snap.TStrV_GetI,None,TStrV)
TStrV.AddV = new_instancemethod(_snap.TStrV_AddV,None,TStrV)
TStrV.AddSorted = new_instancemethod(_snap.TStrV_AddSorted,None,TStrV)
TStrV.AddBackSorted = new_instancemethod(_snap.TStrV_AddBackSorted,None,TStrV)
TStrV.AddVMerged = new_instancemethod(_snap.TStrV_AddVMerged,None,TStrV)
TStrV.AddUnique = new_instancemethod(_snap.TStrV_AddUnique,None,TStrV)
TStrV.GetVal = new_instancemethod(_snap.TStrV_GetVal,None,TStrV)
TStrV.GetSubValV = new_instancemethod(_snap.TStrV_GetSubValV,None,TStrV)
TStrV.Ins = new_instancemethod(_snap.TStrV_Ins,None,TStrV)
TStrV.Del = new_instancemethod(_snap.TStrV_Del,None,TStrV)
TStrV.DelLast = new_instancemethod(_snap.TStrV_DelLast,None,TStrV)
TStrV.DelIfIn = new_instancemethod(_snap.TStrV_DelIfIn,None,TStrV)
TStrV.DelAll = new_instancemethod(_snap.TStrV_DelAll,None,TStrV)
TStrV.PutAll = new_instancemethod(_snap.TStrV_PutAll,None,TStrV)
TStrV.Swap = new_instancemethod(_snap.TStrV_Swap,None,TStrV)
TStrV.NextPerm = new_instancemethod(_snap.TStrV_NextPerm,None,TStrV)
TStrV.PrevPerm = new_instancemethod(_snap.TStrV_PrevPerm,None,TStrV)
TStrV.GetPivotValN = new_instancemethod(_snap.TStrV_GetPivotValN,None,TStrV)
TStrV.BSort = new_instancemethod(_snap.TStrV_BSort,None,TStrV)
TStrV.ISort = new_instancemethod(_snap.TStrV_ISort,None,TStrV)
TStrV.Partition = new_instancemethod(_snap.TStrV_Partition,None,TStrV)
TStrV.QSort = new_instancemethod(_snap.TStrV_QSort,None,TStrV)
TStrV.Sort = new_instancemethod(_snap.TStrV_Sort,None,TStrV)
TStrV.IsSorted = new_instancemethod(_snap.TStrV_IsSorted,None,TStrV)
TStrV.Shuffle = new_instancemethod(_snap.TStrV_Shuffle,None,TStrV)
TStrV.Reverse = new_instancemethod(_snap.TStrV_Reverse,None,TStrV)
TStrV.Merge = new_instancemethod(_snap.TStrV_Merge,None,TStrV)
TStrV.Intrs = new_instancemethod(_snap.TStrV_Intrs,None,TStrV)
TStrV.Union = new_instancemethod(_snap.TStrV_Union,None,TStrV)
TStrV.Diff = new_instancemethod(_snap.TStrV_Diff,None,TStrV)
TStrV.IntrsLen = new_instancemethod(_snap.TStrV_IntrsLen,None,TStrV)
TStrV.UnionLen = new_instancemethod(_snap.TStrV_UnionLen,None,TStrV)
TStrV.Count = new_instancemethod(_snap.TStrV_Count,None,TStrV)
TStrV.SearchBin = new_instancemethod(_snap.TStrV_SearchBin,None,TStrV)
TStrV.SearchForw = new_instancemethod(_snap.TStrV_SearchForw,None,TStrV)
TStrV.SearchBack = new_instancemethod(_snap.TStrV_SearchBack,None,TStrV)
TStrV.SearchVForw = new_instancemethod(_snap.TStrV_SearchVForw,None,TStrV)
TStrV.IsIn = new_instancemethod(_snap.TStrV_IsIn,None,TStrV)
TStrV.IsInBin = new_instancemethod(_snap.TStrV_IsInBin,None,TStrV)
TStrV.GetDat = new_instancemethod(_snap.TStrV_GetDat,None,TStrV)
TStrV.GetAddDat = new_instancemethod(_snap.TStrV_GetAddDat,None,TStrV)
TStrV.GetMxValN = new_instancemethod(_snap.TStrV_GetMxValN,None,TStrV)
TStrV_swigregister = _snap.TStrV_swigregister
TStrV_swigregister(TStrV)
def TStrV_SwapI(*args):
"""
TStrV_SwapI(TStr LVal, TStr RVal)
Parameters:
LVal: TVec< TStr,int >::TIter
RVal: TVec< TStr,int >::TIter
"""
return _snap.TStrV_SwapI(*args)
def TStrV_GetV(*args):
"""
GetV(TStr Val1) -> TStrV
Parameters:
Val1: TStr const &
GetV(TStr Val1, TStr Val2) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7, TStr Val8) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
Val8: TStr const &
TStrV_GetV(TStr Val1, TStr Val2, TStr Val3, TStr Val4, TStr Val5, TStr Val6, TStr Val7, TStr Val8,
TStr Val9) -> TStrV
Parameters:
Val1: TStr const &
Val2: TStr const &
Val3: TStr const &
Val4: TStr const &
Val5: TStr const &
Val6: TStr const &
Val7: TStr const &
Val8: TStr const &
Val9: TStr const &
"""
return _snap.TStrV_GetV(*args)
class TNGraphNodeI(object):
"""Proxy of C++ TNGraphNodeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNGraphNodeI self) -> TNGraphNodeI
__init__(TNGraphNodeI self, TNGraph::TNodeI const & NodeI) -> TNGraphNodeI
Parameters:
NodeI: TNGraph::TNodeI const &
"""
_snap.TNGraphNodeI_swiginit(self,_snap.new_TNGraphNodeI(*args))
def Next(self):
"""
Next(TNGraphNodeI self) -> TNGraphNodeI
Parameters:
self: TNGraphNodeI *
"""
return _snap.TNGraphNodeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNGraphNodeI self, TNGraphNodeI NodeI) -> bool
Parameters:
NodeI: TNGraphNodeI const &
"""
return _snap.TNGraphNodeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNGraphNodeI self, TNGraphNodeI NodeI) -> bool
Parameters:
NodeI: TNGraphNodeI const &
"""
return _snap.TNGraphNodeI___eq__(self, *args)
def GetId(self):
"""
GetId(TNGraphNodeI self) -> int
Parameters:
self: TNGraphNodeI const *
"""
return _snap.TNGraphNodeI_GetId(self)
def GetDeg(self):
"""
GetDeg(TNGraphNodeI self) -> int
Parameters:
self: TNGraphNodeI const *
"""
return _snap.TNGraphNodeI_GetDeg(self)
def GetInDeg(self):
"""
GetInDeg(TNGraphNodeI self) -> int
Parameters:
self: TNGraphNodeI const *
"""
return _snap.TNGraphNodeI_GetInDeg(self)
def GetOutDeg(self):
"""
GetOutDeg(TNGraphNodeI self) -> int
Parameters:
self: TNGraphNodeI const *
"""
return _snap.TNGraphNodeI_GetOutDeg(self)
def GetInNId(self, *args):
"""
GetInNId(TNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNGraphNodeI_GetInNId(self, *args)
def GetOutNId(self, *args):
"""
GetOutNId(TNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNGraphNodeI_GetOutNId(self, *args)
def GetNbrNId(self, *args):
"""
GetNbrNId(TNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNGraphNodeI_GetNbrNId(self, *args)
def IsInNId(self, *args):
"""
IsInNId(TNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNGraphNodeI_IsInNId(self, *args)
def IsOutNId(self, *args):
"""
IsOutNId(TNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNGraphNodeI_IsOutNId(self, *args)
def IsNbrNId(self, *args):
"""
IsNbrNId(TNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNGraphNodeI_IsNbrNId(self, *args)
__swig_destroy__ = _snap.delete_TNGraphNodeI
TNGraphNodeI.Next = new_instancemethod(_snap.TNGraphNodeI_Next,None,TNGraphNodeI)
TNGraphNodeI.__lt__ = new_instancemethod(_snap.TNGraphNodeI___lt__,None,TNGraphNodeI)
TNGraphNodeI.__eq__ = new_instancemethod(_snap.TNGraphNodeI___eq__,None,TNGraphNodeI)
TNGraphNodeI.GetId = new_instancemethod(_snap.TNGraphNodeI_GetId,None,TNGraphNodeI)
TNGraphNodeI.GetDeg = new_instancemethod(_snap.TNGraphNodeI_GetDeg,None,TNGraphNodeI)
TNGraphNodeI.GetInDeg = new_instancemethod(_snap.TNGraphNodeI_GetInDeg,None,TNGraphNodeI)
TNGraphNodeI.GetOutDeg = new_instancemethod(_snap.TNGraphNodeI_GetOutDeg,None,TNGraphNodeI)
TNGraphNodeI.GetInNId = new_instancemethod(_snap.TNGraphNodeI_GetInNId,None,TNGraphNodeI)
TNGraphNodeI.GetOutNId = new_instancemethod(_snap.TNGraphNodeI_GetOutNId,None,TNGraphNodeI)
TNGraphNodeI.GetNbrNId = new_instancemethod(_snap.TNGraphNodeI_GetNbrNId,None,TNGraphNodeI)
TNGraphNodeI.IsInNId = new_instancemethod(_snap.TNGraphNodeI_IsInNId,None,TNGraphNodeI)
TNGraphNodeI.IsOutNId = new_instancemethod(_snap.TNGraphNodeI_IsOutNId,None,TNGraphNodeI)
TNGraphNodeI.IsNbrNId = new_instancemethod(_snap.TNGraphNodeI_IsNbrNId,None,TNGraphNodeI)
TNGraphNodeI_swigregister = _snap.TNGraphNodeI_swigregister
TNGraphNodeI_swigregister(TNGraphNodeI)
class TNGraphEdgeI(object):
"""Proxy of C++ TNGraphEdgeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNGraphEdgeI self) -> TNGraphEdgeI
__init__(TNGraphEdgeI self, TNGraph::TEdgeI const & EdgeI) -> TNGraphEdgeI
Parameters:
EdgeI: TNGraph::TEdgeI const &
"""
_snap.TNGraphEdgeI_swiginit(self,_snap.new_TNGraphEdgeI(*args))
def Next(self):
"""
Next(TNGraphEdgeI self) -> TNGraphEdgeI
Parameters:
self: TNGraphEdgeI *
"""
return _snap.TNGraphEdgeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNGraphEdgeI self, TNGraphEdgeI EdgeI) -> bool
Parameters:
EdgeI: TNGraphEdgeI const &
"""
return _snap.TNGraphEdgeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNGraphEdgeI self, TNGraphEdgeI EdgeI) -> bool
Parameters:
EdgeI: TNGraphEdgeI const &
"""
return _snap.TNGraphEdgeI___eq__(self, *args)
def GetId(self):
"""
GetId(TNGraphEdgeI self) -> int
Parameters:
self: TNGraphEdgeI const *
"""
return _snap.TNGraphEdgeI_GetId(self)
def GetSrcNId(self):
"""
GetSrcNId(TNGraphEdgeI self) -> int
Parameters:
self: TNGraphEdgeI const *
"""
return _snap.TNGraphEdgeI_GetSrcNId(self)
def GetDstNId(self):
"""
GetDstNId(TNGraphEdgeI self) -> int
Parameters:
self: TNGraphEdgeI const *
"""
return _snap.TNGraphEdgeI_GetDstNId(self)
__swig_destroy__ = _snap.delete_TNGraphEdgeI
TNGraphEdgeI.Next = new_instancemethod(_snap.TNGraphEdgeI_Next,None,TNGraphEdgeI)
TNGraphEdgeI.__lt__ = new_instancemethod(_snap.TNGraphEdgeI___lt__,None,TNGraphEdgeI)
TNGraphEdgeI.__eq__ = new_instancemethod(_snap.TNGraphEdgeI___eq__,None,TNGraphEdgeI)
TNGraphEdgeI.GetId = new_instancemethod(_snap.TNGraphEdgeI_GetId,None,TNGraphEdgeI)
TNGraphEdgeI.GetSrcNId = new_instancemethod(_snap.TNGraphEdgeI_GetSrcNId,None,TNGraphEdgeI)
TNGraphEdgeI.GetDstNId = new_instancemethod(_snap.TNGraphEdgeI_GetDstNId,None,TNGraphEdgeI)
TNGraphEdgeI_swigregister = _snap.TNGraphEdgeI_swigregister
TNGraphEdgeI_swigregister(TNGraphEdgeI)
class TUNGraphNodeI(object):
"""Proxy of C++ TUNGraphNodeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TUNGraphNodeI self) -> TUNGraphNodeI
__init__(TUNGraphNodeI self, TUNGraph::TNodeI const & NodeI) -> TUNGraphNodeI
Parameters:
NodeI: TUNGraph::TNodeI const &
"""
_snap.TUNGraphNodeI_swiginit(self,_snap.new_TUNGraphNodeI(*args))
def Next(self):
"""
Next(TUNGraphNodeI self) -> TUNGraphNodeI
Parameters:
self: TUNGraphNodeI *
"""
return _snap.TUNGraphNodeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TUNGraphNodeI self, TUNGraphNodeI NodeI) -> bool
Parameters:
NodeI: TUNGraphNodeI const &
"""
return _snap.TUNGraphNodeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TUNGraphNodeI self, TUNGraphNodeI NodeI) -> bool
Parameters:
NodeI: TUNGraphNodeI const &
"""
return _snap.TUNGraphNodeI___eq__(self, *args)
def GetId(self):
"""
GetId(TUNGraphNodeI self) -> int
Parameters:
self: TUNGraphNodeI const *
"""
return _snap.TUNGraphNodeI_GetId(self)
def GetDeg(self):
"""
GetDeg(TUNGraphNodeI self) -> int
Parameters:
self: TUNGraphNodeI const *
"""
return _snap.TUNGraphNodeI_GetDeg(self)
def GetInDeg(self):
"""
GetInDeg(TUNGraphNodeI self) -> int
Parameters:
self: TUNGraphNodeI const *
"""
return _snap.TUNGraphNodeI_GetInDeg(self)
def GetOutDeg(self):
"""
GetOutDeg(TUNGraphNodeI self) -> int
Parameters:
self: TUNGraphNodeI const *
"""
return _snap.TUNGraphNodeI_GetOutDeg(self)
def GetInNId(self, *args):
"""
GetInNId(TUNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TUNGraphNodeI_GetInNId(self, *args)
def GetOutNId(self, *args):
"""
GetOutNId(TUNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TUNGraphNodeI_GetOutNId(self, *args)
def GetNbrNId(self, *args):
"""
GetNbrNId(TUNGraphNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TUNGraphNodeI_GetNbrNId(self, *args)
def IsInNId(self, *args):
"""
IsInNId(TUNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraphNodeI_IsInNId(self, *args)
def IsOutNId(self, *args):
"""
IsOutNId(TUNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraphNodeI_IsOutNId(self, *args)
def IsNbrNId(self, *args):
"""
IsNbrNId(TUNGraphNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TUNGraphNodeI_IsNbrNId(self, *args)
__swig_destroy__ = _snap.delete_TUNGraphNodeI
TUNGraphNodeI.Next = new_instancemethod(_snap.TUNGraphNodeI_Next,None,TUNGraphNodeI)
TUNGraphNodeI.__lt__ = new_instancemethod(_snap.TUNGraphNodeI___lt__,None,TUNGraphNodeI)
TUNGraphNodeI.__eq__ = new_instancemethod(_snap.TUNGraphNodeI___eq__,None,TUNGraphNodeI)
TUNGraphNodeI.GetId = new_instancemethod(_snap.TUNGraphNodeI_GetId,None,TUNGraphNodeI)
TUNGraphNodeI.GetDeg = new_instancemethod(_snap.TUNGraphNodeI_GetDeg,None,TUNGraphNodeI)
TUNGraphNodeI.GetInDeg = new_instancemethod(_snap.TUNGraphNodeI_GetInDeg,None,TUNGraphNodeI)
TUNGraphNodeI.GetOutDeg = new_instancemethod(_snap.TUNGraphNodeI_GetOutDeg,None,TUNGraphNodeI)
TUNGraphNodeI.GetInNId = new_instancemethod(_snap.TUNGraphNodeI_GetInNId,None,TUNGraphNodeI)
TUNGraphNodeI.GetOutNId = new_instancemethod(_snap.TUNGraphNodeI_GetOutNId,None,TUNGraphNodeI)
TUNGraphNodeI.GetNbrNId = new_instancemethod(_snap.TUNGraphNodeI_GetNbrNId,None,TUNGraphNodeI)
TUNGraphNodeI.IsInNId = new_instancemethod(_snap.TUNGraphNodeI_IsInNId,None,TUNGraphNodeI)
TUNGraphNodeI.IsOutNId = new_instancemethod(_snap.TUNGraphNodeI_IsOutNId,None,TUNGraphNodeI)
TUNGraphNodeI.IsNbrNId = new_instancemethod(_snap.TUNGraphNodeI_IsNbrNId,None,TUNGraphNodeI)
TUNGraphNodeI_swigregister = _snap.TUNGraphNodeI_swigregister
TUNGraphNodeI_swigregister(TUNGraphNodeI)
class TUNGraphEdgeI(object):
"""Proxy of C++ TUNGraphEdgeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TUNGraphEdgeI self) -> TUNGraphEdgeI
__init__(TUNGraphEdgeI self, TUNGraph::TEdgeI const & EdgeI) -> TUNGraphEdgeI
Parameters:
EdgeI: TUNGraph::TEdgeI const &
"""
_snap.TUNGraphEdgeI_swiginit(self,_snap.new_TUNGraphEdgeI(*args))
def Next(self):
"""
Next(TUNGraphEdgeI self) -> TUNGraphEdgeI
Parameters:
self: TUNGraphEdgeI *
"""
return _snap.TUNGraphEdgeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TUNGraphEdgeI self, TUNGraphEdgeI EdgeI) -> bool
Parameters:
EdgeI: TUNGraphEdgeI const &
"""
return _snap.TUNGraphEdgeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TUNGraphEdgeI self, TUNGraphEdgeI EdgeI) -> bool
Parameters:
EdgeI: TUNGraphEdgeI const &
"""
return _snap.TUNGraphEdgeI___eq__(self, *args)
def GetId(self):
"""
GetId(TUNGraphEdgeI self) -> int
Parameters:
self: TUNGraphEdgeI const *
"""
return _snap.TUNGraphEdgeI_GetId(self)
def GetSrcNId(self):
"""
GetSrcNId(TUNGraphEdgeI self) -> int
Parameters:
self: TUNGraphEdgeI const *
"""
return _snap.TUNGraphEdgeI_GetSrcNId(self)
def GetDstNId(self):
"""
GetDstNId(TUNGraphEdgeI self) -> int
Parameters:
self: TUNGraphEdgeI const *
"""
return _snap.TUNGraphEdgeI_GetDstNId(self)
__swig_destroy__ = _snap.delete_TUNGraphEdgeI
TUNGraphEdgeI.Next = new_instancemethod(_snap.TUNGraphEdgeI_Next,None,TUNGraphEdgeI)
TUNGraphEdgeI.__lt__ = new_instancemethod(_snap.TUNGraphEdgeI___lt__,None,TUNGraphEdgeI)
TUNGraphEdgeI.__eq__ = new_instancemethod(_snap.TUNGraphEdgeI___eq__,None,TUNGraphEdgeI)
TUNGraphEdgeI.GetId = new_instancemethod(_snap.TUNGraphEdgeI_GetId,None,TUNGraphEdgeI)
TUNGraphEdgeI.GetSrcNId = new_instancemethod(_snap.TUNGraphEdgeI_GetSrcNId,None,TUNGraphEdgeI)
TUNGraphEdgeI.GetDstNId = new_instancemethod(_snap.TUNGraphEdgeI_GetDstNId,None,TUNGraphEdgeI)
TUNGraphEdgeI_swigregister = _snap.TUNGraphEdgeI_swigregister
TUNGraphEdgeI_swigregister(TUNGraphEdgeI)
class TNEANetNodeI(object):
"""Proxy of C++ TNEANetNodeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetNodeI self) -> TNEANetNodeI
__init__(TNEANetNodeI self, TNEANet::TNodeI const & NodeI) -> TNEANetNodeI
Parameters:
NodeI: TNEANet::TNodeI const &
"""
_snap.TNEANetNodeI_swiginit(self,_snap.new_TNEANetNodeI(*args))
def Next(self):
"""
Next(TNEANetNodeI self) -> TNEANetNodeI
Parameters:
self: TNEANetNodeI *
"""
return _snap.TNEANetNodeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetNodeI self, TNEANetNodeI NodeI) -> bool
Parameters:
NodeI: TNEANetNodeI const &
"""
return _snap.TNEANetNodeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetNodeI self, TNEANetNodeI NodeI) -> bool
Parameters:
NodeI: TNEANetNodeI const &
"""
return _snap.TNEANetNodeI___eq__(self, *args)
def GetId(self):
"""
GetId(TNEANetNodeI self) -> int
Parameters:
self: TNEANetNodeI const *
"""
return _snap.TNEANetNodeI_GetId(self)
def GetDeg(self):
"""
GetDeg(TNEANetNodeI self) -> int
Parameters:
self: TNEANetNodeI const *
"""
return _snap.TNEANetNodeI_GetDeg(self)
def GetInDeg(self):
"""
GetInDeg(TNEANetNodeI self) -> int
Parameters:
self: TNEANetNodeI const *
"""
return _snap.TNEANetNodeI_GetInDeg(self)
def GetOutDeg(self):
"""
GetOutDeg(TNEANetNodeI self) -> int
Parameters:
self: TNEANetNodeI const *
"""
return _snap.TNEANetNodeI_GetOutDeg(self)
def GetInNId(self, *args):
"""
GetInNId(TNEANetNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNEANetNodeI_GetInNId(self, *args)
def GetOutNId(self, *args):
"""
GetOutNId(TNEANetNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNEANetNodeI_GetOutNId(self, *args)
def GetNbrNId(self, *args):
"""
GetNbrNId(TNEANetNodeI self, int const & NodeN) -> int
Parameters:
NodeN: int const &
"""
return _snap.TNEANetNodeI_GetNbrNId(self, *args)
def IsInNId(self, *args):
"""
IsInNId(TNEANetNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEANetNodeI_IsInNId(self, *args)
def IsOutNId(self, *args):
"""
IsOutNId(TNEANetNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEANetNodeI_IsOutNId(self, *args)
def IsNbrNId(self, *args):
"""
IsNbrNId(TNEANetNodeI self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEANetNodeI_IsNbrNId(self, *args)
__swig_destroy__ = _snap.delete_TNEANetNodeI
TNEANetNodeI.Next = new_instancemethod(_snap.TNEANetNodeI_Next,None,TNEANetNodeI)
TNEANetNodeI.__lt__ = new_instancemethod(_snap.TNEANetNodeI___lt__,None,TNEANetNodeI)
TNEANetNodeI.__eq__ = new_instancemethod(_snap.TNEANetNodeI___eq__,None,TNEANetNodeI)
TNEANetNodeI.GetId = new_instancemethod(_snap.TNEANetNodeI_GetId,None,TNEANetNodeI)
TNEANetNodeI.GetDeg = new_instancemethod(_snap.TNEANetNodeI_GetDeg,None,TNEANetNodeI)
TNEANetNodeI.GetInDeg = new_instancemethod(_snap.TNEANetNodeI_GetInDeg,None,TNEANetNodeI)
TNEANetNodeI.GetOutDeg = new_instancemethod(_snap.TNEANetNodeI_GetOutDeg,None,TNEANetNodeI)
TNEANetNodeI.GetInNId = new_instancemethod(_snap.TNEANetNodeI_GetInNId,None,TNEANetNodeI)
TNEANetNodeI.GetOutNId = new_instancemethod(_snap.TNEANetNodeI_GetOutNId,None,TNEANetNodeI)
TNEANetNodeI.GetNbrNId = new_instancemethod(_snap.TNEANetNodeI_GetNbrNId,None,TNEANetNodeI)
TNEANetNodeI.IsInNId = new_instancemethod(_snap.TNEANetNodeI_IsInNId,None,TNEANetNodeI)
TNEANetNodeI.IsOutNId = new_instancemethod(_snap.TNEANetNodeI_IsOutNId,None,TNEANetNodeI)
TNEANetNodeI.IsNbrNId = new_instancemethod(_snap.TNEANetNodeI_IsNbrNId,None,TNEANetNodeI)
TNEANetNodeI_swigregister = _snap.TNEANetNodeI_swigregister
TNEANetNodeI_swigregister(TNEANetNodeI)
class TNEANetEdgeI(object):
"""Proxy of C++ TNEANetEdgeI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetEdgeI self) -> TNEANetEdgeI
__init__(TNEANetEdgeI self, TNEANet::TEdgeI const & EdgeI) -> TNEANetEdgeI
Parameters:
EdgeI: TNEANet::TEdgeI const &
"""
_snap.TNEANetEdgeI_swiginit(self,_snap.new_TNEANetEdgeI(*args))
def Next(self):
"""
Next(TNEANetEdgeI self) -> TNEANetEdgeI
Parameters:
self: TNEANetEdgeI *
"""
return _snap.TNEANetEdgeI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetEdgeI self, TNEANetEdgeI EdgeI) -> bool
Parameters:
EdgeI: TNEANetEdgeI const &
"""
return _snap.TNEANetEdgeI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetEdgeI self, TNEANetEdgeI EdgeI) -> bool
Parameters:
EdgeI: TNEANetEdgeI const &
"""
return _snap.TNEANetEdgeI___eq__(self, *args)
def GetId(self):
"""
GetId(TNEANetEdgeI self) -> int
Parameters:
self: TNEANetEdgeI const *
"""
return _snap.TNEANetEdgeI_GetId(self)
def GetSrcNId(self):
"""
GetSrcNId(TNEANetEdgeI self) -> int
Parameters:
self: TNEANetEdgeI const *
"""
return _snap.TNEANetEdgeI_GetSrcNId(self)
def GetDstNId(self):
"""
GetDstNId(TNEANetEdgeI self) -> int
Parameters:
self: TNEANetEdgeI const *
"""
return _snap.TNEANetEdgeI_GetDstNId(self)
__swig_destroy__ = _snap.delete_TNEANetEdgeI
TNEANetEdgeI.Next = new_instancemethod(_snap.TNEANetEdgeI_Next,None,TNEANetEdgeI)
TNEANetEdgeI.__lt__ = new_instancemethod(_snap.TNEANetEdgeI___lt__,None,TNEANetEdgeI)
TNEANetEdgeI.__eq__ = new_instancemethod(_snap.TNEANetEdgeI___eq__,None,TNEANetEdgeI)
TNEANetEdgeI.GetId = new_instancemethod(_snap.TNEANetEdgeI_GetId,None,TNEANetEdgeI)
TNEANetEdgeI.GetSrcNId = new_instancemethod(_snap.TNEANetEdgeI_GetSrcNId,None,TNEANetEdgeI)
TNEANetEdgeI.GetDstNId = new_instancemethod(_snap.TNEANetEdgeI_GetDstNId,None,TNEANetEdgeI)
TNEANetEdgeI_swigregister = _snap.TNEANetEdgeI_swigregister
TNEANetEdgeI_swigregister(TNEANetEdgeI)
class TNEANetAIntI(object):
"""Proxy of C++ TNEANetAIntI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetAIntI self) -> TNEANetAIntI
__init__(TNEANetAIntI self, TIntVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAIntI
Parameters:
HIter: TIntVecIter const &
attribute: TStr
isEdgeIter: bool
GraphPt: TNEANet const *
__init__(TNEANetAIntI self, TNEANet::TAIntI const & I) -> TNEANetAIntI
Parameters:
I: TNEANet::TAIntI const &
"""
_snap.TNEANetAIntI_swiginit(self,_snap.new_TNEANetAIntI(*args))
def Next(self):
"""
Next(TNEANetAIntI self) -> TNEANetAIntI
Parameters:
self: TNEANetAIntI *
"""
return _snap.TNEANetAIntI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetAIntI self, TNEANetAIntI I) -> bool
Parameters:
I: TNEANetAIntI const &
"""
return _snap.TNEANetAIntI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetAIntI self, TNEANetAIntI I) -> bool
Parameters:
I: TNEANetAIntI const &
"""
return _snap.TNEANetAIntI___eq__(self, *args)
def GetDat(self):
"""
GetDat(TNEANetAIntI self) -> int
Parameters:
self: TNEANetAIntI const *
"""
return _snap.TNEANetAIntI_GetDat(self)
def IsDeleted(self):
"""
IsDeleted(TNEANetAIntI self) -> bool
Parameters:
self: TNEANetAIntI const *
"""
return _snap.TNEANetAIntI_IsDeleted(self)
__swig_destroy__ = _snap.delete_TNEANetAIntI
TNEANetAIntI.Next = new_instancemethod(_snap.TNEANetAIntI_Next,None,TNEANetAIntI)
TNEANetAIntI.__lt__ = new_instancemethod(_snap.TNEANetAIntI___lt__,None,TNEANetAIntI)
TNEANetAIntI.__eq__ = new_instancemethod(_snap.TNEANetAIntI___eq__,None,TNEANetAIntI)
TNEANetAIntI.GetDat = new_instancemethod(_snap.TNEANetAIntI_GetDat,None,TNEANetAIntI)
TNEANetAIntI.IsDeleted = new_instancemethod(_snap.TNEANetAIntI_IsDeleted,None,TNEANetAIntI)
TNEANetAIntI_swigregister = _snap.TNEANetAIntI_swigregister
TNEANetAIntI_swigregister(TNEANetAIntI)
class TNEANetAStrI(object):
"""Proxy of C++ TNEANetAStrI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetAStrI self) -> TNEANetAStrI
__init__(TNEANetAStrI self, TStrVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAStrI
Parameters:
HIter: TStrVecIter const &
attribute: TStr
isEdgeIter: bool
GraphPt: TNEANet const *
__init__(TNEANetAStrI self, TNEANet::TAStrI const & I) -> TNEANetAStrI
Parameters:
I: TNEANet::TAStrI const &
"""
_snap.TNEANetAStrI_swiginit(self,_snap.new_TNEANetAStrI(*args))
def Next(self):
"""
Next(TNEANetAStrI self) -> TNEANetAStrI
Parameters:
self: TNEANetAStrI *
"""
return _snap.TNEANetAStrI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetAStrI self, TNEANetAStrI I) -> bool
Parameters:
I: TNEANetAStrI const &
"""
return _snap.TNEANetAStrI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetAStrI self, TNEANetAStrI I) -> bool
Parameters:
I: TNEANetAStrI const &
"""
return _snap.TNEANetAStrI___eq__(self, *args)
def GetDat(self):
"""
GetDat(TNEANetAStrI self) -> char *
Parameters:
self: TNEANetAStrI const *
"""
return _snap.TNEANetAStrI_GetDat(self)
def IsDeleted(self):
"""
IsDeleted(TNEANetAStrI self) -> bool
Parameters:
self: TNEANetAStrI const *
"""
return _snap.TNEANetAStrI_IsDeleted(self)
__swig_destroy__ = _snap.delete_TNEANetAStrI
TNEANetAStrI.Next = new_instancemethod(_snap.TNEANetAStrI_Next,None,TNEANetAStrI)
TNEANetAStrI.__lt__ = new_instancemethod(_snap.TNEANetAStrI___lt__,None,TNEANetAStrI)
TNEANetAStrI.__eq__ = new_instancemethod(_snap.TNEANetAStrI___eq__,None,TNEANetAStrI)
TNEANetAStrI.GetDat = new_instancemethod(_snap.TNEANetAStrI_GetDat,None,TNEANetAStrI)
TNEANetAStrI.IsDeleted = new_instancemethod(_snap.TNEANetAStrI_IsDeleted,None,TNEANetAStrI)
TNEANetAStrI_swigregister = _snap.TNEANetAStrI_swigregister
TNEANetAStrI_swigregister(TNEANetAStrI)
class TNEANetAFltI(object):
"""Proxy of C++ TNEANetAFltI class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANetAFltI self) -> TNEANetAFltI
__init__(TNEANetAFltI self, TFltVecIter const & HIter, TStr attribute, bool isEdgeIter, TNEANet GraphPt) -> TNEANetAFltI
Parameters:
HIter: TFltVecIter const &
attribute: TStr
isEdgeIter: bool
GraphPt: TNEANet const *
__init__(TNEANetAFltI self, TNEANet::TAFltI const & I) -> TNEANetAFltI
Parameters:
I: TNEANet::TAFltI const &
"""
_snap.TNEANetAFltI_swiginit(self,_snap.new_TNEANetAFltI(*args))
def Next(self):
"""
Next(TNEANetAFltI self) -> TNEANetAFltI
Parameters:
self: TNEANetAFltI *
"""
return _snap.TNEANetAFltI_Next(self)
def __lt__(self, *args):
"""
__lt__(TNEANetAFltI self, TNEANetAFltI I) -> bool
Parameters:
I: TNEANetAFltI const &
"""
return _snap.TNEANetAFltI___lt__(self, *args)
def __eq__(self, *args):
"""
__eq__(TNEANetAFltI self, TNEANetAFltI I) -> bool
Parameters:
I: TNEANetAFltI const &
"""
return _snap.TNEANetAFltI___eq__(self, *args)
def GetDat(self):
"""
GetDat(TNEANetAFltI self) -> double
Parameters:
self: TNEANetAFltI const *
"""
return _snap.TNEANetAFltI_GetDat(self)
def IsDeleted(self):
"""
IsDeleted(TNEANetAFltI self) -> bool
Parameters:
self: TNEANetAFltI const *
"""
return _snap.TNEANetAFltI_IsDeleted(self)
__swig_destroy__ = _snap.delete_TNEANetAFltI
TNEANetAFltI.Next = new_instancemethod(_snap.TNEANetAFltI_Next,None,TNEANetAFltI)
TNEANetAFltI.__lt__ = new_instancemethod(_snap.TNEANetAFltI___lt__,None,TNEANetAFltI)
TNEANetAFltI.__eq__ = new_instancemethod(_snap.TNEANetAFltI___eq__,None,TNEANetAFltI)
TNEANetAFltI.GetDat = new_instancemethod(_snap.TNEANetAFltI_GetDat,None,TNEANetAFltI)
TNEANetAFltI.IsDeleted = new_instancemethod(_snap.TNEANetAFltI_IsDeleted,None,TNEANetAFltI)
TNEANetAFltI_swigregister = _snap.TNEANetAFltI_swigregister
TNEANetAFltI_swigregister(TNEANetAFltI)
def TPrGraph(*args):
"""
TPrGraph(PUNGraph G) -> TUNGraph
Parameters:
G: PUNGraph
"""
return _snap.TPrGraph(*args)
def accept_array(*args):
"""
accept_array(int [] array) -> int
Parameters:
array: int []
"""
return _snap.accept_array(*args)
def print_array(*args):
"""
print_array(int * x, int length)
Parameters:
x: int *
length: int
"""
return _snap.print_array(*args)
def PyTFltV(*args):
"""
PyTFltV(double [10] x) -> TFltV
Parameters:
x: double [10]
"""
return _snap.PyTFltV(*args)
def PyToTIntV(*args):
"""
PyToTIntV(int * array) -> TIntV
Parameters:
array: int *
"""
return _snap.PyToTIntV(*args)
def count(*args):
"""
count(char * str, char c) -> int
Parameters:
str: char *
c: char
"""
return _snap.count(*args)
def TIntVToPy(*args):
"""
TIntVToPy(TIntV originalList)
Parameters:
originalList: TIntV
"""
return _snap.TIntVToPy(*args)
class TNEANet(object):
"""Proxy of C++ TNEANet class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(TNEANet self) -> TNEANet
__init__(TNEANet self, int const & Nodes, int const & Edges) -> TNEANet
Parameters:
Nodes: int const &
Edges: int const &
__init__(TNEANet self, TNEANet Graph) -> TNEANet
Parameters:
Graph: TNEANet const &
__init__(TNEANet self, TSIn SIn) -> TNEANet
Parameters:
SIn: TSIn &
"""
_snap.TNEANet_swiginit(self,_snap.new_TNEANet(*args))
def Save(self, *args):
"""
Save(TNEANet self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.TNEANet_Save(self, *args)
def New(*args):
"""
New() -> PNEANet
New(int const & Nodes, int const & Edges) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEANet_New(*args)
New = staticmethod(New)
def Load(*args):
"""
Load(TSIn SIn) -> PNEANet
Parameters:
SIn: TSIn &
"""
return _snap.TNEANet_Load(*args)
Load = staticmethod(Load)
def HasFlag(self, *args):
"""
HasFlag(TNEANet self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.TNEANet_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(TNEANet self) -> int
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(TNEANet self, int NId=-1) -> int
Parameters:
NId: int
AddNode(TNEANet self) -> int
AddNode(TNEANet self, TNEANet::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
"""
return _snap.TNEANet_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(TNEANet self, int const & NId)
Parameters:
NId: int const &
DelNode(TNEANet self, TNEANet::TNode const & NodeI)
Parameters:
NodeI: TNEANet::TNode const &
"""
return _snap.TNEANet_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(TNEANet self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.TNEANet_IsNode(self, *args)
def GetNI(self, *args):
"""
GetNI(TNEANet self, int const & NId) -> TNEANet::TNodeI
Parameters:
NId: int const &
"""
return _snap.TNEANet_GetNI(self, *args)
def GetNAIntI(self, *args):
"""
GetNAIntI(TNEANet self, TStr attr, int const & NId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.TNEANet_GetNAIntI(self, *args)
def GetNAStrI(self, *args):
"""
GetNAStrI(TNEANet self, TStr attr, int const & NId) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.TNEANet_GetNAStrI(self, *args)
def GetNAFltI(self, *args):
"""
GetNAFltI(TNEANet self, TStr attr, int const & NId) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.TNEANet_GetNAFltI(self, *args)
def AttrNameNI(self, *args):
"""
AttrNameNI(TNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
AttrNameNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_AttrNameNI(self, *args)
def AttrValueNI(self, *args):
"""
AttrValueNI(TNEANet self, TInt NId, TStrV Values)
Parameters:
NId: TInt const &
Values: TStrV &
AttrValueNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.TNEANet_AttrValueNI(self, *args)
def IntAttrNameNI(self, *args):
"""
IntAttrNameNI(TNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
IntAttrNameNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_IntAttrNameNI(self, *args)
def IntAttrValueNI(self, *args):
"""
IntAttrValueNI(TNEANet self, TInt NId, TIntV Values)
Parameters:
NId: TInt const &
Values: TIntV &
IntAttrValueNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TIntV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.TNEANet_IntAttrValueNI(self, *args)
def StrAttrNameNI(self, *args):
"""
StrAttrNameNI(TNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
StrAttrNameNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_StrAttrNameNI(self, *args)
def StrAttrValueNI(self, *args):
"""
StrAttrValueNI(TNEANet self, TInt NId, TStrV Values)
Parameters:
NId: TInt const &
Values: TStrV &
StrAttrValueNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.TNEANet_StrAttrValueNI(self, *args)
def FltAttrNameNI(self, *args):
"""
FltAttrNameNI(TNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
FltAttrNameNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_FltAttrNameNI(self, *args)
def FltAttrValueNI(self, *args):
"""
FltAttrValueNI(TNEANet self, TInt NId, TFltV & Values)
Parameters:
NId: TInt const &
Values: TFltV &
FltAttrValueNI(TNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TFltV & Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.TNEANet_FltAttrValueNI(self, *args)
def AttrNameEI(self, *args):
"""
AttrNameEI(TNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
AttrNameEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_AttrNameEI(self, *args)
def AttrValueEI(self, *args):
"""
AttrValueEI(TNEANet self, TInt EId, TStrV Values)
Parameters:
EId: TInt const &
Values: TStrV &
AttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.TNEANet_AttrValueEI(self, *args)
def IntAttrNameEI(self, *args):
"""
IntAttrNameEI(TNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
IntAttrNameEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_IntAttrNameEI(self, *args)
def IntAttrValueEI(self, *args):
"""
IntAttrValueEI(TNEANet self, TInt EId, TIntV Values)
Parameters:
EId: TInt const &
Values: TIntV &
IntAttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TIntV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.TNEANet_IntAttrValueEI(self, *args)
def StrAttrNameEI(self, *args):
"""
StrAttrNameEI(TNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
StrAttrNameEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_StrAttrNameEI(self, *args)
def StrAttrValueEI(self, *args):
"""
StrAttrValueEI(TNEANet self, TInt EId, TStrV Values)
Parameters:
EId: TInt const &
Values: TStrV &
StrAttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.TNEANet_StrAttrValueEI(self, *args)
def FltAttrNameEI(self, *args):
"""
FltAttrNameEI(TNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
FltAttrNameEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.TNEANet_FltAttrNameEI(self, *args)
def FltAttrValueEI(self, *args):
"""
FltAttrValueEI(TNEANet self, TInt EId, TFltV & Values)
Parameters:
EId: TInt const &
Values: TFltV &
FltAttrValueEI(TNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TFltV & Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.TNEANet_FltAttrValueEI(self, *args)
def GetEAIntI(self, *args):
"""
GetEAIntI(TNEANet self, TStr attr, int const & EId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.TNEANet_GetEAIntI(self, *args)
def GetEAStrI(self, *args):
"""
GetEAStrI(TNEANet self, TStr attr, int const & EId) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.TNEANet_GetEAStrI(self, *args)
def GetEAFltI(self, *args):
"""
GetEAFltI(TNEANet self, TStr attr, int const & EId) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.TNEANet_GetEAFltI(self, *args)
def GetMxNId(self):
"""
GetMxNId(TNEANet self) -> int
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(TNEANet self) -> int
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(TNEANet self, int const & SrcNId, int const & DstNId, int EId=-1) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int
AddEdge(TNEANet self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(TNEANet self, TNEANet::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TNEANet::TEdgeI const &
"""
return _snap.TNEANet_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(TNEANet self, int const & EId)
Parameters:
EId: int const &
DelEdge(TNEANet self, int const & SrcNId, int const & DstNId, bool const & IsDir=True)
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
DelEdge(TNEANet self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEANet_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(TNEANet self, int const & EId) -> bool
Parameters:
EId: int const &
IsEdge(TNEANet self, int const & SrcNId, int const & DstNId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
IsEdge(TNEANet self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsEdge(TNEANet self, int const & SrcNId, int const & DstNId, int & EId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
IsDir: bool const &
IsEdge(TNEANet self, int const & SrcNId, int const & DstNId, int & EId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
"""
return _snap.TNEANet_IsEdge(self, *args)
def GetEId(self, *args):
"""
GetEId(TNEANet self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEANet_GetEId(self, *args)
def GetEI(self, *args):
"""
GetEI(TNEANet self, int const & SrcNId, int const & DstNId) -> TNEANet::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.TNEANet_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(TNEANet self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(TNEANet self) -> int
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(TNEANet self, TRnd Rnd=Rnd) -> TNEANet::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(TNEANet self) -> TNEANet::TNodeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndNI(self, *args)
def GetRndEId(self, *args):
"""
GetRndEId(TNEANet self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndEId(TNEANet self) -> int
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndEId(self, *args)
def GetRndEI(self, *args):
"""
GetRndEI(TNEANet self, TRnd Rnd=Rnd) -> TNEANet::TEdgeI
Parameters:
Rnd: TRnd &
GetRndEI(TNEANet self) -> TNEANet::TEdgeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_GetRndEI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(TNEANet self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.TNEANet_GetNIdV(self, *args)
def GetEIdV(self, *args):
"""
GetEIdV(TNEANet self, TIntV EIdV)
Parameters:
EIdV: TIntV &
"""
return _snap.TNEANet_GetEIdV(self, *args)
def Empty(self):
"""
Empty(TNEANet self) -> bool
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_Empty(self)
def Clr(self):
"""
Clr(TNEANet self)
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_Clr(self)
def Reserve(self, *args):
"""
Reserve(TNEANet self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEANet_Reserve(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(TNEANet self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(TNEANet self)
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(TNEANet self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(TNEANet self) -> bool
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(TNEANet self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(TNEANet self)
Parameters:
self: TNEANet const *
"""
return _snap.TNEANet_Dump(self, *args)
def AddIntAttrDatN(self, *args):
"""
AddIntAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TInt value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TInt const &
attr: TStr const &
AddIntAttrDatN(TNEANet self, int const & NId, TInt value, TStr attr) -> int
Parameters:
NId: int const &
value: TInt const &
attr: TStr const &
"""
return _snap.TNEANet_AddIntAttrDatN(self, *args)
def AddStrAttrDatN(self, *args):
"""
AddStrAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TStr const &
attr: TStr const &
AddStrAttrDatN(TNEANet self, int const & NId, TStr value, TStr attr) -> int
Parameters:
NId: int const &
value: TStr const &
attr: TStr const &
"""
return _snap.TNEANet_AddStrAttrDatN(self, *args)
def AddFltAttrDatN(self, *args):
"""
AddFltAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TFlt value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TFlt const &
attr: TStr const &
AddFltAttrDatN(TNEANet self, int const & NId, TFlt value, TStr attr) -> int
Parameters:
NId: int const &
value: TFlt const &
attr: TStr const &
"""
return _snap.TNEANet_AddFltAttrDatN(self, *args)
def AddIntAttrDatE(self, *args):
"""
AddIntAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TInt value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TInt const &
attr: TStr const &
AddIntAttrDatE(TNEANet self, int const & EId, TInt value, TStr attr) -> int
Parameters:
EId: int const &
value: TInt const &
attr: TStr const &
"""
return _snap.TNEANet_AddIntAttrDatE(self, *args)
def AddStrAttrDatE(self, *args):
"""
AddStrAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TStr const &
attr: TStr const &
AddStrAttrDatE(TNEANet self, int const & EId, TStr value, TStr attr) -> int
Parameters:
EId: int const &
value: TStr const &
attr: TStr const &
"""
return _snap.TNEANet_AddStrAttrDatE(self, *args)
def AddFltAttrDatE(self, *args):
"""
AddFltAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TFlt value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TFlt const &
attr: TStr const &
AddFltAttrDatE(TNEANet self, int const & EId, TFlt value, TStr attr) -> int
Parameters:
EId: int const &
value: TFlt const &
attr: TStr const &
"""
return _snap.TNEANet_AddFltAttrDatE(self, *args)
def GetIntAttrDatN(self, *args):
"""
GetIntAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TInt
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetIntAttrDatN(TNEANet self, int const & NId, TStr attr) -> TInt
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetIntAttrDatN(self, *args)
def GetStrAttrDatN(self, *args):
"""
GetStrAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TStr
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetStrAttrDatN(TNEANet self, int const & NId, TStr attr) -> TStr
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetStrAttrDatN(self, *args)
def GetFltAttrDatN(self, *args):
"""
GetFltAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TFlt
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetFltAttrDatN(TNEANet self, int const & NId, TStr attr) -> TFlt
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetFltAttrDatN(self, *args)
def GetIntAttrDatE(self, *args):
"""
GetIntAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TInt
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetIntAttrDatE(TNEANet self, int const & EId, TStr attr) -> TInt
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetIntAttrDatE(self, *args)
def GetStrAttrDatE(self, *args):
"""
GetStrAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TStr
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetStrAttrDatE(TNEANet self, int const & EId, TStr attr) -> TStr
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetStrAttrDatE(self, *args)
def GetFltAttrDatE(self, *args):
"""
GetFltAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TFlt
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetFltAttrDatE(TNEANet self, int const & EId, TStr attr) -> TFlt
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.TNEANet_GetFltAttrDatE(self, *args)
def DelAttrDatN(self, *args):
"""
DelAttrDatN(TNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
DelAttrDatN(TNEANet self, int const & NId, TStr attr) -> int
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.TNEANet_DelAttrDatN(self, *args)
def DelAttrDatE(self, *args):
"""
DelAttrDatE(TNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
DelAttrDatE(TNEANet self, int const & EId, TStr attr) -> int
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.TNEANet_DelAttrDatE(self, *args)
def AddIntAttrN(self, *args):
"""
AddIntAttrN(TNEANet self, TStr attr, TInt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TInt
AddIntAttrN(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddIntAttrN(self, *args)
def AddStrAttrN(self, *args):
"""
AddStrAttrN(TNEANet self, TStr attr, TStr defaultValue=TStr::GetNullStr()) -> int
Parameters:
attr: TStr const &
defaultValue: TStr
AddStrAttrN(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddStrAttrN(self, *args)
def AddFltAttrN(self, *args):
"""
AddFltAttrN(TNEANet self, TStr attr, TFlt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TFlt
AddFltAttrN(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddFltAttrN(self, *args)
def AddIntAttrE(self, *args):
"""
AddIntAttrE(TNEANet self, TStr attr, TInt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TInt
AddIntAttrE(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddIntAttrE(self, *args)
def AddStrAttrE(self, *args):
"""
AddStrAttrE(TNEANet self, TStr attr, TStr defaultValue=TStr::GetNullStr()) -> int
Parameters:
attr: TStr const &
defaultValue: TStr
AddStrAttrE(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddStrAttrE(self, *args)
def AddFltAttrE(self, *args):
"""
AddFltAttrE(TNEANet self, TStr attr, TFlt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TFlt
AddFltAttrE(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_AddFltAttrE(self, *args)
def DelAttrN(self, *args):
"""
DelAttrN(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_DelAttrN(self, *args)
def DelAttrE(self, *args):
"""
DelAttrE(TNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_DelAttrE(self, *args)
def NodeAttrIsDeleted(self, *args):
"""
NodeAttrIsDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_NodeAttrIsDeleted(self, *args)
def NodeAttrIsIntDeleted(self, *args):
"""
NodeAttrIsIntDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_NodeAttrIsIntDeleted(self, *args)
def NodeAttrIsStrDeleted(self, *args):
"""
NodeAttrIsStrDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_NodeAttrIsStrDeleted(self, *args)
def NodeAttrIsFltDeleted(self, *args):
"""
NodeAttrIsFltDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_NodeAttrIsFltDeleted(self, *args)
def EdgeAttrIsDeleted(self, *args):
"""
EdgeAttrIsDeleted(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_EdgeAttrIsDeleted(self, *args)
def EdgeAttrIsIntDeleted(self, *args):
"""
EdgeAttrIsIntDeleted(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_EdgeAttrIsIntDeleted(self, *args)
def EdgeAttrIsStrDeleted(self, *args):
"""
EdgeAttrIsStrDeleted(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_EdgeAttrIsStrDeleted(self, *args)
def EdgeAttrIsFltDeleted(self, *args):
"""
EdgeAttrIsFltDeleted(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_EdgeAttrIsFltDeleted(self, *args)
def GetNodeAttrValue(self, *args):
"""
GetNodeAttrValue(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> TStr
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_GetNodeAttrValue(self, *args)
def GetEdgeAttrValue(self, *args):
"""
GetEdgeAttrValue(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> TStr
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.TNEANet_GetEdgeAttrValue(self, *args)
def BegNI(self, *args):
"""
BegNI(TNEANet self) -> TNEANet::TNodeI
BegNI(TNEANet self) -> TNEANetNodeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_BegNI(self, *args)
def EndNI(self, *args):
"""
EndNI(TNEANet self) -> TNEANet::TNodeI
EndNI(TNEANet self) -> TNEANetNodeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_EndNI(self, *args)
def BegEI(self, *args):
"""
BegEI(TNEANet self) -> TNEANet::TEdgeI
BegEI(TNEANet self) -> TNEANetEdgeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_BegEI(self, *args)
def EndEI(self, *args):
"""
EndEI(TNEANet self) -> TNEANet::TEdgeI
EndEI(TNEANet self) -> TNEANetEdgeI
Parameters:
self: TNEANet *
"""
return _snap.TNEANet_EndEI(self, *args)
def BegNAIntI(self, *args):
"""
BegNAIntI(TNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
BegNAIntI(TNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegNAIntI(self, *args)
def EndNAIntI(self, *args):
"""
EndNAIntI(TNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EndNAIntI(TNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndNAIntI(self, *args)
def BegNAStrI(self, *args):
"""
BegNAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegNAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegNAStrI(self, *args)
def EndNAStrI(self, *args):
"""
EndNAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EndNAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndNAStrI(self, *args)
def BegNAFltI(self, *args):
"""
BegNAFltI(TNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
BegNAFltI(TNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegNAFltI(self, *args)
def EndNAFltI(self, *args):
"""
EndNAFltI(TNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EndNAFltI(TNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndNAFltI(self, *args)
def BegEAIntI(self, *args):
"""
BegEAIntI(TNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
BegEAIntI(TNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegEAIntI(self, *args)
def EndEAIntI(self, *args):
"""
EndEAIntI(TNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EndEAIntI(TNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndEAIntI(self, *args)
def BegEAStrI(self, *args):
"""
BegEAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegEAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegEAStrI(self, *args)
def EndEAStrI(self, *args):
"""
EndEAStrI(TNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EndEAStrI(TNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndEAStrI(self, *args)
def BegEAFltI(self, *args):
"""
BegEAFltI(TNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
BegEAFltI(TNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_BegEAFltI(self, *args)
def EndEAFltI(self, *args):
"""
EndEAFltI(TNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EndEAFltI(TNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.TNEANet_EndEAFltI(self, *args)
__swig_destroy__ = _snap.delete_TNEANet
TNEANet.Save = new_instancemethod(_snap.TNEANet_Save,None,TNEANet)
TNEANet.HasFlag = new_instancemethod(_snap.TNEANet_HasFlag,None,TNEANet)
TNEANet.GetNodes = new_instancemethod(_snap.TNEANet_GetNodes,None,TNEANet)
TNEANet.AddNode = new_instancemethod(_snap.TNEANet_AddNode,None,TNEANet)
TNEANet.DelNode = new_instancemethod(_snap.TNEANet_DelNode,None,TNEANet)
TNEANet.IsNode = new_instancemethod(_snap.TNEANet_IsNode,None,TNEANet)
TNEANet.GetNI = new_instancemethod(_snap.TNEANet_GetNI,None,TNEANet)
TNEANet.GetNAIntI = new_instancemethod(_snap.TNEANet_GetNAIntI,None,TNEANet)
TNEANet.GetNAStrI = new_instancemethod(_snap.TNEANet_GetNAStrI,None,TNEANet)
TNEANet.GetNAFltI = new_instancemethod(_snap.TNEANet_GetNAFltI,None,TNEANet)
TNEANet.AttrNameNI = new_instancemethod(_snap.TNEANet_AttrNameNI,None,TNEANet)
TNEANet.AttrValueNI = new_instancemethod(_snap.TNEANet_AttrValueNI,None,TNEANet)
TNEANet.IntAttrNameNI = new_instancemethod(_snap.TNEANet_IntAttrNameNI,None,TNEANet)
TNEANet.IntAttrValueNI = new_instancemethod(_snap.TNEANet_IntAttrValueNI,None,TNEANet)
TNEANet.StrAttrNameNI = new_instancemethod(_snap.TNEANet_StrAttrNameNI,None,TNEANet)
TNEANet.StrAttrValueNI = new_instancemethod(_snap.TNEANet_StrAttrValueNI,None,TNEANet)
TNEANet.FltAttrNameNI = new_instancemethod(_snap.TNEANet_FltAttrNameNI,None,TNEANet)
TNEANet.FltAttrValueNI = new_instancemethod(_snap.TNEANet_FltAttrValueNI,None,TNEANet)
TNEANet.AttrNameEI = new_instancemethod(_snap.TNEANet_AttrNameEI,None,TNEANet)
TNEANet.AttrValueEI = new_instancemethod(_snap.TNEANet_AttrValueEI,None,TNEANet)
TNEANet.IntAttrNameEI = new_instancemethod(_snap.TNEANet_IntAttrNameEI,None,TNEANet)
TNEANet.IntAttrValueEI = new_instancemethod(_snap.TNEANet_IntAttrValueEI,None,TNEANet)
TNEANet.StrAttrNameEI = new_instancemethod(_snap.TNEANet_StrAttrNameEI,None,TNEANet)
TNEANet.StrAttrValueEI = new_instancemethod(_snap.TNEANet_StrAttrValueEI,None,TNEANet)
TNEANet.FltAttrNameEI = new_instancemethod(_snap.TNEANet_FltAttrNameEI,None,TNEANet)
TNEANet.FltAttrValueEI = new_instancemethod(_snap.TNEANet_FltAttrValueEI,None,TNEANet)
TNEANet.GetEAIntI = new_instancemethod(_snap.TNEANet_GetEAIntI,None,TNEANet)
TNEANet.GetEAStrI = new_instancemethod(_snap.TNEANet_GetEAStrI,None,TNEANet)
TNEANet.GetEAFltI = new_instancemethod(_snap.TNEANet_GetEAFltI,None,TNEANet)
TNEANet.GetMxNId = new_instancemethod(_snap.TNEANet_GetMxNId,None,TNEANet)
TNEANet.GetEdges = new_instancemethod(_snap.TNEANet_GetEdges,None,TNEANet)
TNEANet.AddEdge = new_instancemethod(_snap.TNEANet_AddEdge,None,TNEANet)
TNEANet.DelEdge = new_instancemethod(_snap.TNEANet_DelEdge,None,TNEANet)
TNEANet.IsEdge = new_instancemethod(_snap.TNEANet_IsEdge,None,TNEANet)
TNEANet.GetEId = new_instancemethod(_snap.TNEANet_GetEId,None,TNEANet)
TNEANet.GetEI = new_instancemethod(_snap.TNEANet_GetEI,None,TNEANet)
TNEANet.GetRndNId = new_instancemethod(_snap.TNEANet_GetRndNId,None,TNEANet)
TNEANet.GetRndNI = new_instancemethod(_snap.TNEANet_GetRndNI,None,TNEANet)
TNEANet.GetRndEId = new_instancemethod(_snap.TNEANet_GetRndEId,None,TNEANet)
TNEANet.GetRndEI = new_instancemethod(_snap.TNEANet_GetRndEI,None,TNEANet)
TNEANet.GetNIdV = new_instancemethod(_snap.TNEANet_GetNIdV,None,TNEANet)
TNEANet.GetEIdV = new_instancemethod(_snap.TNEANet_GetEIdV,None,TNEANet)
TNEANet.Empty = new_instancemethod(_snap.TNEANet_Empty,None,TNEANet)
TNEANet.Clr = new_instancemethod(_snap.TNEANet_Clr,None,TNEANet)
TNEANet.Reserve = new_instancemethod(_snap.TNEANet_Reserve,None,TNEANet)
TNEANet.Defrag = new_instancemethod(_snap.TNEANet_Defrag,None,TNEANet)
TNEANet.IsOk = new_instancemethod(_snap.TNEANet_IsOk,None,TNEANet)
TNEANet.Dump = new_instancemethod(_snap.TNEANet_Dump,None,TNEANet)
TNEANet.AddIntAttrDatN = new_instancemethod(_snap.TNEANet_AddIntAttrDatN,None,TNEANet)
TNEANet.AddStrAttrDatN = new_instancemethod(_snap.TNEANet_AddStrAttrDatN,None,TNEANet)
TNEANet.AddFltAttrDatN = new_instancemethod(_snap.TNEANet_AddFltAttrDatN,None,TNEANet)
TNEANet.AddIntAttrDatE = new_instancemethod(_snap.TNEANet_AddIntAttrDatE,None,TNEANet)
TNEANet.AddStrAttrDatE = new_instancemethod(_snap.TNEANet_AddStrAttrDatE,None,TNEANet)
TNEANet.AddFltAttrDatE = new_instancemethod(_snap.TNEANet_AddFltAttrDatE,None,TNEANet)
TNEANet.GetIntAttrDatN = new_instancemethod(_snap.TNEANet_GetIntAttrDatN,None,TNEANet)
TNEANet.GetStrAttrDatN = new_instancemethod(_snap.TNEANet_GetStrAttrDatN,None,TNEANet)
TNEANet.GetFltAttrDatN = new_instancemethod(_snap.TNEANet_GetFltAttrDatN,None,TNEANet)
TNEANet.GetIntAttrDatE = new_instancemethod(_snap.TNEANet_GetIntAttrDatE,None,TNEANet)
TNEANet.GetStrAttrDatE = new_instancemethod(_snap.TNEANet_GetStrAttrDatE,None,TNEANet)
TNEANet.GetFltAttrDatE = new_instancemethod(_snap.TNEANet_GetFltAttrDatE,None,TNEANet)
TNEANet.DelAttrDatN = new_instancemethod(_snap.TNEANet_DelAttrDatN,None,TNEANet)
TNEANet.DelAttrDatE = new_instancemethod(_snap.TNEANet_DelAttrDatE,None,TNEANet)
TNEANet.AddIntAttrN = new_instancemethod(_snap.TNEANet_AddIntAttrN,None,TNEANet)
TNEANet.AddStrAttrN = new_instancemethod(_snap.TNEANet_AddStrAttrN,None,TNEANet)
TNEANet.AddFltAttrN = new_instancemethod(_snap.TNEANet_AddFltAttrN,None,TNEANet)
TNEANet.AddIntAttrE = new_instancemethod(_snap.TNEANet_AddIntAttrE,None,TNEANet)
TNEANet.AddStrAttrE = new_instancemethod(_snap.TNEANet_AddStrAttrE,None,TNEANet)
TNEANet.AddFltAttrE = new_instancemethod(_snap.TNEANet_AddFltAttrE,None,TNEANet)
TNEANet.DelAttrN = new_instancemethod(_snap.TNEANet_DelAttrN,None,TNEANet)
TNEANet.DelAttrE = new_instancemethod(_snap.TNEANet_DelAttrE,None,TNEANet)
TNEANet.NodeAttrIsDeleted = new_instancemethod(_snap.TNEANet_NodeAttrIsDeleted,None,TNEANet)
TNEANet.NodeAttrIsIntDeleted = new_instancemethod(_snap.TNEANet_NodeAttrIsIntDeleted,None,TNEANet)
TNEANet.NodeAttrIsStrDeleted = new_instancemethod(_snap.TNEANet_NodeAttrIsStrDeleted,None,TNEANet)
TNEANet.NodeAttrIsFltDeleted = new_instancemethod(_snap.TNEANet_NodeAttrIsFltDeleted,None,TNEANet)
TNEANet.EdgeAttrIsDeleted = new_instancemethod(_snap.TNEANet_EdgeAttrIsDeleted,None,TNEANet)
TNEANet.EdgeAttrIsIntDeleted = new_instancemethod(_snap.TNEANet_EdgeAttrIsIntDeleted,None,TNEANet)
TNEANet.EdgeAttrIsStrDeleted = new_instancemethod(_snap.TNEANet_EdgeAttrIsStrDeleted,None,TNEANet)
TNEANet.EdgeAttrIsFltDeleted = new_instancemethod(_snap.TNEANet_EdgeAttrIsFltDeleted,None,TNEANet)
TNEANet.GetNodeAttrValue = new_instancemethod(_snap.TNEANet_GetNodeAttrValue,None,TNEANet)
TNEANet.GetEdgeAttrValue = new_instancemethod(_snap.TNEANet_GetEdgeAttrValue,None,TNEANet)
TNEANet.BegNI = new_instancemethod(_snap.TNEANet_BegNI,None,TNEANet)
TNEANet.EndNI = new_instancemethod(_snap.TNEANet_EndNI,None,TNEANet)
TNEANet.BegEI = new_instancemethod(_snap.TNEANet_BegEI,None,TNEANet)
TNEANet.EndEI = new_instancemethod(_snap.TNEANet_EndEI,None,TNEANet)
TNEANet.BegNAIntI = new_instancemethod(_snap.TNEANet_BegNAIntI,None,TNEANet)
TNEANet.EndNAIntI = new_instancemethod(_snap.TNEANet_EndNAIntI,None,TNEANet)
TNEANet.BegNAStrI = new_instancemethod(_snap.TNEANet_BegNAStrI,None,TNEANet)
TNEANet.EndNAStrI = new_instancemethod(_snap.TNEANet_EndNAStrI,None,TNEANet)
TNEANet.BegNAFltI = new_instancemethod(_snap.TNEANet_BegNAFltI,None,TNEANet)
TNEANet.EndNAFltI = new_instancemethod(_snap.TNEANet_EndNAFltI,None,TNEANet)
TNEANet.BegEAIntI = new_instancemethod(_snap.TNEANet_BegEAIntI,None,TNEANet)
TNEANet.EndEAIntI = new_instancemethod(_snap.TNEANet_EndEAIntI,None,TNEANet)
TNEANet.BegEAStrI = new_instancemethod(_snap.TNEANet_BegEAStrI,None,TNEANet)
TNEANet.EndEAStrI = new_instancemethod(_snap.TNEANet_EndEAStrI,None,TNEANet)
TNEANet.BegEAFltI = new_instancemethod(_snap.TNEANet_BegEAFltI,None,TNEANet)
TNEANet.EndEAFltI = new_instancemethod(_snap.TNEANet_EndEAFltI,None,TNEANet)
TNEANet_swigregister = _snap.TNEANet_swigregister
TNEANet_swigregister(TNEANet)
def TNEANet_New(*args):
"""
New() -> PNEANet
TNEANet_New(int const & Nodes, int const & Edges) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.TNEANet_New(*args)
def TNEANet_Load(*args):
"""
TNEANet_Load(TSIn SIn) -> PNEANet
Parameters:
SIn: TSIn &
"""
return _snap.TNEANet_Load(*args)
def PercentDegree(*args):
"""
PercentDegree(PNEANet Graph, int const Threshold=0) -> double
Parameters:
Graph: TPt< TNEANet > const &
Threshold: int const
PercentDegree(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.PercentDegree(*args)
def PercentMxWcc(*args):
"""
PercentMxWcc(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.PercentMxWcc(*args)
def PercentMxScc(*args):
"""
PercentMxScc(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.PercentMxScc(*args)
def LoadEdgeList(*args):
"""
LoadEdgeList(TStr InFNm, int const & SrcColId=0, int const & DstColId=1) -> PNEANet
Parameters:
InFNm: TStr const &
SrcColId: int const &
DstColId: int const &
LoadEdgeList(TStr InFNm, int const & SrcColId=0) -> PNEANet
Parameters:
InFNm: TStr const &
SrcColId: int const &
LoadEdgeList(TStr InFNm) -> PNEANet
Parameters:
InFNm: TStr const &
LoadEdgeList(TStr InFNm, int const & SrcColId, int const & DstColId, char const & Separator) -> PNEANet
Parameters:
InFNm: TStr const &
SrcColId: int const &
DstColId: int const &
Separator: char const &
"""
return _snap.LoadEdgeList(*args)
def PrintGraphStatTable(*args):
"""
PrintGraphStatTable(PNEANet G, TStr OutFNm, TStr Desc="")
Parameters:
G: TPt< TNEANet > const &
OutFNm: TStr
Desc: TStr
PrintGraphStatTable(PNEANet G, TStr OutFNm)
Parameters:
G: TPt< TNEANet > const &
OutFNm: TStr
"""
return _snap.PrintGraphStatTable(*args)
def GenRndGnm(*args):
"""
GenRndGnm(int const & Nodes, int const & Edges, bool const & IsDir=True, TRnd Rnd=Rnd) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
IsDir: bool const &
Rnd: TRnd &
GenRndGnm(int const & Nodes, int const & Edges, bool const & IsDir=True) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
IsDir: bool const &
GenRndGnm(int const & Nodes, int const & Edges) -> PNEANet
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.GenRndGnm(*args)
def NodesGTEDegree(*args):
"""
NodesGTEDegree(PNEANet Graph, int const Threshold=0) -> int
Parameters:
Graph: TPt< TNEANet > const &
Threshold: int const
NodesGTEDegree(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.NodesGTEDegree(*args)
def MxDegree(*args):
"""
MxDegree(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.MxDegree(*args)
def MxSccSz(*args):
"""
MxSccSz(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.MxSccSz(*args)
def MxWccSz(*args):
"""
MxWccSz(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.MxWccSz(*args)
class PNEANet(object):
"""Proxy of C++ TPt<(TNEANet)> class"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
__repr__ = _swig_repr
def New():
"""New() -> PNEANet"""
return _snap.PNEANet_New()
New = staticmethod(New)
__swig_destroy__ = _snap.delete_PNEANet
def Save(self, *args):
"""
Save(PNEANet self, TSOut SOut)
Parameters:
SOut: TSOut &
"""
return _snap.PNEANet_Save(self, *args)
def __deref__(self):
"""
__deref__(PNEANet self) -> TNEANet
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet___deref__(self)
def __ref__(self):
"""
__ref__(PNEANet self) -> TNEANet
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet___ref__(self)
def __call__(self):
"""
__call__(PNEANet self) -> TNEANet
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet___call__(self)
def Empty(self):
"""
Empty(PNEANet self) -> bool
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_Empty(self)
def Clr(self):
"""
Clr(PNEANet self)
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_Clr(self)
def GetRefs(self):
"""
GetRefs(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_GetRefs(self)
def Load(self, *args):
"""
Load(PNEANet self, TSIn SIn) -> PNEANet
Parameters:
SIn: TSIn &
"""
return _snap.PNEANet_Load(self, *args)
def HasFlag(self, *args):
"""
HasFlag(PNEANet self, TGraphFlag const & Flag) -> bool
Parameters:
Flag: TGraphFlag const &
"""
return _snap.PNEANet_HasFlag(self, *args)
def GetNodes(self):
"""
GetNodes(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_GetNodes(self)
def AddNode(self, *args):
"""
AddNode(PNEANet self, int NId=-1) -> int
Parameters:
NId: int
AddNode(PNEANet self) -> int
AddNode(PNEANet self, TNEANet::TNodeI const & NodeId) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
"""
return _snap.PNEANet_AddNode(self, *args)
def DelNode(self, *args):
"""
DelNode(PNEANet self, int const & NId)
Parameters:
NId: int const &
DelNode(PNEANet self, TNEANet::TNode const & NodeI)
Parameters:
NodeI: TNEANet::TNode const &
"""
return _snap.PNEANet_DelNode(self, *args)
def IsNode(self, *args):
"""
IsNode(PNEANet self, int const & NId) -> bool
Parameters:
NId: int const &
"""
return _snap.PNEANet_IsNode(self, *args)
def BegNI(self, *args):
"""
BegNI(PNEANet self) -> TNEANet::TNodeI
BegNI(PNEANet self) -> TNEANetNodeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_BegNI(self, *args)
def EndNI(self, *args):
"""
EndNI(PNEANet self) -> TNEANet::TNodeI
EndNI(PNEANet self) -> TNEANetNodeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_EndNI(self, *args)
def GetNI(self, *args):
"""
GetNI(PNEANet self, int const & NId) -> TNEANet::TNodeI
Parameters:
NId: int const &
"""
return _snap.PNEANet_GetNI(self, *args)
def BegNAIntI(self, *args):
"""
BegNAIntI(PNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
BegNAIntI(PNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegNAIntI(self, *args)
def EndNAIntI(self, *args):
"""
EndNAIntI(PNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EndNAIntI(PNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndNAIntI(self, *args)
def GetNAIntI(self, *args):
"""
GetNAIntI(PNEANet self, TStr attr, int const & NId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.PNEANet_GetNAIntI(self, *args)
def BegNAStrI(self, *args):
"""
BegNAStrI(PNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegNAStrI(PNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegNAStrI(self, *args)
def EndNAStrI(self, *args):
"""
EndNAStrI(PNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EndNAStrI(PNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndNAStrI(self, *args)
def GetNAStrI(self, *args):
"""
GetNAStrI(PNEANet self, TStr attr, int const & NId) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.PNEANet_GetNAStrI(self, *args)
def BegNAFltI(self, *args):
"""
BegNAFltI(PNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
BegNAFltI(PNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegNAFltI(self, *args)
def EndNAFltI(self, *args):
"""
EndNAFltI(PNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EndNAFltI(PNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndNAFltI(self, *args)
def GetNAFltI(self, *args):
"""
GetNAFltI(PNEANet self, TStr attr, int const & NId) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
NId: int const &
"""
return _snap.PNEANet_GetNAFltI(self, *args)
def AttrNameNI(self, *args):
"""
AttrNameNI(PNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
AttrNameNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_AttrNameNI(self, *args)
def AttrValueNI(self, *args):
"""
AttrValueNI(PNEANet self, TInt NId, TStrV Values)
Parameters:
NId: TInt const &
Values: TStrV &
AttrValueNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.PNEANet_AttrValueNI(self, *args)
def IntAttrNameNI(self, *args):
"""
IntAttrNameNI(PNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
IntAttrNameNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_IntAttrNameNI(self, *args)
def IntAttrValueNI(self, *args):
"""
IntAttrValueNI(PNEANet self, TInt NId, TIntV Values)
Parameters:
NId: TInt const &
Values: TIntV &
IntAttrValueNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TIntV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.PNEANet_IntAttrValueNI(self, *args)
def StrAttrNameNI(self, *args):
"""
StrAttrNameNI(PNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
StrAttrNameNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_StrAttrNameNI(self, *args)
def StrAttrValueNI(self, *args):
"""
StrAttrValueNI(PNEANet self, TInt NId, TStrV Values)
Parameters:
NId: TInt const &
Values: TStrV &
StrAttrValueNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.PNEANet_StrAttrValueNI(self, *args)
def FltAttrNameNI(self, *args):
"""
FltAttrNameNI(PNEANet self, TInt NId, TStrV Names)
Parameters:
NId: TInt const &
Names: TStrV &
FltAttrNameNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TStrV Names)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_FltAttrNameNI(self, *args)
def FltAttrValueNI(self, *args):
"""
FltAttrValueNI(PNEANet self, TInt NId, TFltV & Values)
Parameters:
NId: TInt const &
Values: TFltV &
FltAttrValueNI(PNEANet self, TInt NId, TStrIntPrH::TIter NodeHI, TFltV & Values)
Parameters:
NId: TInt const &
NodeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.PNEANet_FltAttrValueNI(self, *args)
def AttrNameEI(self, *args):
"""
AttrNameEI(PNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
AttrNameEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_AttrNameEI(self, *args)
def AttrValueEI(self, *args):
"""
AttrValueEI(PNEANet self, TInt EId, TStrV Values)
Parameters:
EId: TInt const &
Values: TStrV &
AttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.PNEANet_AttrValueEI(self, *args)
def IntAttrNameEI(self, *args):
"""
IntAttrNameEI(PNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
IntAttrNameEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_IntAttrNameEI(self, *args)
def IntAttrValueEI(self, *args):
"""
IntAttrValueEI(PNEANet self, TInt EId, TIntV Values)
Parameters:
EId: TInt const &
Values: TIntV &
IntAttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TIntV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TIntV &
"""
return _snap.PNEANet_IntAttrValueEI(self, *args)
def StrAttrNameEI(self, *args):
"""
StrAttrNameEI(PNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
StrAttrNameEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_StrAttrNameEI(self, *args)
def StrAttrValueEI(self, *args):
"""
StrAttrValueEI(PNEANet self, TInt EId, TStrV Values)
Parameters:
EId: TInt const &
Values: TStrV &
StrAttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TStrV &
"""
return _snap.PNEANet_StrAttrValueEI(self, *args)
def FltAttrNameEI(self, *args):
"""
FltAttrNameEI(PNEANet self, TInt EId, TStrV Names)
Parameters:
EId: TInt const &
Names: TStrV &
FltAttrNameEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TStrV Names)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Names: TStrV &
"""
return _snap.PNEANet_FltAttrNameEI(self, *args)
def FltAttrValueEI(self, *args):
"""
FltAttrValueEI(PNEANet self, TInt EId, TFltV & Values)
Parameters:
EId: TInt const &
Values: TFltV &
FltAttrValueEI(PNEANet self, TInt EId, TStrIntPrH::TIter EdgeHI, TFltV & Values)
Parameters:
EId: TInt const &
EdgeHI: TStrIntPrH::TIter
Values: TFltV &
"""
return _snap.PNEANet_FltAttrValueEI(self, *args)
def BegEAIntI(self, *args):
"""
BegEAIntI(PNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
BegEAIntI(PNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegEAIntI(self, *args)
def EndEAIntI(self, *args):
"""
EndEAIntI(PNEANet self, TStr attr) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EndEAIntI(PNEANet self, TStr attr) -> TNEANetAIntI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndEAIntI(self, *args)
def GetEAIntI(self, *args):
"""
GetEAIntI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAIntI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.PNEANet_GetEAIntI(self, *args)
def BegEAStrI(self, *args):
"""
BegEAStrI(PNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
BegEAStrI(PNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegEAStrI(self, *args)
def EndEAStrI(self, *args):
"""
EndEAStrI(PNEANet self, TStr attr) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EndEAStrI(PNEANet self, TStr attr) -> TNEANetAStrI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndEAStrI(self, *args)
def GetEAStrI(self, *args):
"""
GetEAStrI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAStrI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.PNEANet_GetEAStrI(self, *args)
def BegEAFltI(self, *args):
"""
BegEAFltI(PNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
BegEAFltI(PNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_BegEAFltI(self, *args)
def EndEAFltI(self, *args):
"""
EndEAFltI(PNEANet self, TStr attr) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EndEAFltI(PNEANet self, TStr attr) -> TNEANetAFltI
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_EndEAFltI(self, *args)
def GetEAFltI(self, *args):
"""
GetEAFltI(PNEANet self, TStr attr, int const & EId) -> TNEANet::TAFltI
Parameters:
attr: TStr const &
EId: int const &
"""
return _snap.PNEANet_GetEAFltI(self, *args)
def GetMxNId(self):
"""
GetMxNId(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_GetMxNId(self)
def GetEdges(self):
"""
GetEdges(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_GetEdges(self)
def AddEdge(self, *args):
"""
AddEdge(PNEANet self, int const & SrcNId, int const & DstNId, int EId=-1) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int
AddEdge(PNEANet self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
AddEdge(PNEANet self, TNEANet::TEdgeI const & EdgeI) -> int
Parameters:
EdgeI: TNEANet::TEdgeI const &
"""
return _snap.PNEANet_AddEdge(self, *args)
def DelEdge(self, *args):
"""
DelEdge(PNEANet self, int const & EId)
Parameters:
EId: int const &
DelEdge(PNEANet self, int const & SrcNId, int const & DstNId, bool const & IsDir=True)
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
DelEdge(PNEANet self, int const & SrcNId, int const & DstNId)
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.PNEANet_DelEdge(self, *args)
def IsEdge(self, *args):
"""
IsEdge(PNEANet self, int const & EId) -> bool
Parameters:
EId: int const &
IsEdge(PNEANet self, int const & SrcNId, int const & DstNId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
IsEdge(PNEANet self, int const & SrcNId, int const & DstNId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
IsEdge(PNEANet self, int const & SrcNId, int const & DstNId, int & EId, bool const & IsDir=True) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
IsDir: bool const &
IsEdge(PNEANet self, int const & SrcNId, int const & DstNId, int & EId) -> bool
Parameters:
SrcNId: int const &
DstNId: int const &
EId: int &
"""
return _snap.PNEANet_IsEdge(self, *args)
def GetEId(self, *args):
"""
GetEId(PNEANet self, int const & SrcNId, int const & DstNId) -> int
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.PNEANet_GetEId(self, *args)
def BegEI(self, *args):
"""
BegEI(PNEANet self) -> TNEANet::TEdgeI
BegEI(PNEANet self) -> TNEANetEdgeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_BegEI(self, *args)
def EndEI(self, *args):
"""
EndEI(PNEANet self) -> TNEANet::TEdgeI
EndEI(PNEANet self) -> TNEANetEdgeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_EndEI(self, *args)
def GetEI(self, *args):
"""
GetEI(PNEANet self, int const & SrcNId, int const & DstNId) -> TNEANet::TEdgeI
Parameters:
SrcNId: int const &
DstNId: int const &
"""
return _snap.PNEANet_GetEI(self, *args)
def GetRndNId(self, *args):
"""
GetRndNId(PNEANet self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndNId(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_GetRndNId(self, *args)
def GetRndNI(self, *args):
"""
GetRndNI(PNEANet self, TRnd Rnd=Rnd) -> TNEANet::TNodeI
Parameters:
Rnd: TRnd &
GetRndNI(PNEANet self) -> TNEANet::TNodeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_GetRndNI(self, *args)
def GetRndEId(self, *args):
"""
GetRndEId(PNEANet self, TRnd Rnd=Rnd) -> int
Parameters:
Rnd: TRnd &
GetRndEId(PNEANet self) -> int
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_GetRndEId(self, *args)
def GetRndEI(self, *args):
"""
GetRndEI(PNEANet self, TRnd Rnd=Rnd) -> TNEANet::TEdgeI
Parameters:
Rnd: TRnd &
GetRndEI(PNEANet self) -> TNEANet::TEdgeI
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_GetRndEI(self, *args)
def GetNIdV(self, *args):
"""
GetNIdV(PNEANet self, TIntV NIdV)
Parameters:
NIdV: TIntV &
"""
return _snap.PNEANet_GetNIdV(self, *args)
def GetEIdV(self, *args):
"""
GetEIdV(PNEANet self, TIntV EIdV)
Parameters:
EIdV: TIntV &
"""
return _snap.PNEANet_GetEIdV(self, *args)
def Reserve(self, *args):
"""
Reserve(PNEANet self, int const & Nodes, int const & Edges)
Parameters:
Nodes: int const &
Edges: int const &
"""
return _snap.PNEANet_Reserve(self, *args)
def Defrag(self, OnlyNodeLinks=False):
"""
Defrag(PNEANet self, bool const & OnlyNodeLinks=False)
Parameters:
OnlyNodeLinks: bool const &
Defrag(PNEANet self)
Parameters:
self: TPt< TNEANet > *
"""
return _snap.PNEANet_Defrag(self, OnlyNodeLinks)
def IsOk(self, ThrowExcept=True):
"""
IsOk(PNEANet self, bool const & ThrowExcept=True) -> bool
Parameters:
ThrowExcept: bool const &
IsOk(PNEANet self) -> bool
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_IsOk(self, ThrowExcept)
def Dump(self, *args):
"""
Dump(PNEANet self, FILE * OutF=stdout)
Parameters:
OutF: FILE *
Dump(PNEANet self)
Parameters:
self: TPt< TNEANet > const *
"""
return _snap.PNEANet_Dump(self, *args)
def AddIntAttrDatN(self, *args):
"""
AddIntAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TInt value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TInt const &
attr: TStr const &
AddIntAttrDatN(PNEANet self, int const & NId, TInt value, TStr attr) -> int
Parameters:
NId: int const &
value: TInt const &
attr: TStr const &
"""
return _snap.PNEANet_AddIntAttrDatN(self, *args)
def AddStrAttrDatN(self, *args):
"""
AddStrAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TStr const &
attr: TStr const &
AddStrAttrDatN(PNEANet self, int const & NId, TStr value, TStr attr) -> int
Parameters:
NId: int const &
value: TStr const &
attr: TStr const &
"""
return _snap.PNEANet_AddStrAttrDatN(self, *args)
def AddFltAttrDatN(self, *args):
"""
AddFltAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TFlt value, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
value: TFlt const &
attr: TStr const &
AddFltAttrDatN(PNEANet self, int const & NId, TFlt value, TStr attr) -> int
Parameters:
NId: int const &
value: TFlt const &
attr: TStr const &
"""
return _snap.PNEANet_AddFltAttrDatN(self, *args)
def AddIntAttrDatE(self, *args):
"""
AddIntAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TInt value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TInt const &
attr: TStr const &
AddIntAttrDatE(PNEANet self, int const & EId, TInt value, TStr attr) -> int
Parameters:
EId: int const &
value: TInt const &
attr: TStr const &
"""
return _snap.PNEANet_AddIntAttrDatE(self, *args)
def AddStrAttrDatE(self, *args):
"""
AddStrAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TStr const &
attr: TStr const &
AddStrAttrDatE(PNEANet self, int const & EId, TStr value, TStr attr) -> int
Parameters:
EId: int const &
value: TStr const &
attr: TStr const &
"""
return _snap.PNEANet_AddStrAttrDatE(self, *args)
def AddFltAttrDatE(self, *args):
"""
AddFltAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TFlt value, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
value: TFlt const &
attr: TStr const &
AddFltAttrDatE(PNEANet self, int const & EId, TFlt value, TStr attr) -> int
Parameters:
EId: int const &
value: TFlt const &
attr: TStr const &
"""
return _snap.PNEANet_AddFltAttrDatE(self, *args)
def GetIntAttrDatN(self, *args):
"""
GetIntAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TInt
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetIntAttrDatN(PNEANet self, int const & NId, TStr attr) -> TInt
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetIntAttrDatN(self, *args)
def GetStrAttrDatN(self, *args):
"""
GetStrAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TStr
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetStrAttrDatN(PNEANet self, int const & NId, TStr attr) -> TStr
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetStrAttrDatN(self, *args)
def GetFltAttrDatN(self, *args):
"""
GetFltAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> TFlt
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
GetFltAttrDatN(PNEANet self, int const & NId, TStr attr) -> TFlt
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetFltAttrDatN(self, *args)
def GetIntAttrDatE(self, *args):
"""
GetIntAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TInt
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetIntAttrDatE(PNEANet self, int const & EId, TStr attr) -> TInt
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetIntAttrDatE(self, *args)
def GetStrAttrDatE(self, *args):
"""
GetStrAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TStr
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetStrAttrDatE(PNEANet self, int const & EId, TStr attr) -> TStr
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetStrAttrDatE(self, *args)
def GetFltAttrDatE(self, *args):
"""
GetFltAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> TFlt
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
GetFltAttrDatE(PNEANet self, int const & EId, TStr attr) -> TFlt
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.PNEANet_GetFltAttrDatE(self, *args)
def DelAttrDatN(self, *args):
"""
DelAttrDatN(PNEANet self, TNEANet::TNodeI const & NodeId, TStr attr) -> int
Parameters:
NodeId: TNEANet::TNodeI const &
attr: TStr const &
DelAttrDatN(PNEANet self, int const & NId, TStr attr) -> int
Parameters:
NId: int const &
attr: TStr const &
"""
return _snap.PNEANet_DelAttrDatN(self, *args)
def DelAttrDatE(self, *args):
"""
DelAttrDatE(PNEANet self, TNEANet::TEdgeI const & EdgeId, TStr attr) -> int
Parameters:
EdgeId: TNEANet::TEdgeI const &
attr: TStr const &
DelAttrDatE(PNEANet self, int const & EId, TStr attr) -> int
Parameters:
EId: int const &
attr: TStr const &
"""
return _snap.PNEANet_DelAttrDatE(self, *args)
def AddIntAttrN(self, *args):
"""
AddIntAttrN(PNEANet self, TStr attr, TInt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TInt
AddIntAttrN(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddIntAttrN(self, *args)
def AddStrAttrN(self, *args):
"""
AddStrAttrN(PNEANet self, TStr attr, TStr defaultValue=TStr::GetNullStr()) -> int
Parameters:
attr: TStr const &
defaultValue: TStr
AddStrAttrN(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddStrAttrN(self, *args)
def AddFltAttrN(self, *args):
"""
AddFltAttrN(PNEANet self, TStr attr, TFlt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TFlt
AddFltAttrN(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddFltAttrN(self, *args)
def AddIntAttrE(self, *args):
"""
AddIntAttrE(PNEANet self, TStr attr, TInt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TInt
AddIntAttrE(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddIntAttrE(self, *args)
def AddStrAttrE(self, *args):
"""
AddStrAttrE(PNEANet self, TStr attr, TStr defaultValue=TStr::GetNullStr()) -> int
Parameters:
attr: TStr const &
defaultValue: TStr
AddStrAttrE(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddStrAttrE(self, *args)
def AddFltAttrE(self, *args):
"""
AddFltAttrE(PNEANet self, TStr attr, TFlt defaultValue=Mn) -> int
Parameters:
attr: TStr const &
defaultValue: TFlt
AddFltAttrE(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_AddFltAttrE(self, *args)
def DelAttrN(self, *args):
"""
DelAttrN(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_DelAttrN(self, *args)
def DelAttrE(self, *args):
"""
DelAttrE(PNEANet self, TStr attr) -> int
Parameters:
attr: TStr const &
"""
return _snap.PNEANet_DelAttrE(self, *args)
def NodeAttrIsDeleted(self, *args):
"""
NodeAttrIsDeleted(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_NodeAttrIsDeleted(self, *args)
def NodeAttrIsIntDeleted(self, *args):
"""
NodeAttrIsIntDeleted(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_NodeAttrIsIntDeleted(self, *args)
def NodeAttrIsStrDeleted(self, *args):
"""
NodeAttrIsStrDeleted(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_NodeAttrIsStrDeleted(self, *args)
def NodeAttrIsFltDeleted(self, *args):
"""
NodeAttrIsFltDeleted(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_NodeAttrIsFltDeleted(self, *args)
def EdgeAttrIsDeleted(self, *args):
"""
EdgeAttrIsDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsDeleted(self, *args)
def EdgeAttrIsIntDeleted(self, *args):
"""
EdgeAttrIsIntDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsIntDeleted(self, *args)
def EdgeAttrIsStrDeleted(self, *args):
"""
EdgeAttrIsStrDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsStrDeleted(self, *args)
def EdgeAttrIsFltDeleted(self, *args):
"""
EdgeAttrIsFltDeleted(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> bool
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_EdgeAttrIsFltDeleted(self, *args)
def GetNodeAttrValue(self, *args):
"""
GetNodeAttrValue(PNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> TStr
Parameters:
NId: int const &
NodeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_GetNodeAttrValue(self, *args)
def GetEdgeAttrValue(self, *args):
"""
GetEdgeAttrValue(PNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> TStr
Parameters:
EId: int const &
EdgeHI: TStrIntPrH::TIter const &
"""
return _snap.PNEANet_GetEdgeAttrValue(self, *args)
PNEANet.Save = new_instancemethod(_snap.PNEANet_Save,None,PNEANet)
PNEANet.__deref__ = new_instancemethod(_snap.PNEANet___deref__,None,PNEANet)
PNEANet.__ref__ = new_instancemethod(_snap.PNEANet___ref__,None,PNEANet)
PNEANet.__call__ = new_instancemethod(_snap.PNEANet___call__,None,PNEANet)
PNEANet.Empty = new_instancemethod(_snap.PNEANet_Empty,None,PNEANet)
PNEANet.Clr = new_instancemethod(_snap.PNEANet_Clr,None,PNEANet)
PNEANet.GetRefs = new_instancemethod(_snap.PNEANet_GetRefs,None,PNEANet)
PNEANet.Load = new_instancemethod(_snap.PNEANet_Load,None,PNEANet)
PNEANet.HasFlag = new_instancemethod(_snap.PNEANet_HasFlag,None,PNEANet)
PNEANet.GetNodes = new_instancemethod(_snap.PNEANet_GetNodes,None,PNEANet)
PNEANet.AddNode = new_instancemethod(_snap.PNEANet_AddNode,None,PNEANet)
PNEANet.DelNode = new_instancemethod(_snap.PNEANet_DelNode,None,PNEANet)
PNEANet.IsNode = new_instancemethod(_snap.PNEANet_IsNode,None,PNEANet)
PNEANet.BegNI = new_instancemethod(_snap.PNEANet_BegNI,None,PNEANet)
PNEANet.EndNI = new_instancemethod(_snap.PNEANet_EndNI,None,PNEANet)
PNEANet.GetNI = new_instancemethod(_snap.PNEANet_GetNI,None,PNEANet)
PNEANet.BegNAIntI = new_instancemethod(_snap.PNEANet_BegNAIntI,None,PNEANet)
PNEANet.EndNAIntI = new_instancemethod(_snap.PNEANet_EndNAIntI,None,PNEANet)
PNEANet.GetNAIntI = new_instancemethod(_snap.PNEANet_GetNAIntI,None,PNEANet)
PNEANet.BegNAStrI = new_instancemethod(_snap.PNEANet_BegNAStrI,None,PNEANet)
PNEANet.EndNAStrI = new_instancemethod(_snap.PNEANet_EndNAStrI,None,PNEANet)
PNEANet.GetNAStrI = new_instancemethod(_snap.PNEANet_GetNAStrI,None,PNEANet)
PNEANet.BegNAFltI = new_instancemethod(_snap.PNEANet_BegNAFltI,None,PNEANet)
PNEANet.EndNAFltI = new_instancemethod(_snap.PNEANet_EndNAFltI,None,PNEANet)
PNEANet.GetNAFltI = new_instancemethod(_snap.PNEANet_GetNAFltI,None,PNEANet)
PNEANet.AttrNameNI = new_instancemethod(_snap.PNEANet_AttrNameNI,None,PNEANet)
PNEANet.AttrValueNI = new_instancemethod(_snap.PNEANet_AttrValueNI,None,PNEANet)
PNEANet.IntAttrNameNI = new_instancemethod(_snap.PNEANet_IntAttrNameNI,None,PNEANet)
PNEANet.IntAttrValueNI = new_instancemethod(_snap.PNEANet_IntAttrValueNI,None,PNEANet)
PNEANet.StrAttrNameNI = new_instancemethod(_snap.PNEANet_StrAttrNameNI,None,PNEANet)
PNEANet.StrAttrValueNI = new_instancemethod(_snap.PNEANet_StrAttrValueNI,None,PNEANet)
PNEANet.FltAttrNameNI = new_instancemethod(_snap.PNEANet_FltAttrNameNI,None,PNEANet)
PNEANet.FltAttrValueNI = new_instancemethod(_snap.PNEANet_FltAttrValueNI,None,PNEANet)
PNEANet.AttrNameEI = new_instancemethod(_snap.PNEANet_AttrNameEI,None,PNEANet)
PNEANet.AttrValueEI = new_instancemethod(_snap.PNEANet_AttrValueEI,None,PNEANet)
PNEANet.IntAttrNameEI = new_instancemethod(_snap.PNEANet_IntAttrNameEI,None,PNEANet)
PNEANet.IntAttrValueEI = new_instancemethod(_snap.PNEANet_IntAttrValueEI,None,PNEANet)
PNEANet.StrAttrNameEI = new_instancemethod(_snap.PNEANet_StrAttrNameEI,None,PNEANet)
PNEANet.StrAttrValueEI = new_instancemethod(_snap.PNEANet_StrAttrValueEI,None,PNEANet)
PNEANet.FltAttrNameEI = new_instancemethod(_snap.PNEANet_FltAttrNameEI,None,PNEANet)
PNEANet.FltAttrValueEI = new_instancemethod(_snap.PNEANet_FltAttrValueEI,None,PNEANet)
PNEANet.BegEAIntI = new_instancemethod(_snap.PNEANet_BegEAIntI,None,PNEANet)
PNEANet.EndEAIntI = new_instancemethod(_snap.PNEANet_EndEAIntI,None,PNEANet)
PNEANet.GetEAIntI = new_instancemethod(_snap.PNEANet_GetEAIntI,None,PNEANet)
PNEANet.BegEAStrI = new_instancemethod(_snap.PNEANet_BegEAStrI,None,PNEANet)
PNEANet.EndEAStrI = new_instancemethod(_snap.PNEANet_EndEAStrI,None,PNEANet)
PNEANet.GetEAStrI = new_instancemethod(_snap.PNEANet_GetEAStrI,None,PNEANet)
PNEANet.BegEAFltI = new_instancemethod(_snap.PNEANet_BegEAFltI,None,PNEANet)
PNEANet.EndEAFltI = new_instancemethod(_snap.PNEANet_EndEAFltI,None,PNEANet)
PNEANet.GetEAFltI = new_instancemethod(_snap.PNEANet_GetEAFltI,None,PNEANet)
PNEANet.GetMxNId = new_instancemethod(_snap.PNEANet_GetMxNId,None,PNEANet)
PNEANet.GetEdges = new_instancemethod(_snap.PNEANet_GetEdges,None,PNEANet)
PNEANet.AddEdge = new_instancemethod(_snap.PNEANet_AddEdge,None,PNEANet)
PNEANet.DelEdge = new_instancemethod(_snap.PNEANet_DelEdge,None,PNEANet)
PNEANet.IsEdge = new_instancemethod(_snap.PNEANet_IsEdge,None,PNEANet)
PNEANet.GetEId = new_instancemethod(_snap.PNEANet_GetEId,None,PNEANet)
PNEANet.BegEI = new_instancemethod(_snap.PNEANet_BegEI,None,PNEANet)
PNEANet.EndEI = new_instancemethod(_snap.PNEANet_EndEI,None,PNEANet)
PNEANet.GetEI = new_instancemethod(_snap.PNEANet_GetEI,None,PNEANet)
PNEANet.GetRndNId = new_instancemethod(_snap.PNEANet_GetRndNId,None,PNEANet)
PNEANet.GetRndNI = new_instancemethod(_snap.PNEANet_GetRndNI,None,PNEANet)
PNEANet.GetRndEId = new_instancemethod(_snap.PNEANet_GetRndEId,None,PNEANet)
PNEANet.GetRndEI = new_instancemethod(_snap.PNEANet_GetRndEI,None,PNEANet)
PNEANet.GetNIdV = new_instancemethod(_snap.PNEANet_GetNIdV,None,PNEANet)
PNEANet.GetEIdV = new_instancemethod(_snap.PNEANet_GetEIdV,None,PNEANet)
PNEANet.Reserve = new_instancemethod(_snap.PNEANet_Reserve,None,PNEANet)
PNEANet.Defrag = new_instancemethod(_snap.PNEANet_Defrag,None,PNEANet)
PNEANet.IsOk = new_instancemethod(_snap.PNEANet_IsOk,None,PNEANet)
PNEANet.Dump = new_instancemethod(_snap.PNEANet_Dump,None,PNEANet)
PNEANet.AddIntAttrDatN = new_instancemethod(_snap.PNEANet_AddIntAttrDatN,None,PNEANet)
PNEANet.AddStrAttrDatN = new_instancemethod(_snap.PNEANet_AddStrAttrDatN,None,PNEANet)
PNEANet.AddFltAttrDatN = new_instancemethod(_snap.PNEANet_AddFltAttrDatN,None,PNEANet)
PNEANet.AddIntAttrDatE = new_instancemethod(_snap.PNEANet_AddIntAttrDatE,None,PNEANet)
PNEANet.AddStrAttrDatE = new_instancemethod(_snap.PNEANet_AddStrAttrDatE,None,PNEANet)
PNEANet.AddFltAttrDatE = new_instancemethod(_snap.PNEANet_AddFltAttrDatE,None,PNEANet)
PNEANet.GetIntAttrDatN = new_instancemethod(_snap.PNEANet_GetIntAttrDatN,None,PNEANet)
PNEANet.GetStrAttrDatN = new_instancemethod(_snap.PNEANet_GetStrAttrDatN,None,PNEANet)
PNEANet.GetFltAttrDatN = new_instancemethod(_snap.PNEANet_GetFltAttrDatN,None,PNEANet)
PNEANet.GetIntAttrDatE = new_instancemethod(_snap.PNEANet_GetIntAttrDatE,None,PNEANet)
PNEANet.GetStrAttrDatE = new_instancemethod(_snap.PNEANet_GetStrAttrDatE,None,PNEANet)
PNEANet.GetFltAttrDatE = new_instancemethod(_snap.PNEANet_GetFltAttrDatE,None,PNEANet)
PNEANet.DelAttrDatN = new_instancemethod(_snap.PNEANet_DelAttrDatN,None,PNEANet)
PNEANet.DelAttrDatE = new_instancemethod(_snap.PNEANet_DelAttrDatE,None,PNEANet)
PNEANet.AddIntAttrN = new_instancemethod(_snap.PNEANet_AddIntAttrN,None,PNEANet)
PNEANet.AddStrAttrN = new_instancemethod(_snap.PNEANet_AddStrAttrN,None,PNEANet)
PNEANet.AddFltAttrN = new_instancemethod(_snap.PNEANet_AddFltAttrN,None,PNEANet)
PNEANet.AddIntAttrE = new_instancemethod(_snap.PNEANet_AddIntAttrE,None,PNEANet)
PNEANet.AddStrAttrE = new_instancemethod(_snap.PNEANet_AddStrAttrE,None,PNEANet)
PNEANet.AddFltAttrE = new_instancemethod(_snap.PNEANet_AddFltAttrE,None,PNEANet)
PNEANet.DelAttrN = new_instancemethod(_snap.PNEANet_DelAttrN,None,PNEANet)
PNEANet.DelAttrE = new_instancemethod(_snap.PNEANet_DelAttrE,None,PNEANet)
PNEANet.NodeAttrIsDeleted = new_instancemethod(_snap.PNEANet_NodeAttrIsDeleted,None,PNEANet)
PNEANet.NodeAttrIsIntDeleted = new_instancemethod(_snap.PNEANet_NodeAttrIsIntDeleted,None,PNEANet)
PNEANet.NodeAttrIsStrDeleted = new_instancemethod(_snap.PNEANet_NodeAttrIsStrDeleted,None,PNEANet)
PNEANet.NodeAttrIsFltDeleted = new_instancemethod(_snap.PNEANet_NodeAttrIsFltDeleted,None,PNEANet)
PNEANet.EdgeAttrIsDeleted = new_instancemethod(_snap.PNEANet_EdgeAttrIsDeleted,None,PNEANet)
PNEANet.EdgeAttrIsIntDeleted = new_instancemethod(_snap.PNEANet_EdgeAttrIsIntDeleted,None,PNEANet)
PNEANet.EdgeAttrIsStrDeleted = new_instancemethod(_snap.PNEANet_EdgeAttrIsStrDeleted,None,PNEANet)
PNEANet.EdgeAttrIsFltDeleted = new_instancemethod(_snap.PNEANet_EdgeAttrIsFltDeleted,None,PNEANet)
PNEANet.GetNodeAttrValue = new_instancemethod(_snap.PNEANet_GetNodeAttrValue,None,PNEANet)
PNEANet.GetEdgeAttrValue = new_instancemethod(_snap.PNEANet_GetEdgeAttrValue,None,PNEANet)
PNEANet_swigregister = _snap.PNEANet_swigregister
PNEANet_swigregister(PNEANet)
def PNEANet_New():
"""PNEANet_New() -> PNEANet"""
return _snap.PNEANet_New()
def GetNodeWcc(*args):
"""
GetNodeWcc(PNEANet Graph, int const & NId, TIntV CnCom)
Parameters:
Graph: TPt< TNEANet > const &
NId: int const &
CnCom: TIntV &
"""
return _snap.GetNodeWcc(*args)
def IsConnected(*args):
"""
IsConnected(PNEANet Graph) -> bool
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.IsConnected(*args)
def IsWeaklyConn(*args):
"""
IsWeaklyConn(PNEANet Graph) -> bool
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.IsWeaklyConn(*args)
def GetWccSzCnt(*args):
"""
GetWccSzCnt(PNEANet Graph, TIntPrV & WccSzCnt)
Parameters:
Graph: TPt< TNEANet > const &
WccSzCnt: TIntPrV &
"""
return _snap.GetWccSzCnt(*args)
def GetWccs(*args):
"""
GetWccs(PNEANet Graph, TCnComV & CnComV)
Parameters:
Graph: TPt< TNEANet > const &
CnComV: TCnComV &
"""
return _snap.GetWccs(*args)
def GetSccSzCnt(*args):
"""
GetSccSzCnt(PNEANet Graph, TIntPrV & SccSzCnt)
Parameters:
Graph: TPt< TNEANet > const &
SccSzCnt: TIntPrV &
"""
return _snap.GetSccSzCnt(*args)
def GetSccs(*args):
"""
GetSccs(PNEANet Graph, TCnComV & CnComV)
Parameters:
Graph: TPt< TNEANet > const &
CnComV: TCnComV &
"""
return _snap.GetSccs(*args)
def GetMxWccSz(*args):
"""
GetMxWccSz(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxWccSz(*args)
def GetMxWcc(*args):
"""
GetMxWcc(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxWcc(*args)
def GetMxScc(*args):
"""
GetMxScc(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxScc(*args)
def GetMxBiCon(*args):
"""
GetMxBiCon(PUNGraph const & Graph, bool const & RenumberNodes=False) -> PUNGraph
Parameters:
Graph: PUNGraph const &
RenumberNodes: bool const &
GetMxBiCon(PUNGraph const & Graph) -> PUNGraph
Parameters:
Graph: PUNGraph const &
GetMxBiCon(PNEANet Graph) -> PNEANet
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxBiCon(*args)
def CntInDegNodes(*args):
"""
CntInDegNodes(PNEANet Graph, int const & NodeInDeg) -> int
Parameters:
Graph: TPt< TNEANet > const &
NodeInDeg: int const &
"""
return _snap.CntInDegNodes(*args)
def CntOutDegNodes(*args):
"""
CntOutDegNodes(PNEANet Graph, int const & NodeOutDeg) -> int
Parameters:
Graph: TPt< TNEANet > const &
NodeOutDeg: int const &
"""
return _snap.CntOutDegNodes(*args)
def CntDegNodes(*args):
"""
CntDegNodes(PNEANet Graph, int const & NodeDeg) -> int
Parameters:
Graph: TPt< TNEANet > const &
NodeDeg: int const &
"""
return _snap.CntDegNodes(*args)
def CntNonZNodes(*args):
"""
CntNonZNodes(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntNonZNodes(*args)
def CntEdgesToSet(*args):
"""
CntEdgesToSet(PNEANet Graph, int const & NId, TIntSet const & NodeSet) -> int
Parameters:
Graph: TPt< TNEANet > const &
NId: int const &
NodeSet: TIntSet const &
"""
return _snap.CntEdgesToSet(*args)
def GetMxDegNId(*args):
"""
GetMxDegNId(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxDegNId(*args)
def GetMxInDegNId(*args):
"""
GetMxInDegNId(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxInDegNId(*args)
def GetMxOutDegNId(*args):
"""
GetMxOutDegNId(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxOutDegNId(*args)
def GetInDegCnt(*args):
"""
GetInDegCnt(PNEANet Graph, TIntPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TIntPrV &
GetInDegCnt(PNEANet Graph, TFltPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TFltPrV &
"""
return _snap.GetInDegCnt(*args)
def GetOutDegCnt(*args):
"""
GetOutDegCnt(PNEANet Graph, TIntPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TIntPrV &
GetOutDegCnt(PNEANet Graph, TFltPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TFltPrV &
"""
return _snap.GetOutDegCnt(*args)
def GetDegCnt(*args):
"""
GetDegCnt(PNEANet Graph, TIntPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TIntPrV &
GetDegCnt(PNEANet Graph, TFltPrV & DegToCntV)
Parameters:
Graph: TPt< TNEANet > const &
DegToCntV: TFltPrV &
"""
return _snap.GetDegCnt(*args)
def GetDegSeqV(*args):
"""
GetDegSeqV(PNEANet Graph, TIntV DegV)
Parameters:
Graph: TPt< TNEANet > const &
DegV: TIntV &
GetDegSeqV(PNEANet Graph, TIntV InDegV, TIntV OutDegV)
Parameters:
Graph: TPt< TNEANet > const &
InDegV: TIntV &
OutDegV: TIntV &
"""
return _snap.GetDegSeqV(*args)
def GetNodeInDegV(*args):
"""
GetNodeInDegV(PNEANet Graph, TIntPrV & NIdInDegV)
Parameters:
Graph: TPt< TNEANet > const &
NIdInDegV: TIntPrV &
"""
return _snap.GetNodeInDegV(*args)
def GetNodeOutDegV(*args):
"""
GetNodeOutDegV(PNEANet Graph, TIntPrV & NIdOutDegV)
Parameters:
Graph: TPt< TNEANet > const &
NIdOutDegV: TIntPrV &
"""
return _snap.GetNodeOutDegV(*args)
def CntUniqUndirEdges(*args):
"""
CntUniqUndirEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntUniqUndirEdges(*args)
def CntUniqDirEdges(*args):
"""
CntUniqDirEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntUniqDirEdges(*args)
def CntUniqBiDirEdges(*args):
"""
CntUniqBiDirEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntUniqBiDirEdges(*args)
def CntSelfEdges(*args):
"""
CntSelfEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.CntSelfEdges(*args)
def GetBfsTree(*args):
"""
GetBfsTree(PNEANet Graph, int const & StartNId, bool const & FollowOut, bool const & FollowIn) -> PNGraph
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
FollowOut: bool const &
FollowIn: bool const &
"""
return _snap.GetBfsTree(*args)
def GetSubTreeSz(*args):
"""
GetSubTreeSz(PNEANet Graph, int const & StartNId, bool const & FollowOut, bool const & FollowIn,
int & TreeSz, int & TreeDepth) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
FollowOut: bool const &
FollowIn: bool const &
TreeSz: int &
TreeDepth: int &
"""
return _snap.GetSubTreeSz(*args)
def GetNodesAtHop(*args):
"""
GetNodesAtHop(PNEANet Graph, int const & StartNId, int const & Hop, TIntV NIdV, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
Hop: int const &
NIdV: TIntV &
IsDir: bool const &
GetNodesAtHop(PNEANet Graph, int const & StartNId, int const & Hop, TIntV NIdV) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
Hop: int const &
NIdV: TIntV &
"""
return _snap.GetNodesAtHop(*args)
def GetNodesAtHops(*args):
"""
GetNodesAtHops(PNEANet Graph, int const & StartNId, TIntPrV & HopCntV, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
HopCntV: TIntPrV &
IsDir: bool const &
GetNodesAtHops(PNEANet Graph, int const & StartNId, TIntPrV & HopCntV) -> int
Parameters:
Graph: TPt< TNEANet > const &
StartNId: int const &
HopCntV: TIntPrV &
"""
return _snap.GetNodesAtHops(*args)
def GetShortPath(*args):
"""
GetShortPath(PNEANet Graph, int const & SrcNId, int const & DstNId, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
DstNId: int const &
IsDir: bool const &
GetShortPath(PNEANet Graph, int const & SrcNId, int const & DstNId) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
DstNId: int const &
GetShortPath(PNEANet Graph, int const & SrcNId, TIntH NIdToDistH, bool const & IsDir=False, int const & MaxDist=Mx) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
NIdToDistH: TIntH &
IsDir: bool const &
MaxDist: int const &
GetShortPath(PNEANet Graph, int const & SrcNId, TIntH NIdToDistH, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
NIdToDistH: TIntH &
IsDir: bool const &
GetShortPath(PNEANet Graph, int const & SrcNId, TIntH NIdToDistH) -> int
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
NIdToDistH: TIntH &
"""
return _snap.GetShortPath(*args)
def GetBfsFullDiam(*args):
"""
GetBfsFullDiam(PNEANet Graph, int const & NTestNodes, bool const & IsDir=False) -> int
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
IsDir: bool const &
GetBfsFullDiam(PNEANet Graph, int const & NTestNodes) -> int
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
"""
return _snap.GetBfsFullDiam(*args)
def GetBfsEffDiam(*args):
"""
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes, bool const & IsDir=False) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
IsDir: bool const &
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes, bool const & IsDir, double & EffDiam, int & FullDiam) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
IsDir: bool const &
EffDiam: double &
FullDiam: int &
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes, bool const & IsDir, double & EffDiam, int & FullDiam,
double & AvgSPL) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
IsDir: bool const &
EffDiam: double &
FullDiam: int &
AvgSPL: double &
GetBfsEffDiam(PNEANet Graph, int const & NTestNodes, TIntV SubGraphNIdV, bool const & IsDir, double & EffDiam,
int & FullDiam) -> double
Parameters:
Graph: TPt< TNEANet > const &
NTestNodes: int const &
SubGraphNIdV: TIntV const &
IsDir: bool const &
EffDiam: double &
FullDiam: int &
"""
return _snap.GetBfsEffDiam(*args)
def DrawGViz(*args):
"""
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm, TStr Desc=TStr(), bool const & NodeLabels=False,
TIntStrH const & NIdColorH=TIntStrH())
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
Desc: TStr const &
NodeLabels: bool const &
NIdColorH: TIntStrH const &
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm, TStr Desc=TStr(), bool const & NodeLabels=False)
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
Desc: TStr const &
NodeLabels: bool const &
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm, TStr Desc=TStr())
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
Desc: TStr const &
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm)
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
DrawGViz(PNEANet Graph, TGVizLayout const & Layout, TStr PltFNm, TStr Desc, TIntStrH const & NodeLabelH)
Parameters:
Graph: TPt< TNEANet > const &
Layout: TGVizLayout const &
PltFNm: TStr const &
Desc: TStr const &
NodeLabelH: TIntStrH const &
"""
return _snap.DrawGViz(*args)
def GetClustCf(*args):
"""
GetClustCf(PNEANet Graph, int SampleNodes=-1) -> double
Parameters:
Graph: TPt< TNEANet > const &
SampleNodes: int
GetClustCf(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
GetClustCf(PNEANet Graph, TFltPrV & DegToCCfV, int SampleNodes=-1) -> double
Parameters:
Graph: TPt< TNEANet > const &
DegToCCfV: TFltPrV &
SampleNodes: int
GetClustCf(PNEANet Graph, TFltPrV & DegToCCfV) -> double
Parameters:
Graph: TPt< TNEANet > const &
DegToCCfV: TFltPrV &
GetClustCf(PNEANet Graph, TFltPrV & DegToCCfV, int64 & ClosedTriads, int64 & OpenTriads, int SampleNodes=-1) -> double
Parameters:
Graph: TPt< TNEANet > const &
DegToCCfV: TFltPrV &
ClosedTriads: int64 &
OpenTriads: int64 &
SampleNodes: int
GetClustCf(PNEANet Graph, TFltPrV & DegToCCfV, int64 & ClosedTriads, int64 & OpenTriads) -> double
Parameters:
Graph: TPt< TNEANet > const &
DegToCCfV: TFltPrV &
ClosedTriads: int64 &
OpenTriads: int64 &
"""
return _snap.GetClustCf(*args)
def GetNodeClustCf(*args):
"""
GetNodeClustCf(PNEANet Graph, int const & NId) -> double
Parameters:
Graph: TPt< TNEANet > const &
NId: int const &
GetNodeClustCf(PNEANet Graph, TIntFltH & NIdCCfH)
Parameters:
Graph: TPt< TNEANet > const &
NIdCCfH: TIntFltH &
"""
return _snap.GetNodeClustCf(*args)
def GetTriads(*args):
"""
GetTriads(PNEANet Graph, int SampleNodes=-1) -> int64
Parameters:
Graph: TPt< TNEANet > const &
SampleNodes: int
GetTriads(PNEANet Graph) -> int64
Parameters:
Graph: TPt< TNEANet > const &
GetTriads(PNEANet Graph, int64 & ClosedTriads, int64 & OpenTriads, int SampleNodes) -> int64
Parameters:
Graph: TPt< TNEANet > const &
ClosedTriads: int64 &
OpenTriads: int64 &
SampleNodes: int
GetTriads(PNEANet Graph, TIntTrV & NIdCOTriadV, int SampleNodes=-1)
Parameters:
Graph: TPt< TNEANet > const &
NIdCOTriadV: TIntTrV &
SampleNodes: int
GetTriads(PNEANet Graph, TIntTrV & NIdCOTriadV)
Parameters:
Graph: TPt< TNEANet > const &
NIdCOTriadV: TIntTrV &
"""
return _snap.GetTriads(*args)
def GetTriadEdges(*args):
"""
GetTriadEdges(PNEANet Graph, int SampleEdges=-1) -> int
Parameters:
Graph: TPt< TNEANet > const &
SampleEdges: int
GetTriadEdges(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetTriadEdges(*args)
def GetTriadParticip(*args):
"""
GetTriadParticip(PNEANet Graph, TIntPrV & TriadCntV)
Parameters:
Graph: TPt< TNEANet > const &
TriadCntV: TIntPrV &
"""
return _snap.GetTriadParticip(*args)
def GetCmnNbrs(*args):
"""
GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2) -> int
Parameters:
Graph: TPt< TNEANet > const &
NId1: int const &
NId2: int const &
GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2, TIntV NbrV) -> int
Parameters:
Graph: TPt< TNEANet > const &
NId1: int const &
NId2: int const &
NbrV: TIntV &
"""
return _snap.GetCmnNbrs(*args)
def GetModularity(*args):
"""
GetModularity(PNEANet G, TIntV NIdV, int GEdges=-1) -> double
Parameters:
G: TPt< TNEANet > const &
NIdV: TIntV const &
GEdges: int
GetModularity(PNEANet G, TIntV NIdV) -> double
Parameters:
G: TPt< TNEANet > const &
NIdV: TIntV const &
GetModularity(PNEANet G, TCnComV const & CmtyV, int GEdges=-1) -> double
Parameters:
G: TPt< TNEANet > const &
CmtyV: TCnComV const &
GEdges: int
GetModularity(PNEANet G, TCnComV const & CmtyV) -> double
Parameters:
G: TPt< TNEANet > const &
CmtyV: TCnComV const &
"""
return _snap.GetModularity(*args)
def GetEdgesInOut(*args):
"""
GetEdgesInOut(PNEANet Graph, TIntV NIdV, int & EdgesIn, int & EdgesOut)
Parameters:
Graph: TPt< TNEANet > const &
NIdV: TIntV const &
EdgesIn: int &
EdgesOut: int &
"""
return _snap.GetEdgesInOut(*args)
def GetAnf(*args):
"""
GetAnf(PNEANet Graph, int const & SrcNId, TIntFltKdV & DistNbrsV, int const & MxDist, bool const & IsDir,
int const & NApprox=32)
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
DistNbrsV: TIntFltKdV &
MxDist: int const &
IsDir: bool const &
NApprox: int const &
GetAnf(PNEANet Graph, int const & SrcNId, TIntFltKdV & DistNbrsV, int const & MxDist, bool const & IsDir)
Parameters:
Graph: TPt< TNEANet > const &
SrcNId: int const &
DistNbrsV: TIntFltKdV &
MxDist: int const &
IsDir: bool const &
GetAnf(PNEANet Graph, TIntFltKdV & DistNbrsV, int const & MxDist, bool const & IsDir, int const & NApprox=32)
Parameters:
Graph: TPt< TNEANet > const &
DistNbrsV: TIntFltKdV &
MxDist: int const &
IsDir: bool const &
NApprox: int const &
GetAnf(PNEANet Graph, TIntFltKdV & DistNbrsV, int const & MxDist, bool const & IsDir)
Parameters:
Graph: TPt< TNEANet > const &
DistNbrsV: TIntFltKdV &
MxDist: int const &
IsDir: bool const &
"""
return _snap.GetAnf(*args)
def GetAnfEffDiam(*args):
"""
GetAnfEffDiam(PNEANet Graph, bool const & IsDir, double const & Percentile, int const & NApprox) -> double
Parameters:
Graph: TPt< TNEANet > const &
IsDir: bool const &
Percentile: double const &
NApprox: int const &
GetAnfEffDiam(PNEANet Graph, int const NRuns=1, int NApprox=-1) -> double
Parameters:
Graph: TPt< TNEANet > const &
NRuns: int const
NApprox: int
GetAnfEffDiam(PNEANet Graph, int const NRuns=1) -> double
Parameters:
Graph: TPt< TNEANet > const &
NRuns: int const
GetAnfEffDiam(PNEANet Graph) -> double
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetAnfEffDiam(*args) | 0.404037 | 0.111338 |
import socket
from uasync import Promise
class AsyncSocket:
def __init__(self, sock):
self.sock = sock
self.current_task = None
self.ready = False
self.sock.setblocking(False)
def ready_callback(sock):
self.ready = True
if self.current_task:
task = self.current_task
self.current_task = None
task()
self.sock.setsockopt(socket.SOL_SOCKET, 20, ready_callback)
def send(self, data):
self.sock.setblocking(True)
self.sock.send(data)
self.sock.setblocking(False)
def sendall(self, data):
self.sock.setblocking(True)
self.sock.sendall(data)
self.sock.setblocking(False)
def close(self):
self.sock.close()
def wait(self):
def wrapper(resolve, _reject):
if self.ready:
resolve()
if self.current_task is not None:
raise RuntimeError("Cannot have multiple socket waits")
self.current_task = resolve
return Promise(wrapper)
async def _readinto(self, buffer, length):
if not self.ready:
await self.wait()
read = self.sock.readinto(buffer, length)
if read == length or read == 0:
return read
if read is None:
read = 0
self.ready = False
read += await self.readinto(buffer[read:], length-read)
return read
def readinto(self, buffer, length):
if not isinstance(buffer, memoryview):
buffer = memoryview(buffer)
return self._readinto(buffer, length)
async def recv(self, length):
buffer = memoryview(bytearray(length))
read = await self._readinto(buffer, length)
if read < length:
buffer = buffer[:read]
return buffer
def connect(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0][-1])
return AsyncSocket(s)
async def simple_http_request(address, path="/"):
s = connect(address, 80)
try:
s.send(f"GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n".encode('ascii'))
result = await s.recv(1024)
finally:
s.close()
return bytes(result).split(b"\r\n\r\n", 1)[-1].decode('utf-8') | server/asocket.py | import socket
from uasync import Promise
class AsyncSocket:
def __init__(self, sock):
self.sock = sock
self.current_task = None
self.ready = False
self.sock.setblocking(False)
def ready_callback(sock):
self.ready = True
if self.current_task:
task = self.current_task
self.current_task = None
task()
self.sock.setsockopt(socket.SOL_SOCKET, 20, ready_callback)
def send(self, data):
self.sock.setblocking(True)
self.sock.send(data)
self.sock.setblocking(False)
def sendall(self, data):
self.sock.setblocking(True)
self.sock.sendall(data)
self.sock.setblocking(False)
def close(self):
self.sock.close()
def wait(self):
def wrapper(resolve, _reject):
if self.ready:
resolve()
if self.current_task is not None:
raise RuntimeError("Cannot have multiple socket waits")
self.current_task = resolve
return Promise(wrapper)
async def _readinto(self, buffer, length):
if not self.ready:
await self.wait()
read = self.sock.readinto(buffer, length)
if read == length or read == 0:
return read
if read is None:
read = 0
self.ready = False
read += await self.readinto(buffer[read:], length-read)
return read
def readinto(self, buffer, length):
if not isinstance(buffer, memoryview):
buffer = memoryview(buffer)
return self._readinto(buffer, length)
async def recv(self, length):
buffer = memoryview(bytearray(length))
read = await self._readinto(buffer, length)
if read < length:
buffer = buffer[:read]
return buffer
def connect(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0][-1])
return AsyncSocket(s)
async def simple_http_request(address, path="/"):
s = connect(address, 80)
try:
s.send(f"GET {path} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n".encode('ascii'))
result = await s.recv(1024)
finally:
s.close()
return bytes(result).split(b"\r\n\r\n", 1)[-1].decode('utf-8') | 0.391871 | 0.070208 |
import asyncio
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
from typing import List, Set
import arrow
import asyncpg
import psutil
from bot import run_cluster
from classyjson import ClassyDict
from util.code import execute_code, format_exception
from util.cooldowns import CooldownManager, MaxConcurrencyManager
from util.ipc import PacketHandlerRegistry, PacketType, Server, handle_packet
from util.misc import MultiLock
from util.setup import load_data, load_secrets, setup_karen_logging
class MechaKaren(PacketHandlerRegistry):
class Share:
def __init__(self):
self.start_time = arrow.utcnow()
self.mine_commands = defaultdict(int) # {user_id: command_count}, also used for fishing btw
self.trivia_commands = defaultdict(int) # {user_id: trivia_command_count}
self.active_effects = defaultdict(set) # {user_id: [effect, potion, effect,..]}
self.pillages = defaultdict(int) # {user_id: num_successful_pillages}
self.econ_paused_users = {} # {user_id: time.time()}
def __init__(self):
self.k = load_secrets()
self.d = load_data()
self.v = self.Share()
self.logger = setup_karen_logging()
self.db: asyncpg.Pool = None
self.cooldowns = CooldownManager(self.d.cooldown_rates)
self.concurrency = MaxConcurrencyManager()
self.pillage_lock = MultiLock()
self.server = Server(self.k.manager.host, self.k.manager.port, self.k.manager.auth, self.get_packet_handlers())
self.shard_ids = list(range(self.k.shard_count))
self.online_clusters: Set[int] = set()
self.eval_env = {"karen": self, **self.v.__dict__}
self.broadcasts = {} # {broadcast_id: {ready: asyncio.Event, responses: [response, response,..]}}
self.dm_messages = {} # {user_id: {event: asyncio.Event, content: "contents of message"}}
self.current_id = 0
self.commands = defaultdict(int)
self.commands_lock = asyncio.Lock()
self.commands_task = None
self.heal_users_task = None
self.clear_trivia_commands_task = None
self.reminders_task = None
@handle_packet(PacketType.MISSING_PACKET)
async def handle_missing_packet(self, packet: ClassyDict):
try:
packet_type = PacketType(packet.get("type"))
except ValueError:
packet_type = packet.get("type")
self.logger.error(f"Missing packet handler for packet type {packet_type}")
@handle_packet(PacketType.CLUSTER_READY)
async def handle_cluster_ready_packet(self, packet: ClassyDict):
self.online_clusters.add(packet.cluster_id)
if len(self.online_clusters) == self.k.cluster_count:
self.logger.info(f"\u001b[36;1mALL CLUSTERS\u001b[0m [0-{self.k.cluster_count-1}] \u001b[36;1mREADY\u001b[0m")
@handle_packet(PacketType.EVAL)
async def handle_eval_packet(self, packet: ClassyDict):
try:
result = eval(packet.code, self.eval_env)
success = True
except Exception as e:
result = format_exception(e)
success = False
self.logger.error(result)
return {"type": PacketType.EVAL_RESPONSE, "result": result, "success": success}
@handle_packet(PacketType.EXEC)
async def handle_exec_packet(self, packet: ClassyDict):
try:
result = await execute_code(packet.code, self.eval_env)
success = True
except Exception as e:
result = format_exception(e)
success = False
self.logger.error(result)
return {"type": PacketType.EXEC_RESPONSE, "result": result, "success": success}
@handle_packet(PacketType.BROADCAST_REQUEST)
async def handle_broadcast_request_packet(self, packet: ClassyDict):
"""broadcasts the packet to every connection including the broadcaster, and waits for responses"""
broadcast_id = f"b{self.current_id}"
self.current_id += 1
broadcast_packet = {**packet.packet, "id": broadcast_id}
broadcast_coros = [s.write_packet(broadcast_packet) for s in self.server.connections]
broadcast = self.broadcasts[broadcast_id] = {
"ready": asyncio.Event(),
"responses": [],
"expects": len(broadcast_coros),
}
await asyncio.wait(broadcast_coros)
await broadcast["ready"].wait()
return {"type": PacketType.BROADCAST_RESPONSE, "responses": broadcast["responses"]}
@handle_packet(PacketType.BROADCAST_RESPONSE)
async def handle_broadcast_response_packet(self, packet: ClassyDict):
broadcast = self.broadcasts[packet.id]
broadcast["responses"].append(packet)
if len(broadcast["responses"]) == broadcast["expects"]:
broadcast["ready"].set()
@handle_packet(PacketType.COOLDOWN)
async def handle_cooldown_packet(self, packet: ClassyDict):
cooldown_info = self.cooldowns.check(packet.command, packet.user_id)
return {"type": PacketType.COOLDOWN_RESPONSE, **cooldown_info}
@handle_packet(PacketType.COOLDOWN_ADD)
async def handle_cooldown_add_packet(self, packet: ClassyDict):
self.cooldowns.add_cooldown(packet.command, packet.user_id)
@handle_packet(PacketType.COOLDOWN_RESET)
async def handle_cooldown_reset_packet(self, packet: ClassyDict):
self.cooldowns.clear_cooldown(packet.command, packet.user_id)
@handle_packet(PacketType.DM_MESSAGE_REQUEST)
async def handle_dm_message_request_packet(self, packet: ClassyDict):
entry = self.dm_messages[packet.user_id] = {"event": asyncio.Event(), "content": None}
await entry["event"].wait()
self.dm_messages.pop(packet.user_id, None)
return {"type": PacketType.DM_MESSAGE, "content": entry["content"]}
@handle_packet(PacketType.DM_MESSAGE)
async def handle_dm_message_packet(self, packet: ClassyDict):
entry = self.dm_messages.get(packet.user_id)
if entry is None:
return
entry["content"] = packet.content
entry["event"].set()
@handle_packet(PacketType.MINE_COMMAND)
async def handle_mine_command_packet(self, packet: ClassyDict): # used for fishing too
self.v.mine_commands[packet.user_id] += packet.addition
return {"type": PacketType.MINE_COMMAND_RESPONSE, "current": self.v.mine_commands[packet.user_id]}
@handle_packet(PacketType.MINE_COMMANDS_RESET)
async def handle_mine_commands_reset_packet(self, packet: ClassyDict):
self.v.mine_commands[packet.user] = 0
@handle_packet(PacketType.CONCURRENCY_CHECK)
async def handle_concurrency_check_packet(self, packet: ClassyDict):
return {
"type": PacketType.CONCURRENCY_CHECK_RESPONSE,
"can_run": self.concurrency.check(packet.command, packet.user_id),
}
@handle_packet(PacketType.CONCURRENCY_ACQUIRE)
async def handle_concurrency_acquire_packet(self, packet: ClassyDict):
self.concurrency.acquire(packet.command, packet.user_id)
@handle_packet(PacketType.CONCURRENCY_RELEASE)
async def handle_concurrency_release_packet(self, packet: ClassyDict):
self.concurrency.release(packet.command, packet.user_id)
@handle_packet(PacketType.COMMAND_RAN)
async def handle_command_ran_packet(self, packet: ClassyDict):
async with self.commands_lock:
self.commands[packet.user_id] += 1
@handle_packet(PacketType.ACQUIRE_PILLAGE_LOCK)
async def handle_acquire_pillage_lock_packet(self, packet: ClassyDict):
await self.pillage_lock.acquire(packet.user_ids)
return {}
@handle_packet(PacketType.RELEASE_PILLAGE_LOCK)
async def handle_release_pillage_lock_packet(self, packet: ClassyDict):
self.pillage_lock.release(packet.user_ids)
@handle_packet(PacketType.PILLAGE)
async def handle_pillage_packet(self, packet: ClassyDict):
self.v.pillages[packet.pillager] += 1
return {"pillager": self.v.pillages[packet.pillager] - 1, "victim": self.v.pillages[packet.victim] - 1}
@handle_packet(PacketType.FETCH_STATS)
async def handle_fetch_stats_packet(self, packet: ClassyDict):
proc = psutil.Process()
with proc.oneshot():
mem_usage = proc.memory_full_info().uss
threads = proc.num_threads()
return {"type": PacketType.STATS_RESPONSE, "stats": [mem_usage, threads, len(asyncio.all_tasks())] + [0] * 7}
@handle_packet(PacketType.TRIVIA)
async def handle_trivia_packet(self, packet: ClassyDict):
self.v.trivia_commands[packet.author] += 1
return {"do_reward": self.v.trivia_commands[packet.author] < 5}
async def commands_dump_loop(self):
try:
while True:
await asyncio.sleep(60)
if self.commands:
async with self.commands_lock:
commands_dump = list(self.commands.items())
user_ids = [(user_id,) for user_id in list(self.commands.keys())]
self.commands.clear()
await self.db.executemany(
'INSERT INTO users (user_id) VALUES ($1) ON CONFLICT ("user_id") DO NOTHING', user_ids
) # ensure users are in the database first
await self.db.executemany(
'INSERT INTO leaderboards (user_id, commands) VALUES ($1, $2) ON CONFLICT ("user_id") DO UPDATE SET "commands" = leaderboards.commands + $2 WHERE leaderboards.user_id = $1',
commands_dump,
)
except Exception as e:
self.logger.error(format_exception(e))
async def heal_users_loop(self):
while True:
await asyncio.sleep(32)
try:
await self.db.execute("UPDATE users SET health = health + 1 WHERE health < 20")
except Exception as e:
self.logger.error(format_exception(e))
async def clear_trivia_commands_loop(self):
while True:
await asyncio.sleep(10 * 60)
try:
self.v.trivia_commands.clear()
except Exception as e:
self.logger.error(format_exception(e))
async def remind_reminders_loop(self):
while True:
await asyncio.sleep(5)
try:
reminders = await self.db.fetch(
"DELETE FROM reminders WHERE at <= NOW() RETURNING channel_id, user_id, message_id, reminder"
)
for reminder in reminders:
broadcast_id = f"b{self.current_id}"
self.current_id += 1
broadcast_packet = {"type": PacketType.REMINDER, "id": broadcast_id, **reminder}
broadcast_coros = [s.write_packet(broadcast_packet) for s in self.server.connections]
broadcast = self.broadcasts[broadcast_id] = {
"ready": asyncio.Event(),
"responses": [],
"expects": len(broadcast_coros),
}
await asyncio.wait(broadcast_coros)
await broadcast["ready"].wait()
except Exception as e:
self.logger.error(format_exception(e))
with open("reminderrors.txt", "a+") as f:
f.write("\n" + format_exception(e) + "\n")
async def start(self, pp):
self.db = await asyncpg.create_pool(
host=self.k.database.host, # where db is hosted
database=self.k.database.name, # name of database
user=self.k.database.user, # database username
password=self.<PASSWORD>, # password which goes with user
max_size=3,
min_size=1,
)
await self.server.start()
self.cooldowns.start()
self.commands_task = asyncio.create_task(self.commands_dump_loop())
self.heal_users_task = asyncio.create_task(self.heal_users_loop())
self.clear_trivia_commands_task = asyncio.create_task(self.clear_trivia_commands_loop())
self.reminders_task = asyncio.create_task(self.remind_reminders_loop())
loop = asyncio.get_event_loop()
# calculate max connections to the db server per process allowed
# postgresql is usually configured to allow 100 max, so we use
# 75 to leave room for other stuff using the db server
db_pool_size_per: int = 75 // self.k.cluster_count
cluster_size: int = self.k.shard_count // self.k.cluster_count # how many shards per cluster
clusters: List[asyncio.Future] = []
shard_ids_chunked = [self.shard_ids[i : i + cluster_size] for i in range(0, self.k.shard_count, cluster_size)]
# create and run clusters
for cluster_id, shard_ids in enumerate(shard_ids_chunked):
clusters.append(loop.run_in_executor(pp, run_cluster, cluster_id, self.k.shard_count, shard_ids, db_pool_size_per))
await asyncio.wait(clusters)
self.cooldowns.stop()
self.commands_task.cancel()
self.heal_users_task.cancel()
self.clear_trivia_commands_task.cancel()
self.reminders_task.cancel()
await self.db.close()
def run(self):
with ProcessPoolExecutor(self.k.cluster_count) as pp:
asyncio.run(self.start(pp)) | villager-bot/karen.py | import asyncio
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
from typing import List, Set
import arrow
import asyncpg
import psutil
from bot import run_cluster
from classyjson import ClassyDict
from util.code import execute_code, format_exception
from util.cooldowns import CooldownManager, MaxConcurrencyManager
from util.ipc import PacketHandlerRegistry, PacketType, Server, handle_packet
from util.misc import MultiLock
from util.setup import load_data, load_secrets, setup_karen_logging
class MechaKaren(PacketHandlerRegistry):
class Share:
def __init__(self):
self.start_time = arrow.utcnow()
self.mine_commands = defaultdict(int) # {user_id: command_count}, also used for fishing btw
self.trivia_commands = defaultdict(int) # {user_id: trivia_command_count}
self.active_effects = defaultdict(set) # {user_id: [effect, potion, effect,..]}
self.pillages = defaultdict(int) # {user_id: num_successful_pillages}
self.econ_paused_users = {} # {user_id: time.time()}
def __init__(self):
self.k = load_secrets()
self.d = load_data()
self.v = self.Share()
self.logger = setup_karen_logging()
self.db: asyncpg.Pool = None
self.cooldowns = CooldownManager(self.d.cooldown_rates)
self.concurrency = MaxConcurrencyManager()
self.pillage_lock = MultiLock()
self.server = Server(self.k.manager.host, self.k.manager.port, self.k.manager.auth, self.get_packet_handlers())
self.shard_ids = list(range(self.k.shard_count))
self.online_clusters: Set[int] = set()
self.eval_env = {"karen": self, **self.v.__dict__}
self.broadcasts = {} # {broadcast_id: {ready: asyncio.Event, responses: [response, response,..]}}
self.dm_messages = {} # {user_id: {event: asyncio.Event, content: "contents of message"}}
self.current_id = 0
self.commands = defaultdict(int)
self.commands_lock = asyncio.Lock()
self.commands_task = None
self.heal_users_task = None
self.clear_trivia_commands_task = None
self.reminders_task = None
@handle_packet(PacketType.MISSING_PACKET)
async def handle_missing_packet(self, packet: ClassyDict):
try:
packet_type = PacketType(packet.get("type"))
except ValueError:
packet_type = packet.get("type")
self.logger.error(f"Missing packet handler for packet type {packet_type}")
@handle_packet(PacketType.CLUSTER_READY)
async def handle_cluster_ready_packet(self, packet: ClassyDict):
self.online_clusters.add(packet.cluster_id)
if len(self.online_clusters) == self.k.cluster_count:
self.logger.info(f"\u001b[36;1mALL CLUSTERS\u001b[0m [0-{self.k.cluster_count-1}] \u001b[36;1mREADY\u001b[0m")
@handle_packet(PacketType.EVAL)
async def handle_eval_packet(self, packet: ClassyDict):
try:
result = eval(packet.code, self.eval_env)
success = True
except Exception as e:
result = format_exception(e)
success = False
self.logger.error(result)
return {"type": PacketType.EVAL_RESPONSE, "result": result, "success": success}
@handle_packet(PacketType.EXEC)
async def handle_exec_packet(self, packet: ClassyDict):
try:
result = await execute_code(packet.code, self.eval_env)
success = True
except Exception as e:
result = format_exception(e)
success = False
self.logger.error(result)
return {"type": PacketType.EXEC_RESPONSE, "result": result, "success": success}
@handle_packet(PacketType.BROADCAST_REQUEST)
async def handle_broadcast_request_packet(self, packet: ClassyDict):
"""broadcasts the packet to every connection including the broadcaster, and waits for responses"""
broadcast_id = f"b{self.current_id}"
self.current_id += 1
broadcast_packet = {**packet.packet, "id": broadcast_id}
broadcast_coros = [s.write_packet(broadcast_packet) for s in self.server.connections]
broadcast = self.broadcasts[broadcast_id] = {
"ready": asyncio.Event(),
"responses": [],
"expects": len(broadcast_coros),
}
await asyncio.wait(broadcast_coros)
await broadcast["ready"].wait()
return {"type": PacketType.BROADCAST_RESPONSE, "responses": broadcast["responses"]}
@handle_packet(PacketType.BROADCAST_RESPONSE)
async def handle_broadcast_response_packet(self, packet: ClassyDict):
broadcast = self.broadcasts[packet.id]
broadcast["responses"].append(packet)
if len(broadcast["responses"]) == broadcast["expects"]:
broadcast["ready"].set()
@handle_packet(PacketType.COOLDOWN)
async def handle_cooldown_packet(self, packet: ClassyDict):
cooldown_info = self.cooldowns.check(packet.command, packet.user_id)
return {"type": PacketType.COOLDOWN_RESPONSE, **cooldown_info}
@handle_packet(PacketType.COOLDOWN_ADD)
async def handle_cooldown_add_packet(self, packet: ClassyDict):
self.cooldowns.add_cooldown(packet.command, packet.user_id)
@handle_packet(PacketType.COOLDOWN_RESET)
async def handle_cooldown_reset_packet(self, packet: ClassyDict):
self.cooldowns.clear_cooldown(packet.command, packet.user_id)
@handle_packet(PacketType.DM_MESSAGE_REQUEST)
async def handle_dm_message_request_packet(self, packet: ClassyDict):
entry = self.dm_messages[packet.user_id] = {"event": asyncio.Event(), "content": None}
await entry["event"].wait()
self.dm_messages.pop(packet.user_id, None)
return {"type": PacketType.DM_MESSAGE, "content": entry["content"]}
@handle_packet(PacketType.DM_MESSAGE)
async def handle_dm_message_packet(self, packet: ClassyDict):
entry = self.dm_messages.get(packet.user_id)
if entry is None:
return
entry["content"] = packet.content
entry["event"].set()
@handle_packet(PacketType.MINE_COMMAND)
async def handle_mine_command_packet(self, packet: ClassyDict): # used for fishing too
self.v.mine_commands[packet.user_id] += packet.addition
return {"type": PacketType.MINE_COMMAND_RESPONSE, "current": self.v.mine_commands[packet.user_id]}
@handle_packet(PacketType.MINE_COMMANDS_RESET)
async def handle_mine_commands_reset_packet(self, packet: ClassyDict):
self.v.mine_commands[packet.user] = 0
@handle_packet(PacketType.CONCURRENCY_CHECK)
async def handle_concurrency_check_packet(self, packet: ClassyDict):
return {
"type": PacketType.CONCURRENCY_CHECK_RESPONSE,
"can_run": self.concurrency.check(packet.command, packet.user_id),
}
@handle_packet(PacketType.CONCURRENCY_ACQUIRE)
async def handle_concurrency_acquire_packet(self, packet: ClassyDict):
self.concurrency.acquire(packet.command, packet.user_id)
@handle_packet(PacketType.CONCURRENCY_RELEASE)
async def handle_concurrency_release_packet(self, packet: ClassyDict):
self.concurrency.release(packet.command, packet.user_id)
@handle_packet(PacketType.COMMAND_RAN)
async def handle_command_ran_packet(self, packet: ClassyDict):
async with self.commands_lock:
self.commands[packet.user_id] += 1
@handle_packet(PacketType.ACQUIRE_PILLAGE_LOCK)
async def handle_acquire_pillage_lock_packet(self, packet: ClassyDict):
await self.pillage_lock.acquire(packet.user_ids)
return {}
@handle_packet(PacketType.RELEASE_PILLAGE_LOCK)
async def handle_release_pillage_lock_packet(self, packet: ClassyDict):
self.pillage_lock.release(packet.user_ids)
@handle_packet(PacketType.PILLAGE)
async def handle_pillage_packet(self, packet: ClassyDict):
self.v.pillages[packet.pillager] += 1
return {"pillager": self.v.pillages[packet.pillager] - 1, "victim": self.v.pillages[packet.victim] - 1}
@handle_packet(PacketType.FETCH_STATS)
async def handle_fetch_stats_packet(self, packet: ClassyDict):
proc = psutil.Process()
with proc.oneshot():
mem_usage = proc.memory_full_info().uss
threads = proc.num_threads()
return {"type": PacketType.STATS_RESPONSE, "stats": [mem_usage, threads, len(asyncio.all_tasks())] + [0] * 7}
@handle_packet(PacketType.TRIVIA)
async def handle_trivia_packet(self, packet: ClassyDict):
self.v.trivia_commands[packet.author] += 1
return {"do_reward": self.v.trivia_commands[packet.author] < 5}
async def commands_dump_loop(self):
try:
while True:
await asyncio.sleep(60)
if self.commands:
async with self.commands_lock:
commands_dump = list(self.commands.items())
user_ids = [(user_id,) for user_id in list(self.commands.keys())]
self.commands.clear()
await self.db.executemany(
'INSERT INTO users (user_id) VALUES ($1) ON CONFLICT ("user_id") DO NOTHING', user_ids
) # ensure users are in the database first
await self.db.executemany(
'INSERT INTO leaderboards (user_id, commands) VALUES ($1, $2) ON CONFLICT ("user_id") DO UPDATE SET "commands" = leaderboards.commands + $2 WHERE leaderboards.user_id = $1',
commands_dump,
)
except Exception as e:
self.logger.error(format_exception(e))
async def heal_users_loop(self):
while True:
await asyncio.sleep(32)
try:
await self.db.execute("UPDATE users SET health = health + 1 WHERE health < 20")
except Exception as e:
self.logger.error(format_exception(e))
async def clear_trivia_commands_loop(self):
while True:
await asyncio.sleep(10 * 60)
try:
self.v.trivia_commands.clear()
except Exception as e:
self.logger.error(format_exception(e))
async def remind_reminders_loop(self):
while True:
await asyncio.sleep(5)
try:
reminders = await self.db.fetch(
"DELETE FROM reminders WHERE at <= NOW() RETURNING channel_id, user_id, message_id, reminder"
)
for reminder in reminders:
broadcast_id = f"b{self.current_id}"
self.current_id += 1
broadcast_packet = {"type": PacketType.REMINDER, "id": broadcast_id, **reminder}
broadcast_coros = [s.write_packet(broadcast_packet) for s in self.server.connections]
broadcast = self.broadcasts[broadcast_id] = {
"ready": asyncio.Event(),
"responses": [],
"expects": len(broadcast_coros),
}
await asyncio.wait(broadcast_coros)
await broadcast["ready"].wait()
except Exception as e:
self.logger.error(format_exception(e))
with open("reminderrors.txt", "a+") as f:
f.write("\n" + format_exception(e) + "\n")
async def start(self, pp):
self.db = await asyncpg.create_pool(
host=self.k.database.host, # where db is hosted
database=self.k.database.name, # name of database
user=self.k.database.user, # database username
password=self.<PASSWORD>, # password which goes with user
max_size=3,
min_size=1,
)
await self.server.start()
self.cooldowns.start()
self.commands_task = asyncio.create_task(self.commands_dump_loop())
self.heal_users_task = asyncio.create_task(self.heal_users_loop())
self.clear_trivia_commands_task = asyncio.create_task(self.clear_trivia_commands_loop())
self.reminders_task = asyncio.create_task(self.remind_reminders_loop())
loop = asyncio.get_event_loop()
# calculate max connections to the db server per process allowed
# postgresql is usually configured to allow 100 max, so we use
# 75 to leave room for other stuff using the db server
db_pool_size_per: int = 75 // self.k.cluster_count
cluster_size: int = self.k.shard_count // self.k.cluster_count # how many shards per cluster
clusters: List[asyncio.Future] = []
shard_ids_chunked = [self.shard_ids[i : i + cluster_size] for i in range(0, self.k.shard_count, cluster_size)]
# create and run clusters
for cluster_id, shard_ids in enumerate(shard_ids_chunked):
clusters.append(loop.run_in_executor(pp, run_cluster, cluster_id, self.k.shard_count, shard_ids, db_pool_size_per))
await asyncio.wait(clusters)
self.cooldowns.stop()
self.commands_task.cancel()
self.heal_users_task.cancel()
self.clear_trivia_commands_task.cancel()
self.reminders_task.cancel()
await self.db.close()
def run(self):
with ProcessPoolExecutor(self.k.cluster_count) as pp:
asyncio.run(self.start(pp)) | 0.565539 | 0.12424 |
import csv
import sys
import datetime
import sqlite3
import os
from typing import List, Any, Union, NamedTuple, Tuple
from .env import TWDFT_DATA_DIR, INSPECTORS
def conv_site_name_to_id(site: str) -> str:
db_filename = "twdft.db"
db_path = os.path.join(TWDFT_DATA_DIR, db_filename)
with sqlite3.connect(db_path) as conn:
c = conn.cursor()
return c.execute(f"SELECT id FROM site WHERE name={site}")
def create_db_entry(
site: str,
inspection_date: str,
inspection_time: str,
inspection_status: str,
inspectors: Tuple[str],
) -> None:
"""Create an inspection object in the database."""
db_filename = "twdft.db"
db_path = os.path.join(TWDFT_DATA_DIR, db_filename)
with sqlite3.connect(db_path) as conn:
c = conn.cursor()
site_id = c.execute(f'SELECT id FROM site WHERE name="{site}"').fetchone()[0]
data = (site_id, inspection_date, inspection_status, inspection_time)
c.execute(
f"""INSERT INTO inspection(
site,
date,
status,
time) VALUES (?,?,?,?)""",
data,
)
insp_id = c.lastrowid
inspector_ids = [
c.execute("SELECT id FROM inspector WHERE first_name=?", (x,)).fetchone()[0]
for x in inspectors
]
for iid in inspector_ids:
c.execute(
"INSERT INTO inspector_inspections(inspector, inspection) VALUES (?,?)",
(iid, insp_id),
)
class Site(NamedTuple):
id: str
name: str
site_type: str
sub_category: str
address_1: str
address_2: str
town: str
county: str
country: str
postcode: str
site_category: str
freq_target: str
created: str
notes: str
last_inspection: str
next_inspection: str
pfsp_approval: str
pfsp_expiry: str
unlocode: str
pfso: str
pso: str
pfsa_approval: str
pfsa_expiry: str
team: str
created_by: str
last_updated: str
updated_by: str
afp_loc: str
rdf: str
classification: str
article24: str
psa_approval: str
inspection_due: str
def clean_inspection_freq_data(
data: list, sortkey: str, limit: int, filter: str
) -> tuple:
"""
takes a list of (site_name, last_inspection, frequence_target)
tuples and converts t[x] into a date and t[2] into an integer.
"""
SORT_KEYS = {"last_inspection": 1, "freq_target": 2, "days_since": 4, "along": 5}
errors = []
out = []
for t in data:
frequency_target = int(t[2])
days_in_freq = days_in_frequency_target(frequency_target)
try:
d_obj = convert_date_str(t[1])
days = days_since(d_obj).days
county = t[3]
percent_along_frequency_period = int((days / days_in_freq) * 100)
if filter:
if filter in t[0]:
out.append(
(
t[0],
d_obj,
frequency_target,
county,
days,
percent_along_frequency_period,
)
)
else:
out.append(
(
t[0],
d_obj,
frequency_target,
county,
days,
percent_along_frequency_period,
)
)
out = sorted(out, key=lambda item: item[SORT_KEYS[sortkey]], reverse=True)
except ValueError:
errors.append(t)
if limit:
out = out[:limit]
return errors, out
def get_inspection_periods_all_sites(db_name, team: str) -> List[Any]:
"""
Provide data for how a single site fairs in terms
of inspection frequency.
"""
db_file = os.path.join(TWDFT_DATA_DIR, db_name)
try:
conn = sqlite3.connect(db_file)
except FileNotFoundError:
raise
c = conn.cursor()
if not team:
c.execute("SELECT name, last_inspection, freq_target, county FROM site WHERE NOT site_type =\"PSA\"")
else:
team = " ".join(["Maritime", team])
c.execute("SELECT name, last_inspection, freq_target, county FROM site WHERE team=? AND NOT site_type =\"PSA\" AND rdf=0", (team,))
result = c.fetchall()
conn.close()
return result
def get_inspection_periods(db_name, site_name) -> tuple:
"""
Provide data for how a single site fairs in terms
of inspection frequency.
"""
db_file = os.path.join(TWDFT_DATA_DIR, db_name)
try:
conn = sqlite3.connect(db_file)
except FileNotFoundError:
raise
c = conn.cursor()
c.execute(
"SELECT last_inspection, frequency_target FROM inspections WHERE site_name=?",
(site_name,),
)
result = c.fetchone()
conn.close()
return result
def initial_db_setup() -> None:
"""
Initial db file set up.
"""
db_filename = "twdft.db"
db_path = os.path.join(TWDFT_DATA_DIR, db_filename)
csv_filename = "sites.csv"
csv_path = os.path.join(TWDFT_DATA_DIR, csv_filename)
db_is_new = not os.path.exists(db_path)
sites_csv = os.path.join(TWDFT_DATA_DIR, csv_filename)
if db_is_new:
with sqlite3.connect(db_path) as conn:
c = conn.cursor()
# first we create a site object
c.execute(
"""
CREATE TABLE site(
id INTEGER PRIMARY KEY,
name TEXT,
site_type TEXT,
sub_category TEXT,
address_1 TEXT,
address_2 TEXT,
town TEXT,
county TEXT,
country TEXT,
postcode TEXT,
site_category TEXT,
freq_target TEXT,
created TEXT,
notes TEXT,
last_inspection TEXT,
next_inspection TEXT,
pfsp_approval TEXT,
pfsp_expiry TEXT,
unlocode TEXT,
pfso TEXT,
pso TEXT,
pfsa_approval TEXT,
pfsa_expiry TEXT,
team TEXT,
created_by TEXT,
last_updated TEXT,
updated_by TEXT,
afp_loc TEXT,
rdf TEXT,
classification TEXT,
article24 TEXT,
psa_approval TEXT,
inspection_due TEXT
)
"""
)
conn.commit()
# next we want an inspection table
c.execute(
"""
CREATE TABLE inspection(
id INTEGER PRIMARY KEY,
site INTEGER,
date TEXT,
status TEXT,
time TEXT,
FOREIGN KEY(site) REFERENCES site(id)
)
"""
)
conn.commit()
# next we want an inspector table
c.execute(
"""
create table inspector(
id integer primary key,
first_name text,
last_name text
)
"""
)
conn.commit()
for i in INSPECTORS:
first = i.split(" ")[0]
last = i.split(" ")[1]
c.execute(
"INSERT INTO inspector(first_name, last_name) VALUES (?,?)",
(first, last),
)
# a table that links inspectors with inspections
c.execute(
"""
CREATE TABLE inspector_inspections(
inspector INTEGER,
inspection INTEGER,
FOREIGN KEY (inspector) REFERENCES inspector(id),
FOREIGN KEY (inspection) REFERENCES inspection(id)
)
"""
)
conn.commit()
for site in map(Site._make, csv.reader(open(csv_path, "r"))):
try:
c.execute(
f"""
INSERT INTO site VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
int(site.id.replace(",", "")),
site.name,
site.site_type,
site.sub_category,
site.address_1,
site.address_2,
site.town,
site.county,
site.country,
site.postcode,
site.site_category,
site.freq_target,
site.created,
site.notes,
site.last_inspection,
site.next_inspection,
site.pfsp_approval,
site.pfsp_expiry,
site.unlocode,
site.pfso,
site.pso,
site.pfsa_approval,
site.pfsa_expiry,
site.team,
site.created_by,
site.last_updated,
site.updated_by,
site.afp_loc,
site.rdf,
site.classification,
site.article24,
site.psa_approval,
site.inspection_due,
),
)
except sqlite3.IntegrityError as e:
print("That hasnae worked", site.inspection_due)
def convert_date_str(date_str: str) -> datetime.date:
"Convert from this 16-06-2016 0:00 into a date object."
date_str = date_str.split(" ")[0]
date_str_l: Union[List[str], List[int]] = date_str.split("-")
try:
date_str_l = [int(x) for x in date_str_l]
except ValueError:
raise
date_str_l = [date_str_l[2], date_str_l[1], date_str_l[0]]
return datetime.date(*date_str_l)
def days_since(d: datetime.date) -> datetime.timedelta:
"Returns number of days since a date."
return datetime.date.today() - d
def days_in_frequency_target(target: int) -> int:
"""
Returns number in a frequence period.
e.g. in Mallard, frequence period may be 12, 6,
18, etc to represent the numbner of months between
inspections - ideally. We are simply converting
that to days.
"""
return int((target / 12) * 365) | twdft/database.py | import csv
import sys
import datetime
import sqlite3
import os
from typing import List, Any, Union, NamedTuple, Tuple
from .env import TWDFT_DATA_DIR, INSPECTORS
def conv_site_name_to_id(site: str) -> str:
db_filename = "twdft.db"
db_path = os.path.join(TWDFT_DATA_DIR, db_filename)
with sqlite3.connect(db_path) as conn:
c = conn.cursor()
return c.execute(f"SELECT id FROM site WHERE name={site}")
def create_db_entry(
site: str,
inspection_date: str,
inspection_time: str,
inspection_status: str,
inspectors: Tuple[str],
) -> None:
"""Create an inspection object in the database."""
db_filename = "twdft.db"
db_path = os.path.join(TWDFT_DATA_DIR, db_filename)
with sqlite3.connect(db_path) as conn:
c = conn.cursor()
site_id = c.execute(f'SELECT id FROM site WHERE name="{site}"').fetchone()[0]
data = (site_id, inspection_date, inspection_status, inspection_time)
c.execute(
f"""INSERT INTO inspection(
site,
date,
status,
time) VALUES (?,?,?,?)""",
data,
)
insp_id = c.lastrowid
inspector_ids = [
c.execute("SELECT id FROM inspector WHERE first_name=?", (x,)).fetchone()[0]
for x in inspectors
]
for iid in inspector_ids:
c.execute(
"INSERT INTO inspector_inspections(inspector, inspection) VALUES (?,?)",
(iid, insp_id),
)
class Site(NamedTuple):
id: str
name: str
site_type: str
sub_category: str
address_1: str
address_2: str
town: str
county: str
country: str
postcode: str
site_category: str
freq_target: str
created: str
notes: str
last_inspection: str
next_inspection: str
pfsp_approval: str
pfsp_expiry: str
unlocode: str
pfso: str
pso: str
pfsa_approval: str
pfsa_expiry: str
team: str
created_by: str
last_updated: str
updated_by: str
afp_loc: str
rdf: str
classification: str
article24: str
psa_approval: str
inspection_due: str
def clean_inspection_freq_data(
data: list, sortkey: str, limit: int, filter: str
) -> tuple:
"""
takes a list of (site_name, last_inspection, frequence_target)
tuples and converts t[x] into a date and t[2] into an integer.
"""
SORT_KEYS = {"last_inspection": 1, "freq_target": 2, "days_since": 4, "along": 5}
errors = []
out = []
for t in data:
frequency_target = int(t[2])
days_in_freq = days_in_frequency_target(frequency_target)
try:
d_obj = convert_date_str(t[1])
days = days_since(d_obj).days
county = t[3]
percent_along_frequency_period = int((days / days_in_freq) * 100)
if filter:
if filter in t[0]:
out.append(
(
t[0],
d_obj,
frequency_target,
county,
days,
percent_along_frequency_period,
)
)
else:
out.append(
(
t[0],
d_obj,
frequency_target,
county,
days,
percent_along_frequency_period,
)
)
out = sorted(out, key=lambda item: item[SORT_KEYS[sortkey]], reverse=True)
except ValueError:
errors.append(t)
if limit:
out = out[:limit]
return errors, out
def get_inspection_periods_all_sites(db_name, team: str) -> List[Any]:
"""
Provide data for how a single site fairs in terms
of inspection frequency.
"""
db_file = os.path.join(TWDFT_DATA_DIR, db_name)
try:
conn = sqlite3.connect(db_file)
except FileNotFoundError:
raise
c = conn.cursor()
if not team:
c.execute("SELECT name, last_inspection, freq_target, county FROM site WHERE NOT site_type =\"PSA\"")
else:
team = " ".join(["Maritime", team])
c.execute("SELECT name, last_inspection, freq_target, county FROM site WHERE team=? AND NOT site_type =\"PSA\" AND rdf=0", (team,))
result = c.fetchall()
conn.close()
return result
def get_inspection_periods(db_name, site_name) -> tuple:
"""
Provide data for how a single site fairs in terms
of inspection frequency.
"""
db_file = os.path.join(TWDFT_DATA_DIR, db_name)
try:
conn = sqlite3.connect(db_file)
except FileNotFoundError:
raise
c = conn.cursor()
c.execute(
"SELECT last_inspection, frequency_target FROM inspections WHERE site_name=?",
(site_name,),
)
result = c.fetchone()
conn.close()
return result
def initial_db_setup() -> None:
"""
Initial db file set up.
"""
db_filename = "twdft.db"
db_path = os.path.join(TWDFT_DATA_DIR, db_filename)
csv_filename = "sites.csv"
csv_path = os.path.join(TWDFT_DATA_DIR, csv_filename)
db_is_new = not os.path.exists(db_path)
sites_csv = os.path.join(TWDFT_DATA_DIR, csv_filename)
if db_is_new:
with sqlite3.connect(db_path) as conn:
c = conn.cursor()
# first we create a site object
c.execute(
"""
CREATE TABLE site(
id INTEGER PRIMARY KEY,
name TEXT,
site_type TEXT,
sub_category TEXT,
address_1 TEXT,
address_2 TEXT,
town TEXT,
county TEXT,
country TEXT,
postcode TEXT,
site_category TEXT,
freq_target TEXT,
created TEXT,
notes TEXT,
last_inspection TEXT,
next_inspection TEXT,
pfsp_approval TEXT,
pfsp_expiry TEXT,
unlocode TEXT,
pfso TEXT,
pso TEXT,
pfsa_approval TEXT,
pfsa_expiry TEXT,
team TEXT,
created_by TEXT,
last_updated TEXT,
updated_by TEXT,
afp_loc TEXT,
rdf TEXT,
classification TEXT,
article24 TEXT,
psa_approval TEXT,
inspection_due TEXT
)
"""
)
conn.commit()
# next we want an inspection table
c.execute(
"""
CREATE TABLE inspection(
id INTEGER PRIMARY KEY,
site INTEGER,
date TEXT,
status TEXT,
time TEXT,
FOREIGN KEY(site) REFERENCES site(id)
)
"""
)
conn.commit()
# next we want an inspector table
c.execute(
"""
create table inspector(
id integer primary key,
first_name text,
last_name text
)
"""
)
conn.commit()
for i in INSPECTORS:
first = i.split(" ")[0]
last = i.split(" ")[1]
c.execute(
"INSERT INTO inspector(first_name, last_name) VALUES (?,?)",
(first, last),
)
# a table that links inspectors with inspections
c.execute(
"""
CREATE TABLE inspector_inspections(
inspector INTEGER,
inspection INTEGER,
FOREIGN KEY (inspector) REFERENCES inspector(id),
FOREIGN KEY (inspection) REFERENCES inspection(id)
)
"""
)
conn.commit()
for site in map(Site._make, csv.reader(open(csv_path, "r"))):
try:
c.execute(
f"""
INSERT INTO site VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
int(site.id.replace(",", "")),
site.name,
site.site_type,
site.sub_category,
site.address_1,
site.address_2,
site.town,
site.county,
site.country,
site.postcode,
site.site_category,
site.freq_target,
site.created,
site.notes,
site.last_inspection,
site.next_inspection,
site.pfsp_approval,
site.pfsp_expiry,
site.unlocode,
site.pfso,
site.pso,
site.pfsa_approval,
site.pfsa_expiry,
site.team,
site.created_by,
site.last_updated,
site.updated_by,
site.afp_loc,
site.rdf,
site.classification,
site.article24,
site.psa_approval,
site.inspection_due,
),
)
except sqlite3.IntegrityError as e:
print("That hasnae worked", site.inspection_due)
def convert_date_str(date_str: str) -> datetime.date:
"Convert from this 16-06-2016 0:00 into a date object."
date_str = date_str.split(" ")[0]
date_str_l: Union[List[str], List[int]] = date_str.split("-")
try:
date_str_l = [int(x) for x in date_str_l]
except ValueError:
raise
date_str_l = [date_str_l[2], date_str_l[1], date_str_l[0]]
return datetime.date(*date_str_l)
def days_since(d: datetime.date) -> datetime.timedelta:
"Returns number of days since a date."
return datetime.date.today() - d
def days_in_frequency_target(target: int) -> int:
"""
Returns number in a frequence period.
e.g. in Mallard, frequence period may be 12, 6,
18, etc to represent the numbner of months between
inspections - ideally. We are simply converting
that to days.
"""
return int((target / 12) * 365) | 0.484868 | 0.191876 |
import os
import logging
import random
from flask import Flask, request
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
logger = logging.getLogger(__name__)
app = Flask(__name__)
moves = ['F', 'T', 'L', 'R']
def my_data(all_data):
my_name = all_data['_links']['self']['href']
my_coord = all_data["arena"]["state"][my_name]
return my_coord, my_name
"""
def if_in_corner(my_coord_x, my_coord_y, arena_max_x, arena_max_y):
if my_coord_x == 0 or my_coord_x == arena_max_x - 1 or my_coord_y == 0 or my_coord_y == arena_max_y - 1:
return True
else:
return False
"""
def get_command(my_direction, my_coord_x, my_coord_y, arena_x, arena_y, all_user_data):
if my_direction == "N":
# X axis constant
# Y decreases as we move forward
if my_coord_y == 0:
return "R"
elif is_someone_present([my_coord_x], [my_coord_y-1, my_coord_y-2, my_coord_y-3], all_user_data):
return "T"
else:
return "F"
elif my_direction == "S":
# X axis constant
# Y increases as we move forward
if my_coord_y == arena_y - 1:
return "R"
elif is_someone_present([my_coord_x], [my_coord_y+1, my_coord_y+2, my_coord_y+3], all_user_data):
return "T"
else:
return "F"
elif my_direction == "E":
# Y axis constant
# X increases as we move forward
if my_coord_x == arena_x - 1:
return "R"
elif is_someone_present([my_coord_x+1, my_coord_x+2, my_coord_x+3], [my_coord_y], all_user_data):
return "T"
else:
return "F"
elif my_direction == "W":
# Y axis constant
# X decreases as we move forward
if my_coord_x == 0:
return "R"
elif is_someone_present([my_coord_x-1, my_coord_x-2, my_coord_x-3], [my_coord_y], all_user_data):
return "T"
else:
return "F"
else:
return moves[random.randrange(len(moves))]
def is_someone_present(possible_points_x, possible_points_y, all_user_data):
for _each_user_name, each_user_stats in all_user_data.items():
if each_user_stats["x"] in possible_points_x and each_user_stats["y"] in possible_points_y:
return True
else:
return False
@app.route("/", methods=['POST'])
def move():
request.get_data()
logger.info(request.json)
my_coord, my_name = my_data(request.json)
arena_x, arena_y = request.json["arena"]["dims"]
return get_command(my_coord['direction'], my_coord['x'], my_coord['y'], arena_x, arena_y, request.json["arena"]["state"])
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0',
port=int(os.environ.get('PORT', 8080))) | samples/python/main.py | import os
import logging
import random
from flask import Flask, request
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
logger = logging.getLogger(__name__)
app = Flask(__name__)
moves = ['F', 'T', 'L', 'R']
def my_data(all_data):
my_name = all_data['_links']['self']['href']
my_coord = all_data["arena"]["state"][my_name]
return my_coord, my_name
"""
def if_in_corner(my_coord_x, my_coord_y, arena_max_x, arena_max_y):
if my_coord_x == 0 or my_coord_x == arena_max_x - 1 or my_coord_y == 0 or my_coord_y == arena_max_y - 1:
return True
else:
return False
"""
def get_command(my_direction, my_coord_x, my_coord_y, arena_x, arena_y, all_user_data):
if my_direction == "N":
# X axis constant
# Y decreases as we move forward
if my_coord_y == 0:
return "R"
elif is_someone_present([my_coord_x], [my_coord_y-1, my_coord_y-2, my_coord_y-3], all_user_data):
return "T"
else:
return "F"
elif my_direction == "S":
# X axis constant
# Y increases as we move forward
if my_coord_y == arena_y - 1:
return "R"
elif is_someone_present([my_coord_x], [my_coord_y+1, my_coord_y+2, my_coord_y+3], all_user_data):
return "T"
else:
return "F"
elif my_direction == "E":
# Y axis constant
# X increases as we move forward
if my_coord_x == arena_x - 1:
return "R"
elif is_someone_present([my_coord_x+1, my_coord_x+2, my_coord_x+3], [my_coord_y], all_user_data):
return "T"
else:
return "F"
elif my_direction == "W":
# Y axis constant
# X decreases as we move forward
if my_coord_x == 0:
return "R"
elif is_someone_present([my_coord_x-1, my_coord_x-2, my_coord_x-3], [my_coord_y], all_user_data):
return "T"
else:
return "F"
else:
return moves[random.randrange(len(moves))]
def is_someone_present(possible_points_x, possible_points_y, all_user_data):
for _each_user_name, each_user_stats in all_user_data.items():
if each_user_stats["x"] in possible_points_x and each_user_stats["y"] in possible_points_y:
return True
else:
return False
@app.route("/", methods=['POST'])
def move():
request.get_data()
logger.info(request.json)
my_coord, my_name = my_data(request.json)
arena_x, arena_y = request.json["arena"]["dims"]
return get_command(my_coord['direction'], my_coord['x'], my_coord['y'], arena_x, arena_y, request.json["arena"]["state"])
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0',
port=int(os.environ.get('PORT', 8080))) | 0.308919 | 0.193642 |
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any, Dict
import aiohttp
from .client import GitHubClient
from .const import (
BASE_GITHUB_URL,
OAUTH_ACCESS_TOKEN_PATH,
OAUTH_DEVICE_LOGIN_PATH,
DeviceFlowError,
GitHubClientKwarg,
GitHubRequestKwarg,
HttpMethod,
)
from .exceptions import GitHubException
from .legacy.device import AIOGitHubAPIDeviceLogin as LegacyAIOGitHubAPIDeviceLogin
from .models.base import GitHubBase
from .models.device_login import GitHubLoginDeviceModel
from .models.login_oauth import GitHubLoginOauthModel
from .models.response import GitHubResponseModel
class AIOGitHubAPIDeviceLogin(LegacyAIOGitHubAPIDeviceLogin):
"""Dummy class to not break existing code."""
class GitHubDeviceAPI(GitHubBase):
"""GitHub API OAuth device flow"""
_close_session = False
def __init__(
self,
client_id: str,
session: aiohttp.ClientSession | None = None,
**kwargs: Dict[GitHubClientKwarg, Any],
):
"""
Initialises a GitHub API OAuth device flow.
**Arguments**:
`client_id` (Optional)
The client ID of your OAuth app.
`session` (Optional)
`aiohttp.ClientSession` to be used by this package.
If you do not pass one, one will be created for you.
`**kwargs` (Optional)
Pass additional arguments.
See the `aiogithubapi.const.GitHubClientKwarg` enum for valid options.
https://docs.github.com/en/developers/apps/authorizing-oauth-apps#device-flow
"""
self.client_id = client_id
self._interval = 5
self._expires = None
if session is None:
session = aiohttp.ClientSession()
self._close_session = True
self._session = session
if GitHubClientKwarg.BASE_URL not in kwargs:
kwargs[GitHubClientKwarg.BASE_URL] = BASE_GITHUB_URL
self._client = GitHubClient(session=session, **kwargs)
async def __aenter__(self) -> GitHubDeviceAPI:
"""Async enter."""
return self
async def __aexit__(self, *exc_info) -> None:
"""Async exit."""
await self.close_session()
async def close_session(self) -> None:
"""Close open client session."""
if self._session and self._close_session:
await self._session.close()
async def register(
self,
**kwargs: Dict[GitHubRequestKwarg, Any],
) -> GitHubResponseModel[GitHubLoginDeviceModel]:
"""Register the device and return a object that contains the user code for authorization."""
response = await self._client.async_call_api(
endpoint=OAUTH_DEVICE_LOGIN_PATH,
**{
**kwargs,
GitHubRequestKwarg.METHOD: HttpMethod.POST,
GitHubRequestKwarg.PARAMS: {
"client_id": self.client_id,
"scope": kwargs.get(GitHubRequestKwarg.SCOPE, ""),
},
},
)
response.data = GitHubLoginDeviceModel(response.data)
self._interval = response.data.interval
self._expires = datetime.timestamp(datetime.now()) + response.data.expires_in
return response
async def activation(
self,
device_code: str,
**kwargs: Dict[GitHubRequestKwarg, Any],
) -> GitHubResponseModel[GitHubLoginOauthModel]:
"""
Wait for the user to enter the code and activate the device.
**Arguments**:
`device_code`
The device_code that was returned when registering the device.
"""
if self._expires is None:
raise GitHubException("Expiration has passed, re-run the registration")
_user_confirmed = None
while _user_confirmed is None:
if self._expires < datetime.timestamp(datetime.now()):
raise GitHubException("User took too long to enter key")
response = await self._client.async_call_api(
endpoint=OAUTH_ACCESS_TOKEN_PATH,
**{
**kwargs,
GitHubRequestKwarg.METHOD: HttpMethod.POST,
GitHubRequestKwarg.PARAMS: {
"client_id": self.client_id,
"device_code": device_code,
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
},
},
)
if error := response.data.get("error"):
if error == DeviceFlowError.AUTHORIZATION_PENDING:
self.logger.debug(response.data.get("error_description"))
await asyncio.sleep(self._interval)
else:
raise GitHubException(response.data.get("error_description"))
else:
response.data = GitHubLoginOauthModel(response.data)
break
return response | aiogithubapi/device.py | from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any, Dict
import aiohttp
from .client import GitHubClient
from .const import (
BASE_GITHUB_URL,
OAUTH_ACCESS_TOKEN_PATH,
OAUTH_DEVICE_LOGIN_PATH,
DeviceFlowError,
GitHubClientKwarg,
GitHubRequestKwarg,
HttpMethod,
)
from .exceptions import GitHubException
from .legacy.device import AIOGitHubAPIDeviceLogin as LegacyAIOGitHubAPIDeviceLogin
from .models.base import GitHubBase
from .models.device_login import GitHubLoginDeviceModel
from .models.login_oauth import GitHubLoginOauthModel
from .models.response import GitHubResponseModel
class AIOGitHubAPIDeviceLogin(LegacyAIOGitHubAPIDeviceLogin):
"""Dummy class to not break existing code."""
class GitHubDeviceAPI(GitHubBase):
"""GitHub API OAuth device flow"""
_close_session = False
def __init__(
self,
client_id: str,
session: aiohttp.ClientSession | None = None,
**kwargs: Dict[GitHubClientKwarg, Any],
):
"""
Initialises a GitHub API OAuth device flow.
**Arguments**:
`client_id` (Optional)
The client ID of your OAuth app.
`session` (Optional)
`aiohttp.ClientSession` to be used by this package.
If you do not pass one, one will be created for you.
`**kwargs` (Optional)
Pass additional arguments.
See the `aiogithubapi.const.GitHubClientKwarg` enum for valid options.
https://docs.github.com/en/developers/apps/authorizing-oauth-apps#device-flow
"""
self.client_id = client_id
self._interval = 5
self._expires = None
if session is None:
session = aiohttp.ClientSession()
self._close_session = True
self._session = session
if GitHubClientKwarg.BASE_URL not in kwargs:
kwargs[GitHubClientKwarg.BASE_URL] = BASE_GITHUB_URL
self._client = GitHubClient(session=session, **kwargs)
async def __aenter__(self) -> GitHubDeviceAPI:
"""Async enter."""
return self
async def __aexit__(self, *exc_info) -> None:
"""Async exit."""
await self.close_session()
async def close_session(self) -> None:
"""Close open client session."""
if self._session and self._close_session:
await self._session.close()
async def register(
self,
**kwargs: Dict[GitHubRequestKwarg, Any],
) -> GitHubResponseModel[GitHubLoginDeviceModel]:
"""Register the device and return a object that contains the user code for authorization."""
response = await self._client.async_call_api(
endpoint=OAUTH_DEVICE_LOGIN_PATH,
**{
**kwargs,
GitHubRequestKwarg.METHOD: HttpMethod.POST,
GitHubRequestKwarg.PARAMS: {
"client_id": self.client_id,
"scope": kwargs.get(GitHubRequestKwarg.SCOPE, ""),
},
},
)
response.data = GitHubLoginDeviceModel(response.data)
self._interval = response.data.interval
self._expires = datetime.timestamp(datetime.now()) + response.data.expires_in
return response
async def activation(
self,
device_code: str,
**kwargs: Dict[GitHubRequestKwarg, Any],
) -> GitHubResponseModel[GitHubLoginOauthModel]:
"""
Wait for the user to enter the code and activate the device.
**Arguments**:
`device_code`
The device_code that was returned when registering the device.
"""
if self._expires is None:
raise GitHubException("Expiration has passed, re-run the registration")
_user_confirmed = None
while _user_confirmed is None:
if self._expires < datetime.timestamp(datetime.now()):
raise GitHubException("User took too long to enter key")
response = await self._client.async_call_api(
endpoint=OAUTH_ACCESS_TOKEN_PATH,
**{
**kwargs,
GitHubRequestKwarg.METHOD: HttpMethod.POST,
GitHubRequestKwarg.PARAMS: {
"client_id": self.client_id,
"device_code": device_code,
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
},
},
)
if error := response.data.get("error"):
if error == DeviceFlowError.AUTHORIZATION_PENDING:
self.logger.debug(response.data.get("error_description"))
await asyncio.sleep(self._interval)
else:
raise GitHubException(response.data.get("error_description"))
else:
response.data = GitHubLoginOauthModel(response.data)
break
return response | 0.682256 | 0.08152 |
from __future__ import print_function
import imp
import fnmatch
import os
import shutil
import subprocess
import sys
import time
from collections import OrderedDict
try:
import configparser
except ImportError:
import ConfigParser as configparser
from . import toml
if 'FileNotFoundError' not in globals():
#pylint:disable=redefined-builtin
FileNotFoundError = IOError
class PManException(Exception):
pass
class NoConfigError(PManException):
pass
class CouldNotFindPythonError(PManException):
pass
class BuildError(PManException):
pass
class FrozenEnvironmentError(PManException):
def __init__(self):
PManException.__init__(self, "Operation not supported in frozen applications")
if '__file__' not in globals():
__IS_FROZEN = True
__file__ = ''
else:
__IS_FROZEN = False
_CONFIG_DEFAULTS = OrderedDict([
('general', OrderedDict([
('name', 'Game'),
('render_plugin', ''),
])),
('build', OrderedDict([
('asset_dir', 'assets/'),
('export_dir', 'game/assets/'),
('ignore_patterns', ['*.blend1', '*.blend2']),
('converter_hooks', ['pman.hooks.converter_blend_bam']),
])),
('run', OrderedDict([
('main_file', 'game/main.py'),
('auto_build', True),
('auto_save', True),
])),
])
_USER_CONFIG_DEFAULTS = OrderedDict([
('blender', OrderedDict([
('last_path', 'blender'),
('use_last_path', True),
])),
('python', OrderedDict([
('path', ''),
])),
])
def _convert_conf_to_toml(configpath):
config = configparser.ConfigParser()
config.read(configpath)
confdict = {
s: dict(config.items(s))
for s in config.sections()
}
if 'build' in confdict:
confdict['build']['ignore_patterns'] = [
i.strip() for i in confdict['build']['ignore_patterns'].split(',')
]
if 'run' in confdict:
confdict['run']['auto_build'] = config.getboolean('run', 'auto_build')
confdict['run']['auto_save'] = config.getboolean('run', 'auto_save')
if 'blender' in confdict:
confdict['blender']['use_last_path'] = config.getboolean('blender', 'use_last_path')
return confdict
def _update_conf(config):
if 'general' in config:
if 'render_plugin' in config['general'] and '/' in config['general']['render_plugin']:
# Convert from path to module
renderplugin = config['general']['render_plugin']
rppath = get_abs_path(config, renderplugin)
maindir = os.path.dirname(get_abs_path(config, config['run']['main_file']))
rppath = os.path.splitext(os.path.relpath(rppath, maindir))[0]
module_parts = rppath.split(os.sep)
modname = '.'.join(module_parts)
config['general']['render_plugin'] = modname
def _get_config(startdir, conf_name, defaults):
try:
if startdir is None:
startdir = os.getcwd()
except FileNotFoundError:
# The project folder was deleted on us
raise NoConfigError("Could not find config file")
dirs = os.path.abspath(startdir).split(os.sep)
while dirs:
cdir = os.sep.join(dirs)
if cdir.strip() and conf_name in os.listdir(cdir):
configpath = os.path.join(cdir, conf_name)
with open(configpath) as f:
confdata = f.read()
istoml = (
'"' in confdata or
"'" in confdata or
confdata == ''
)
if istoml:
confdict = toml.load(configpath)
else:
confdict = _convert_conf_to_toml(configpath)
confdict = {
k: dict(defaults.get(k, {}), **confdict.get(k, {}))
for k in set(defaults.keys()) | set(confdict.keys())
}
confdict['internal'] = {
'projectdir': os.path.dirname(configpath),
}
_update_conf(confdict)
return confdict
dirs.pop()
# No config found
raise NoConfigError("Could not find config file")
def get_config(startdir=None):
return _get_config(startdir, '.pman', _CONFIG_DEFAULTS)
def config_exists(startdir=None):
try:
get_config(startdir)
have_config = True
except NoConfigError:
have_config = False
return have_config
def get_user_config(startdir=None):
try:
return _get_config(startdir, '.pman.user', _USER_CONFIG_DEFAULTS)
except NoConfigError:
# No user config, just create one
config = get_config(startdir)
file_path = os.path.join(config['internal']['projectdir'], '.pman.user')
print("Creating user config at {}".format(file_path))
open(file_path, 'w').close()
return _get_config(startdir, '.pman.user', _USER_CONFIG_DEFAULTS)
def _write_config(config, conf_name):
writecfg = config.copy()
del writecfg['internal']
with open(os.path.join(config['internal']['projectdir'], conf_name), 'w') as f:
toml.dump(writecfg, f)
def write_config(config):
_write_config(config, '.pman')
def write_user_config(user_config):
_write_config(user_config, '.pman.user')
def is_frozen():
return __IS_FROZEN
def create_project(projectdir):
if is_frozen():
raise FrozenEnvironmentError()
confpath = os.path.join(projectdir, '.pman')
if os.path.exists(confpath):
print("Updating project in {}".format(projectdir))
else:
print("Creating new project in {}".format(projectdir))
# Touch config file to make sure it is present
with open(confpath, 'a') as f:
pass
config = get_config(projectdir)
write_config(config)
pmandir = os.path.dirname(__file__)
templatedir = os.path.join(pmandir, 'templates')
bpmodpath = os.path.join(projectdir, 'game/blenderpanda')
print("Creating directories...")
dirs = [
'assets',
'game',
]
bpanda_mod_files = [
os.path.join(templatedir, '__init__.py'),
os.path.join(templatedir, 'bpbase.py'),
]
pman_files = [
'__init__.py',
'rendermanager.py',
'toml.py',
'hooks.py',
'pman_build.py',
]
dirs = [os.path.join(projectdir, i) for i in dirs]
for d in dirs:
if os.path.exists(d):
print("\tSkipping existing directory: {}".format(d))
else:
print("\tCreating directory: {}".format(d))
os.mkdir(d)
print("Creating main.py")
with open(os.path.join(templatedir, 'main.py')) as f:
main_data = f.read()
mainpath = os.path.join(projectdir, 'game', 'main.py')
if os.path.exists(mainpath):
print("\tmain.py already exists at {}".format(mainpath))
else:
with open(mainpath, 'w') as f:
f.write(main_data)
print("\tmain.py created at {}".format(mainpath))
if os.path.exists(bpmodpath):
print("Updating blenderpanda module")
shutil.rmtree(bpmodpath)
else:
print("Creating blenderpanda module")
os.mkdir(bpmodpath)
for copy_file in bpanda_mod_files:
bname = os.path.basename(copy_file)
print("\tCopying over {}".format(bname))
cfsrc = os.path.join(pmandir, copy_file)
cfdst = os.path.join(projectdir, 'game', 'blenderpanda', bname)
print(cfsrc, cfdst)
if os.path.isdir(cfsrc):
shutil.copytree(cfsrc, cfdst)
else:
shutil.copy(cfsrc, cfdst)
print("\t\t{} created at {}".format(bname, cfdst))
print("Copying pman")
pmantarget = os.path.join(bpmodpath, 'pman')
if os.path.exists(pmantarget):
shutil.rmtree(pmantarget)
os.mkdir(pmantarget)
for copy_file in pman_files:
shutil.copy(
os.path.join(pmandir, copy_file),
os.path.join(pmantarget, copy_file)
)
def get_abs_path(config, path):
return PMan(config=config).get_abs_path(path)
def get_rel_path(config, path):
return PMan(config=config).get_rel_path(path)
def get_python_program(config=None):
python_programs = [
'ppython',
'python3',
'python',
'python2',
]
if config is not None:
user_config = get_user_config(config['internal']['projectdir'])
confpy = user_config['python']['path']
if confpy:
python_programs.insert(0, confpy)
# Check to see if there is a version of Python that can import panda3d
for pyprog in python_programs:
args = [
pyprog,
'-c',
'import panda3d.core; import direct',
]
with open(os.devnull, 'w') as f:
try:
retcode = subprocess.call(args, stderr=f)
except FileNotFoundError:
retcode = 1
if retcode == 0:
return pyprog
# We couldn't find a python program to run
raise CouldNotFindPythonError('Could not find a usable Python install')
def load_module(modname, config=None):
return PMan(config=config).load_module(modname)
def build(config=None):
PMan(config=config).build()
def run(config=None):
PMan(config=config).run()
def converter_copy(_config, _user_config, srcdir, dstdir, assets):
for asset in assets:
src = asset
dst = src.replace(srcdir, dstdir)
print('Copying non-blend file from "{}" to "{}"'.format(src, dst))
if not os.path.exists(os.path.dirname(dst)):
os.makedirs(os.path.dirname(dst))
shutil.copyfile(src, dst)
class PMan(object):
def __init__(self, config=None, config_startdir=None):
if config:
self.config = config
self.user_config = get_user_config(config['internal']['projectdir'])
else:
self.config = get_config(config_startdir)
self.user_config = get_user_config(config_startdir)
self.converters = self._init_hooks(self.config['build']['converter_hooks'])
def _init_hooks(self, hooks_list):
new_hooks = []
for hook in hooks_list:
modparts = hook.split('.')
module = '.'.join(modparts[:-1])
func = modparts[-1]
mod = self.load_module(module)
new_hooks.append(getattr(mod, func))
return new_hooks
def get_abs_path(self, path):
return os.path.join(
self.config['internal']['projectdir'],
path
)
def get_rel_path(self, path):
return os.path.relpath(path, self.config['internal']['projectdir'])
def load_module(self, modname):
mod = None
module_parts = modname.split('.')
maindir = os.path.dirname(self.get_abs_path(self.config['run']['main_file']))
pmandir = os.path.dirname(__file__) if not is_frozen() else None
fix_path = False
def _load_module(modname, modinfo):
mod = None
try:
mod = imp.load_module(modname, *modinfo)
finally:
if modinfo[0]:
modinfo[0].close()
return mod
if is_frozen():
modinfo = imp.find_module(modname)
mod = _load_module(modname, modinfo)
else:
if maindir not in sys.path:
sys.path.append(maindir)
fix_path = True
mod = None
for modname in module_parts:
if modname == 'pman':
modpath = [os.path.join(pmandir, '..')]
else:
modpath = None if mod is None else mod.__path__
modinfo = imp.find_module(modname, modpath)
mod = _load_module(modname, modinfo)
if fix_path:
sys.path.remove(maindir)
return mod
def build(self):
if is_frozen():
raise FrozenEnvironmentError()
if hasattr(time, 'perf_counter'):
#pylint:disable=no-member
stime = time.perf_counter()
else:
stime = time.time()
print("Starting build")
srcdir = self.get_abs_path(self.config['build']['asset_dir'])
dstdir = self.get_abs_path(self.config['build']['export_dir'])
if not os.path.exists(srcdir):
raise BuildError("Could not find asset directory: {}".format(srcdir))
if not os.path.exists(dstdir):
print("Creating asset export directory at {}".format(dstdir))
os.makedirs(dstdir)
print("Read assets from: {}".format(srcdir))
print("Export them to: {}".format(dstdir))
ignore_patterns = self.config['build']['ignore_patterns']
print("Ignoring file patterns: {}".format(ignore_patterns))
# Gather files and group by extension
ext_asset_map = {}
ext_dst_map = {}
ext_converter_map = {}
for converter in self.converters:
ext_dst_map.update(converter.ext_dst_map)
for ext in converter.supported_exts:
ext_converter_map[ext] = converter
for root, _dirs, files in os.walk(srcdir):
for asset in files:
src = os.path.join(root, asset)
dst = src.replace(srcdir, dstdir)
ignore_pattern = None
for pattern in ignore_patterns:
if fnmatch.fnmatch(asset, pattern):
ignore_pattern = pattern
break
if ignore_pattern is not None:
print('Skip building file {} that matched ignore pattern {}'.format(asset, ignore_pattern))
continue
ext = os.path.splitext(asset)[1]
if ext in ext_dst_map:
dst = dst.replace(ext, ext_dst_map[ext])
if os.path.exists(dst) and os.stat(src).st_mtime <= os.stat(dst).st_mtime:
print('Skip building up-to-date file: {}'.format(dst))
continue
if ext not in ext_asset_map:
ext_asset_map[ext] = []
print('Adding {} to conversion list to satisfy {}'.format(src, dst))
ext_asset_map[ext].append(os.path.join(root, asset))
# Find which extensions have hooks available
convert_hooks = []
for ext, converter in ext_converter_map.items():
if ext in ext_asset_map:
convert_hooks.append((converter, ext_asset_map[ext]))
del ext_asset_map[ext]
# Copy what is left
for ext in ext_asset_map:
converter_copy(self.config, self.user_config, srcdir, dstdir, ext_asset_map[ext])
# Now run hooks that non-converted assets are in place (copied)
for convert_hook in convert_hooks:
convert_hook[0](self.config, self.user_config, srcdir, dstdir, convert_hook[1])
if hasattr(time, 'perf_counter'):
#pylint:disable=no-member
etime = time.perf_counter()
else:
etime = time.time()
print("Build took {:.4f}s".format(etime - stime))
def run(self):
if is_frozen():
raise FrozenEnvironmentError()
mainfile = self.get_abs_path(self.config['run']['main_file'])
print("Running main file: {}".format(mainfile))
args = [get_python_program(self.config), mainfile]
#print("Args: {}".format(args))
subprocess.Popen(args, cwd=self.config['internal']['projectdir']) | game/blenderpanda/pman/__init__.py | from __future__ import print_function
import imp
import fnmatch
import os
import shutil
import subprocess
import sys
import time
from collections import OrderedDict
try:
import configparser
except ImportError:
import ConfigParser as configparser
from . import toml
if 'FileNotFoundError' not in globals():
#pylint:disable=redefined-builtin
FileNotFoundError = IOError
class PManException(Exception):
pass
class NoConfigError(PManException):
pass
class CouldNotFindPythonError(PManException):
pass
class BuildError(PManException):
pass
class FrozenEnvironmentError(PManException):
def __init__(self):
PManException.__init__(self, "Operation not supported in frozen applications")
if '__file__' not in globals():
__IS_FROZEN = True
__file__ = ''
else:
__IS_FROZEN = False
_CONFIG_DEFAULTS = OrderedDict([
('general', OrderedDict([
('name', 'Game'),
('render_plugin', ''),
])),
('build', OrderedDict([
('asset_dir', 'assets/'),
('export_dir', 'game/assets/'),
('ignore_patterns', ['*.blend1', '*.blend2']),
('converter_hooks', ['pman.hooks.converter_blend_bam']),
])),
('run', OrderedDict([
('main_file', 'game/main.py'),
('auto_build', True),
('auto_save', True),
])),
])
_USER_CONFIG_DEFAULTS = OrderedDict([
('blender', OrderedDict([
('last_path', 'blender'),
('use_last_path', True),
])),
('python', OrderedDict([
('path', ''),
])),
])
def _convert_conf_to_toml(configpath):
config = configparser.ConfigParser()
config.read(configpath)
confdict = {
s: dict(config.items(s))
for s in config.sections()
}
if 'build' in confdict:
confdict['build']['ignore_patterns'] = [
i.strip() for i in confdict['build']['ignore_patterns'].split(',')
]
if 'run' in confdict:
confdict['run']['auto_build'] = config.getboolean('run', 'auto_build')
confdict['run']['auto_save'] = config.getboolean('run', 'auto_save')
if 'blender' in confdict:
confdict['blender']['use_last_path'] = config.getboolean('blender', 'use_last_path')
return confdict
def _update_conf(config):
if 'general' in config:
if 'render_plugin' in config['general'] and '/' in config['general']['render_plugin']:
# Convert from path to module
renderplugin = config['general']['render_plugin']
rppath = get_abs_path(config, renderplugin)
maindir = os.path.dirname(get_abs_path(config, config['run']['main_file']))
rppath = os.path.splitext(os.path.relpath(rppath, maindir))[0]
module_parts = rppath.split(os.sep)
modname = '.'.join(module_parts)
config['general']['render_plugin'] = modname
def _get_config(startdir, conf_name, defaults):
try:
if startdir is None:
startdir = os.getcwd()
except FileNotFoundError:
# The project folder was deleted on us
raise NoConfigError("Could not find config file")
dirs = os.path.abspath(startdir).split(os.sep)
while dirs:
cdir = os.sep.join(dirs)
if cdir.strip() and conf_name in os.listdir(cdir):
configpath = os.path.join(cdir, conf_name)
with open(configpath) as f:
confdata = f.read()
istoml = (
'"' in confdata or
"'" in confdata or
confdata == ''
)
if istoml:
confdict = toml.load(configpath)
else:
confdict = _convert_conf_to_toml(configpath)
confdict = {
k: dict(defaults.get(k, {}), **confdict.get(k, {}))
for k in set(defaults.keys()) | set(confdict.keys())
}
confdict['internal'] = {
'projectdir': os.path.dirname(configpath),
}
_update_conf(confdict)
return confdict
dirs.pop()
# No config found
raise NoConfigError("Could not find config file")
def get_config(startdir=None):
return _get_config(startdir, '.pman', _CONFIG_DEFAULTS)
def config_exists(startdir=None):
try:
get_config(startdir)
have_config = True
except NoConfigError:
have_config = False
return have_config
def get_user_config(startdir=None):
try:
return _get_config(startdir, '.pman.user', _USER_CONFIG_DEFAULTS)
except NoConfigError:
# No user config, just create one
config = get_config(startdir)
file_path = os.path.join(config['internal']['projectdir'], '.pman.user')
print("Creating user config at {}".format(file_path))
open(file_path, 'w').close()
return _get_config(startdir, '.pman.user', _USER_CONFIG_DEFAULTS)
def _write_config(config, conf_name):
writecfg = config.copy()
del writecfg['internal']
with open(os.path.join(config['internal']['projectdir'], conf_name), 'w') as f:
toml.dump(writecfg, f)
def write_config(config):
_write_config(config, '.pman')
def write_user_config(user_config):
_write_config(user_config, '.pman.user')
def is_frozen():
return __IS_FROZEN
def create_project(projectdir):
if is_frozen():
raise FrozenEnvironmentError()
confpath = os.path.join(projectdir, '.pman')
if os.path.exists(confpath):
print("Updating project in {}".format(projectdir))
else:
print("Creating new project in {}".format(projectdir))
# Touch config file to make sure it is present
with open(confpath, 'a') as f:
pass
config = get_config(projectdir)
write_config(config)
pmandir = os.path.dirname(__file__)
templatedir = os.path.join(pmandir, 'templates')
bpmodpath = os.path.join(projectdir, 'game/blenderpanda')
print("Creating directories...")
dirs = [
'assets',
'game',
]
bpanda_mod_files = [
os.path.join(templatedir, '__init__.py'),
os.path.join(templatedir, 'bpbase.py'),
]
pman_files = [
'__init__.py',
'rendermanager.py',
'toml.py',
'hooks.py',
'pman_build.py',
]
dirs = [os.path.join(projectdir, i) for i in dirs]
for d in dirs:
if os.path.exists(d):
print("\tSkipping existing directory: {}".format(d))
else:
print("\tCreating directory: {}".format(d))
os.mkdir(d)
print("Creating main.py")
with open(os.path.join(templatedir, 'main.py')) as f:
main_data = f.read()
mainpath = os.path.join(projectdir, 'game', 'main.py')
if os.path.exists(mainpath):
print("\tmain.py already exists at {}".format(mainpath))
else:
with open(mainpath, 'w') as f:
f.write(main_data)
print("\tmain.py created at {}".format(mainpath))
if os.path.exists(bpmodpath):
print("Updating blenderpanda module")
shutil.rmtree(bpmodpath)
else:
print("Creating blenderpanda module")
os.mkdir(bpmodpath)
for copy_file in bpanda_mod_files:
bname = os.path.basename(copy_file)
print("\tCopying over {}".format(bname))
cfsrc = os.path.join(pmandir, copy_file)
cfdst = os.path.join(projectdir, 'game', 'blenderpanda', bname)
print(cfsrc, cfdst)
if os.path.isdir(cfsrc):
shutil.copytree(cfsrc, cfdst)
else:
shutil.copy(cfsrc, cfdst)
print("\t\t{} created at {}".format(bname, cfdst))
print("Copying pman")
pmantarget = os.path.join(bpmodpath, 'pman')
if os.path.exists(pmantarget):
shutil.rmtree(pmantarget)
os.mkdir(pmantarget)
for copy_file in pman_files:
shutil.copy(
os.path.join(pmandir, copy_file),
os.path.join(pmantarget, copy_file)
)
def get_abs_path(config, path):
return PMan(config=config).get_abs_path(path)
def get_rel_path(config, path):
return PMan(config=config).get_rel_path(path)
def get_python_program(config=None):
python_programs = [
'ppython',
'python3',
'python',
'python2',
]
if config is not None:
user_config = get_user_config(config['internal']['projectdir'])
confpy = user_config['python']['path']
if confpy:
python_programs.insert(0, confpy)
# Check to see if there is a version of Python that can import panda3d
for pyprog in python_programs:
args = [
pyprog,
'-c',
'import panda3d.core; import direct',
]
with open(os.devnull, 'w') as f:
try:
retcode = subprocess.call(args, stderr=f)
except FileNotFoundError:
retcode = 1
if retcode == 0:
return pyprog
# We couldn't find a python program to run
raise CouldNotFindPythonError('Could not find a usable Python install')
def load_module(modname, config=None):
return PMan(config=config).load_module(modname)
def build(config=None):
PMan(config=config).build()
def run(config=None):
PMan(config=config).run()
def converter_copy(_config, _user_config, srcdir, dstdir, assets):
for asset in assets:
src = asset
dst = src.replace(srcdir, dstdir)
print('Copying non-blend file from "{}" to "{}"'.format(src, dst))
if not os.path.exists(os.path.dirname(dst)):
os.makedirs(os.path.dirname(dst))
shutil.copyfile(src, dst)
class PMan(object):
def __init__(self, config=None, config_startdir=None):
if config:
self.config = config
self.user_config = get_user_config(config['internal']['projectdir'])
else:
self.config = get_config(config_startdir)
self.user_config = get_user_config(config_startdir)
self.converters = self._init_hooks(self.config['build']['converter_hooks'])
def _init_hooks(self, hooks_list):
new_hooks = []
for hook in hooks_list:
modparts = hook.split('.')
module = '.'.join(modparts[:-1])
func = modparts[-1]
mod = self.load_module(module)
new_hooks.append(getattr(mod, func))
return new_hooks
def get_abs_path(self, path):
return os.path.join(
self.config['internal']['projectdir'],
path
)
def get_rel_path(self, path):
return os.path.relpath(path, self.config['internal']['projectdir'])
def load_module(self, modname):
mod = None
module_parts = modname.split('.')
maindir = os.path.dirname(self.get_abs_path(self.config['run']['main_file']))
pmandir = os.path.dirname(__file__) if not is_frozen() else None
fix_path = False
def _load_module(modname, modinfo):
mod = None
try:
mod = imp.load_module(modname, *modinfo)
finally:
if modinfo[0]:
modinfo[0].close()
return mod
if is_frozen():
modinfo = imp.find_module(modname)
mod = _load_module(modname, modinfo)
else:
if maindir not in sys.path:
sys.path.append(maindir)
fix_path = True
mod = None
for modname in module_parts:
if modname == 'pman':
modpath = [os.path.join(pmandir, '..')]
else:
modpath = None if mod is None else mod.__path__
modinfo = imp.find_module(modname, modpath)
mod = _load_module(modname, modinfo)
if fix_path:
sys.path.remove(maindir)
return mod
def build(self):
if is_frozen():
raise FrozenEnvironmentError()
if hasattr(time, 'perf_counter'):
#pylint:disable=no-member
stime = time.perf_counter()
else:
stime = time.time()
print("Starting build")
srcdir = self.get_abs_path(self.config['build']['asset_dir'])
dstdir = self.get_abs_path(self.config['build']['export_dir'])
if not os.path.exists(srcdir):
raise BuildError("Could not find asset directory: {}".format(srcdir))
if not os.path.exists(dstdir):
print("Creating asset export directory at {}".format(dstdir))
os.makedirs(dstdir)
print("Read assets from: {}".format(srcdir))
print("Export them to: {}".format(dstdir))
ignore_patterns = self.config['build']['ignore_patterns']
print("Ignoring file patterns: {}".format(ignore_patterns))
# Gather files and group by extension
ext_asset_map = {}
ext_dst_map = {}
ext_converter_map = {}
for converter in self.converters:
ext_dst_map.update(converter.ext_dst_map)
for ext in converter.supported_exts:
ext_converter_map[ext] = converter
for root, _dirs, files in os.walk(srcdir):
for asset in files:
src = os.path.join(root, asset)
dst = src.replace(srcdir, dstdir)
ignore_pattern = None
for pattern in ignore_patterns:
if fnmatch.fnmatch(asset, pattern):
ignore_pattern = pattern
break
if ignore_pattern is not None:
print('Skip building file {} that matched ignore pattern {}'.format(asset, ignore_pattern))
continue
ext = os.path.splitext(asset)[1]
if ext in ext_dst_map:
dst = dst.replace(ext, ext_dst_map[ext])
if os.path.exists(dst) and os.stat(src).st_mtime <= os.stat(dst).st_mtime:
print('Skip building up-to-date file: {}'.format(dst))
continue
if ext not in ext_asset_map:
ext_asset_map[ext] = []
print('Adding {} to conversion list to satisfy {}'.format(src, dst))
ext_asset_map[ext].append(os.path.join(root, asset))
# Find which extensions have hooks available
convert_hooks = []
for ext, converter in ext_converter_map.items():
if ext in ext_asset_map:
convert_hooks.append((converter, ext_asset_map[ext]))
del ext_asset_map[ext]
# Copy what is left
for ext in ext_asset_map:
converter_copy(self.config, self.user_config, srcdir, dstdir, ext_asset_map[ext])
# Now run hooks that non-converted assets are in place (copied)
for convert_hook in convert_hooks:
convert_hook[0](self.config, self.user_config, srcdir, dstdir, convert_hook[1])
if hasattr(time, 'perf_counter'):
#pylint:disable=no-member
etime = time.perf_counter()
else:
etime = time.time()
print("Build took {:.4f}s".format(etime - stime))
def run(self):
if is_frozen():
raise FrozenEnvironmentError()
mainfile = self.get_abs_path(self.config['run']['main_file'])
print("Running main file: {}".format(mainfile))
args = [get_python_program(self.config), mainfile]
#print("Args: {}".format(args))
subprocess.Popen(args, cwd=self.config['internal']['projectdir']) | 0.205057 | 0.066509 |
from treebank_toolkit.sentence import ConllSent
from treebank_toolkit.parser_state import State
class TransitionSystemBase(object):
_actions_list = None
@classmethod
def _valid_transitions(cls, parserstate):
""" Prepares the set of gold transitions given a parser state """
raise NotImplementedError()
@classmethod
def step(cls, parserstate, action):
""" Move a step to a new parser state given an action """
raise NotImplementedError()
@classmethod
def gold_action(cls, parserstate):
""" Returns the next gold transition given the set of gold arcs """
raise NotImplementedError()
@classmethod
def action_to_str(cls, action, control):
raise NotImplementedError()
@classmethod
def str_to_action(cls, string, control):
raise NotImplementedError()
@classmethod
def actions_list(cls):
return cls._actions_list
class ArcStandard(TransitionSystemBase):
_actions_list = ["Shift", "LeftReduce", "RightReduce"]
@classmethod
def _valid_transitions(cls, parser_state):
SHIFT, LEFT, RIGHT = cls._actions_list
stack, buf = parser_state.stack, parser_state.buf
valid_transitions = []
if len(buf) > 0:
valid_transitions.append(SHIFT)
if len(stack) > 2:
valid_transitions.extend([LEFT, RIGHT])
elif len(stack) == 2 and len(buf) == 0:
valid_transitions = [RIGHT]
return valid_transitions
@classmethod
def step(cls, parser_state, action):
"""
action is a tuple of str
"""
SHIFT, LEFT, RIGHT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, "_"
state = State.copy(parser_state)
stack = state.stack
buf = state.buf
tags = state.tags
arcs = state.arcs
cand = cls._valid_transitions(state)
assert tsn in cand
if tsn == SHIFT:
tags[buf[-1]] = lbl
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = True
elif tsn == LEFT:
arcs[stack[-2]] = (stack[-1], lbl)
stack.pop(-2)
elif tsn == RIGHT:
arcs[stack[-1]] = (stack[-2], lbl)
stack.pop()
return state
@classmethod
def gold_action(cls, parser_state):
"""
derive next gold action from reference, which in included in the parser_state.
"""
SHIFT, LEFT, RIGHT = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
upos = parser_state.sent.upos
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
stack_top_children = parser_state.sent.children[stack[-1]]
stack_top_done = True
for x in buf:
if x in stack_top_children:
stack_top_done = False
break
if len(stack) > 2 and heads[stack[-2]] == stack[-1]:
lbl = deprels[stack[-2]]
tsn = LEFT
elif len(stack) > 1 and heads[stack[-1]] == stack[-2] and stack_top_done:
lbl = deprels[stack[-1]]
tsn = RIGHT
else:
lbl = upos[buf[-1]]
tsn = SHIFT
return (tsn, lbl)
@classmethod
def action_to_str(cls, action, control="normal"):
SHIFT, LEFT, RIGHT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, '_'
if control == "normal":
if tsn == SHIFT:
return tsn
else:
return "{}-{}".format(tsn, lbl)
elif control == "backbone":
return tsn
@classmethod
def str_to_action(cls, string, control="normal"):
SHIFT, LEFT, RIGHT = cls._actions_list
if control == "normal":
if string.startswith(SHIFT):
tsn, lbl = string, "_"
else:
tsn, lbl = string.split("-", 1)
elif control == "backbone":
tsn, lbl = string, "_"
return (tsn, lbl)
class ArcHybrid(ArcStandard):
@classmethod
def _valid_transitions(cls, parser_state):
SHIFT, LEFT, RIGHT = cls._actions_list
stack, buf, arcs = parser_state.stack, parser_state.buf, parser_state.arcs
valid_transitions = []
if len(buf) > 0:
valid_transitions.append(SHIFT)
if len(buf) > 0 and len(stack) > 1:
valid_transitions.append(LEFT)
if len(stack) > 2: # and stack[-1] not in arcs:
valid_transitions.append(RIGHT)
if len(stack) == 2 and len(buf) == 0:
valid_transitions = [RIGHT]
return valid_transitions
@classmethod
def step(cls, parser_state, action):
SHIFT, LEFT, RIGHT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, '_'
state = State.copy(parser_state)
stack = state.stack
buf = state.buf
tags = state.tags
arcs = state.arcs
cand = cls._valid_transitions(state)
if tsn == SHIFT:
tags[buf[-1]] = lbl
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = False
elif tsn == LEFT:
arcs[stack[-1]] = (buf[-1], lbl)
stack.pop()
elif tsn == RIGHT:
arcs[stack[-1]] = (stack[-2], lbl)
stack.pop()
return state
@classmethod
def gold_action(cls, parser_state):
"""
derive next gold action from reference, which in included in the parser_state.
"""
SHIFT, LEFT, RIGHT = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
upos = parser_state.sent.upos
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
stack_top_children = parser_state.sent.children[stack[-1]]
stack_top_done = True
for x in buf:
if x in stack_top_children:
stack_top_done = False
break
if len(buf) > 0 and heads[stack[-1]] == buf[-1]:
lbl = deprels[stack[-1]]
tsn = LEFT
elif len(stack) > 1 and heads[stack[-1]] == stack[-2] and stack_top_done:
lbl = deprels[stack[-1]]
tsn = RIGHT
else:
lbl = upos[buf[-1]]
tsn = SHIFT
return (tsn, lbl)
class ArcEagerReduce(TransitionSystemBase):
"""
Modified as Nivre and Fernandex-Gonzalez (2014) `Arc-Eager Parsing with the Tree Constraint`, adding a new transition Unshift and adding a new member in parser state, and the modification to the parser state in extended to all the parser states, even those used with Arc Standard, though it is not needed.
ref: http://www.aclweb.org/anthology/J14-2002
"""
_actions_list = ["Shift", "LeftArc", "RightArc", "Reduce", "Unshift"]
@classmethod
def _valid_transitions(cls, parser_state):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
stack, buf, tags, arcs = parser_state.stack, parser_state.buf, parser_state.tags, parser_state.arcs
valid_transitions = []
if len(buf) > 1 and not parser_state.seen_the_end: # before we have seen the end
valid_transitions.append(SHIFT)
if len(buf) == 0 and parser_state.seen_the_end and stack[-1] not in arcs:
valid_transitions.append(UNSHIFT)
if (len(stack) > 2 or len(stack) == 2 and len(buf) == 0) and stack[-1] in arcs:
valid_transitions.append(REDUCE)
if len(buf) > 0 and len(stack) > 1 and stack[-1] not in arcs:
valid_transitions.append(LEFT)
if len(buf) > 0 and (len(stack) > 1 or (len(stack) == 1 and not any([arcs[x][0] == 0 for x in arcs]))):
valid_transitions.append(RIGHT)
return valid_transitions
@classmethod
def step(cls, parser_state, action):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, "_"
state = State.copy(parser_state)
stack = state.stack
buf = state.buf
tags = state.tags
arcs = state.arcs
cand = cls._valid_transitions(state)
assert tsn in cand
if tsn == SHIFT:
tags[buf[-1]] = lbl
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = True
elif tsn == LEFT:
arcs[stack[-1]] = (buf[-1], lbl)
stack.pop()
elif tsn == RIGHT:
#tags[buf[-1]] = lbl # it is safe to do so, only tag when reduce
arcs[buf[-1]] = (stack[-1], lbl)
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = True
elif tsn == UNSHIFT:
buf.append(stack.pop())
else: #reduce
tags[stack[-1]] = lbl
stack.pop()
return state
@classmethod
def gold_action(cls, parser_state):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
arcs = parser_state.arcs
upos = parser_state.sent.upos
state = parser_state
# reference
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
stack_top_children = parser_state.sent.children[stack[-1]]
stack_top_done = True
for x in buf:
if x in stack_top_children:
stack_top_done = False
break
if len(stack) > 1 and len(buf) > 0 and heads[stack[-1]] == buf[-1]:
lbl = deprels[stack[-1]]
tsn = LEFT
elif len(stack) > 0 and len(buf) > 0 and heads[buf[-1]] == stack[-1]:
lbl = deprels[buf[-1]]
tsn = RIGHT
elif len(stack) > 1 and stack[-1] in arcs and stack_top_done:
lbl = upos[stack[-1]]
tsn = REDUCE
elif state.seen_the_end and (buf) == 0 and len(stack) > 1 and not stack[-1] in arcs:
lbl = upos[stack[-1]]
tsn = UNSHIFT
elif not state.seen_the_end:
lbl = upos[buf[-1]]
tsn = SHIFT
return (tsn, lbl)
@classmethod
def action_to_str(cls, action, control="normal"):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, '_'
if control == "normal":
if tsn == SHIFT or tsn == REDUCE or tsn == UNSHIFT:
return tsn
else:
return "{}-{}".format(tsn, lbl)
elif control == "backbone":
return tsn
@classmethod
def str_to_action(cls, string, control="normal"):
"""
Note that if you expect Shift-POS to cover the whole sentence, it is impossible
"""
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
if control == "normal":
if string.startswith(SHIFT) or string.startswith(REDUCE) or string.startswith(UNSHIFT):
tsn, lbl = string, "_"
else:
tsn, lbl = string.split("-", 1)
elif control == "backbone":
tsn, lbl = string, "_"
return (tsn, lbl)
class ArcEagerShift(ArcEagerReduce):
@classmethod
def gold_action(cls, parser_state):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
arcs = parser_state.arcs
upos = parser_state.sent.upos
state = parser_state
# reference
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
stack_top_children = parser_state.sent.children[stack[-1]]
has_right_children = False
for i in buf:
if i in stack_top_children:
has_right_children = True
break
must_reduce = False
if len(buf) > 0:
for i in reversed(stack):
if heads[i] == buf[-1] or heads[buf[-1]] == i:
must_reduce = True
break
if i not in arcs:
break
if len(stack) > 1 and len(buf) > 0 and heads[stack[-1]] == buf[-1]:
lbl = deprels[stack[-1]]
tsn = LEFT
elif len(stack) > 0 and len(buf) > 0 and heads[buf[-1]] == stack[-1]:
lbl = deprels[buf[-1]]
tsn = RIGHT
elif (not state.seen_the_end) and not must_reduce or stack[-1] not in arcs or has_right_children:
lbl = upos[buf[-1]]
tsn = SHIFT
elif len(stack) > 1 and stack[-1] in arcs:
lbl = upos[stack[-1]]
tsn = REDUCE
elif state.seen_the_end and (buf) == 0 and len(stack) > 1 and not stack[-1] in arcs:
lbl = upos[stack[-1]]
tsn = UNSHIFT
return (tsn, lbl)
class ArcStandardSwap(TransitionSystemBase):
_actions_list = ["Shift", "LeftReduce", "RightReduce", "Swap"]
@classmethod
def _valid_transitions(cls, parser_state):
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
stack, buf = parser_state.stack, parser_state.buf
valid_transitions = []
if len(buf) > 0:
valid_transitions.append(SHIFT)
if len(stack) > 2:
valid_transitions.extend([LEFT, RIGHT])
if stack[-1] > stack[-2]:
valid_transitions.extend([SWAP])
elif len(stack) == 2 and len(buf) == 0:
valid_transitions = [RIGHT]
return valid_transitions
@classmethod
def gold_action(cls, parser_state):
"""
derive next gold action from reference, which in included in the parser_state.
"""
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
upos = parser_state.sent.upos
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
projective_order = parser_state.sent.porder
stack_top_children = parser_state.sent.children[stack[-1]]
if len(stack) > 1:
stack2_children = parser_state.sent.children[stack[-2]]
stack_top_done = True
for x in buf:
if x in stack_top_children:
stack_top_done = False
break
if len(stack) > 1:
stack2_children = parser_state.sent.children[stack[-2]]
stack2_done = True
for x in buf:
if x in stack2_children:
stack2_done = False
break
if len(stack) > 2 and heads[stack[-2]] == stack[-1] and stack2_done:
lbl = deprels[stack[-2]]
tsn = LEFT
elif len(stack) > 1 and heads[stack[-1]] == stack[-2] and stack_top_done:
lbl = deprels[stack[-1]]
tsn = RIGHT
elif len(stack) > 2 and projective_order.index(stack[-1]) < projective_order.index(stack[-2]):
lbl = upos[stack[-2]]
tsn = SWAP
else:
lbl = upos[buf[-1]]
tsn = SHIFT
return (tsn, lbl)
@classmethod
def step(cls, parser_state, action):
"""
action is a tuple of str
"""
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, "_"
state = State.copy(parser_state)
stack = state.stack
buf = state.buf
tags = state.tags
arcs = state.arcs
cand = cls._valid_transitions(state)
assert tsn in cand
if tsn == SHIFT:
tags[buf[-1]] = lbl
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = True
elif tsn == LEFT:
arcs[stack[-2]] = (stack[-1], lbl)
stack.pop(-2)
elif tsn == RIGHT:
arcs[stack[-1]] = (stack[-2], lbl)
stack.pop()
elif tsn == SWAP:
buf.append(stack.pop(-2))
return state
@classmethod
def action_to_str(cls, action, control="normal"):
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, '_'
if control == "normal":
if tsn == SHIFT or tsn == SWAP:
return tsn
else:
return "{}-{}".format(tsn, lbl)
elif control == "backbone":
return tsn
@classmethod
def str_to_action(cls, string, control="normal"):
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
if control == "normal":
if string.startswith(SHIFT) or string.startswith(SWAP):
tsn, lbl = string, "_"
else:
tsn, lbl = string.split("-", 1)
elif control == "backbone":
tsn, lbl = string, "_"
return (tsn, lbl) | treebank_toolkit/transition_system.py | from treebank_toolkit.sentence import ConllSent
from treebank_toolkit.parser_state import State
class TransitionSystemBase(object):
_actions_list = None
@classmethod
def _valid_transitions(cls, parserstate):
""" Prepares the set of gold transitions given a parser state """
raise NotImplementedError()
@classmethod
def step(cls, parserstate, action):
""" Move a step to a new parser state given an action """
raise NotImplementedError()
@classmethod
def gold_action(cls, parserstate):
""" Returns the next gold transition given the set of gold arcs """
raise NotImplementedError()
@classmethod
def action_to_str(cls, action, control):
raise NotImplementedError()
@classmethod
def str_to_action(cls, string, control):
raise NotImplementedError()
@classmethod
def actions_list(cls):
return cls._actions_list
class ArcStandard(TransitionSystemBase):
_actions_list = ["Shift", "LeftReduce", "RightReduce"]
@classmethod
def _valid_transitions(cls, parser_state):
SHIFT, LEFT, RIGHT = cls._actions_list
stack, buf = parser_state.stack, parser_state.buf
valid_transitions = []
if len(buf) > 0:
valid_transitions.append(SHIFT)
if len(stack) > 2:
valid_transitions.extend([LEFT, RIGHT])
elif len(stack) == 2 and len(buf) == 0:
valid_transitions = [RIGHT]
return valid_transitions
@classmethod
def step(cls, parser_state, action):
"""
action is a tuple of str
"""
SHIFT, LEFT, RIGHT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, "_"
state = State.copy(parser_state)
stack = state.stack
buf = state.buf
tags = state.tags
arcs = state.arcs
cand = cls._valid_transitions(state)
assert tsn in cand
if tsn == SHIFT:
tags[buf[-1]] = lbl
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = True
elif tsn == LEFT:
arcs[stack[-2]] = (stack[-1], lbl)
stack.pop(-2)
elif tsn == RIGHT:
arcs[stack[-1]] = (stack[-2], lbl)
stack.pop()
return state
@classmethod
def gold_action(cls, parser_state):
"""
derive next gold action from reference, which in included in the parser_state.
"""
SHIFT, LEFT, RIGHT = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
upos = parser_state.sent.upos
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
stack_top_children = parser_state.sent.children[stack[-1]]
stack_top_done = True
for x in buf:
if x in stack_top_children:
stack_top_done = False
break
if len(stack) > 2 and heads[stack[-2]] == stack[-1]:
lbl = deprels[stack[-2]]
tsn = LEFT
elif len(stack) > 1 and heads[stack[-1]] == stack[-2] and stack_top_done:
lbl = deprels[stack[-1]]
tsn = RIGHT
else:
lbl = upos[buf[-1]]
tsn = SHIFT
return (tsn, lbl)
@classmethod
def action_to_str(cls, action, control="normal"):
SHIFT, LEFT, RIGHT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, '_'
if control == "normal":
if tsn == SHIFT:
return tsn
else:
return "{}-{}".format(tsn, lbl)
elif control == "backbone":
return tsn
@classmethod
def str_to_action(cls, string, control="normal"):
SHIFT, LEFT, RIGHT = cls._actions_list
if control == "normal":
if string.startswith(SHIFT):
tsn, lbl = string, "_"
else:
tsn, lbl = string.split("-", 1)
elif control == "backbone":
tsn, lbl = string, "_"
return (tsn, lbl)
class ArcHybrid(ArcStandard):
@classmethod
def _valid_transitions(cls, parser_state):
SHIFT, LEFT, RIGHT = cls._actions_list
stack, buf, arcs = parser_state.stack, parser_state.buf, parser_state.arcs
valid_transitions = []
if len(buf) > 0:
valid_transitions.append(SHIFT)
if len(buf) > 0 and len(stack) > 1:
valid_transitions.append(LEFT)
if len(stack) > 2: # and stack[-1] not in arcs:
valid_transitions.append(RIGHT)
if len(stack) == 2 and len(buf) == 0:
valid_transitions = [RIGHT]
return valid_transitions
@classmethod
def step(cls, parser_state, action):
SHIFT, LEFT, RIGHT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, '_'
state = State.copy(parser_state)
stack = state.stack
buf = state.buf
tags = state.tags
arcs = state.arcs
cand = cls._valid_transitions(state)
if tsn == SHIFT:
tags[buf[-1]] = lbl
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = False
elif tsn == LEFT:
arcs[stack[-1]] = (buf[-1], lbl)
stack.pop()
elif tsn == RIGHT:
arcs[stack[-1]] = (stack[-2], lbl)
stack.pop()
return state
@classmethod
def gold_action(cls, parser_state):
"""
derive next gold action from reference, which in included in the parser_state.
"""
SHIFT, LEFT, RIGHT = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
upos = parser_state.sent.upos
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
stack_top_children = parser_state.sent.children[stack[-1]]
stack_top_done = True
for x in buf:
if x in stack_top_children:
stack_top_done = False
break
if len(buf) > 0 and heads[stack[-1]] == buf[-1]:
lbl = deprels[stack[-1]]
tsn = LEFT
elif len(stack) > 1 and heads[stack[-1]] == stack[-2] and stack_top_done:
lbl = deprels[stack[-1]]
tsn = RIGHT
else:
lbl = upos[buf[-1]]
tsn = SHIFT
return (tsn, lbl)
class ArcEagerReduce(TransitionSystemBase):
"""
Modified as Nivre and Fernandex-Gonzalez (2014) `Arc-Eager Parsing with the Tree Constraint`, adding a new transition Unshift and adding a new member in parser state, and the modification to the parser state in extended to all the parser states, even those used with Arc Standard, though it is not needed.
ref: http://www.aclweb.org/anthology/J14-2002
"""
_actions_list = ["Shift", "LeftArc", "RightArc", "Reduce", "Unshift"]
@classmethod
def _valid_transitions(cls, parser_state):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
stack, buf, tags, arcs = parser_state.stack, parser_state.buf, parser_state.tags, parser_state.arcs
valid_transitions = []
if len(buf) > 1 and not parser_state.seen_the_end: # before we have seen the end
valid_transitions.append(SHIFT)
if len(buf) == 0 and parser_state.seen_the_end and stack[-1] not in arcs:
valid_transitions.append(UNSHIFT)
if (len(stack) > 2 or len(stack) == 2 and len(buf) == 0) and stack[-1] in arcs:
valid_transitions.append(REDUCE)
if len(buf) > 0 and len(stack) > 1 and stack[-1] not in arcs:
valid_transitions.append(LEFT)
if len(buf) > 0 and (len(stack) > 1 or (len(stack) == 1 and not any([arcs[x][0] == 0 for x in arcs]))):
valid_transitions.append(RIGHT)
return valid_transitions
@classmethod
def step(cls, parser_state, action):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, "_"
state = State.copy(parser_state)
stack = state.stack
buf = state.buf
tags = state.tags
arcs = state.arcs
cand = cls._valid_transitions(state)
assert tsn in cand
if tsn == SHIFT:
tags[buf[-1]] = lbl
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = True
elif tsn == LEFT:
arcs[stack[-1]] = (buf[-1], lbl)
stack.pop()
elif tsn == RIGHT:
#tags[buf[-1]] = lbl # it is safe to do so, only tag when reduce
arcs[buf[-1]] = (stack[-1], lbl)
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = True
elif tsn == UNSHIFT:
buf.append(stack.pop())
else: #reduce
tags[stack[-1]] = lbl
stack.pop()
return state
@classmethod
def gold_action(cls, parser_state):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
arcs = parser_state.arcs
upos = parser_state.sent.upos
state = parser_state
# reference
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
stack_top_children = parser_state.sent.children[stack[-1]]
stack_top_done = True
for x in buf:
if x in stack_top_children:
stack_top_done = False
break
if len(stack) > 1 and len(buf) > 0 and heads[stack[-1]] == buf[-1]:
lbl = deprels[stack[-1]]
tsn = LEFT
elif len(stack) > 0 and len(buf) > 0 and heads[buf[-1]] == stack[-1]:
lbl = deprels[buf[-1]]
tsn = RIGHT
elif len(stack) > 1 and stack[-1] in arcs and stack_top_done:
lbl = upos[stack[-1]]
tsn = REDUCE
elif state.seen_the_end and (buf) == 0 and len(stack) > 1 and not stack[-1] in arcs:
lbl = upos[stack[-1]]
tsn = UNSHIFT
elif not state.seen_the_end:
lbl = upos[buf[-1]]
tsn = SHIFT
return (tsn, lbl)
@classmethod
def action_to_str(cls, action, control="normal"):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, '_'
if control == "normal":
if tsn == SHIFT or tsn == REDUCE or tsn == UNSHIFT:
return tsn
else:
return "{}-{}".format(tsn, lbl)
elif control == "backbone":
return tsn
@classmethod
def str_to_action(cls, string, control="normal"):
"""
Note that if you expect Shift-POS to cover the whole sentence, it is impossible
"""
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
if control == "normal":
if string.startswith(SHIFT) or string.startswith(REDUCE) or string.startswith(UNSHIFT):
tsn, lbl = string, "_"
else:
tsn, lbl = string.split("-", 1)
elif control == "backbone":
tsn, lbl = string, "_"
return (tsn, lbl)
class ArcEagerShift(ArcEagerReduce):
@classmethod
def gold_action(cls, parser_state):
SHIFT, LEFT, RIGHT, REDUCE, UNSHIFT = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
arcs = parser_state.arcs
upos = parser_state.sent.upos
state = parser_state
# reference
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
stack_top_children = parser_state.sent.children[stack[-1]]
has_right_children = False
for i in buf:
if i in stack_top_children:
has_right_children = True
break
must_reduce = False
if len(buf) > 0:
for i in reversed(stack):
if heads[i] == buf[-1] or heads[buf[-1]] == i:
must_reduce = True
break
if i not in arcs:
break
if len(stack) > 1 and len(buf) > 0 and heads[stack[-1]] == buf[-1]:
lbl = deprels[stack[-1]]
tsn = LEFT
elif len(stack) > 0 and len(buf) > 0 and heads[buf[-1]] == stack[-1]:
lbl = deprels[buf[-1]]
tsn = RIGHT
elif (not state.seen_the_end) and not must_reduce or stack[-1] not in arcs or has_right_children:
lbl = upos[buf[-1]]
tsn = SHIFT
elif len(stack) > 1 and stack[-1] in arcs:
lbl = upos[stack[-1]]
tsn = REDUCE
elif state.seen_the_end and (buf) == 0 and len(stack) > 1 and not stack[-1] in arcs:
lbl = upos[stack[-1]]
tsn = UNSHIFT
return (tsn, lbl)
class ArcStandardSwap(TransitionSystemBase):
_actions_list = ["Shift", "LeftReduce", "RightReduce", "Swap"]
@classmethod
def _valid_transitions(cls, parser_state):
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
stack, buf = parser_state.stack, parser_state.buf
valid_transitions = []
if len(buf) > 0:
valid_transitions.append(SHIFT)
if len(stack) > 2:
valid_transitions.extend([LEFT, RIGHT])
if stack[-1] > stack[-2]:
valid_transitions.extend([SWAP])
elif len(stack) == 2 and len(buf) == 0:
valid_transitions = [RIGHT]
return valid_transitions
@classmethod
def gold_action(cls, parser_state):
"""
derive next gold action from reference, which in included in the parser_state.
"""
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
stack = parser_state.stack
buf = parser_state.buf
upos = parser_state.sent.upos
heads = parser_state.sent.head
deprels = parser_state.sent.deprel
projective_order = parser_state.sent.porder
stack_top_children = parser_state.sent.children[stack[-1]]
if len(stack) > 1:
stack2_children = parser_state.sent.children[stack[-2]]
stack_top_done = True
for x in buf:
if x in stack_top_children:
stack_top_done = False
break
if len(stack) > 1:
stack2_children = parser_state.sent.children[stack[-2]]
stack2_done = True
for x in buf:
if x in stack2_children:
stack2_done = False
break
if len(stack) > 2 and heads[stack[-2]] == stack[-1] and stack2_done:
lbl = deprels[stack[-2]]
tsn = LEFT
elif len(stack) > 1 and heads[stack[-1]] == stack[-2] and stack_top_done:
lbl = deprels[stack[-1]]
tsn = RIGHT
elif len(stack) > 2 and projective_order.index(stack[-1]) < projective_order.index(stack[-2]):
lbl = upos[stack[-2]]
tsn = SWAP
else:
lbl = upos[buf[-1]]
tsn = SHIFT
return (tsn, lbl)
@classmethod
def step(cls, parser_state, action):
"""
action is a tuple of str
"""
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, "_"
state = State.copy(parser_state)
stack = state.stack
buf = state.buf
tags = state.tags
arcs = state.arcs
cand = cls._valid_transitions(state)
assert tsn in cand
if tsn == SHIFT:
tags[buf[-1]] = lbl
stack.append(buf.pop())
if len(buf) == 0:
state.seen_the_end = True
elif tsn == LEFT:
arcs[stack[-2]] = (stack[-1], lbl)
stack.pop(-2)
elif tsn == RIGHT:
arcs[stack[-1]] = (stack[-2], lbl)
stack.pop()
elif tsn == SWAP:
buf.append(stack.pop(-2))
return state
@classmethod
def action_to_str(cls, action, control="normal"):
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
if isinstance(action, tuple):
tsn, lbl = action
else:
tsn, lbl = action, '_'
if control == "normal":
if tsn == SHIFT or tsn == SWAP:
return tsn
else:
return "{}-{}".format(tsn, lbl)
elif control == "backbone":
return tsn
@classmethod
def str_to_action(cls, string, control="normal"):
SHIFT, LEFT, RIGHT, SWAP = cls._actions_list
if control == "normal":
if string.startswith(SHIFT) or string.startswith(SWAP):
tsn, lbl = string, "_"
else:
tsn, lbl = string.split("-", 1)
elif control == "backbone":
tsn, lbl = string, "_"
return (tsn, lbl) | 0.684159 | 0.483405 |
import numpy
import pytest
import skimage.data
import skimage.color
import skimage.filters
import skimage.measure
import cellprofiler.__main__
import cellprofiler_core.image
import cellprofiler_core.measurement
import cellprofiler_core.object
import cellprofiler_core.pipeline
import cellprofiler_core.preferences
import cellprofiler_core.utilities.java
import cellprofiler_core.workspace
def pytest_sessionstart(session):
cellprofiler_core.preferences.set_headless()
cellprofiler_core.utilities.java.start_java()
def pytest_sessionfinish(session, exitstatus):
cellprofiler.__main__.stop_cellprofiler()
return exitstatus
@pytest.fixture(
scope="module",
params=[
(skimage.data.camera()[0:128, 0:128], 2),
(skimage.data.astronaut()[0:128, 0:128, :], 2),
(numpy.tile(skimage.data.camera()[0:32, 0:32], (2, 1)).reshape(2, 32, 32), 3),
],
ids=["grayscale_image", "multichannel_image", "grayscale_volume"],
)
def image(request):
data, dimensions = request.param
return cellprofiler_core.image.Image(image=data, dimensions=dimensions)
@pytest.fixture(scope="module")
def image_empty():
image = cellprofiler_core.image.Image()
return image
@pytest.fixture(scope="function")
def image_set(image, image_set_list):
image_set = image_set_list.get_image_set(0)
image_set.add("example", image)
return image_set
@pytest.fixture(scope="function")
def image_set_empty(image_empty, image_set_list):
image_set = image_set_list.get_image_set(0)
image_set.add("example", image_empty)
return image_set
@pytest.fixture(scope="function")
def image_set_list():
return cellprofiler_core.image.ImageSetList()
@pytest.fixture(scope="function")
def measurements():
return cellprofiler_core.measurement.Measurements()
@pytest.fixture(scope="module")
def module(request):
instance = getattr(request.module, "instance")
return instance
@pytest.fixture(scope="function")
def pipeline():
return cellprofiler_core.pipeline.Pipeline()
@pytest.fixture(scope="function")
def workspace(pipeline, module, image_set, object_set, measurements, image_set_list):
return cellprofiler_core.workspace.Workspace(
pipeline, module, image_set, object_set, measurements, image_set_list
)
@pytest.fixture(scope="function")
def workspace_empty(
pipeline, module, image_set_empty, object_set_empty, measurements, image_set_list
):
return cellprofiler_core.workspace.Workspace(
pipeline,
module,
image_set_empty,
object_set_empty,
measurements,
image_set_list,
)
@pytest.fixture(scope="function")
def workspace_with_data(
pipeline, module, image_set, object_set_with_data, measurements, image_set_list
):
return cellprofiler_core.workspace.Workspace(
pipeline, module, image_set, object_set_with_data, measurements, image_set_list
)
@pytest.fixture(scope="function")
def objects(image):
obj = cellprofiler_core.object.Objects()
obj.parent_image = image
return obj
@pytest.fixture(scope="function")
def objects_empty():
obj = cellprofiler_core.object.Objects()
return obj
@pytest.fixture(scope="function")
def object_set(objects):
objects_set = cellprofiler_core.object.ObjectSet()
objects_set.add_objects(objects, "InputObjects")
return objects_set
@pytest.fixture(scope="function")
def object_set_empty(objects_empty):
objects_set = cellprofiler_core.object.ObjectSet()
objects_set.add_objects(objects_empty, "InputObjects")
return objects_set
@pytest.fixture(scope="function")
def object_with_data(image):
data = image.pixel_data
if image.multichannel:
data = skimage.color.rgb2gray(data)
binary = data > skimage.filters.threshold_li(data)
labels = skimage.measure.label(binary)
objects = cellprofiler_core.object.Objects()
objects.segmented = labels
objects.parent_image = image
return objects
@pytest.fixture(scope="function")
def object_set_with_data(object_with_data):
objects_set = cellprofiler_core.object.ObjectSet()
objects_set.add_objects(object_with_data, "InputObjects")
return objects_set | CellProfiler/tests/conftest.py | import numpy
import pytest
import skimage.data
import skimage.color
import skimage.filters
import skimage.measure
import cellprofiler.__main__
import cellprofiler_core.image
import cellprofiler_core.measurement
import cellprofiler_core.object
import cellprofiler_core.pipeline
import cellprofiler_core.preferences
import cellprofiler_core.utilities.java
import cellprofiler_core.workspace
def pytest_sessionstart(session):
cellprofiler_core.preferences.set_headless()
cellprofiler_core.utilities.java.start_java()
def pytest_sessionfinish(session, exitstatus):
cellprofiler.__main__.stop_cellprofiler()
return exitstatus
@pytest.fixture(
scope="module",
params=[
(skimage.data.camera()[0:128, 0:128], 2),
(skimage.data.astronaut()[0:128, 0:128, :], 2),
(numpy.tile(skimage.data.camera()[0:32, 0:32], (2, 1)).reshape(2, 32, 32), 3),
],
ids=["grayscale_image", "multichannel_image", "grayscale_volume"],
)
def image(request):
data, dimensions = request.param
return cellprofiler_core.image.Image(image=data, dimensions=dimensions)
@pytest.fixture(scope="module")
def image_empty():
image = cellprofiler_core.image.Image()
return image
@pytest.fixture(scope="function")
def image_set(image, image_set_list):
image_set = image_set_list.get_image_set(0)
image_set.add("example", image)
return image_set
@pytest.fixture(scope="function")
def image_set_empty(image_empty, image_set_list):
image_set = image_set_list.get_image_set(0)
image_set.add("example", image_empty)
return image_set
@pytest.fixture(scope="function")
def image_set_list():
return cellprofiler_core.image.ImageSetList()
@pytest.fixture(scope="function")
def measurements():
return cellprofiler_core.measurement.Measurements()
@pytest.fixture(scope="module")
def module(request):
instance = getattr(request.module, "instance")
return instance
@pytest.fixture(scope="function")
def pipeline():
return cellprofiler_core.pipeline.Pipeline()
@pytest.fixture(scope="function")
def workspace(pipeline, module, image_set, object_set, measurements, image_set_list):
return cellprofiler_core.workspace.Workspace(
pipeline, module, image_set, object_set, measurements, image_set_list
)
@pytest.fixture(scope="function")
def workspace_empty(
pipeline, module, image_set_empty, object_set_empty, measurements, image_set_list
):
return cellprofiler_core.workspace.Workspace(
pipeline,
module,
image_set_empty,
object_set_empty,
measurements,
image_set_list,
)
@pytest.fixture(scope="function")
def workspace_with_data(
pipeline, module, image_set, object_set_with_data, measurements, image_set_list
):
return cellprofiler_core.workspace.Workspace(
pipeline, module, image_set, object_set_with_data, measurements, image_set_list
)
@pytest.fixture(scope="function")
def objects(image):
obj = cellprofiler_core.object.Objects()
obj.parent_image = image
return obj
@pytest.fixture(scope="function")
def objects_empty():
obj = cellprofiler_core.object.Objects()
return obj
@pytest.fixture(scope="function")
def object_set(objects):
objects_set = cellprofiler_core.object.ObjectSet()
objects_set.add_objects(objects, "InputObjects")
return objects_set
@pytest.fixture(scope="function")
def object_set_empty(objects_empty):
objects_set = cellprofiler_core.object.ObjectSet()
objects_set.add_objects(objects_empty, "InputObjects")
return objects_set
@pytest.fixture(scope="function")
def object_with_data(image):
data = image.pixel_data
if image.multichannel:
data = skimage.color.rgb2gray(data)
binary = data > skimage.filters.threshold_li(data)
labels = skimage.measure.label(binary)
objects = cellprofiler_core.object.Objects()
objects.segmented = labels
objects.parent_image = image
return objects
@pytest.fixture(scope="function")
def object_set_with_data(object_with_data):
objects_set = cellprofiler_core.object.ObjectSet()
objects_set.add_objects(object_with_data, "InputObjects")
return objects_set | 0.451568 | 0.302275 |
import argparse
import itertools as it
import json
import math
import matplotlib.pyplot as plt
import os
import pathlib
_here = pathlib.Path(__file__).resolve().parent
def main(dataset, models, forward, accepts, rejects):
assert not (accepts and rejects)
if forward:
if accepts:
string = 'forward_accept_ts'
elif rejects:
string = 'forward_reject_ts'
else:
string = 'forward_ts'
else:
if accepts:
string = 'backward_accept_ts'
elif rejects:
string = 'backward_reject_ts'
else:
string = 'backward_ts'
loc = _here / 'results' / dataset
results = {}
num_results = math.inf
for folder in os.listdir(loc):
if all(model_spec in folder for model_spec in models):
results[folder] = []
for run in os.listdir(loc / folder):
with open(loc / folder / run, 'r') as f:
content = json.load(f)
ts = []
for info in content['history']:
ts.extend(info['train_metrics'][string])
results[folder].append(ts)
num_results = min(num_results, len(results[folder]))
results = {folder: list(it.chain(*result[:num_results])) for folder, result in results.items()}
colours = ['tab:red', 'tab:blue']
assert len(colours) >= len(results)
plt.figure(figsize=(7, 2))
for c, (folder, ts) in (zip(colours, results.items())):
if 'True' in folder:
folder = 'Seminorm'
else:
folder = 'Default norm'
plt.hist(ts, alpha=0.8, label=folder, bins=200, color=c)
plt.xlabel('t')
plt.ylabel('# Steps' if accepts or rejects else '# NFE')
plt.legend()
plt.tight_layout()
plt.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dataset')
parser.add_argument('models', nargs='*')
parser.add_argument('--forward', action='store_true')
parser.add_argument('--accepts', action='store_true')
parser.add_argument('--rejects', action='store_true')
args = parser.parse_args()
main(args.dataset, args.models, args.forward, args.accepts, args.rejects) | histogram.py | import argparse
import itertools as it
import json
import math
import matplotlib.pyplot as plt
import os
import pathlib
_here = pathlib.Path(__file__).resolve().parent
def main(dataset, models, forward, accepts, rejects):
assert not (accepts and rejects)
if forward:
if accepts:
string = 'forward_accept_ts'
elif rejects:
string = 'forward_reject_ts'
else:
string = 'forward_ts'
else:
if accepts:
string = 'backward_accept_ts'
elif rejects:
string = 'backward_reject_ts'
else:
string = 'backward_ts'
loc = _here / 'results' / dataset
results = {}
num_results = math.inf
for folder in os.listdir(loc):
if all(model_spec in folder for model_spec in models):
results[folder] = []
for run in os.listdir(loc / folder):
with open(loc / folder / run, 'r') as f:
content = json.load(f)
ts = []
for info in content['history']:
ts.extend(info['train_metrics'][string])
results[folder].append(ts)
num_results = min(num_results, len(results[folder]))
results = {folder: list(it.chain(*result[:num_results])) for folder, result in results.items()}
colours = ['tab:red', 'tab:blue']
assert len(colours) >= len(results)
plt.figure(figsize=(7, 2))
for c, (folder, ts) in (zip(colours, results.items())):
if 'True' in folder:
folder = 'Seminorm'
else:
folder = 'Default norm'
plt.hist(ts, alpha=0.8, label=folder, bins=200, color=c)
plt.xlabel('t')
plt.ylabel('# Steps' if accepts or rejects else '# NFE')
plt.legend()
plt.tight_layout()
plt.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dataset')
parser.add_argument('models', nargs='*')
parser.add_argument('--forward', action='store_true')
parser.add_argument('--accepts', action='store_true')
parser.add_argument('--rejects', action='store_true')
args = parser.parse_args()
main(args.dataset, args.models, args.forward, args.accepts, args.rejects) | 0.270866 | 0.208018 |
import unittest
from dcpquery import config
from dcpquery.db.models import File, BundleFileLink
from dcpquery.exceptions import DCPFileNotFoundError
from tests import vx_bf_links
class TestFiles(unittest.TestCase):
project_file = next(l.file for l in vx_bf_links if l.name == 'project_0.json')
process_file = next(l.file for l in vx_bf_links if l.name == 'process_0.json')
def test_select_file(self):
result = File.select_file(file_fqid=self.project_file.fqid)
self.assertEqual(result.uuid, self.project_file.uuid)
self.assertEqual(result.version, self.project_file.version)
expect_version = self.project_file.version.strftime("%Y-%m-%dT%H%M%S.%fZ")
self.assertEqual(result.fqid, f"{self.project_file.uuid}.{expect_version}")
self.assertEqual(result.body, self.project_file.body)
def test_delete_files(self):
file_fqids = [file[0] for file in config.db_session.query("fqid FROM files LIMIT 3;").all()]
# Need to delete bundle_file_links with fk to file prior to deleting the file
BundleFileLink.delete_links_for_files(file_fqids)
File.delete_files(file_fqids)
for file_fqid in file_fqids:
self.assertEqual(File.select_file(file_fqid=file_fqid), None)
def test_select_files_for_uuid(self):
file_uuid = config.db_session.execute("SELECT uuid from files_all_versions limit 1;").fetchall()[0][0]
expected_files = config.db_session.execute("SELECT * FROM files_all_versions where uuid = :file_uuid",
{"file_uuid": file_uuid}).fetchall()
files = File.select_files_for_uuid(str(file_uuid))
self.assertEqual(len(expected_files), len(files))
# check fqids match
self.assertEqual(sorted([x[0] for x in expected_files]), sorted([x.fqid for x in files]))
def test_select_files_for_non_existent_uuid(self):
file_uuid = 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA'
with self.assertRaises(DCPFileNotFoundError):
File.select_files_for_uuid(file_uuid)
if __name__ == '__main__':
unittest.main() | tests/unit/test_orm/test_files.py | import unittest
from dcpquery import config
from dcpquery.db.models import File, BundleFileLink
from dcpquery.exceptions import DCPFileNotFoundError
from tests import vx_bf_links
class TestFiles(unittest.TestCase):
project_file = next(l.file for l in vx_bf_links if l.name == 'project_0.json')
process_file = next(l.file for l in vx_bf_links if l.name == 'process_0.json')
def test_select_file(self):
result = File.select_file(file_fqid=self.project_file.fqid)
self.assertEqual(result.uuid, self.project_file.uuid)
self.assertEqual(result.version, self.project_file.version)
expect_version = self.project_file.version.strftime("%Y-%m-%dT%H%M%S.%fZ")
self.assertEqual(result.fqid, f"{self.project_file.uuid}.{expect_version}")
self.assertEqual(result.body, self.project_file.body)
def test_delete_files(self):
file_fqids = [file[0] for file in config.db_session.query("fqid FROM files LIMIT 3;").all()]
# Need to delete bundle_file_links with fk to file prior to deleting the file
BundleFileLink.delete_links_for_files(file_fqids)
File.delete_files(file_fqids)
for file_fqid in file_fqids:
self.assertEqual(File.select_file(file_fqid=file_fqid), None)
def test_select_files_for_uuid(self):
file_uuid = config.db_session.execute("SELECT uuid from files_all_versions limit 1;").fetchall()[0][0]
expected_files = config.db_session.execute("SELECT * FROM files_all_versions where uuid = :file_uuid",
{"file_uuid": file_uuid}).fetchall()
files = File.select_files_for_uuid(str(file_uuid))
self.assertEqual(len(expected_files), len(files))
# check fqids match
self.assertEqual(sorted([x[0] for x in expected_files]), sorted([x.fqid for x in files]))
def test_select_files_for_non_existent_uuid(self):
file_uuid = 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA'
with self.assertRaises(DCPFileNotFoundError):
File.select_files_for_uuid(file_uuid)
if __name__ == '__main__':
unittest.main() | 0.416797 | 0.269344 |
"""Tests for LlvmEnv.fork()."""
from time import time
from compiler_gym.envs import LlvmEnv
from compiler_gym.util.runfiles_path import runfiles_path
from tests.test_main import main
pytest_plugins = ["tests.envs.llvm.fixtures"]
EXAMPLE_BITCODE_FILE = runfiles_path(
"CompilerGym/compiler_gym/third_party/cBench/cBench-v0/crc32.bc"
)
EXAMPLE_BITCODE_IR_INSTRUCTION_COUNT = 196
def test_fork_state(env: LlvmEnv):
env.reset("cBench-v0/crc32")
env.step(0)
assert env.actions == [0]
new_env = env.fork()
try:
assert new_env.benchmark == new_env.benchmark
assert new_env.actions == env.actions
finally:
new_env.close()
def test_fork_reset(env: LlvmEnv):
env.reset("cBench-v0/crc32")
env.step(0)
env.step(1)
env.step(2)
new_env = env.fork()
try:
new_env.step(3)
assert env.actions == [0, 1, 2]
assert new_env.actions == [0, 1, 2, 3]
new_env.reset()
assert env.actions == [0, 1, 2]
assert new_env.actions == []
finally:
new_env.close()
def test_fork_custom_benchmark(env: LlvmEnv):
benchmark = env.make_benchmark(EXAMPLE_BITCODE_FILE)
env.reset(benchmark=benchmark)
def ir(env):
"""Strip the ModuleID line from IR."""
return "\n".join(env.ir.split("\n")[1:])
try:
new_env = env.fork()
assert ir(env) == ir(new_env)
new_env.reset()
assert ir(env) == ir(new_env)
finally:
new_env.close()
FUZZ_TIME_SECONDS = 5
A_FEW_RANDOM_ACTIONS = 10
def test_fork_state_fuzz_test(env: LlvmEnv):
"""Run random episodes and check that fork() produces equivalent state."""
end_time = time() + FUZZ_TIME_SECONDS
while time() < end_time:
env.reset()
# Take a few warmup steps to get an environment in a random state.
for _ in range(A_FEW_RANDOM_ACTIONS):
_, _, done, _ = env.step(env.action_space.sample())
if done: # Broken episode, restart.
break
else:
# Fork the environment and check that the states are equivalent.
new_env = env.fork()
try:
assert env.state == new_env.state
# Check that environment states remain equal if identical
# subsequent steps are taken.
for _ in range(A_FEW_RANDOM_ACTIONS):
action = env.action_space.sample()
_, _, done_a, _ = env.step(action)
_, _, done_b, _ = new_env.step(action)
assert done_a == done_b
if done_a: # Broken episode, restart.
break
assert env.state == new_env.state
finally:
new_env.close()
if __name__ == "__main__":
main() | tests/envs/llvm/fork_env_test.py | """Tests for LlvmEnv.fork()."""
from time import time
from compiler_gym.envs import LlvmEnv
from compiler_gym.util.runfiles_path import runfiles_path
from tests.test_main import main
pytest_plugins = ["tests.envs.llvm.fixtures"]
EXAMPLE_BITCODE_FILE = runfiles_path(
"CompilerGym/compiler_gym/third_party/cBench/cBench-v0/crc32.bc"
)
EXAMPLE_BITCODE_IR_INSTRUCTION_COUNT = 196
def test_fork_state(env: LlvmEnv):
env.reset("cBench-v0/crc32")
env.step(0)
assert env.actions == [0]
new_env = env.fork()
try:
assert new_env.benchmark == new_env.benchmark
assert new_env.actions == env.actions
finally:
new_env.close()
def test_fork_reset(env: LlvmEnv):
env.reset("cBench-v0/crc32")
env.step(0)
env.step(1)
env.step(2)
new_env = env.fork()
try:
new_env.step(3)
assert env.actions == [0, 1, 2]
assert new_env.actions == [0, 1, 2, 3]
new_env.reset()
assert env.actions == [0, 1, 2]
assert new_env.actions == []
finally:
new_env.close()
def test_fork_custom_benchmark(env: LlvmEnv):
benchmark = env.make_benchmark(EXAMPLE_BITCODE_FILE)
env.reset(benchmark=benchmark)
def ir(env):
"""Strip the ModuleID line from IR."""
return "\n".join(env.ir.split("\n")[1:])
try:
new_env = env.fork()
assert ir(env) == ir(new_env)
new_env.reset()
assert ir(env) == ir(new_env)
finally:
new_env.close()
FUZZ_TIME_SECONDS = 5
A_FEW_RANDOM_ACTIONS = 10
def test_fork_state_fuzz_test(env: LlvmEnv):
"""Run random episodes and check that fork() produces equivalent state."""
end_time = time() + FUZZ_TIME_SECONDS
while time() < end_time:
env.reset()
# Take a few warmup steps to get an environment in a random state.
for _ in range(A_FEW_RANDOM_ACTIONS):
_, _, done, _ = env.step(env.action_space.sample())
if done: # Broken episode, restart.
break
else:
# Fork the environment and check that the states are equivalent.
new_env = env.fork()
try:
assert env.state == new_env.state
# Check that environment states remain equal if identical
# subsequent steps are taken.
for _ in range(A_FEW_RANDOM_ACTIONS):
action = env.action_space.sample()
_, _, done_a, _ = env.step(action)
_, _, done_b, _ = new_env.step(action)
assert done_a == done_b
if done_a: # Broken episode, restart.
break
assert env.state == new_env.state
finally:
new_env.close()
if __name__ == "__main__":
main() | 0.598195 | 0.507263 |
import argparse
import re
import os
import ray
from ray.tune import run_experiments
from ray.tune.registry import register_trainable, register_env, get_trainable_cls
import ray.rllib.contrib.maddpg.maddpg as maddpg
from rllib_multiagent_particle_env import env_creator
from util import parse_args
def setup_ray():
ray.init(address='auto')
register_env('particle', env_creator)
def gen_policy(args, env, id):
use_local_critic = [
args.adv_policy == 'ddpg' if id < args.num_adversaries else
args.good_policy == 'ddpg' for id in range(env.num_agents)
]
return (
None,
env.observation_space_dict[id],
env.action_space_dict[id],
{
'agent_id': id,
'use_local_critic': use_local_critic[id],
'obs_space_dict': env.observation_space_dict,
'act_space_dict': env.action_space_dict,
}
)
def gen_policies(args, env_config):
env = env_creator(env_config)
return {'policy_%d' % i: gen_policy(args, env, i) for i in range(len(env.observation_space_dict))}
def to_multiagent_config(policies):
policy_ids = list(policies.keys())
return {
'policies': policies,
'policy_mapping_fn': lambda index: policy_ids[index]
}
def train(args, env_config):
def stop(trial_id, result):
max_train_time = int(os.environ.get('AML_MAX_TRAIN_TIME_SECONDS', 2 * 60 * 60))
return result['episode_reward_mean'] >= args.final_reward \
or result['time_total_s'] >= max_train_time
run_experiments({
'MADDPG_RLLib': {
'run': 'contrib/MADDPG',
'env': 'particle',
'stop': stop,
# Uncomment to enable more frequent checkpoints:
# 'checkpoint_freq': args.checkpoint_freq,
'checkpoint_at_end': True,
'local_dir': args.local_dir,
'restore': args.restore,
'config': {
# === Log ===
'log_level': 'ERROR',
# === Environment ===
'env_config': env_config,
'num_envs_per_worker': args.num_envs_per_worker,
'horizon': args.max_episode_len,
# === Policy Config ===
# --- Model ---
'good_policy': args.good_policy,
'adv_policy': args.adv_policy,
'actor_hiddens': [args.num_units] * 2,
'actor_hidden_activation': 'relu',
'critic_hiddens': [args.num_units] * 2,
'critic_hidden_activation': 'relu',
'n_step': args.n_step,
'gamma': args.gamma,
# --- Exploration ---
'tau': 0.01,
# --- Replay buffer ---
'buffer_size': int(1e6),
# --- Optimization ---
'actor_lr': args.lr,
'critic_lr': args.lr,
'learning_starts': args.train_batch_size * args.max_episode_len,
'sample_batch_size': args.sample_batch_size,
'train_batch_size': args.train_batch_size,
'batch_mode': 'truncate_episodes',
# --- Parallelism ---
'num_workers': args.num_workers,
'num_gpus': args.num_gpus,
'num_gpus_per_worker': 0,
# === Multi-agent setting ===
'multiagent': to_multiagent_config(gen_policies(args, env_config)),
},
},
}, verbose=1)
if __name__ == '__main__':
args = parse_args()
setup_ray()
env_config = {
'scenario_name': args.scenario,
'horizon': args.max_episode_len,
'video_frequency': args.checkpoint_freq,
}
train(args, env_config) | how-to-use-azureml/reinforcement-learning/multiagent-particle-envs/files/particle_train.py | import argparse
import re
import os
import ray
from ray.tune import run_experiments
from ray.tune.registry import register_trainable, register_env, get_trainable_cls
import ray.rllib.contrib.maddpg.maddpg as maddpg
from rllib_multiagent_particle_env import env_creator
from util import parse_args
def setup_ray():
ray.init(address='auto')
register_env('particle', env_creator)
def gen_policy(args, env, id):
use_local_critic = [
args.adv_policy == 'ddpg' if id < args.num_adversaries else
args.good_policy == 'ddpg' for id in range(env.num_agents)
]
return (
None,
env.observation_space_dict[id],
env.action_space_dict[id],
{
'agent_id': id,
'use_local_critic': use_local_critic[id],
'obs_space_dict': env.observation_space_dict,
'act_space_dict': env.action_space_dict,
}
)
def gen_policies(args, env_config):
env = env_creator(env_config)
return {'policy_%d' % i: gen_policy(args, env, i) for i in range(len(env.observation_space_dict))}
def to_multiagent_config(policies):
policy_ids = list(policies.keys())
return {
'policies': policies,
'policy_mapping_fn': lambda index: policy_ids[index]
}
def train(args, env_config):
def stop(trial_id, result):
max_train_time = int(os.environ.get('AML_MAX_TRAIN_TIME_SECONDS', 2 * 60 * 60))
return result['episode_reward_mean'] >= args.final_reward \
or result['time_total_s'] >= max_train_time
run_experiments({
'MADDPG_RLLib': {
'run': 'contrib/MADDPG',
'env': 'particle',
'stop': stop,
# Uncomment to enable more frequent checkpoints:
# 'checkpoint_freq': args.checkpoint_freq,
'checkpoint_at_end': True,
'local_dir': args.local_dir,
'restore': args.restore,
'config': {
# === Log ===
'log_level': 'ERROR',
# === Environment ===
'env_config': env_config,
'num_envs_per_worker': args.num_envs_per_worker,
'horizon': args.max_episode_len,
# === Policy Config ===
# --- Model ---
'good_policy': args.good_policy,
'adv_policy': args.adv_policy,
'actor_hiddens': [args.num_units] * 2,
'actor_hidden_activation': 'relu',
'critic_hiddens': [args.num_units] * 2,
'critic_hidden_activation': 'relu',
'n_step': args.n_step,
'gamma': args.gamma,
# --- Exploration ---
'tau': 0.01,
# --- Replay buffer ---
'buffer_size': int(1e6),
# --- Optimization ---
'actor_lr': args.lr,
'critic_lr': args.lr,
'learning_starts': args.train_batch_size * args.max_episode_len,
'sample_batch_size': args.sample_batch_size,
'train_batch_size': args.train_batch_size,
'batch_mode': 'truncate_episodes',
# --- Parallelism ---
'num_workers': args.num_workers,
'num_gpus': args.num_gpus,
'num_gpus_per_worker': 0,
# === Multi-agent setting ===
'multiagent': to_multiagent_config(gen_policies(args, env_config)),
},
},
}, verbose=1)
if __name__ == '__main__':
args = parse_args()
setup_ray()
env_config = {
'scenario_name': args.scenario,
'horizon': args.max_episode_len,
'video_frequency': args.checkpoint_freq,
}
train(args, env_config) | 0.505859 | 0.145996 |
from Stack import Stack
from Brackets import Brackets
def brackets_validator(str):
print(str)
flag = True
opening_bracket_stack = Stack()
position = 0
for ch in str:
position += 1
if (ch == '(' or ch == '[' or ch == '{'):
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
if (ch == ')' or ch == ']' or ch == '}'):
if opening_bracket_stack.empty():
flag = False
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
break
elif (not opening_bracket_stack.top().Match(ch)):
flag = False
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
break
else :
opening_bracket_stack.pop()
if (opening_bracket_stack.empty() and flag):
#print("Success")
return -1
else :
#print(opening_bracket_stack.top().posi)
return opening_bracket_stack.top().posi
def brackets_validator_from_file(file_name):
opening_bracket_stack = Stack()
flag = True
position = 0
with open(file_name) as file:
while(True):
position += 1
ch = file.read(1)
if not ch:
break
if (ch == '(' or ch == '[' or ch == '{'):
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
if (ch == ')' or ch == ']' or ch == '}'):
if opening_bracket_stack.empty():
flag = False
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
break
elif (not opening_bracket_stack.top().Match(ch)):
flag = False
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
break
else :
opening_bracket_stack.pop()
if (opening_bracket_stack.empty() and flag):
#print("Success")
return -1
else :
#print(opening_bracket_stack.top().posi)
return opening_bracket_stack.top().posi | Brackets_Validator.py | from Stack import Stack
from Brackets import Brackets
def brackets_validator(str):
print(str)
flag = True
opening_bracket_stack = Stack()
position = 0
for ch in str:
position += 1
if (ch == '(' or ch == '[' or ch == '{'):
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
if (ch == ')' or ch == ']' or ch == '}'):
if opening_bracket_stack.empty():
flag = False
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
break
elif (not opening_bracket_stack.top().Match(ch)):
flag = False
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
break
else :
opening_bracket_stack.pop()
if (opening_bracket_stack.empty() and flag):
#print("Success")
return -1
else :
#print(opening_bracket_stack.top().posi)
return opening_bracket_stack.top().posi
def brackets_validator_from_file(file_name):
opening_bracket_stack = Stack()
flag = True
position = 0
with open(file_name) as file:
while(True):
position += 1
ch = file.read(1)
if not ch:
break
if (ch == '(' or ch == '[' or ch == '{'):
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
if (ch == ')' or ch == ']' or ch == '}'):
if opening_bracket_stack.empty():
flag = False
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
break
elif (not opening_bracket_stack.top().Match(ch)):
flag = False
temp = Brackets(ch, position)
opening_bracket_stack.push(temp)
break
else :
opening_bracket_stack.pop()
if (opening_bracket_stack.empty() and flag):
#print("Success")
return -1
else :
#print(opening_bracket_stack.top().posi)
return opening_bracket_stack.top().posi | 0.099099 | 0.277914 |
import os
import time
import json
import urllib
import subprocess
TRACE_PATH = '../cooked_traces/'
with open('./chrome_retry_log', 'wb') as f:
f.write('chrome retry log\n')
os.system('sudo sysctl -w net.ipv4.ip_forward=1')
ip_data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
ip = str(ip_data['ip'])
ABR_ALGO = 'BB'
PROCESS_ID = 0
command_BB = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'RB'
PROCESS_ID = 1
command_RB = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
print command_RB
ABR_ALGO = 'FIXED'
PROCESS_ID = 2
command_FIXED = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'FESTIVE'
PROCESS_ID = 3
command_FESTIVE = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'BOLA'
PROCESS_ID = 4
command_BOLA = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'fastMPC'
PROCESS_ID = 5
command_fastMPC = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'robustMPC'
PROCESS_ID = 6
command_robustMPC = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'RL'
PROCESS_ID = 7
command_RL = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
# proc_BB = subprocess.Popen(command_BB,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
proc_RB = subprocess.Popen(command_RB,
shell=True)
# stdout=subprocess.PIPE,
time.sleep(0.1)
# proc_FIXED = subprocess.Popen(command_FIXED,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_FESTIVE = subprocess.Popen(command_FESTIVE,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_BOLA = subprocess.Popen(command_BOLA,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_fastMPC = subprocess.Popen(command_fastMPC,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_robustMPC = subprocess.Popen(command_robustMPC,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_RL = subprocess.Popen(command_RL, stdout=subprocess.PIPE, shell=True)
# time.sleep(0.1)
# proc_BB.wait()
proc_RB.wait()
# proc_FIXED.wait()
# proc_FESTIVE.wait()
# proc_BOLA.wait()
# proc_fastMPC.wait()
# proc_robustMPC.wait()
# proc_RL.wait() | run_exp/run_all_traces.py | import os
import time
import json
import urllib
import subprocess
TRACE_PATH = '../cooked_traces/'
with open('./chrome_retry_log', 'wb') as f:
f.write('chrome retry log\n')
os.system('sudo sysctl -w net.ipv4.ip_forward=1')
ip_data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
ip = str(ip_data['ip'])
ABR_ALGO = 'BB'
PROCESS_ID = 0
command_BB = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'RB'
PROCESS_ID = 1
command_RB = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
print command_RB
ABR_ALGO = 'FIXED'
PROCESS_ID = 2
command_FIXED = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'FESTIVE'
PROCESS_ID = 3
command_FESTIVE = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'BOLA'
PROCESS_ID = 4
command_BOLA = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'fastMPC'
PROCESS_ID = 5
command_fastMPC = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'robustMPC'
PROCESS_ID = 6
command_robustMPC = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
ABR_ALGO = 'RL'
PROCESS_ID = 7
command_RL = 'python run_traces.py ' + TRACE_PATH + ' ' + ABR_ALGO + ' ' + str(PROCESS_ID) + ' ' + ip
# proc_BB = subprocess.Popen(command_BB,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
proc_RB = subprocess.Popen(command_RB,
shell=True)
# stdout=subprocess.PIPE,
time.sleep(0.1)
# proc_FIXED = subprocess.Popen(command_FIXED,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_FESTIVE = subprocess.Popen(command_FESTIVE,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_BOLA = subprocess.Popen(command_BOLA,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_fastMPC = subprocess.Popen(command_fastMPC,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_robustMPC = subprocess.Popen(command_robustMPC,
# stdout=subprocess.PIPE,
# shell=True)
# time.sleep(0.1)
# proc_RL = subprocess.Popen(command_RL, stdout=subprocess.PIPE, shell=True)
# time.sleep(0.1)
# proc_BB.wait()
proc_RB.wait()
# proc_FIXED.wait()
# proc_FESTIVE.wait()
# proc_BOLA.wait()
# proc_fastMPC.wait()
# proc_robustMPC.wait()
# proc_RL.wait() | 0.062238 | 0.046055 |
import pytest
from valida.conditions import (
KeyDataType,
KeyLength,
ValueDataType,
ValueLength,
KeyLike,
Value,
Key,
Index,
NullCondition,
ConditionAnd,
ConditionOr,
ConditionXor,
ConditionLike,
)
from valida.datapath import DataPath, ListValue, MapValue
from valida.errors import InvalidCallable, MalformedConditionLikeSpec
def test_mixed_key_index_binary_condition_raises_type_error():
with pytest.raises(TypeError):
Key.equal_to(1) | Index.equal_to(1)
def test_mixed_key_index_second_order_binary_condition_raises_type_error():
with pytest.raises(TypeError):
vc1 = Value.equal_to(1)
kc1 = Key.equal_to(1)
ic1 = Index.equal_to(1)
mc1 = vc1 | kc1
mc2 = vc1 | ic1
mc1 | mc2
def test_null_condition_does_not_generate_binary_condition():
c1 = Value.equal_to(1)
assert ConditionAnd(c1, NullCondition()) == c1
assert ConditionAnd(NullCondition(), c1) == c1
assert ConditionOr(c1, NullCondition()) == c1
assert ConditionOr(NullCondition(), c1) == c1
assert ConditionXor(c1, NullCondition()) == c1
assert ConditionXor(NullCondition(), c1) == c1
def test_null_condition_filter_includes_all_list_items():
my_list = [1, 2, 3]
assert NullCondition().filter(my_list).data == my_list
def test_null_condition_filter_includes_all_map_items():
my_dict = {"a": 1, "b": 2, "c": 3}
assert NullCondition().filter(my_dict).data == list(my_dict.values())
def test_condition_callable_aliases():
assert Value.eq(1) == Value.equal_to(1)
assert Value.lt(1) == Value.less_than(1)
assert Value.gt(1) == Value.greater_than(1)
assert Value.lte(1) == Value.less_than_or_equal_to(1)
assert Value.gte(1) == Value.greater_than_or_equal_to(1)
def test_removal_of_null_condition_from_binary_ops():
c1 = Value.gt(5) & NullCondition()
assert not any(i.is_null for i in c1.flatten()[0])
c1 = Value.lt(3) | Value.gt(5) & NullCondition()
assert not any(i.is_null for i in c1.flatten()[0])
def test_equality():
c1 = Value.truthy()
c2 = Value.truthy()
assert c1 == c2
c1 = Value.gte(3.5)
c2 = Value.gte(3.5)
assert c1 == c2
c1 = Value.equal_to(1.2)
c2 = Value.equal_to(2.1)
assert c1 != c2
c1 = Value.equal_to(1.2)
c2 = Value.gte(1.2)
assert c1 != c2
c1 = Value.length.equal_to(1)
c2 = Value.length.equal_to(1)
assert c1 == c2
c1 = Key.in_([1, 2, 3])
c2 = Key.in_([1, 2, 3])
assert c1 == c2
def test_evalable_repr_for_simple_conditions():
c1 = Value.equal_to(1)
c2 = Value.lte(2)
c3 = Value.not_equal_to(1)
c4 = c1 & c2
c5 = c2 | c3 & c1
for i in (c1, c2, c3, c4, c5):
assert eval(repr(i)) == i
def test_evalable_repr_for_simple_list_value():
ind_conds = (None, 0, Index.equal_to(0))
val_conds = (None, 1, Value.equal_to(1))
labels = (None, "my_list_value")
for i in ind_conds:
for j in val_conds:
for k in labels:
list_val = ListValue(index=i, value=j, label=k)
assert eval(repr(list_val)) == list_val
def test_evalable_repr_for_simple_map_value():
key_conds = (None, 0, Key.equal_to(0))
val_conds = (None, 1, Value.equal_to(1))
labels = (None, "my_list_value")
for i in key_conds:
for j in val_conds:
for k in labels:
map_val = MapValue(key=i, value=j, label=k)
assert eval(repr(map_val)) == map_val
def test_binary_op_equality():
bo1 = Value.eq(1) & Value.lte(2)
bo2 = Value.eq(1) & Value.lte(2)
assert bo1 == bo2
bo1 = Value.eq(1) | Value.lte(2)
bo2 = Value.eq(1) | Value.lte(2)
assert bo1 == bo2
bo1 = Value.eq(1) ^ Value.lte(2)
bo2 = Value.eq(1) ^ Value.lte(2)
assert bo1 == bo2
bo1 = Value.eq(1) & Value.lte(2) & Value.gt(0)
bo2 = Value.eq(1) & Value.lte(2) & Value.gt(0)
assert bo1 == bo2
def test_commutativity_of_binary_ops():
v1a = Value.lt(2)
v1b = Value.gt(2)
v1c = Value.eq(3)
assert v1a & v1b == v1b & v1a
assert v1a | v1b == v1b | v1a
assert v1a ^ v1b == v1b ^ v1a
assert v1a & (v1b | v1c) == (v1b | v1c) & v1a == (v1c | v1b) & v1a
def test_truthy_falsy_for_integers():
data = [0, 1, 2]
assert Value.truthy().filter(data).data == [1, 2]
assert Value.falsy().filter(data).data == [0]
def test_value_null_condition_list_value():
assert ListValue() == ListValue(value=NullCondition())
def test_value_null_condition_map_value():
assert MapValue() == MapValue(value=NullCondition())
def test_raise_on_defined_callable_not_returning_bool():
def my_callable(x):
return None
with pytest.raises(InvalidCallable):
Value(my_callable).test(1)
def test_raise_on_lambda_callable_not_returning_bool():
my_callable = lambda x: None
with pytest.raises(InvalidCallable):
Value(my_callable).test(1)
def test_is_key_like_condition():
assert Key.eq(1).is_key_like
def test_is_key_like_condition_binary():
k1 = Key.eq(1)
k2 = Key.gt(2)
assert (k1 | k2).is_key_like
def test_is_key_like_condition_ternary():
k1 = Key.eq(1)
k2 = Key.gt(2)
k3 = Key.lt(10)
assert (k1 | k2 & k3).is_key_like
def test_is_index_like_condition():
assert Index.eq(1).is_index_like
def test_is_index_like_condition_binary():
k1 = Index.eq(1)
k2 = Index.gt(2)
assert (k1 | k2).is_index_like
def test_is_index_like_condition_ternary():
k1 = Index.eq(1)
k2 = Index.gt(2)
k3 = Index.lt(10)
assert (k1 | k2 & k3).is_index_like
def test_is_value_like_condition():
assert Value.eq(1).is_value_like
def test_is_value_like_condition_binary():
k1 = Value.eq(1)
k2 = Value.gt(2)
assert (k1 | k2).is_value_like
def test_is_value_like_condition_ternary():
k1 = Value.eq(1)
k2 = Value.gt(2)
k3 = Value.lt(10)
assert (k1 | k2 & k3).is_value_like
def test_raise_on_unknown_spec_key():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"bad_key": 1})
def test_raise_on_unknown_spec_key_binary_op():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"or": [{"bad_key": 1}, {"value.eq": 2}]})
def test_raise_on_non_list_argument_to_binary_op():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"or": {"value.eq": 1, "value.eq": 2}})
def test_raise_on_non_multiple_keys_in_binary_op_spec():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec(
{
"and": [
{
"value.lt": 1,
"value.gt": 2,
}
]
}
)
def test_raise_on_multiple_keys_in_condition_spec():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"value.lt": 2, "value.gt": 0})
def test_empty_binary_op_is_null_condition():
assert ConditionLike.from_spec({"and": []}) == NullCondition()
def test_from_spec_callable_invocation_for_multi_arg_callable():
assert ConditionLike.from_spec(
{"value.in_range": {"lower": 1, "upper": 2}}
) == ConditionLike.from_spec({"value.in_range": [1, 2]})
def test_KeyDataType_is_key_like():
assert KeyDataType.equal_to(str).is_key_like
def test_KeyLength_is_key_like():
assert KeyLength.equal_to(2).is_key_like
def test_KeyDataType_is_key_like():
assert ValueDataType.equal_to(str).is_value_like
def test_KeyDataType_is_key_like():
assert ValueLength.equal_to(2).is_value_like
def test_equivalence_of_ConditionLike_from_spec_value_dtype_int_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "int"}
) == ConditionLike.from_spec({"value.dtype.eq": int})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_float_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "float"}
) == ConditionLike.from_spec({"value.dtype.eq": float})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_str_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "str"}
) == ConditionLike.from_spec({"value.dtype.eq": str})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_list_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "list"}
) == ConditionLike.from_spec({"value.dtype.eq": list})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_dict_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "dict"}
) == ConditionLike.from_spec({"value.dtype.eq": dict})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_map_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "map"}
) == ConditionLike.from_spec({"value.dtype.eq": dict})
def test_equivalence_of_ConditionLike_from_spec_type_and_dtype():
assert ConditionLike.from_spec({"value.type.eq": int}) == ConditionLike.from_spec(
{"value.dtype.eq": int}
)
def test_equivalence_of_ConditionLike_from_spec_length_and_len():
assert ConditionLike.from_spec({"value.length.eq": 2}) == ConditionLike.from_spec(
{"value.len.eq": 2}
)
def test_equivalence_of_ConditionLike_from_spec_callable_in_and_in_():
assert ConditionLike.from_spec({"value.in": [1, 2]}) == ConditionLike.from_spec(
{"value.in_": [1, 2]}
)
def test_ConditionLike_from_spec_raise_on_missing_callable():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"value": 1})
def test_ConditionLike_from_spec_raise_on_missing_callable_with_preprocessor():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"value.length": 1})
def test_ConditionLike_from_spec_case_insensitivity_datum_type():
assert (
ConditionLike.from_spec({"value.eq": 1})
== ConditionLike.from_spec({"Value.eq": 1})
== ConditionLike.from_spec({"vAlue.eq": 1})
== ConditionLike.from_spec({"VALUE.eq": 1})
)
def test_ConditionLike_from_spec_case_insensitivity_callable_name():
assert (
ConditionLike.from_spec({"value.eq": 1})
== ConditionLike.from_spec({"value.Eq": 1})
== ConditionLike.from_spec({"value.eQ": 1})
== ConditionLike.from_spec({"value.EQ": 1})
)
def test_ConditionLike_from_spec_case_insensitivity_preprocessor_name():
assert (
ConditionLike.from_spec({"value.len.eq": 1})
== ConditionLike.from_spec({"value.Len.eq": 1})
== ConditionLike.from_spec({"value.lEn.eq": 1})
== ConditionLike.from_spec({"value.LEN.eq": 1})
)
def test_ConditionLike_from_spec_single_arg_callable_DataPath():
assert ConditionLike.from_spec(
{"value.equal_to": {"path": ("a", "b")}}
) == Value.eq(DataPath("a", "b"))
def test_ConditionLike_from_spec_single_arg_callable_DataPath_case_insensitivity():
assert (
ConditionLike.from_spec({"value.equal_to": {"path": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"Path": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"paTh": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"PATH": ("a", "b")}})
)
def test_ConditionLike_from_spec_single_arg_callable_DataPath_map_keys():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.map_keys": ("a", "b")}}
) == Value.eq(DataPath("a", "b").map_keys())
def test_ConditionLike_from_spec_single_arg_callable_DataPath_map_keys_case_insensitivity():
assert (
ConditionLike.from_spec({"value.equal_to": {"path.map_keys": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"path.Map_Keys": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"path.map_kEys": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"path.MAP_KEYS": ("a", "b")}})
)
def test_ConditionLike_from_spec_single_arg_callable_DataPath_map_values():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.map_values": ("a", "b")}}
) == Value.eq(DataPath("a", "b").map_values())
def test_ConditionLike_from_spec_single_arg_callable_DataPath_length():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.length": ("a", "b")}}
) == Value.eq(DataPath("a", "b").length())
def test_ConditionLike_from_spec_single_arg_callable_DataPath_dtype():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.dtype": ("a", "b")}}
) == Value.eq(DataPath("a", "b").dtype())
def test_equivalence_ConditionLike_from_spec_single_arg_callable_DataPath_dtype_type():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.dtype": ("a", "b")}}
) == ConditionLike.from_spec({"value.equal_to": {"path.type": ("a", "b")}})
def test_equivalence_ConditionLike_from_spec_single_arg_callable_DataPath_len_length():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.len": ("a", "b")}}
) == ConditionLike.from_spec({"value.equal_to": {"path.length": ("a", "b")}})
def test_equivalence_ConditionLike_from_spec_multi_arg_callable_DataPath():
assert (
ConditionLike.from_spec(
{
"value.in_range": {
"lower": {"path": ("A", "lower")},
"upper": {"path": ("A", "upper")},
}
}
)
== Value.in_range(lower=DataPath("A", "lower"), upper=DataPath("A", "upper"))
)
def test_ConditionLike_from_spec_DataPath_escape():
assert ConditionLike.from_spec(
{"value.equal_to": {r"\path": ["A", "B"]}}
) == Value.equal_to({"path": ["A", "B"]})
def test_ConditionLike_from_spec_DataPath_escape_multi_item():
assert ConditionLike.from_spec(
{"value.equal_to": {r"\path": ["A", "B"], "key": "val"}}
) == Value.equal_to({"path": ["A", "B"], "key": "val"})
def test_ConditionLike_from_spec_DataPath_escape_slashed():
assert ConditionLike.from_spec(
{"value.equal_to": {r"\\path": ["A", "B"]}}
) == Value.equal_to({"\path": ["A", "B"]})
def test_ConditionLike_from_spec_DataPath_map_values_escape():
assert ConditionLike.from_spec(
{"value.equal_to": {r"\path.map_values": ["A", "B"]}}
) == Value.equal_to({"path.map_values": ["A", "B"]})
def test_ConditionLike_from_spec_equivalence_value_equal_to():
assert ConditionLike.from_spec({"value.equal_to": 4}) == Value.equal_to(4)
def test_ConditionLike_from_spec_dtype_case_insensitivity():
assert (
ConditionLike.from_spec({"value.dtype.equal_to": "str"})
== ConditionLike.from_spec({"value.dtype.equal_to": "STR"})
== ConditionLike.from_spec({"value.dtype.equal_to": "sTr"})
)
def test_ConditionLike_from_spec_dtype_native_type_equivalence():
assert ConditionLike.from_spec(
{"value.dtype.equal_to": "str"}
) == ConditionLike.from_spec({"value.dtype.equal_to": str})
def test_ConditionLike_from_spec_equivalence_is_instance_single_cls():
assert ConditionLike.from_spec({"value.is_instance": ["str"]}) == Value.is_instance(
str
)
def test_ConditionLike_from_spec_equivalence_is_instance_multiple_cls():
assert ConditionLike.from_spec(
{"value.is_instance": ["str", "int"]}
) == Value.is_instance(str, int)
def test_ConditionLike_from_spec_equivalence_is_instance_native_type():
assert ConditionLike.from_spec(
{"value.is_instance": ["str", "int"]}
) == ConditionLike.from_spec({"value.is_instance": [str, int]}) | tests/test_conditions.py | import pytest
from valida.conditions import (
KeyDataType,
KeyLength,
ValueDataType,
ValueLength,
KeyLike,
Value,
Key,
Index,
NullCondition,
ConditionAnd,
ConditionOr,
ConditionXor,
ConditionLike,
)
from valida.datapath import DataPath, ListValue, MapValue
from valida.errors import InvalidCallable, MalformedConditionLikeSpec
def test_mixed_key_index_binary_condition_raises_type_error():
with pytest.raises(TypeError):
Key.equal_to(1) | Index.equal_to(1)
def test_mixed_key_index_second_order_binary_condition_raises_type_error():
with pytest.raises(TypeError):
vc1 = Value.equal_to(1)
kc1 = Key.equal_to(1)
ic1 = Index.equal_to(1)
mc1 = vc1 | kc1
mc2 = vc1 | ic1
mc1 | mc2
def test_null_condition_does_not_generate_binary_condition():
c1 = Value.equal_to(1)
assert ConditionAnd(c1, NullCondition()) == c1
assert ConditionAnd(NullCondition(), c1) == c1
assert ConditionOr(c1, NullCondition()) == c1
assert ConditionOr(NullCondition(), c1) == c1
assert ConditionXor(c1, NullCondition()) == c1
assert ConditionXor(NullCondition(), c1) == c1
def test_null_condition_filter_includes_all_list_items():
my_list = [1, 2, 3]
assert NullCondition().filter(my_list).data == my_list
def test_null_condition_filter_includes_all_map_items():
my_dict = {"a": 1, "b": 2, "c": 3}
assert NullCondition().filter(my_dict).data == list(my_dict.values())
def test_condition_callable_aliases():
assert Value.eq(1) == Value.equal_to(1)
assert Value.lt(1) == Value.less_than(1)
assert Value.gt(1) == Value.greater_than(1)
assert Value.lte(1) == Value.less_than_or_equal_to(1)
assert Value.gte(1) == Value.greater_than_or_equal_to(1)
def test_removal_of_null_condition_from_binary_ops():
c1 = Value.gt(5) & NullCondition()
assert not any(i.is_null for i in c1.flatten()[0])
c1 = Value.lt(3) | Value.gt(5) & NullCondition()
assert not any(i.is_null for i in c1.flatten()[0])
def test_equality():
c1 = Value.truthy()
c2 = Value.truthy()
assert c1 == c2
c1 = Value.gte(3.5)
c2 = Value.gte(3.5)
assert c1 == c2
c1 = Value.equal_to(1.2)
c2 = Value.equal_to(2.1)
assert c1 != c2
c1 = Value.equal_to(1.2)
c2 = Value.gte(1.2)
assert c1 != c2
c1 = Value.length.equal_to(1)
c2 = Value.length.equal_to(1)
assert c1 == c2
c1 = Key.in_([1, 2, 3])
c2 = Key.in_([1, 2, 3])
assert c1 == c2
def test_evalable_repr_for_simple_conditions():
c1 = Value.equal_to(1)
c2 = Value.lte(2)
c3 = Value.not_equal_to(1)
c4 = c1 & c2
c5 = c2 | c3 & c1
for i in (c1, c2, c3, c4, c5):
assert eval(repr(i)) == i
def test_evalable_repr_for_simple_list_value():
ind_conds = (None, 0, Index.equal_to(0))
val_conds = (None, 1, Value.equal_to(1))
labels = (None, "my_list_value")
for i in ind_conds:
for j in val_conds:
for k in labels:
list_val = ListValue(index=i, value=j, label=k)
assert eval(repr(list_val)) == list_val
def test_evalable_repr_for_simple_map_value():
key_conds = (None, 0, Key.equal_to(0))
val_conds = (None, 1, Value.equal_to(1))
labels = (None, "my_list_value")
for i in key_conds:
for j in val_conds:
for k in labels:
map_val = MapValue(key=i, value=j, label=k)
assert eval(repr(map_val)) == map_val
def test_binary_op_equality():
bo1 = Value.eq(1) & Value.lte(2)
bo2 = Value.eq(1) & Value.lte(2)
assert bo1 == bo2
bo1 = Value.eq(1) | Value.lte(2)
bo2 = Value.eq(1) | Value.lte(2)
assert bo1 == bo2
bo1 = Value.eq(1) ^ Value.lte(2)
bo2 = Value.eq(1) ^ Value.lte(2)
assert bo1 == bo2
bo1 = Value.eq(1) & Value.lte(2) & Value.gt(0)
bo2 = Value.eq(1) & Value.lte(2) & Value.gt(0)
assert bo1 == bo2
def test_commutativity_of_binary_ops():
v1a = Value.lt(2)
v1b = Value.gt(2)
v1c = Value.eq(3)
assert v1a & v1b == v1b & v1a
assert v1a | v1b == v1b | v1a
assert v1a ^ v1b == v1b ^ v1a
assert v1a & (v1b | v1c) == (v1b | v1c) & v1a == (v1c | v1b) & v1a
def test_truthy_falsy_for_integers():
data = [0, 1, 2]
assert Value.truthy().filter(data).data == [1, 2]
assert Value.falsy().filter(data).data == [0]
def test_value_null_condition_list_value():
assert ListValue() == ListValue(value=NullCondition())
def test_value_null_condition_map_value():
assert MapValue() == MapValue(value=NullCondition())
def test_raise_on_defined_callable_not_returning_bool():
def my_callable(x):
return None
with pytest.raises(InvalidCallable):
Value(my_callable).test(1)
def test_raise_on_lambda_callable_not_returning_bool():
my_callable = lambda x: None
with pytest.raises(InvalidCallable):
Value(my_callable).test(1)
def test_is_key_like_condition():
assert Key.eq(1).is_key_like
def test_is_key_like_condition_binary():
k1 = Key.eq(1)
k2 = Key.gt(2)
assert (k1 | k2).is_key_like
def test_is_key_like_condition_ternary():
k1 = Key.eq(1)
k2 = Key.gt(2)
k3 = Key.lt(10)
assert (k1 | k2 & k3).is_key_like
def test_is_index_like_condition():
assert Index.eq(1).is_index_like
def test_is_index_like_condition_binary():
k1 = Index.eq(1)
k2 = Index.gt(2)
assert (k1 | k2).is_index_like
def test_is_index_like_condition_ternary():
k1 = Index.eq(1)
k2 = Index.gt(2)
k3 = Index.lt(10)
assert (k1 | k2 & k3).is_index_like
def test_is_value_like_condition():
assert Value.eq(1).is_value_like
def test_is_value_like_condition_binary():
k1 = Value.eq(1)
k2 = Value.gt(2)
assert (k1 | k2).is_value_like
def test_is_value_like_condition_ternary():
k1 = Value.eq(1)
k2 = Value.gt(2)
k3 = Value.lt(10)
assert (k1 | k2 & k3).is_value_like
def test_raise_on_unknown_spec_key():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"bad_key": 1})
def test_raise_on_unknown_spec_key_binary_op():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"or": [{"bad_key": 1}, {"value.eq": 2}]})
def test_raise_on_non_list_argument_to_binary_op():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"or": {"value.eq": 1, "value.eq": 2}})
def test_raise_on_non_multiple_keys_in_binary_op_spec():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec(
{
"and": [
{
"value.lt": 1,
"value.gt": 2,
}
]
}
)
def test_raise_on_multiple_keys_in_condition_spec():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"value.lt": 2, "value.gt": 0})
def test_empty_binary_op_is_null_condition():
assert ConditionLike.from_spec({"and": []}) == NullCondition()
def test_from_spec_callable_invocation_for_multi_arg_callable():
assert ConditionLike.from_spec(
{"value.in_range": {"lower": 1, "upper": 2}}
) == ConditionLike.from_spec({"value.in_range": [1, 2]})
def test_KeyDataType_is_key_like():
assert KeyDataType.equal_to(str).is_key_like
def test_KeyLength_is_key_like():
assert KeyLength.equal_to(2).is_key_like
def test_KeyDataType_is_key_like():
assert ValueDataType.equal_to(str).is_value_like
def test_KeyDataType_is_key_like():
assert ValueLength.equal_to(2).is_value_like
def test_equivalence_of_ConditionLike_from_spec_value_dtype_int_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "int"}
) == ConditionLike.from_spec({"value.dtype.eq": int})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_float_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "float"}
) == ConditionLike.from_spec({"value.dtype.eq": float})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_str_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "str"}
) == ConditionLike.from_spec({"value.dtype.eq": str})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_list_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "list"}
) == ConditionLike.from_spec({"value.dtype.eq": list})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_dict_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "dict"}
) == ConditionLike.from_spec({"value.dtype.eq": dict})
def test_equivalence_of_ConditionLike_from_spec_value_dtype_map_spec():
assert ConditionLike.from_spec(
{"value.dtype.eq": "map"}
) == ConditionLike.from_spec({"value.dtype.eq": dict})
def test_equivalence_of_ConditionLike_from_spec_type_and_dtype():
assert ConditionLike.from_spec({"value.type.eq": int}) == ConditionLike.from_spec(
{"value.dtype.eq": int}
)
def test_equivalence_of_ConditionLike_from_spec_length_and_len():
assert ConditionLike.from_spec({"value.length.eq": 2}) == ConditionLike.from_spec(
{"value.len.eq": 2}
)
def test_equivalence_of_ConditionLike_from_spec_callable_in_and_in_():
assert ConditionLike.from_spec({"value.in": [1, 2]}) == ConditionLike.from_spec(
{"value.in_": [1, 2]}
)
def test_ConditionLike_from_spec_raise_on_missing_callable():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"value": 1})
def test_ConditionLike_from_spec_raise_on_missing_callable_with_preprocessor():
with pytest.raises(MalformedConditionLikeSpec):
ConditionLike.from_spec({"value.length": 1})
def test_ConditionLike_from_spec_case_insensitivity_datum_type():
assert (
ConditionLike.from_spec({"value.eq": 1})
== ConditionLike.from_spec({"Value.eq": 1})
== ConditionLike.from_spec({"vAlue.eq": 1})
== ConditionLike.from_spec({"VALUE.eq": 1})
)
def test_ConditionLike_from_spec_case_insensitivity_callable_name():
assert (
ConditionLike.from_spec({"value.eq": 1})
== ConditionLike.from_spec({"value.Eq": 1})
== ConditionLike.from_spec({"value.eQ": 1})
== ConditionLike.from_spec({"value.EQ": 1})
)
def test_ConditionLike_from_spec_case_insensitivity_preprocessor_name():
assert (
ConditionLike.from_spec({"value.len.eq": 1})
== ConditionLike.from_spec({"value.Len.eq": 1})
== ConditionLike.from_spec({"value.lEn.eq": 1})
== ConditionLike.from_spec({"value.LEN.eq": 1})
)
def test_ConditionLike_from_spec_single_arg_callable_DataPath():
assert ConditionLike.from_spec(
{"value.equal_to": {"path": ("a", "b")}}
) == Value.eq(DataPath("a", "b"))
def test_ConditionLike_from_spec_single_arg_callable_DataPath_case_insensitivity():
assert (
ConditionLike.from_spec({"value.equal_to": {"path": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"Path": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"paTh": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"PATH": ("a", "b")}})
)
def test_ConditionLike_from_spec_single_arg_callable_DataPath_map_keys():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.map_keys": ("a", "b")}}
) == Value.eq(DataPath("a", "b").map_keys())
def test_ConditionLike_from_spec_single_arg_callable_DataPath_map_keys_case_insensitivity():
assert (
ConditionLike.from_spec({"value.equal_to": {"path.map_keys": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"path.Map_Keys": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"path.map_kEys": ("a", "b")}})
== ConditionLike.from_spec({"value.equal_to": {"path.MAP_KEYS": ("a", "b")}})
)
def test_ConditionLike_from_spec_single_arg_callable_DataPath_map_values():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.map_values": ("a", "b")}}
) == Value.eq(DataPath("a", "b").map_values())
def test_ConditionLike_from_spec_single_arg_callable_DataPath_length():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.length": ("a", "b")}}
) == Value.eq(DataPath("a", "b").length())
def test_ConditionLike_from_spec_single_arg_callable_DataPath_dtype():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.dtype": ("a", "b")}}
) == Value.eq(DataPath("a", "b").dtype())
def test_equivalence_ConditionLike_from_spec_single_arg_callable_DataPath_dtype_type():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.dtype": ("a", "b")}}
) == ConditionLike.from_spec({"value.equal_to": {"path.type": ("a", "b")}})
def test_equivalence_ConditionLike_from_spec_single_arg_callable_DataPath_len_length():
assert ConditionLike.from_spec(
{"value.equal_to": {"path.len": ("a", "b")}}
) == ConditionLike.from_spec({"value.equal_to": {"path.length": ("a", "b")}})
def test_equivalence_ConditionLike_from_spec_multi_arg_callable_DataPath():
assert (
ConditionLike.from_spec(
{
"value.in_range": {
"lower": {"path": ("A", "lower")},
"upper": {"path": ("A", "upper")},
}
}
)
== Value.in_range(lower=DataPath("A", "lower"), upper=DataPath("A", "upper"))
)
def test_ConditionLike_from_spec_DataPath_escape():
assert ConditionLike.from_spec(
{"value.equal_to": {r"\path": ["A", "B"]}}
) == Value.equal_to({"path": ["A", "B"]})
def test_ConditionLike_from_spec_DataPath_escape_multi_item():
assert ConditionLike.from_spec(
{"value.equal_to": {r"\path": ["A", "B"], "key": "val"}}
) == Value.equal_to({"path": ["A", "B"], "key": "val"})
def test_ConditionLike_from_spec_DataPath_escape_slashed():
assert ConditionLike.from_spec(
{"value.equal_to": {r"\\path": ["A", "B"]}}
) == Value.equal_to({"\path": ["A", "B"]})
def test_ConditionLike_from_spec_DataPath_map_values_escape():
assert ConditionLike.from_spec(
{"value.equal_to": {r"\path.map_values": ["A", "B"]}}
) == Value.equal_to({"path.map_values": ["A", "B"]})
def test_ConditionLike_from_spec_equivalence_value_equal_to():
assert ConditionLike.from_spec({"value.equal_to": 4}) == Value.equal_to(4)
def test_ConditionLike_from_spec_dtype_case_insensitivity():
assert (
ConditionLike.from_spec({"value.dtype.equal_to": "str"})
== ConditionLike.from_spec({"value.dtype.equal_to": "STR"})
== ConditionLike.from_spec({"value.dtype.equal_to": "sTr"})
)
def test_ConditionLike_from_spec_dtype_native_type_equivalence():
assert ConditionLike.from_spec(
{"value.dtype.equal_to": "str"}
) == ConditionLike.from_spec({"value.dtype.equal_to": str})
def test_ConditionLike_from_spec_equivalence_is_instance_single_cls():
assert ConditionLike.from_spec({"value.is_instance": ["str"]}) == Value.is_instance(
str
)
def test_ConditionLike_from_spec_equivalence_is_instance_multiple_cls():
assert ConditionLike.from_spec(
{"value.is_instance": ["str", "int"]}
) == Value.is_instance(str, int)
def test_ConditionLike_from_spec_equivalence_is_instance_native_type():
assert ConditionLike.from_spec(
{"value.is_instance": ["str", "int"]}
) == ConditionLike.from_spec({"value.is_instance": [str, int]}) | 0.671363 | 0.75638 |
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# TODO: Ask the user how much assignments they want through loop through
untilLooped = input("Enter the amount of assignments you want to loop through: ")
startingNum = 1
# Line Spacer
print("If the website tells you 'wrong username/password', restart the script again and input your right credentials")
# TODO: Ask the user to enter the email and password credentials
userEmail = raw_input('Please input your email: ')
userPass = raw_input('Please input your password: ')
# TODO: Initialize chromedriver and open the zybooks url
browser = webdriver.Chrome('/Users/jesusperez/Downloads/chromedriver')
browser.get('https://learn.zybooks.com/signin')
browser.implicitly_wait(20) # Gives an implicit wait for the functions to run 25 seconds apart
# TODO: Click the Sign In field, enter sign in credentials
emailField = browser.find_element_by_css_selector('input[type=email]')
emailField.send_keys(userEmail)
passField = browser.find_element_by_css_selector('input[type=password]')
passField.send_keys(<PASSWORD>)
passField.send_keys(Keys.ENTER)
# TODO: Find the html with the name of course, click on it
courseName = browser.find_element_by_class_name('zybook-header-img')
courseName.click()
# TODO: Find the assignment button and click on it
assignmentButton = browser.find_element_by_css_selector('.tabs *:nth-child(3)')
assignmentButton.click()
time.sleep(3)
# TODO: Find the assignment text and click on it
assignment = browser.find_element_by_class_name('section-title')
assignment.click()
# TODO: Find the fieldsets, iterate through each child div and click on them
labels = browser.find_elements_by_tag_name('label')
# TODO: Click each radio button on the web page
def clickPoints(containerList):
for labelButton in containerList:
labelButton.click()
time.sleep(3) # Once the loop has exited, wait three seconds until the next thing
clickPoints(labels) # Call the loop
while(startingNum < untilLooped):
# TODO: Scroll down to the bottom of the web page
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# TODO: Go onto the next section once finished with the loop above
nextSection = browser.find_element_by_class_name('nav-link ember-view')
nextSection.click()
time.sleep(5) # Wait for five seconds until the web page loads
clickPoints(labels) # Call the loop for the new web page
startingNum += 1 # Increment the starting num | zybrowser.py | import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# TODO: Ask the user how much assignments they want through loop through
untilLooped = input("Enter the amount of assignments you want to loop through: ")
startingNum = 1
# Line Spacer
print("If the website tells you 'wrong username/password', restart the script again and input your right credentials")
# TODO: Ask the user to enter the email and password credentials
userEmail = raw_input('Please input your email: ')
userPass = raw_input('Please input your password: ')
# TODO: Initialize chromedriver and open the zybooks url
browser = webdriver.Chrome('/Users/jesusperez/Downloads/chromedriver')
browser.get('https://learn.zybooks.com/signin')
browser.implicitly_wait(20) # Gives an implicit wait for the functions to run 25 seconds apart
# TODO: Click the Sign In field, enter sign in credentials
emailField = browser.find_element_by_css_selector('input[type=email]')
emailField.send_keys(userEmail)
passField = browser.find_element_by_css_selector('input[type=password]')
passField.send_keys(<PASSWORD>)
passField.send_keys(Keys.ENTER)
# TODO: Find the html with the name of course, click on it
courseName = browser.find_element_by_class_name('zybook-header-img')
courseName.click()
# TODO: Find the assignment button and click on it
assignmentButton = browser.find_element_by_css_selector('.tabs *:nth-child(3)')
assignmentButton.click()
time.sleep(3)
# TODO: Find the assignment text and click on it
assignment = browser.find_element_by_class_name('section-title')
assignment.click()
# TODO: Find the fieldsets, iterate through each child div and click on them
labels = browser.find_elements_by_tag_name('label')
# TODO: Click each radio button on the web page
def clickPoints(containerList):
for labelButton in containerList:
labelButton.click()
time.sleep(3) # Once the loop has exited, wait three seconds until the next thing
clickPoints(labels) # Call the loop
while(startingNum < untilLooped):
# TODO: Scroll down to the bottom of the web page
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# TODO: Go onto the next section once finished with the loop above
nextSection = browser.find_element_by_class_name('nav-link ember-view')
nextSection.click()
time.sleep(5) # Wait for five seconds until the web page loads
clickPoints(labels) # Call the loop for the new web page
startingNum += 1 # Increment the starting num | 0.064407 | 0.169991 |
import os
import logging
import json
import random
from pathlib import Path
import spacy
from spacy.util import minibatch, compounding
from collections import defaultdict
log = logging.getLogger('CVE_Analyzer')
# ------------------------ PERFORMANCES ------------------------
def _compute_performances(performaces, annotations, entities):
predictions = [[ent.start_char, ent.end_char, ent.label_] for ent in entities]
for entry in annotations + predictions:
if entry in annotations and entry in predictions:
performaces["tp"] += 1
elif entry in annotations and entry not in predictions:
performaces["fn"] += 1
elif entry not in annotations and entry in predictions:
performaces["fp"] += 1
else:
performaces['tn'] += 1
def _compute_precision(performaces):
return float(performaces["tp"]) / (performaces["tp"] + performaces["fp"])
def _compute_recall(performaces):
return float(performaces["tp"]) / (performaces["tp"] + performaces["fn"])
def _compute_f_measure(precision, recall):
return 2*precision*recall / (precision + recall)
def _compute_accuracy(performaces):
return float((performaces['tp'] + performaces['tn'])) / \
float((performaces['tp'] + performaces['tn'] + performaces['fp'] + performaces['fn']))
def _get_dataset(dataset_path):
if not os.path.exists(dataset_path):
raise OSError("Dataset file {} not found".format(dataset_path))
with open(dataset_path, 'r') as dataset_f:
dataset = json.load(dataset_f)
return dataset
def _get_ner_component(nlp):
# Add entity recognizer to model if it's not in the pipeline
# nlp.create_pipe works for built-ins that are registered with spaCy
if 'ner' not in nlp.pipe_names:
ner = nlp.create_pipe('ner')
nlp.add_pipe(ner)
# otherwise, get it, so we can add labels to it
else:
ner = nlp.get_pipe('ner')
return ner
# ------------------------ EXPORTED METHODS ------------------------
def get_train_and_test_sets(dataset_file, split_ratio):
dataset = _get_dataset(dataset_file)
random.shuffle(dataset)
split = int(len(dataset)*split_ratio)
return dataset[:split], dataset[split:]
def pp_performances(accuracy, precision, recall, f_measure):
print("\n-------------------------------------------")
print("PERFORMANCES:")
print("\nAccuracy: {}".format(accuracy))
print("Precision: {}".format(precision))
print("Recall: {}".format(recall))
print("F-measure: {}".format(f_measure))
print("\n-------------------------------------------")
def save_model(output_dir, model_name, nlp):
output_dir = Path(output_dir)
if not output_dir.exists():
output_dir.mkdir(parents=True, exist_ok=True)
nlp.meta['name'] = model_name
nlp.to_disk(output_dir)
log.debug("Saved model to %s", output_dir)
def get_model(model_path):
return spacy.load(model_path)
def test(nlp, testset):
performances = {
"tp": 0,
"fp": 0,
"fn": 0,
"tn": 0
}
for description, annotations in testset:
doc = nlp(description)
_compute_performances(performances, annotations['entities'], doc.ents)
performances['accuracy'] = _compute_accuracy(performances)
performances['precision'] = _compute_precision(performances)
performances['recall'] = _compute_recall(performances)
performances['f_measure'] = _compute_f_measure(performances['precision'], performances['recall'])
return performances
def train(trainset, labels, n_iter, drop_rate):
nlp = spacy.blank('en')
ner = _get_ner_component(nlp)
for label in labels:
ner.add_label(label)
optimizer = nlp.begin_training()
# get names of other pipes to disable them during training
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
with nlp.disable_pipes(*other_pipes): # only train NER
for _ in range(n_iter):
random.shuffle(trainset)
losses = {}
# batch up the examples using spaCy's minibatch
batches = minibatch(trainset, size=compounding(4., 32., 1.001))
for batch in batches:
texts, annotations = zip(*batch)
nlp.update(texts, annotations, sgd=optimizer, drop=drop_rate, losses=losses)
log.debug('Losses %r', losses)
return nlp
def get_prediction_for_description(nlp, description):
doc = nlp(description)
raw_predictions = [[ent.start_char, ent.end_char, ent.label_] for ent in doc.ents]
formatted_prediction = defaultdict(list)
for (start_idx, end_idx, label) in raw_predictions:
formatted_prediction[label].append(description[start_idx: end_idx])
return formatted_prediction
def get_default_model():
return spacy.load(os.path.join(os.path.dirname(__file__), 'model'))
def get_default_dataset():
return _get_dataset(os.path.join(os.path.dirname(__file__), 'dataset/dataset.json')) | cve_analyzer/analyzer.py |
import os
import logging
import json
import random
from pathlib import Path
import spacy
from spacy.util import minibatch, compounding
from collections import defaultdict
log = logging.getLogger('CVE_Analyzer')
# ------------------------ PERFORMANCES ------------------------
def _compute_performances(performaces, annotations, entities):
predictions = [[ent.start_char, ent.end_char, ent.label_] for ent in entities]
for entry in annotations + predictions:
if entry in annotations and entry in predictions:
performaces["tp"] += 1
elif entry in annotations and entry not in predictions:
performaces["fn"] += 1
elif entry not in annotations and entry in predictions:
performaces["fp"] += 1
else:
performaces['tn'] += 1
def _compute_precision(performaces):
return float(performaces["tp"]) / (performaces["tp"] + performaces["fp"])
def _compute_recall(performaces):
return float(performaces["tp"]) / (performaces["tp"] + performaces["fn"])
def _compute_f_measure(precision, recall):
return 2*precision*recall / (precision + recall)
def _compute_accuracy(performaces):
return float((performaces['tp'] + performaces['tn'])) / \
float((performaces['tp'] + performaces['tn'] + performaces['fp'] + performaces['fn']))
def _get_dataset(dataset_path):
if not os.path.exists(dataset_path):
raise OSError("Dataset file {} not found".format(dataset_path))
with open(dataset_path, 'r') as dataset_f:
dataset = json.load(dataset_f)
return dataset
def _get_ner_component(nlp):
# Add entity recognizer to model if it's not in the pipeline
# nlp.create_pipe works for built-ins that are registered with spaCy
if 'ner' not in nlp.pipe_names:
ner = nlp.create_pipe('ner')
nlp.add_pipe(ner)
# otherwise, get it, so we can add labels to it
else:
ner = nlp.get_pipe('ner')
return ner
# ------------------------ EXPORTED METHODS ------------------------
def get_train_and_test_sets(dataset_file, split_ratio):
dataset = _get_dataset(dataset_file)
random.shuffle(dataset)
split = int(len(dataset)*split_ratio)
return dataset[:split], dataset[split:]
def pp_performances(accuracy, precision, recall, f_measure):
print("\n-------------------------------------------")
print("PERFORMANCES:")
print("\nAccuracy: {}".format(accuracy))
print("Precision: {}".format(precision))
print("Recall: {}".format(recall))
print("F-measure: {}".format(f_measure))
print("\n-------------------------------------------")
def save_model(output_dir, model_name, nlp):
output_dir = Path(output_dir)
if not output_dir.exists():
output_dir.mkdir(parents=True, exist_ok=True)
nlp.meta['name'] = model_name
nlp.to_disk(output_dir)
log.debug("Saved model to %s", output_dir)
def get_model(model_path):
return spacy.load(model_path)
def test(nlp, testset):
performances = {
"tp": 0,
"fp": 0,
"fn": 0,
"tn": 0
}
for description, annotations in testset:
doc = nlp(description)
_compute_performances(performances, annotations['entities'], doc.ents)
performances['accuracy'] = _compute_accuracy(performances)
performances['precision'] = _compute_precision(performances)
performances['recall'] = _compute_recall(performances)
performances['f_measure'] = _compute_f_measure(performances['precision'], performances['recall'])
return performances
def train(trainset, labels, n_iter, drop_rate):
nlp = spacy.blank('en')
ner = _get_ner_component(nlp)
for label in labels:
ner.add_label(label)
optimizer = nlp.begin_training()
# get names of other pipes to disable them during training
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
with nlp.disable_pipes(*other_pipes): # only train NER
for _ in range(n_iter):
random.shuffle(trainset)
losses = {}
# batch up the examples using spaCy's minibatch
batches = minibatch(trainset, size=compounding(4., 32., 1.001))
for batch in batches:
texts, annotations = zip(*batch)
nlp.update(texts, annotations, sgd=optimizer, drop=drop_rate, losses=losses)
log.debug('Losses %r', losses)
return nlp
def get_prediction_for_description(nlp, description):
doc = nlp(description)
raw_predictions = [[ent.start_char, ent.end_char, ent.label_] for ent in doc.ents]
formatted_prediction = defaultdict(list)
for (start_idx, end_idx, label) in raw_predictions:
formatted_prediction[label].append(description[start_idx: end_idx])
return formatted_prediction
def get_default_model():
return spacy.load(os.path.join(os.path.dirname(__file__), 'model'))
def get_default_dataset():
return _get_dataset(os.path.join(os.path.dirname(__file__), 'dataset/dataset.json')) | 0.555435 | 0.250322 |
from datetime import datetime
from django.http import HttpResponseNotFound, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import requests
from urllib.parse import urlencode
from uuid import uuid4
from fedireads import models
from fedireads.remote_user import get_or_create_remote_user
from fedireads.broadcast import get_recipients, broadcast
from fedireads.settings import DOMAIN
@csrf_exempt
def outbox(request, username):
''' outbox for the requested user '''
user = models.User.objects.get(localname=username)
if request.method != 'GET':
return HttpResponseNotFound()
# paginated list of messages
if request.GET.get('page'):
limit = 20
min_id = request.GET.get('min_id')
max_id = request.GET.get('max_id')
path = 'https://%s%s?' % (DOMAIN, request.path)
# filters for use in the django queryset min/max
filters = {}
# params for the outbox page id
params = {'page': 'true'}
if min_id != None:
params['min_id'] = min_id
filters['id__gt'] = min_id
if max_id != None:
params['max_id'] = max_id
filters['id__lte'] = max_id
collection_id = path + urlencode(params)
messages = models.Activity.objects.filter(
user=user,
activity_type__in=['Article', 'Note'],
**filters
).all()[:limit]
outbox_page = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': collection_id,
'type': 'OrderedCollectionPage',
'partOf': 'https://oulipo.social/users/mus/outbox',
'orderedItems': [m.content for m in messages],
}
if max_id:
outbox_page['next'] = path + \
urlencode({'min_id': max_id, 'page': 'true'})
if min_id:
outbox_page['prev'] = path + \
urlencode({'max_id': min_id, 'page': 'true'})
return JsonResponse(outbox_page)
# collection overview
size = models.Review.objects.filter(user=user).count()
return JsonResponse({
'@context': 'https://www.w3.org/ns/activitystreams',
'id': '%s/outbox' % user.actor,
'type': 'OrderedCollection',
'totalItems': size,
'first': '%s/outbox?page=true' % user.actor,
'last': '%s/outbox?min_id=0&page=true' % user.actor
})
def handle_account_search(query):
''' webfingerin' other servers '''
user = None
domain = query.split('@')[1]
try:
user = models.User.objects.get(username=query)
except models.User.DoesNotExist:
url = 'https://%s/.well-known/webfinger?resource=acct:%s' % \
(domain, query)
response = requests.get(url)
if not response.ok:
response.raise_for_status()
data = response.json()
for link in data['links']:
if link['rel'] == 'self':
user = get_or_create_remote_user(link['href'])
return user
def handle_outgoing_follow(user, to_follow):
''' someone local wants to follow someone '''
uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': 'https://%s/%s' % (DOMAIN, str(uuid)),
'summary': '',
'type': 'Follow',
'actor': user.actor,
'object': to_follow.actor,
}
errors = broadcast(user, activity, [to_follow.inbox])
for error in errors:
# TODO: following masto users is returning 400
raise(error['error'])
def handle_shelve(user, book, shelf):
''' a local user is getting a book put on their shelf '''
# update the database
models.ShelfBook(book=book, shelf=shelf, added_by=user).save()
# send out the activitypub action
summary = '%s marked %s as %s' % (
user.username,
book.data['title'],
shelf.name
)
uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(uuid),
'summary': summary,
'type': 'Add',
'actor': user.actor,
'object': {
'type': 'Document',
'name': book.data['title'],
'url': book.openlibrary_key
},
'target': {
'type': 'Collection',
'name': shelf.name,
'id': shelf.activitypub_id
}
}
recipients = get_recipients(user, 'public')
models.ShelveActivity(
uuid=uuid,
user=user,
content=activity,
shelf=shelf,
book=book,
).save()
broadcast(user, activity, recipients)
def handle_unshelve(user, book, shelf):
''' a local user is getting a book put on their shelf '''
# update the database
row = models.ShelfBook.objects.get(book=book, shelf=shelf)
row.delete()
# send out the activitypub action
summary = '%s removed %s from %s' % (
user.username,
book.data['title'],
shelf.name
)
uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(uuid),
'summary': summary,
'type': 'Remove',
'actor': user.actor,
'object': {
'type': 'Document',
'name': book.data['title'],
'url': book.openlibrary_key
},
'target': {
'type': 'Collection',
'name': shelf.name,
'id': shelf.activitypub_id
}
}
recipients = get_recipients(user, 'public')
models.ShelveActivity(
uuid=uuid,
user=user,
content=activity,
shelf=shelf,
book=book,
activity_type='Remove',
).save()
broadcast(user, activity, recipients)
def handle_review(user, book, name, content, rating):
''' post a review '''
review_uuid = uuid4()
obj = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(review_uuid),
'type': 'Article',
'published': datetime.utcnow().isoformat(),
'attributedTo': user.actor,
'content': content,
'inReplyTo': book.openlibrary_key, # TODO is this the right identifier?
'rating': rating, # fedireads-only custom field
'to': 'https://www.w3.org/ns/activitystreams#Public'
}
# TODO: create alt version for mastodon
recipients = get_recipients(user, 'public')
create_uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(create_uuid),
'type': 'Create',
'actor': user.actor,
'to': ['%s/followers' % user.actor],
'cc': ['https://www.w3.org/ns/activitystreams#Public'],
'object': obj,
}
models.Review(
uuid=create_uuid,
user=user,
content=activity,
activity_type='Article',
book=book,
name=name,
rating=rating,
review_content=content,
).save()
broadcast(user, activity, recipients) | fedireads/outgoing.py | from datetime import datetime
from django.http import HttpResponseNotFound, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import requests
from urllib.parse import urlencode
from uuid import uuid4
from fedireads import models
from fedireads.remote_user import get_or_create_remote_user
from fedireads.broadcast import get_recipients, broadcast
from fedireads.settings import DOMAIN
@csrf_exempt
def outbox(request, username):
''' outbox for the requested user '''
user = models.User.objects.get(localname=username)
if request.method != 'GET':
return HttpResponseNotFound()
# paginated list of messages
if request.GET.get('page'):
limit = 20
min_id = request.GET.get('min_id')
max_id = request.GET.get('max_id')
path = 'https://%s%s?' % (DOMAIN, request.path)
# filters for use in the django queryset min/max
filters = {}
# params for the outbox page id
params = {'page': 'true'}
if min_id != None:
params['min_id'] = min_id
filters['id__gt'] = min_id
if max_id != None:
params['max_id'] = max_id
filters['id__lte'] = max_id
collection_id = path + urlencode(params)
messages = models.Activity.objects.filter(
user=user,
activity_type__in=['Article', 'Note'],
**filters
).all()[:limit]
outbox_page = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': collection_id,
'type': 'OrderedCollectionPage',
'partOf': 'https://oulipo.social/users/mus/outbox',
'orderedItems': [m.content for m in messages],
}
if max_id:
outbox_page['next'] = path + \
urlencode({'min_id': max_id, 'page': 'true'})
if min_id:
outbox_page['prev'] = path + \
urlencode({'max_id': min_id, 'page': 'true'})
return JsonResponse(outbox_page)
# collection overview
size = models.Review.objects.filter(user=user).count()
return JsonResponse({
'@context': 'https://www.w3.org/ns/activitystreams',
'id': '%s/outbox' % user.actor,
'type': 'OrderedCollection',
'totalItems': size,
'first': '%s/outbox?page=true' % user.actor,
'last': '%s/outbox?min_id=0&page=true' % user.actor
})
def handle_account_search(query):
''' webfingerin' other servers '''
user = None
domain = query.split('@')[1]
try:
user = models.User.objects.get(username=query)
except models.User.DoesNotExist:
url = 'https://%s/.well-known/webfinger?resource=acct:%s' % \
(domain, query)
response = requests.get(url)
if not response.ok:
response.raise_for_status()
data = response.json()
for link in data['links']:
if link['rel'] == 'self':
user = get_or_create_remote_user(link['href'])
return user
def handle_outgoing_follow(user, to_follow):
''' someone local wants to follow someone '''
uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': 'https://%s/%s' % (DOMAIN, str(uuid)),
'summary': '',
'type': 'Follow',
'actor': user.actor,
'object': to_follow.actor,
}
errors = broadcast(user, activity, [to_follow.inbox])
for error in errors:
# TODO: following masto users is returning 400
raise(error['error'])
def handle_shelve(user, book, shelf):
''' a local user is getting a book put on their shelf '''
# update the database
models.ShelfBook(book=book, shelf=shelf, added_by=user).save()
# send out the activitypub action
summary = '%s marked %s as %s' % (
user.username,
book.data['title'],
shelf.name
)
uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(uuid),
'summary': summary,
'type': 'Add',
'actor': user.actor,
'object': {
'type': 'Document',
'name': book.data['title'],
'url': book.openlibrary_key
},
'target': {
'type': 'Collection',
'name': shelf.name,
'id': shelf.activitypub_id
}
}
recipients = get_recipients(user, 'public')
models.ShelveActivity(
uuid=uuid,
user=user,
content=activity,
shelf=shelf,
book=book,
).save()
broadcast(user, activity, recipients)
def handle_unshelve(user, book, shelf):
''' a local user is getting a book put on their shelf '''
# update the database
row = models.ShelfBook.objects.get(book=book, shelf=shelf)
row.delete()
# send out the activitypub action
summary = '%s removed %s from %s' % (
user.username,
book.data['title'],
shelf.name
)
uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(uuid),
'summary': summary,
'type': 'Remove',
'actor': user.actor,
'object': {
'type': 'Document',
'name': book.data['title'],
'url': book.openlibrary_key
},
'target': {
'type': 'Collection',
'name': shelf.name,
'id': shelf.activitypub_id
}
}
recipients = get_recipients(user, 'public')
models.ShelveActivity(
uuid=uuid,
user=user,
content=activity,
shelf=shelf,
book=book,
activity_type='Remove',
).save()
broadcast(user, activity, recipients)
def handle_review(user, book, name, content, rating):
''' post a review '''
review_uuid = uuid4()
obj = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(review_uuid),
'type': 'Article',
'published': datetime.utcnow().isoformat(),
'attributedTo': user.actor,
'content': content,
'inReplyTo': book.openlibrary_key, # TODO is this the right identifier?
'rating': rating, # fedireads-only custom field
'to': 'https://www.w3.org/ns/activitystreams#Public'
}
# TODO: create alt version for mastodon
recipients = get_recipients(user, 'public')
create_uuid = uuid4()
activity = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': str(create_uuid),
'type': 'Create',
'actor': user.actor,
'to': ['%s/followers' % user.actor],
'cc': ['https://www.w3.org/ns/activitystreams#Public'],
'object': obj,
}
models.Review(
uuid=create_uuid,
user=user,
content=activity,
activity_type='Article',
book=book,
name=name,
rating=rating,
review_content=content,
).save()
broadcast(user, activity, recipients) | 0.376852 | 0.084644 |
import sys
from enum import Enum
class EnumIOType(Enum):
NONE = "IOType.NONE"
OUTPUT = "IOType.OUTPUT"
INPUT = "IOType.INPUT"
from django.db import models
class ConnectedSystem(models.Model):
name = models.CharField(max_length=255,verbose_name="Name of Connection")
lastIP = models.GenericIPAddressField(verbose_name="Last known IP address of Connection")
lastMacAddress = models.CharField(max_length=255,verbose_name="Mac Address of Connection")
serialNumber = models.CharField(max_length=255,verbose_name="Serial Number of Pi",unique=True)
connected = models.BooleanField(default=False,verbose_name="Status of connection to pi")
active = models.BooleanField(default=False,verbose_name="Status of Pi added in UI")
class IO(models.Model):
ioNr = models.IntegerField(primary_key=True,verbose_name='physical io nr on pi')
def getAllObjects(self):
return IO.objects.all()
class IOType(models.Model):
ioType = models.CharField(max_length=255, choices=[(tag,tag.value) for tag in EnumIOType], verbose_name="Type of output")
def getAllObjects(self):
return IOType.objects.all()
class UsedIO(models.Model):
name = models.CharField(max_length=255,verbose_name='human readable name for the io')
pin = models.ForeignKey(IO, on_delete=models.CASCADE, verbose_name='Pin nr')
type = models.ForeignKey(IOType, on_delete=models.CASCADE, verbose_name='Type of IO')
active = models.BooleanField(default=False,verbose_name="Active/Non Active IO")
connectedSystem = models.ForeignKey(ConnectedSystem, on_delete=models.CASCADE,null=True)
timeStart = models.TimeField(verbose_name="Start time of timer",null=True)
timeEnd = models.TimeField(verbose_name="End time of timer",null=True)
class ClientSettings(models.Model):
name = models.CharField(max_length=255, verbose_name='Name of the pi client', default="")
serverAddress = models.CharField(max_length=255,verbose_name='Address of the server that set the ip of the pi'
'',default="")
version = models.CharField(max_length=255,verbose_name="Version of the software",default="")
connectedToServer = models.BooleanField(verbose_name="Flag for connected to server",default=False)
searching = models.BooleanField(verbose_name="Searching flag for client",default=False) | pylightcommon/models.py | import sys
from enum import Enum
class EnumIOType(Enum):
NONE = "IOType.NONE"
OUTPUT = "IOType.OUTPUT"
INPUT = "IOType.INPUT"
from django.db import models
class ConnectedSystem(models.Model):
name = models.CharField(max_length=255,verbose_name="Name of Connection")
lastIP = models.GenericIPAddressField(verbose_name="Last known IP address of Connection")
lastMacAddress = models.CharField(max_length=255,verbose_name="Mac Address of Connection")
serialNumber = models.CharField(max_length=255,verbose_name="Serial Number of Pi",unique=True)
connected = models.BooleanField(default=False,verbose_name="Status of connection to pi")
active = models.BooleanField(default=False,verbose_name="Status of Pi added in UI")
class IO(models.Model):
ioNr = models.IntegerField(primary_key=True,verbose_name='physical io nr on pi')
def getAllObjects(self):
return IO.objects.all()
class IOType(models.Model):
ioType = models.CharField(max_length=255, choices=[(tag,tag.value) for tag in EnumIOType], verbose_name="Type of output")
def getAllObjects(self):
return IOType.objects.all()
class UsedIO(models.Model):
name = models.CharField(max_length=255,verbose_name='human readable name for the io')
pin = models.ForeignKey(IO, on_delete=models.CASCADE, verbose_name='Pin nr')
type = models.ForeignKey(IOType, on_delete=models.CASCADE, verbose_name='Type of IO')
active = models.BooleanField(default=False,verbose_name="Active/Non Active IO")
connectedSystem = models.ForeignKey(ConnectedSystem, on_delete=models.CASCADE,null=True)
timeStart = models.TimeField(verbose_name="Start time of timer",null=True)
timeEnd = models.TimeField(verbose_name="End time of timer",null=True)
class ClientSettings(models.Model):
name = models.CharField(max_length=255, verbose_name='Name of the pi client', default="")
serverAddress = models.CharField(max_length=255,verbose_name='Address of the server that set the ip of the pi'
'',default="")
version = models.CharField(max_length=255,verbose_name="Version of the software",default="")
connectedToServer = models.BooleanField(verbose_name="Flag for connected to server",default=False)
searching = models.BooleanField(verbose_name="Searching flag for client",default=False) | 0.330255 | 0.129926 |
import os, sys, bisect
import numarray as num
import hippoplotter as plot
import irf_loader
from Interpolator import Interpolator
from ks import ks1, ks2
irf_loader.Loader_go()
SkyDir = irf_loader.SkyDir
class Psf(object):
_factory = irf_loader.IrfsFactory_instance()
def __init__(self, irfsName, energy=100., inc=0, phi=0):
self._irfs = self._factory.create(irfsName)
self._psf = self._irfs.psf()
self._energy = energy
self._inc = inc
self._phi = phi
def __call__(self, separation):
psf, energy, inc, phi = self._psf, self._energy, self._inc, self._phi
try:
y = []
for x in separation:
y.append(psf.value(x, energy, inc, phi))
return num.array(y)
except TypeError:
return psf.value(separation, energy, inc, phi)
def app_dir(self):
x = self._psf.app_dir(self._energy, self._inc)
return x.first, x.second
def __getattr__(self, attrname):
return getattr(self._psf, attrname)
class PsfTests(object):
def __init__(self, irfs, separations, roiRadius=20):
self.irfs = irfs
self.seps = separations
def _Npred(self, sep):
srcDir = SkyDir(180., sep)
return self.psf.angularIntegral(self.energy, srcDir, self.scZAxis,
self.scXAxis, self.cones)
def _SampleDist(self, sep, ntrials=20, nsamp=100):
srcDir = SkyDir(180., sep)
nobs = []
for j in range(ntrials):
naccept = 0
for i in range(nsamp):
appDir = self.psf.appDir(self.energy, srcDir, self.scZAxis,
self.scXAxis)
if self.cones[0].inside(appDir):
naccept += 1
nobs.append(naccept)
nobs = num.array(nobs)
navg = sum(nobs)/float(ntrials)
return (navg/float(nsamp),
num.sqrt(sum(nobs**2)/float(ntrials) - navg**2)/float(nsamp))
def _setPsf(self, energy, inc, phi=0):
self.energy = energy
self.inc = inc
self.phi = phi
self.psf = Psf(self.irfs, energy, inc, phi)
self.scZAxis = SkyDir(180, inc)
self.scXAxis = SkyDir(90, 0)
def _setRoi(self, roiRadius=20):
roiCenter = SkyDir(180., 0)
roi = irf_loader.AcceptanceCone(roiCenter, roiRadius)
self.cones = [roi]
def plotResults(self, energy, inclination, ntrials=20, nsamp=100,
plot_residuals=False):
self._setPsf(energy, inclination)
self._setRoi(roiRadius=20)
nobs = []
nobserr = []
npreds = []
colnames = ('separation', 'Npred', 'Nobs', 'Nobserr', 'Nobs - Npred')
nt = plot.newNTuple( [[]]*len(colnames), colnames)
display = plot.Scatter(nt, 'separation', 'Npred', pointRep='Line')
display.setRange('y', 0, 1.1)
plot.XYPlot(nt, 'separation', 'Nobs', yerr='Nobserr',
color='red', oplot=1)
display.setRange('x', min(seps), max(seps))
display.setTitle("%s: %i MeV, %.1f deg" %
(self.irfs, self.energy, self.inc))
if plot_residuals:
resid_display = plot.XYPlot(nt, 'separation', 'Nobs - Npred',
yerr='Nobserr')
resid_display.setRange('x', min(seps), max(seps))
resid_display.setTitle("%s: %i MeV, %.1f deg" %
(self.irfs, self.energy, self.inc))
plot.hline(0)
resid_display.setAutoRanging('y', True)
for sep in self.seps:
nobs, nerr = self._SampleDist(sep)
npred = self._Npred(sep)
nt.addRow( (sep, npred, nobs, nerr, nobs-npred) )
return nt, display
def plot_rspgenIntegral(self, energy, inclination, phi=0, nsamp=2000):
rmin = 1e-2
rmax = 30.
npts = 20
rstep = num.log(rmax/rmin)/(npts-1)
radii = rmin*num.exp(rstep*num.arange(npts))
self._setPsf(energy, inclination, phi)
seps = []
srcDir = SkyDir(180, 0)
for i in range(nsamp):
appDir = self.psf.appDir(energy, srcDir, self.scZAxis,
self.scXAxis)
seps.append(appDir.difference(srcDir)*180./num.pi)
seps.sort()
fraction = num.arange(nsamp, type=num.Float)/nsamp
disp = plot.scatter(seps, fraction, xlog=1,
xname='ROI radius', yname='enclosed Psf fraction',
pointRep='Line', color='red')
disp.setTitle("%s: %i MeV, %.1f deg" %
(self.irfs, energy, inclination))
npred = []
resids = []
for radius in radii:
npred.append(self.psf.angularIntegral(energy, inclination, phi,
radius))
resids.append(num.abs((self._interpolate(seps, fraction, radius)
- npred[-1])/npred[-1]))
plot.scatter(radii, npred, pointRep='Line', oplot=1)
residplot = plot.scatter(radii, resids, 'ROI radius',
yname='abs(sim - npred)/npred',
xlog=1, ylog=1)
# Npred = Interpolator(radii, npred)
ks_prob = ks2(npred, seps)
plot.hline(0)
residplot.setTitle("%s: %i MeV, %.1f deg\n ks prob=%.2e" %
(self.irfs, energy, inclination, ks_prob[1]))
return energy, inclination, ks_prob[1]
def _interpolate(self, x, y, xval):
if xval > x[-1]:
return 1
indx = bisect.bisect(x, xval) - 1
yval = ( (xval - x[indx])/(x[indx+1] - x[indx])
*(y[indx+1] - y[indx]) + y[indx] )
return yval
if __name__ == '__main__':
seps = num.concatenate((num.arange(12, 19), num.arange(19, 21, 0.3),
num.arange(21, 25)))
energies = (30, 50, 100, 300, 1000)#, 3e3, 1e4)
incs = (0, 5, 10, 20, 30)
# energies = (100,)
# incs = (0,)
nt = plot.newNTuple( ([], [], []), ('energy', 'inc', 'ks prob') )
plot.Scatter(nt, 'energy', 'ks prob')
plot.Scatter(nt, 'inc', 'ks prob')
def createPlots(irfs, seps, energies, inclinations):
my_tests = PsfTests(irfs, seps)
for energy in energies:
for inclination in inclinations:
my_tests.plotResults(energy, inclination, plot_residuals=True)
nt.addRow(my_tests.plot_rspgenIntegral(energy, inclination))
irfs = ('testIrfs::Front',) # 'testIrfs::Back')
# 'Glast25::Front', 'Glast25::Back',
# 'DC1::Front', 'DC1::Back')
for irf in irfs:
createPlots(irf, seps, energies, incs) | irfLoader/python/psf_tests.py | import os, sys, bisect
import numarray as num
import hippoplotter as plot
import irf_loader
from Interpolator import Interpolator
from ks import ks1, ks2
irf_loader.Loader_go()
SkyDir = irf_loader.SkyDir
class Psf(object):
_factory = irf_loader.IrfsFactory_instance()
def __init__(self, irfsName, energy=100., inc=0, phi=0):
self._irfs = self._factory.create(irfsName)
self._psf = self._irfs.psf()
self._energy = energy
self._inc = inc
self._phi = phi
def __call__(self, separation):
psf, energy, inc, phi = self._psf, self._energy, self._inc, self._phi
try:
y = []
for x in separation:
y.append(psf.value(x, energy, inc, phi))
return num.array(y)
except TypeError:
return psf.value(separation, energy, inc, phi)
def app_dir(self):
x = self._psf.app_dir(self._energy, self._inc)
return x.first, x.second
def __getattr__(self, attrname):
return getattr(self._psf, attrname)
class PsfTests(object):
def __init__(self, irfs, separations, roiRadius=20):
self.irfs = irfs
self.seps = separations
def _Npred(self, sep):
srcDir = SkyDir(180., sep)
return self.psf.angularIntegral(self.energy, srcDir, self.scZAxis,
self.scXAxis, self.cones)
def _SampleDist(self, sep, ntrials=20, nsamp=100):
srcDir = SkyDir(180., sep)
nobs = []
for j in range(ntrials):
naccept = 0
for i in range(nsamp):
appDir = self.psf.appDir(self.energy, srcDir, self.scZAxis,
self.scXAxis)
if self.cones[0].inside(appDir):
naccept += 1
nobs.append(naccept)
nobs = num.array(nobs)
navg = sum(nobs)/float(ntrials)
return (navg/float(nsamp),
num.sqrt(sum(nobs**2)/float(ntrials) - navg**2)/float(nsamp))
def _setPsf(self, energy, inc, phi=0):
self.energy = energy
self.inc = inc
self.phi = phi
self.psf = Psf(self.irfs, energy, inc, phi)
self.scZAxis = SkyDir(180, inc)
self.scXAxis = SkyDir(90, 0)
def _setRoi(self, roiRadius=20):
roiCenter = SkyDir(180., 0)
roi = irf_loader.AcceptanceCone(roiCenter, roiRadius)
self.cones = [roi]
def plotResults(self, energy, inclination, ntrials=20, nsamp=100,
plot_residuals=False):
self._setPsf(energy, inclination)
self._setRoi(roiRadius=20)
nobs = []
nobserr = []
npreds = []
colnames = ('separation', 'Npred', 'Nobs', 'Nobserr', 'Nobs - Npred')
nt = plot.newNTuple( [[]]*len(colnames), colnames)
display = plot.Scatter(nt, 'separation', 'Npred', pointRep='Line')
display.setRange('y', 0, 1.1)
plot.XYPlot(nt, 'separation', 'Nobs', yerr='Nobserr',
color='red', oplot=1)
display.setRange('x', min(seps), max(seps))
display.setTitle("%s: %i MeV, %.1f deg" %
(self.irfs, self.energy, self.inc))
if plot_residuals:
resid_display = plot.XYPlot(nt, 'separation', 'Nobs - Npred',
yerr='Nobserr')
resid_display.setRange('x', min(seps), max(seps))
resid_display.setTitle("%s: %i MeV, %.1f deg" %
(self.irfs, self.energy, self.inc))
plot.hline(0)
resid_display.setAutoRanging('y', True)
for sep in self.seps:
nobs, nerr = self._SampleDist(sep)
npred = self._Npred(sep)
nt.addRow( (sep, npred, nobs, nerr, nobs-npred) )
return nt, display
def plot_rspgenIntegral(self, energy, inclination, phi=0, nsamp=2000):
rmin = 1e-2
rmax = 30.
npts = 20
rstep = num.log(rmax/rmin)/(npts-1)
radii = rmin*num.exp(rstep*num.arange(npts))
self._setPsf(energy, inclination, phi)
seps = []
srcDir = SkyDir(180, 0)
for i in range(nsamp):
appDir = self.psf.appDir(energy, srcDir, self.scZAxis,
self.scXAxis)
seps.append(appDir.difference(srcDir)*180./num.pi)
seps.sort()
fraction = num.arange(nsamp, type=num.Float)/nsamp
disp = plot.scatter(seps, fraction, xlog=1,
xname='ROI radius', yname='enclosed Psf fraction',
pointRep='Line', color='red')
disp.setTitle("%s: %i MeV, %.1f deg" %
(self.irfs, energy, inclination))
npred = []
resids = []
for radius in radii:
npred.append(self.psf.angularIntegral(energy, inclination, phi,
radius))
resids.append(num.abs((self._interpolate(seps, fraction, radius)
- npred[-1])/npred[-1]))
plot.scatter(radii, npred, pointRep='Line', oplot=1)
residplot = plot.scatter(radii, resids, 'ROI radius',
yname='abs(sim - npred)/npred',
xlog=1, ylog=1)
# Npred = Interpolator(radii, npred)
ks_prob = ks2(npred, seps)
plot.hline(0)
residplot.setTitle("%s: %i MeV, %.1f deg\n ks prob=%.2e" %
(self.irfs, energy, inclination, ks_prob[1]))
return energy, inclination, ks_prob[1]
def _interpolate(self, x, y, xval):
if xval > x[-1]:
return 1
indx = bisect.bisect(x, xval) - 1
yval = ( (xval - x[indx])/(x[indx+1] - x[indx])
*(y[indx+1] - y[indx]) + y[indx] )
return yval
if __name__ == '__main__':
seps = num.concatenate((num.arange(12, 19), num.arange(19, 21, 0.3),
num.arange(21, 25)))
energies = (30, 50, 100, 300, 1000)#, 3e3, 1e4)
incs = (0, 5, 10, 20, 30)
# energies = (100,)
# incs = (0,)
nt = plot.newNTuple( ([], [], []), ('energy', 'inc', 'ks prob') )
plot.Scatter(nt, 'energy', 'ks prob')
plot.Scatter(nt, 'inc', 'ks prob')
def createPlots(irfs, seps, energies, inclinations):
my_tests = PsfTests(irfs, seps)
for energy in energies:
for inclination in inclinations:
my_tests.plotResults(energy, inclination, plot_residuals=True)
nt.addRow(my_tests.plot_rspgenIntegral(energy, inclination))
irfs = ('testIrfs::Front',) # 'testIrfs::Back')
# 'Glast25::Front', 'Glast25::Back',
# 'DC1::Front', 'DC1::Back')
for irf in irfs:
createPlots(irf, seps, energies, incs) | 0.378459 | 0.229935 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from celery.schedules import crontab
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<KEY>'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# origin
'rest_framework',
'rest_framework_swagger',
'django_celery_beat',
'solo',
# own
'users',
'core',
'jsx_compiler',
'parser_olx',
'collection',
'sms_sender',
'parser_ria',
'settings_analyzer',
'parser_rst',
'parser_icar',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'analyzer.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'analyzer.wsgi.application'
AUTH_USER_MODEL = 'users.User'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'analyzer',
'USER': 'analyzer',
'PASSWORD': 'analyzer',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'ru-Ru'
TIME_ZONE = 'Europe/Kiev'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'mail.adm.tools'
EMAIL_PORT = 465
EMAIL_HOST_USER = '<EMAIL>'
EMAIL_HOST_PASSWORD = '<PASSWORD>'
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
DEFAULT_FROM_EMAIL = '<EMAIL>'
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS':
'rest_framework.versioning.NamespaceVersioning',
'ALLOWED_VERSIONS': ('v1.0',),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication'
),
'DEFAULT_PAGINATION_CLASS':
'core.pagination.CustomPagination',
'PAGE_SIZE': 10,
}
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
JSX_COMPILER = {
# Default path 'static/js/src'. Path to compiled js file.
# 'SRC_PATH': os.path.join(BASE_DIR, 'static/js/src'),
# required - TMP_PATH. path to jsx files
'TMP_PATH': os.path.join(BASE_DIR, 'static/js/templates'),
# default True, compile jsx to js every time after restart server
# 'AUTO_COMPILE': True
}
CELERY_BROKER_URL = 'redis://localhost:6379/0'
try:
from .local_settings import *
except ImportError:
pass | analyzer/analyzer/settings.py | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from celery.schedules import crontab
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<KEY>'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# origin
'rest_framework',
'rest_framework_swagger',
'django_celery_beat',
'solo',
# own
'users',
'core',
'jsx_compiler',
'parser_olx',
'collection',
'sms_sender',
'parser_ria',
'settings_analyzer',
'parser_rst',
'parser_icar',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'analyzer.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'analyzer.wsgi.application'
AUTH_USER_MODEL = 'users.User'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'analyzer',
'USER': 'analyzer',
'PASSWORD': 'analyzer',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'ru-Ru'
TIME_ZONE = 'Europe/Kiev'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'mail.adm.tools'
EMAIL_PORT = 465
EMAIL_HOST_USER = '<EMAIL>'
EMAIL_HOST_PASSWORD = '<PASSWORD>'
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
DEFAULT_FROM_EMAIL = '<EMAIL>'
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS':
'rest_framework.versioning.NamespaceVersioning',
'ALLOWED_VERSIONS': ('v1.0',),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication'
),
'DEFAULT_PAGINATION_CLASS':
'core.pagination.CustomPagination',
'PAGE_SIZE': 10,
}
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
JSX_COMPILER = {
# Default path 'static/js/src'. Path to compiled js file.
# 'SRC_PATH': os.path.join(BASE_DIR, 'static/js/src'),
# required - TMP_PATH. path to jsx files
'TMP_PATH': os.path.join(BASE_DIR, 'static/js/templates'),
# default True, compile jsx to js every time after restart server
# 'AUTO_COMPILE': True
}
CELERY_BROKER_URL = 'redis://localhost:6379/0'
try:
from .local_settings import *
except ImportError:
pass | 0.351422 | 0.070304 |
import numpy as np
import torch
import numba as nb
import open3d as o3d
import frnn
import dgl
from numba import types, deferred_type
from numba.typed import Dict, List
import pickle
from Constants import *
from Operator import *
from cuHelper import *
import time
I = 16 # 2^I is for hashing function
Large = 2**I
@nb.njit(parallel=True)
def arr2adj(idx_arr, val_arr, count, tot_size):
i = np.zeros((tot_size, 2), dtype=np.int64)
v = np.zeros((tot_size,), dtype=np.float32)
for row in nb.prange(idx_arr.shape[0]):
neighbor_num = idx_arr[row, 0]
if row == 0:
cursor = 0
else:
cursor = count[row-1]
i[cursor:cursor+neighbor_num, 0] = row
i[cursor:cursor+neighbor_num, 1] = idx_arr[row, 1:neighbor_num+1]
v[cursor:cursor+neighbor_num] = val_arr[row, 1:neighbor_num+1]
return i, v
@nb.njit(parallel=True, fastmath=True)
def get_density(cell, ids, control_radius):
density = np.zeros((len(ids), ), dtype=np.float32)
for i in nb.prange(len(ids)):
id = ids[i]
neighbors = cell.get_cell_neighbor(id)
center_sum = 0.
for neighbor in neighbors:
r = cell.distance(id, neighbor)
if r < control_radius:
w = MPS_KERNEL(r, control_radius)
center_sum += w
density[i] = center_sum
return density
@nb.njit(parallel=True)
def get_gradient(cell, ids, grad_val, control_radius):
gradient = np.zeros((len(ids), 3), dtype=np.float32)
val_min = cell.get_neighbor_min(grad_val, ids, control_radius)
for i in nb.prange(len(ids)):
id = ids[i]
neighbors = cell.get_cell_neighbor(id)
for neighbor in neighbors:
if neighbor != id:
r = cell.distance(id, neighbor)
if r < control_radius:
r_vec = cell.pos[neighbor] - cell.pos[id]
w = MPS_KERNEL(r, control_radius)
val_diff = grad_val[neighbor] - val_min[id]
grad = w * val_diff / r ** 2
for dim in range(3):
gradient[i, dim] += grad * r_vec[dim]
return gradient
@nb.njit
def get_all_collision_neighbor(cell, ids, vel, local_map, ptype, control_radius):
A_ele = np.zeros((len(ids), 64), dtype=np.float32)
A_idx = np.zeros((len(ids), 64), dtype=np.int64)
for row in range(len(ids)):
id = ids[row]
if ptype[id] != 1:
continue
neighbors = cell.get_cell_neighbor(id)
center_sum = 0.0
for neighbor in neighbors:
if neighbor != id:
coll_term = 0.0
r = cell.distance(id, neighbor)
r_vec = cell.pos[neighbor] - cell.pos[id]
v_vec = vel[id] - vel[neighbor]
if r < control_radius:
for dim in range(3):
coll_term += v_vec[dim] * r_vec[dim]
if coll_term > 0.0:
col = local_map.get(neighbor)
coll_term /= r ** 2
center_sum += coll_term
if not (col is None):
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = -coll_term
A_idx[row, cursor] = col
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = center_sum
A_idx[row, cursor] = row
return A_ele, A_idx
@nb.njit(parallel=True)
def get_lap_neighbor(cell, ids, local_map, control_radius, PD=False):
A_ele = np.zeros((len(ids), 384), dtype=np.float32)
A_idx = np.zeros((len(ids), 384), dtype=np.int64)
for row in nb.prange(len(ids)):
id = ids[row]
neighbors = cell.get_cell_neighbor(id)
center_sum = 0.
for neighbor in neighbors:
if neighbor != id:
r = cell.distance(id, neighbor)
col = local_map.get(neighbor)
if r < control_radius:
w = MPS_KERNEL(r, control_radius)
if PD:
w = -w
center_sum += w
if not (col is None):
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = w
A_idx[row, cursor] = col
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = -center_sum
A_idx[row, cursor] = row
return A_ele, A_idx
@nb.njit(parallel=True, fastmath=True)
def get_gcn_neighbor(cell, ids, local_map, control_radius):
A_ele = np.zeros((len(ids), 384), dtype=np.float32)
A_idx = np.zeros((len(ids), 384), dtype=np.int64)
for row in nb.prange(len(ids)):
id = ids[row]
neighbors = cell.get_cell_neighbor(id)
center_sum = 0.
for neighbor in neighbors:
if neighbor != id:
r = cell.distance(id, neighbor)
col = local_map.get(neighbor)
if r < control_radius and col is not None:
w = MPS_KERNEL(r, control_radius)
center_sum += w
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = w
A_idx[row, cursor] = col
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = 1
A_idx[row, cursor] = row
A_ele[row, 1:cursor] /= center_sum
return A_ele, A_idx
def sparse_tensor(idx, val, arr_size):
if isinstance(idx, np.ndarray):
i = torch.from_numpy(idx).view(-1, 2)
v = torch.from_numpy(val).view(-1, )
else:
i = torch.tensor(idx, dtype=torch.int64).view(-1, 2)
v = torch.tensor(val, dtype=torch.float32).view(-1, )
return torch.sparse.FloatTensor(i.t(), v, torch.Size([arr_size, arr_size]))
class Particles:
def __init__(self, positions, velocity, ptype, gravity, visc_coeff, rho, DT):
"""
"""
self.pos = positions.astype(np.float32).reshape(-1, 3)
self.vel = velocity.astype(np.float32).reshape(-1, 3)
self.ptype = ptype.reshape(-1,)
self.fluid_ids = np.argwhere(self.ptype == 1).astype(np.int64).reshape(-1, )
self.nfs_ids = None # non free surface particles
self.non_dum_ids = np.argwhere(self.ptype != 3).astype(np.int64).reshape(-1, )
self.total_num = ptype.shape[0]
self.g = gravity
self.nu = visc_coeff
self.rho = rho
self.pres = np.zeros((self.total_num, ))
self.N0 = None
self.N0_lap = None
self.lam = None
self.DT = DT
self.device = None
self.cache = {}
def init_params(self, show_info=True, pass_in=None):
if pass_in is None:
# calculate the constant density of fluid field
self.N0 = np.max(self.get_density(only_fluid=True))
# calculate the density parameter for Laplacian operator
self.N0_lap = np.max(self.get_density(control_radius=LAP_RADIUS, only_fluid=True))
_, sqd_dist = self.get_nbr(LAP_RADIUS)
self.lam = torch.max(torch.sum(sqd_dist, dim=1)).item()/self.N0_lap
self.update_nfs()
else:
self.N0 = pass_in['N0']
self.N0_lap = pass_in['N0_lap']
self.lam = pass_in['lam']
if show_info:
print("fluid particle number: %i" % self.fluid_ids.shape[0])
print("non dummy particle number: %i" % self.non_dum_ids.shape[0])
print("total particle number: %i" % self.total_num)
print("constant density N0: %.8f" % self.N0)
print("constant density of Laplacian operator: %.8f" % self.N0_lap)
print("Laplacian normalizer: %.8f" % self.lam)
def get_nbr(self, cutoff, return_pic=False):
pos_tsr = torch.from_numpy(self.pos).cuda()
fluid_pos_tsr = pos_tsr[self.fluid_ids]
sqd_dist, nbr_idx, _, _ = frnn.frnn_grid_points(
fluid_pos_tsr[None, ...], pos_tsr[None, ...],
K=128,
r=cutoff,
grid=None, return_nn=False, return_sorted=True
)
nbr_idx = nbr_idx.squeeze(0)
center_idx = nbr_idx.clone()
center_idx[:] = torch.from_numpy(self.fluid_ids).to(pos_tsr.device).reshape(-1, 1)
mask = nbr_idx != -1
nbr_idx = nbr_idx[mask]
center_idx = center_idx[mask]
if return_pic:
return torch.unique(nbr_idx).cpu().numpy()
nbr_lst = torch.cat((center_idx.view(-1, 1), nbr_idx.view(-1, 1)), dim=1)
sqd_dist = sqd_dist.squeeze(0)
sqd_dist[sqd_dist < 1e-8] = 0.
return nbr_lst.cpu().numpy(), sqd_dist
def get_graph(self, cutoff, kernel_fn=None, with_col_pic=False):
pos_tsr = torch.from_numpy(self.pos).cuda()
fluid_pos_tsr = pos_tsr[self.fluid_ids]
sqd_dist, nbr_idx, _, _ = frnn.frnn_grid_points(
fluid_pos_tsr[None, ...], pos_tsr[None, ...],
K=128,
r=cutoff,
grid=None, return_nn=False, return_sorted=True
)
nbr_idx = nbr_idx.squeeze(0)
center_idx = nbr_idx.clone()
center_idx[:] = torch.from_numpy(self.fluid_ids).to(pos_tsr.device).reshape(-1, 1)
mask = nbr_idx != -1
nbr_idx = nbr_idx[mask]
center_idx = center_idx[mask]
pic_index = torch.unique(nbr_idx).cpu().numpy()
if with_col_pic:
# col_cutoff = 2.1 * COL_RADIUS
# col_pic_mask = sqd_dist.squeeze(0) < col_cutoff**2
# valid_mask = torch.logical_and(col_pic_mask, mask)
# col_pic = torch.unique(nbr_idx[valid_mask]).cpu().numpy()
col_pic = pic_index
mapped_nbr_idx = self.find_idx(pic_index, nbr_idx.cpu().numpy())
mapped_center_idx = self.find_idx(pic_index, center_idx.cpu().numpy())
graph = dgl.graph((torch.from_numpy(mapped_nbr_idx).cuda(), torch.from_numpy(mapped_center_idx).cuda()))
if kernel_fn is not None:
sqd_dist = sqd_dist.squeeze(0)
sqd_dist = sqd_dist[mask]
w = kernel_fn(torch.sqrt(sqd_dist), cutoff)
graph.edata['w'] = w
if with_col_pic:
return graph, pic_index, col_pic
return graph, pic_index
def add_particles(self, vel, pos, verbose=True):
add_pnum = vel.shape[0]
self.vel = np.concatenate((self.vel, vel), axis=0)
self.pos = np.concatenate((self.pos, pos), axis=0)
self.ptype = np.concatenate((self.ptype, np.ones((add_pnum, ))), axis=0).reshape(-1, )
self.fluid_ids = np.concatenate((self.fluid_ids,
np.arange(add_pnum) + self.total_num),
axis=0).reshape(-1, )
self.total_num = self.ptype.shape[0]
self.pres = np.zeros((self.total_num, ))
if verbose:
print("Add %i particles to fluid field" % add_pnum)
def remove_particle(self, boundary, which_axis=0, verbose=True, right=True):
if right: # particles inside boundary
inbound_fluid = np.logical_and(self.ptype == 1, self.pos[:, which_axis] < boundary)
else: # particles outside boundary
inbound_fluid = np.logical_and(self.ptype == 1, self.pos[:, which_axis] > boundary)
wall = self.ptype != 1
mask = np.logical_or(inbound_fluid, wall)
# remove out of boundary fluid particles from data structure
prev_num = self.total_num
remove_num = prev_num - np.sum(mask)
if verbose:
print("Remove %i particles from fluid field" % remove_num)
if remove_num > 0:
self.vel = self.vel[mask].copy()
self.pos = self.pos[mask].copy()
self.ptype = self.ptype[mask].copy()
self.fluid_ids = np.argwhere(self.ptype == 1).astype(np.int64).reshape(-1, )
self.total_num = self.ptype.shape[0]
self.pres = np.zeros((self.total_num,))
def get_pos(self, ids=None):
return self.pos[self.ptype == 1] if ids is None else self.pos[ids]
def get_vel(self, ids=None):
return self.vel[self.ptype == 1] if ids is None else self.vel[ids]
def move_boundary(self, vel: np.ndarray, dt):
# here, assert the whole system move
self.pos[:] += vel*dt
def get_lap_adjacency(self, control_radius, mode, **kwargs):
# sparse adjacency matrix for laplacian
support_kw = ['ids_type',
'pass_in_ids',
'neg_lap',
'return_sparse_ele']
supported_mode = ['laplacian']
if mode not in supported_mode:
raise Exception(mode + ' is not a supported mode')
for key in kwargs.keys():
if key not in support_kw:
raise Exception(key + ' is not a supported operation')
ids_type = kwargs.get('ids_type')
return_sparse_ele = kwargs.get('return_sparse_ele')
fluid_ids = self.fluid_ids
nd_ids = self.non_dum_ids
nfs_ids = self.nfs_ids
if ids_type == 'fluid' or ids_type is None:
ids = fluid_ids
elif ids_type == 'pass in':
pass_ids = kwargs.get('pass_in_ids')
if pass_ids is None:
raise Exception('There should be ids passed in under pass in ids type')
ids = pass_ids
elif ids_type == 'nfs': # non free surface particles
ids = nfs_ids
elif ids_type == 'nds': # non dummy particles
ids = nd_ids
elif ids_type == 'all': # all particles
ids = np.arange(0, self.total_num, 1).astype(np.int64)
else:
raise Exception("unsupported particle type selecting")
if control_radius != LAP_RADIUS:
print('Default radius of nfs_lap mode should be LAP_RADIUS')
negative = kwargs.get('neg_lap')
arr_size = len(ids)
val_arr, idx_arr, tot_size, count = get_laplacian_cuda(self.pos, self.ptype, ids, control_radius)
if not negative: # negative to make the matrix positive definite, which is necessary for CG method
val_arr = - val_arr
idx, val = arr2adj(idx_arr, val_arr, count, tot_size)
if return_sparse_ele:
return idx, val, arr_size
return sparse_tensor(idx, val, arr_size)
def fluid2id(self, p_in_cell, fld_ids=None):
if fld_ids is None:
fld_ids = self.fluid_ids
p_in_cell = np.array(p_in_cell, dtype=np.int64)
return self._index(p_in_cell, fld_ids)
def get_density(self, control_radius=GRAD_RADIUS, only_fluid=False):
density = get_density_cuda(self.pos, self.ptype, control_radius)
if not only_fluid:
return density
else:
return density[self.fluid_ids]
def get_vel_divergence(self, control_radius=GRAD_RADIUS, only_fluid=False):
div = get_vel_div_cuda(self.vel, self.pos, self.ptype, control_radius)
if not only_fluid:
return div * (-self.N0 * control_radius) / self.rho
else:
return div[self.fluid_ids] * (-self.N0 * control_radius) / self.rho
def update_nfs(self, return_feat=False, clamp_fs=False, only_nfs=False):
density_ = self.get_density()
self.nfs_ids = np.argwhere(density_ > 0.97*self.N0).astype(np.int64).reshape(-1,)
if clamp_fs:
density = (np.ones_like(self.ptype, dtype=np.float32) * self.N0).reshape(-1,)
density[self.nfs_ids] = density_[self.nfs_ids]
else:
density = density_
if return_feat:
return density / self.N0
if only_nfs:
return density[self.nfs_ids]
return density
def predict(self, cache_train_feat=False):
Adj_lap = self.get_lap_adjacency(LAP_RADIUS, mode="laplacian")
with torch.no_grad():
# ==============apply body force================
visc = self.nu * Laplacian(self.vel[self.fluid_ids], Adj_lap, self.N0_lap, self.lam).numpy()
body_force = np.array([0, 0, G])
bf_acc = visc + body_force
vel_bf_prev = self.vel.copy()
pos_bf_prev = self.pos.copy()
self.vel[self.fluid_ids] += bf_acc * self.DT
self.pos[self.fluid_ids] += self.vel[self.fluid_ids] * self.DT
if cache_train_feat:
assert len(self.cache) == 0
self.cache['fluid_idx'] = self.fluid_ids
bf_pic = self.get_nbr(LAP_RADIUS, return_pic=True)
bf_train_feat = {'pos': pos_bf_prev[bf_pic],
'vel': vel_bf_prev[bf_pic],
'acc': bf_acc,
'in_cell_idx': bf_pic}
self.cache['bf'] = bf_train_feat
col_pic = self.get_nbr(COL_RADIUS, return_pic=True)
col_train_feat = {'pos': self.pos[col_pic],
'vel_prev': self.vel[col_pic],
'in_cell_idx': col_pic,
}
vel_cu, pos_cu = get_collision_cuda(self.vel, self.pos, self.ptype, COL_RADIUS)
self.vel = vel_cu
self.pos = pos_cu
if cache_train_feat:
col_train_feat['vel_after'] = self.vel[col_pic]
self.cache['col'] = col_train_feat
density = self.update_nfs()
div = self.get_vel_divergence()
source_term = -0.80 * (div[self.nfs_ids] / self.DT) \
+ 0.20 * (density[self.nfs_ids] - self.N0) / (self.DT**2 * self.N0)
if cache_train_feat:
dns_feat = self.update_nfs(return_feat=True)
prs_train_feat = {
'pos': self.pos[self.nfs_ids],
'dns': dns_feat[self.nfs_ids],
'vel': self.vel[self.nfs_ids],
'nfs_idx': self.nfs_ids}
self.cache['prs'] = prs_train_feat
return source_term
def predict_with_timing(self):
log = {}
visc_nbr_start = time.time()
Adj_lap = self.get_lap_adjacency(LAP_RADIUS, mode="laplacian")
visc_nbr_end = time.time()
log['adv_nbr'] = visc_nbr_end - visc_nbr_start
with torch.no_grad():
# ==============apply body force================
visc_calc_start = time.time()
visc = self.nu * Laplacian(self.vel[self.fluid_ids], Adj_lap, self.N0_lap, self.lam).numpy()
body_force = np.array([0, 0, G])
bf_acc = visc + body_force
self.vel[self.fluid_ids] += bf_acc * self.DT
self.pos[self.fluid_ids] += self.vel[self.fluid_ids] * self.DT
visc_calc_end = time.time()
log['adv_calc'] = visc_calc_end - visc_calc_start
col_start = time.time()
vel_cu, pos_cu = get_collision_cuda(self.vel, self.pos, self.ptype, COL_RADIUS)
col_end = time.time()
log['col'] = col_end - col_start
self.vel = vel_cu
self.pos = pos_cu
source_start = time.time()
density = self.update_nfs()
div = self.get_vel_divergence()
source_term = -0.80 * (div[self.nfs_ids] / self.DT) \
+ 0.20 * (density[self.nfs_ids] - self.N0) / (self.DT**2 * self.N0)
source_end = time.time()
log['prs_source'] = source_end - source_start
return source_term, log
def predict_with_dynamic_bound(self, vel, dt):
Adj_lap = self.get_lap_adjacency(LAP_RADIUS, mode="laplacian")
with torch.no_grad():
# ==============apply body force================
visc = self.nu * Laplacian(self.vel[self.fluid_ids], Adj_lap, self.N0_lap, self.lam).numpy()
body_force = np.array([0, 0, G])
bf_acc = visc + body_force
self.vel[self.fluid_ids] += bf_acc * self.DT
self.pos[self.fluid_ids] += self.vel[self.fluid_ids] * self.DT
mask = np.ones((self.pos.shape[0], ))
mask[self.fluid_ids] = 0
self.pos[mask == 1] += vel*dt
vel_cu, pos_cu = get_collision_cuda(self.vel, self.pos, self.ptype, COL_RADIUS)
self.vel = vel_cu
self.pos = pos_cu
density = self.update_nfs()
div = self.get_vel_divergence()
source_term = -0.80 * (div[self.nfs_ids] / self.DT) \
+ 0.20 * (density[self.nfs_ids] - self.N0) / (self.DT**2 * self.N0)
return source_term
def move_bound(self, vel, dt):
mask = np.ones((self.pos.shape[0],))
mask[self.fluid_ids] = 0
self.pos[mask == 1] += vel * dt
def get_prs_feat(self):
dns_feat = self.update_nfs(return_feat=True)
prs_feat = {
'pos': self.pos[self.nfs_ids],
'dns': dns_feat[self.nfs_ids],
'vel': self.vel[self.nfs_ids],
'nfs_idx': self.nfs_ids}
return prs_feat
def collision(self):
vel_cu, pos_cu = get_collision_cuda(self.vel, self.pos, self.ptype, COL_RADIUS)
self.vel = vel_cu
self.pos = pos_cu
def correct(self, pred_pres, cache_train_feat=False):
self.pres = np.zeros_like(self.pres)
self.pres[self.nfs_ids] = np.where(pred_pres > 0, pred_pres, 0).reshape(-1, )
pres_grad = get_gradient_cuda(self.pres, self.pos, self.ptype, self.fluid_ids, GRAD_RADIUS)
acc = -1./self.rho * pres_grad * 3./self.N0
dt = self.DT
self.pos[self.fluid_ids] += acc * (dt**2)
self.vel[self.fluid_ids] += acc * dt
if cache_train_feat:
assert 'prs' in self.cache.keys()
self.cache['prs']['prs'] = self.pres[self.nfs_ids]
def weak_compress_pressure(self):
density = self.update_nfs(only_nfs=True)
pres = 22.0**2 / self.N0 * (density > self.N0) * (density - self.N0) * self.rho
return pres
def advect(self, ext_force):
self.vel[self.fluid_ids] += ext_force * self.DT
self.pos[self.fluid_ids] += self.vel[self.fluid_ids] * self.DT
def col_correct(self, col_vel):
self.pos[self.fluid_ids] += (col_vel - self.vel[self.fluid_ids]) * self.DT
self.vel[self.fluid_ids] = col_vel
def pres_predict(self):
density_feat = self.update_nfs(return_feat=True)
vel_feat = self.vel
return density_feat, vel_feat
def set_pos(self, pos, ids=None, update_nfs=True):
ids = self.fluid_ids if ids is None else ids
pos_ = pos.copy()
self.pos[ids] = pos_
if update_nfs:
self.update_nfs()
def set_vel(self, vel, ids=None):
ids = self.fluid_ids if ids is None else ids
vel_ = vel.copy()
self.vel[ids] = vel_
def set_state(self, pos, vel, ids=None):
self.set_pos(pos, ids)
self.set_vel(vel, ids)
def write_info(self, output_path, time_step,
x_boundary=None, y_boundary=None, z_boundary=None, write_status=False):
pos = self.pos
vel = self.vel
mask = self.fluid_ids
def mask_out_boundary(mask, bound):
mask = np.intersect1d(mask, np.argwhere(pos[:, 0]) >= bound[0])
mask = np.intersect1d(mask, np.argwhere(pos[:, 0]) <= bound[1])
return mask
if x_boundary is not None:
mask = mask_out_boundary(mask, x_boundary)
if y_boundary is not None:
mask = mask_out_boundary(mask, y_boundary)
if z_boundary is not None:
mask = mask_out_boundary(mask, z_boundary)
info = {'pos': pos[mask], 'vel': vel[mask]}
if write_status:
density = self.get_density(GRAD_RADIUS)
pres = self.pres
vel = self.vel
vel_div = self.get_vel_divergence(GRAD_RADIUS)
info['dns'] = density[mask]
info['prs'] = pres[mask]
info['vel'] = vel[mask]
info['vel_div'] = vel_div[mask]
np.savez_compressed(output_path + 'sim_info' + str(time_step) + '.npz', **info)
def write_data(self, output_path, time_step, dump_only=None):
with open(output_path + 'data' + str(time_step) + '.pkl', 'wb') as pickle_file:
if dump_only is None:
pickle.dump(self.cache, pickle_file)
else:
assert self.cache.get(dump_only) is not None
self.cache[dump_only]['fluid_idx'] = self.cache['fluid_idx']
pickle.dump(self.cache[dump_only], pickle_file)
del self.cache
self.cache = {}
@staticmethod
@nb.njit
def _find_min_max(val, h):
min_ = 1e10
max_ = -1e10
for i in range(val.shape[0]):
if min_ > val[i]:
min_ = val[i]
if max_ < val[i]:
max_ = val[i]
return (min_ - 2 * h), (max_ + 2 * h)
def gen_sparse_map(self, ids):
arr_size = len(ids)
local_ids = np.arange(arr_size).astype(dtype=np.int64)
sparse_map = Dict.empty(
key_type=types.int64,
value_type=types.int64
)
sparse_map = self._gen_sparse_map(sparse_map, ids, local_ids)
return sparse_map
@staticmethod
@nb.njit
def _gen_sparse_map(sp_map, global_ids, local_ids):
for i in range(len(global_ids)):
sp_map[global_ids[i]] = local_ids[i]
return sp_map
@staticmethod
@nb.njit
def _index(ids1, ids2):
"""ids1: sparse encoding,
ids2: fluid ids"""
idx_map = []
cursor = 0
for i, id1 in enumerate(ids1):
id2 = ids2[cursor]
if id2 == id1:
idx_map.append(i)
cursor += 1
if cursor == len(ids2):
break
return idx_map
@staticmethod
def find_idx(to_find_arr, key):
"""
Copied from
https://stackoverflow.com/questions/8251541/numpy-for-every-element-in-one-array-find-the-index-in-another-array
"""
xsorted_idx = np.argsort(to_find_arr)
ypos = np.searchsorted(to_find_arr[xsorted_idx], key)
indices = xsorted_idx[ypos]
return indices | Particles.py | import numpy as np
import torch
import numba as nb
import open3d as o3d
import frnn
import dgl
from numba import types, deferred_type
from numba.typed import Dict, List
import pickle
from Constants import *
from Operator import *
from cuHelper import *
import time
I = 16 # 2^I is for hashing function
Large = 2**I
@nb.njit(parallel=True)
def arr2adj(idx_arr, val_arr, count, tot_size):
i = np.zeros((tot_size, 2), dtype=np.int64)
v = np.zeros((tot_size,), dtype=np.float32)
for row in nb.prange(idx_arr.shape[0]):
neighbor_num = idx_arr[row, 0]
if row == 0:
cursor = 0
else:
cursor = count[row-1]
i[cursor:cursor+neighbor_num, 0] = row
i[cursor:cursor+neighbor_num, 1] = idx_arr[row, 1:neighbor_num+1]
v[cursor:cursor+neighbor_num] = val_arr[row, 1:neighbor_num+1]
return i, v
@nb.njit(parallel=True, fastmath=True)
def get_density(cell, ids, control_radius):
density = np.zeros((len(ids), ), dtype=np.float32)
for i in nb.prange(len(ids)):
id = ids[i]
neighbors = cell.get_cell_neighbor(id)
center_sum = 0.
for neighbor in neighbors:
r = cell.distance(id, neighbor)
if r < control_radius:
w = MPS_KERNEL(r, control_radius)
center_sum += w
density[i] = center_sum
return density
@nb.njit(parallel=True)
def get_gradient(cell, ids, grad_val, control_radius):
gradient = np.zeros((len(ids), 3), dtype=np.float32)
val_min = cell.get_neighbor_min(grad_val, ids, control_radius)
for i in nb.prange(len(ids)):
id = ids[i]
neighbors = cell.get_cell_neighbor(id)
for neighbor in neighbors:
if neighbor != id:
r = cell.distance(id, neighbor)
if r < control_radius:
r_vec = cell.pos[neighbor] - cell.pos[id]
w = MPS_KERNEL(r, control_radius)
val_diff = grad_val[neighbor] - val_min[id]
grad = w * val_diff / r ** 2
for dim in range(3):
gradient[i, dim] += grad * r_vec[dim]
return gradient
@nb.njit
def get_all_collision_neighbor(cell, ids, vel, local_map, ptype, control_radius):
A_ele = np.zeros((len(ids), 64), dtype=np.float32)
A_idx = np.zeros((len(ids), 64), dtype=np.int64)
for row in range(len(ids)):
id = ids[row]
if ptype[id] != 1:
continue
neighbors = cell.get_cell_neighbor(id)
center_sum = 0.0
for neighbor in neighbors:
if neighbor != id:
coll_term = 0.0
r = cell.distance(id, neighbor)
r_vec = cell.pos[neighbor] - cell.pos[id]
v_vec = vel[id] - vel[neighbor]
if r < control_radius:
for dim in range(3):
coll_term += v_vec[dim] * r_vec[dim]
if coll_term > 0.0:
col = local_map.get(neighbor)
coll_term /= r ** 2
center_sum += coll_term
if not (col is None):
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = -coll_term
A_idx[row, cursor] = col
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = center_sum
A_idx[row, cursor] = row
return A_ele, A_idx
@nb.njit(parallel=True)
def get_lap_neighbor(cell, ids, local_map, control_radius, PD=False):
A_ele = np.zeros((len(ids), 384), dtype=np.float32)
A_idx = np.zeros((len(ids), 384), dtype=np.int64)
for row in nb.prange(len(ids)):
id = ids[row]
neighbors = cell.get_cell_neighbor(id)
center_sum = 0.
for neighbor in neighbors:
if neighbor != id:
r = cell.distance(id, neighbor)
col = local_map.get(neighbor)
if r < control_radius:
w = MPS_KERNEL(r, control_radius)
if PD:
w = -w
center_sum += w
if not (col is None):
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = w
A_idx[row, cursor] = col
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = -center_sum
A_idx[row, cursor] = row
return A_ele, A_idx
@nb.njit(parallel=True, fastmath=True)
def get_gcn_neighbor(cell, ids, local_map, control_radius):
A_ele = np.zeros((len(ids), 384), dtype=np.float32)
A_idx = np.zeros((len(ids), 384), dtype=np.int64)
for row in nb.prange(len(ids)):
id = ids[row]
neighbors = cell.get_cell_neighbor(id)
center_sum = 0.
for neighbor in neighbors:
if neighbor != id:
r = cell.distance(id, neighbor)
col = local_map.get(neighbor)
if r < control_radius and col is not None:
w = MPS_KERNEL(r, control_radius)
center_sum += w
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = w
A_idx[row, cursor] = col
A_idx[row, 0] += 1
cursor = A_idx[row, 0]
A_ele[row, cursor] = 1
A_idx[row, cursor] = row
A_ele[row, 1:cursor] /= center_sum
return A_ele, A_idx
def sparse_tensor(idx, val, arr_size):
if isinstance(idx, np.ndarray):
i = torch.from_numpy(idx).view(-1, 2)
v = torch.from_numpy(val).view(-1, )
else:
i = torch.tensor(idx, dtype=torch.int64).view(-1, 2)
v = torch.tensor(val, dtype=torch.float32).view(-1, )
return torch.sparse.FloatTensor(i.t(), v, torch.Size([arr_size, arr_size]))
class Particles:
def __init__(self, positions, velocity, ptype, gravity, visc_coeff, rho, DT):
"""
"""
self.pos = positions.astype(np.float32).reshape(-1, 3)
self.vel = velocity.astype(np.float32).reshape(-1, 3)
self.ptype = ptype.reshape(-1,)
self.fluid_ids = np.argwhere(self.ptype == 1).astype(np.int64).reshape(-1, )
self.nfs_ids = None # non free surface particles
self.non_dum_ids = np.argwhere(self.ptype != 3).astype(np.int64).reshape(-1, )
self.total_num = ptype.shape[0]
self.g = gravity
self.nu = visc_coeff
self.rho = rho
self.pres = np.zeros((self.total_num, ))
self.N0 = None
self.N0_lap = None
self.lam = None
self.DT = DT
self.device = None
self.cache = {}
def init_params(self, show_info=True, pass_in=None):
if pass_in is None:
# calculate the constant density of fluid field
self.N0 = np.max(self.get_density(only_fluid=True))
# calculate the density parameter for Laplacian operator
self.N0_lap = np.max(self.get_density(control_radius=LAP_RADIUS, only_fluid=True))
_, sqd_dist = self.get_nbr(LAP_RADIUS)
self.lam = torch.max(torch.sum(sqd_dist, dim=1)).item()/self.N0_lap
self.update_nfs()
else:
self.N0 = pass_in['N0']
self.N0_lap = pass_in['N0_lap']
self.lam = pass_in['lam']
if show_info:
print("fluid particle number: %i" % self.fluid_ids.shape[0])
print("non dummy particle number: %i" % self.non_dum_ids.shape[0])
print("total particle number: %i" % self.total_num)
print("constant density N0: %.8f" % self.N0)
print("constant density of Laplacian operator: %.8f" % self.N0_lap)
print("Laplacian normalizer: %.8f" % self.lam)
def get_nbr(self, cutoff, return_pic=False):
pos_tsr = torch.from_numpy(self.pos).cuda()
fluid_pos_tsr = pos_tsr[self.fluid_ids]
sqd_dist, nbr_idx, _, _ = frnn.frnn_grid_points(
fluid_pos_tsr[None, ...], pos_tsr[None, ...],
K=128,
r=cutoff,
grid=None, return_nn=False, return_sorted=True
)
nbr_idx = nbr_idx.squeeze(0)
center_idx = nbr_idx.clone()
center_idx[:] = torch.from_numpy(self.fluid_ids).to(pos_tsr.device).reshape(-1, 1)
mask = nbr_idx != -1
nbr_idx = nbr_idx[mask]
center_idx = center_idx[mask]
if return_pic:
return torch.unique(nbr_idx).cpu().numpy()
nbr_lst = torch.cat((center_idx.view(-1, 1), nbr_idx.view(-1, 1)), dim=1)
sqd_dist = sqd_dist.squeeze(0)
sqd_dist[sqd_dist < 1e-8] = 0.
return nbr_lst.cpu().numpy(), sqd_dist
def get_graph(self, cutoff, kernel_fn=None, with_col_pic=False):
pos_tsr = torch.from_numpy(self.pos).cuda()
fluid_pos_tsr = pos_tsr[self.fluid_ids]
sqd_dist, nbr_idx, _, _ = frnn.frnn_grid_points(
fluid_pos_tsr[None, ...], pos_tsr[None, ...],
K=128,
r=cutoff,
grid=None, return_nn=False, return_sorted=True
)
nbr_idx = nbr_idx.squeeze(0)
center_idx = nbr_idx.clone()
center_idx[:] = torch.from_numpy(self.fluid_ids).to(pos_tsr.device).reshape(-1, 1)
mask = nbr_idx != -1
nbr_idx = nbr_idx[mask]
center_idx = center_idx[mask]
pic_index = torch.unique(nbr_idx).cpu().numpy()
if with_col_pic:
# col_cutoff = 2.1 * COL_RADIUS
# col_pic_mask = sqd_dist.squeeze(0) < col_cutoff**2
# valid_mask = torch.logical_and(col_pic_mask, mask)
# col_pic = torch.unique(nbr_idx[valid_mask]).cpu().numpy()
col_pic = pic_index
mapped_nbr_idx = self.find_idx(pic_index, nbr_idx.cpu().numpy())
mapped_center_idx = self.find_idx(pic_index, center_idx.cpu().numpy())
graph = dgl.graph((torch.from_numpy(mapped_nbr_idx).cuda(), torch.from_numpy(mapped_center_idx).cuda()))
if kernel_fn is not None:
sqd_dist = sqd_dist.squeeze(0)
sqd_dist = sqd_dist[mask]
w = kernel_fn(torch.sqrt(sqd_dist), cutoff)
graph.edata['w'] = w
if with_col_pic:
return graph, pic_index, col_pic
return graph, pic_index
def add_particles(self, vel, pos, verbose=True):
add_pnum = vel.shape[0]
self.vel = np.concatenate((self.vel, vel), axis=0)
self.pos = np.concatenate((self.pos, pos), axis=0)
self.ptype = np.concatenate((self.ptype, np.ones((add_pnum, ))), axis=0).reshape(-1, )
self.fluid_ids = np.concatenate((self.fluid_ids,
np.arange(add_pnum) + self.total_num),
axis=0).reshape(-1, )
self.total_num = self.ptype.shape[0]
self.pres = np.zeros((self.total_num, ))
if verbose:
print("Add %i particles to fluid field" % add_pnum)
def remove_particle(self, boundary, which_axis=0, verbose=True, right=True):
if right: # particles inside boundary
inbound_fluid = np.logical_and(self.ptype == 1, self.pos[:, which_axis] < boundary)
else: # particles outside boundary
inbound_fluid = np.logical_and(self.ptype == 1, self.pos[:, which_axis] > boundary)
wall = self.ptype != 1
mask = np.logical_or(inbound_fluid, wall)
# remove out of boundary fluid particles from data structure
prev_num = self.total_num
remove_num = prev_num - np.sum(mask)
if verbose:
print("Remove %i particles from fluid field" % remove_num)
if remove_num > 0:
self.vel = self.vel[mask].copy()
self.pos = self.pos[mask].copy()
self.ptype = self.ptype[mask].copy()
self.fluid_ids = np.argwhere(self.ptype == 1).astype(np.int64).reshape(-1, )
self.total_num = self.ptype.shape[0]
self.pres = np.zeros((self.total_num,))
def get_pos(self, ids=None):
return self.pos[self.ptype == 1] if ids is None else self.pos[ids]
def get_vel(self, ids=None):
return self.vel[self.ptype == 1] if ids is None else self.vel[ids]
def move_boundary(self, vel: np.ndarray, dt):
# here, assert the whole system move
self.pos[:] += vel*dt
def get_lap_adjacency(self, control_radius, mode, **kwargs):
# sparse adjacency matrix for laplacian
support_kw = ['ids_type',
'pass_in_ids',
'neg_lap',
'return_sparse_ele']
supported_mode = ['laplacian']
if mode not in supported_mode:
raise Exception(mode + ' is not a supported mode')
for key in kwargs.keys():
if key not in support_kw:
raise Exception(key + ' is not a supported operation')
ids_type = kwargs.get('ids_type')
return_sparse_ele = kwargs.get('return_sparse_ele')
fluid_ids = self.fluid_ids
nd_ids = self.non_dum_ids
nfs_ids = self.nfs_ids
if ids_type == 'fluid' or ids_type is None:
ids = fluid_ids
elif ids_type == 'pass in':
pass_ids = kwargs.get('pass_in_ids')
if pass_ids is None:
raise Exception('There should be ids passed in under pass in ids type')
ids = pass_ids
elif ids_type == 'nfs': # non free surface particles
ids = nfs_ids
elif ids_type == 'nds': # non dummy particles
ids = nd_ids
elif ids_type == 'all': # all particles
ids = np.arange(0, self.total_num, 1).astype(np.int64)
else:
raise Exception("unsupported particle type selecting")
if control_radius != LAP_RADIUS:
print('Default radius of nfs_lap mode should be LAP_RADIUS')
negative = kwargs.get('neg_lap')
arr_size = len(ids)
val_arr, idx_arr, tot_size, count = get_laplacian_cuda(self.pos, self.ptype, ids, control_radius)
if not negative: # negative to make the matrix positive definite, which is necessary for CG method
val_arr = - val_arr
idx, val = arr2adj(idx_arr, val_arr, count, tot_size)
if return_sparse_ele:
return idx, val, arr_size
return sparse_tensor(idx, val, arr_size)
def fluid2id(self, p_in_cell, fld_ids=None):
if fld_ids is None:
fld_ids = self.fluid_ids
p_in_cell = np.array(p_in_cell, dtype=np.int64)
return self._index(p_in_cell, fld_ids)
def get_density(self, control_radius=GRAD_RADIUS, only_fluid=False):
density = get_density_cuda(self.pos, self.ptype, control_radius)
if not only_fluid:
return density
else:
return density[self.fluid_ids]
def get_vel_divergence(self, control_radius=GRAD_RADIUS, only_fluid=False):
div = get_vel_div_cuda(self.vel, self.pos, self.ptype, control_radius)
if not only_fluid:
return div * (-self.N0 * control_radius) / self.rho
else:
return div[self.fluid_ids] * (-self.N0 * control_radius) / self.rho
def update_nfs(self, return_feat=False, clamp_fs=False, only_nfs=False):
density_ = self.get_density()
self.nfs_ids = np.argwhere(density_ > 0.97*self.N0).astype(np.int64).reshape(-1,)
if clamp_fs:
density = (np.ones_like(self.ptype, dtype=np.float32) * self.N0).reshape(-1,)
density[self.nfs_ids] = density_[self.nfs_ids]
else:
density = density_
if return_feat:
return density / self.N0
if only_nfs:
return density[self.nfs_ids]
return density
def predict(self, cache_train_feat=False):
Adj_lap = self.get_lap_adjacency(LAP_RADIUS, mode="laplacian")
with torch.no_grad():
# ==============apply body force================
visc = self.nu * Laplacian(self.vel[self.fluid_ids], Adj_lap, self.N0_lap, self.lam).numpy()
body_force = np.array([0, 0, G])
bf_acc = visc + body_force
vel_bf_prev = self.vel.copy()
pos_bf_prev = self.pos.copy()
self.vel[self.fluid_ids] += bf_acc * self.DT
self.pos[self.fluid_ids] += self.vel[self.fluid_ids] * self.DT
if cache_train_feat:
assert len(self.cache) == 0
self.cache['fluid_idx'] = self.fluid_ids
bf_pic = self.get_nbr(LAP_RADIUS, return_pic=True)
bf_train_feat = {'pos': pos_bf_prev[bf_pic],
'vel': vel_bf_prev[bf_pic],
'acc': bf_acc,
'in_cell_idx': bf_pic}
self.cache['bf'] = bf_train_feat
col_pic = self.get_nbr(COL_RADIUS, return_pic=True)
col_train_feat = {'pos': self.pos[col_pic],
'vel_prev': self.vel[col_pic],
'in_cell_idx': col_pic,
}
vel_cu, pos_cu = get_collision_cuda(self.vel, self.pos, self.ptype, COL_RADIUS)
self.vel = vel_cu
self.pos = pos_cu
if cache_train_feat:
col_train_feat['vel_after'] = self.vel[col_pic]
self.cache['col'] = col_train_feat
density = self.update_nfs()
div = self.get_vel_divergence()
source_term = -0.80 * (div[self.nfs_ids] / self.DT) \
+ 0.20 * (density[self.nfs_ids] - self.N0) / (self.DT**2 * self.N0)
if cache_train_feat:
dns_feat = self.update_nfs(return_feat=True)
prs_train_feat = {
'pos': self.pos[self.nfs_ids],
'dns': dns_feat[self.nfs_ids],
'vel': self.vel[self.nfs_ids],
'nfs_idx': self.nfs_ids}
self.cache['prs'] = prs_train_feat
return source_term
def predict_with_timing(self):
log = {}
visc_nbr_start = time.time()
Adj_lap = self.get_lap_adjacency(LAP_RADIUS, mode="laplacian")
visc_nbr_end = time.time()
log['adv_nbr'] = visc_nbr_end - visc_nbr_start
with torch.no_grad():
# ==============apply body force================
visc_calc_start = time.time()
visc = self.nu * Laplacian(self.vel[self.fluid_ids], Adj_lap, self.N0_lap, self.lam).numpy()
body_force = np.array([0, 0, G])
bf_acc = visc + body_force
self.vel[self.fluid_ids] += bf_acc * self.DT
self.pos[self.fluid_ids] += self.vel[self.fluid_ids] * self.DT
visc_calc_end = time.time()
log['adv_calc'] = visc_calc_end - visc_calc_start
col_start = time.time()
vel_cu, pos_cu = get_collision_cuda(self.vel, self.pos, self.ptype, COL_RADIUS)
col_end = time.time()
log['col'] = col_end - col_start
self.vel = vel_cu
self.pos = pos_cu
source_start = time.time()
density = self.update_nfs()
div = self.get_vel_divergence()
source_term = -0.80 * (div[self.nfs_ids] / self.DT) \
+ 0.20 * (density[self.nfs_ids] - self.N0) / (self.DT**2 * self.N0)
source_end = time.time()
log['prs_source'] = source_end - source_start
return source_term, log
def predict_with_dynamic_bound(self, vel, dt):
Adj_lap = self.get_lap_adjacency(LAP_RADIUS, mode="laplacian")
with torch.no_grad():
# ==============apply body force================
visc = self.nu * Laplacian(self.vel[self.fluid_ids], Adj_lap, self.N0_lap, self.lam).numpy()
body_force = np.array([0, 0, G])
bf_acc = visc + body_force
self.vel[self.fluid_ids] += bf_acc * self.DT
self.pos[self.fluid_ids] += self.vel[self.fluid_ids] * self.DT
mask = np.ones((self.pos.shape[0], ))
mask[self.fluid_ids] = 0
self.pos[mask == 1] += vel*dt
vel_cu, pos_cu = get_collision_cuda(self.vel, self.pos, self.ptype, COL_RADIUS)
self.vel = vel_cu
self.pos = pos_cu
density = self.update_nfs()
div = self.get_vel_divergence()
source_term = -0.80 * (div[self.nfs_ids] / self.DT) \
+ 0.20 * (density[self.nfs_ids] - self.N0) / (self.DT**2 * self.N0)
return source_term
def move_bound(self, vel, dt):
mask = np.ones((self.pos.shape[0],))
mask[self.fluid_ids] = 0
self.pos[mask == 1] += vel * dt
def get_prs_feat(self):
dns_feat = self.update_nfs(return_feat=True)
prs_feat = {
'pos': self.pos[self.nfs_ids],
'dns': dns_feat[self.nfs_ids],
'vel': self.vel[self.nfs_ids],
'nfs_idx': self.nfs_ids}
return prs_feat
def collision(self):
vel_cu, pos_cu = get_collision_cuda(self.vel, self.pos, self.ptype, COL_RADIUS)
self.vel = vel_cu
self.pos = pos_cu
def correct(self, pred_pres, cache_train_feat=False):
self.pres = np.zeros_like(self.pres)
self.pres[self.nfs_ids] = np.where(pred_pres > 0, pred_pres, 0).reshape(-1, )
pres_grad = get_gradient_cuda(self.pres, self.pos, self.ptype, self.fluid_ids, GRAD_RADIUS)
acc = -1./self.rho * pres_grad * 3./self.N0
dt = self.DT
self.pos[self.fluid_ids] += acc * (dt**2)
self.vel[self.fluid_ids] += acc * dt
if cache_train_feat:
assert 'prs' in self.cache.keys()
self.cache['prs']['prs'] = self.pres[self.nfs_ids]
def weak_compress_pressure(self):
density = self.update_nfs(only_nfs=True)
pres = 22.0**2 / self.N0 * (density > self.N0) * (density - self.N0) * self.rho
return pres
def advect(self, ext_force):
self.vel[self.fluid_ids] += ext_force * self.DT
self.pos[self.fluid_ids] += self.vel[self.fluid_ids] * self.DT
def col_correct(self, col_vel):
self.pos[self.fluid_ids] += (col_vel - self.vel[self.fluid_ids]) * self.DT
self.vel[self.fluid_ids] = col_vel
def pres_predict(self):
density_feat = self.update_nfs(return_feat=True)
vel_feat = self.vel
return density_feat, vel_feat
def set_pos(self, pos, ids=None, update_nfs=True):
ids = self.fluid_ids if ids is None else ids
pos_ = pos.copy()
self.pos[ids] = pos_
if update_nfs:
self.update_nfs()
def set_vel(self, vel, ids=None):
ids = self.fluid_ids if ids is None else ids
vel_ = vel.copy()
self.vel[ids] = vel_
def set_state(self, pos, vel, ids=None):
self.set_pos(pos, ids)
self.set_vel(vel, ids)
def write_info(self, output_path, time_step,
x_boundary=None, y_boundary=None, z_boundary=None, write_status=False):
pos = self.pos
vel = self.vel
mask = self.fluid_ids
def mask_out_boundary(mask, bound):
mask = np.intersect1d(mask, np.argwhere(pos[:, 0]) >= bound[0])
mask = np.intersect1d(mask, np.argwhere(pos[:, 0]) <= bound[1])
return mask
if x_boundary is not None:
mask = mask_out_boundary(mask, x_boundary)
if y_boundary is not None:
mask = mask_out_boundary(mask, y_boundary)
if z_boundary is not None:
mask = mask_out_boundary(mask, z_boundary)
info = {'pos': pos[mask], 'vel': vel[mask]}
if write_status:
density = self.get_density(GRAD_RADIUS)
pres = self.pres
vel = self.vel
vel_div = self.get_vel_divergence(GRAD_RADIUS)
info['dns'] = density[mask]
info['prs'] = pres[mask]
info['vel'] = vel[mask]
info['vel_div'] = vel_div[mask]
np.savez_compressed(output_path + 'sim_info' + str(time_step) + '.npz', **info)
def write_data(self, output_path, time_step, dump_only=None):
with open(output_path + 'data' + str(time_step) + '.pkl', 'wb') as pickle_file:
if dump_only is None:
pickle.dump(self.cache, pickle_file)
else:
assert self.cache.get(dump_only) is not None
self.cache[dump_only]['fluid_idx'] = self.cache['fluid_idx']
pickle.dump(self.cache[dump_only], pickle_file)
del self.cache
self.cache = {}
@staticmethod
@nb.njit
def _find_min_max(val, h):
min_ = 1e10
max_ = -1e10
for i in range(val.shape[0]):
if min_ > val[i]:
min_ = val[i]
if max_ < val[i]:
max_ = val[i]
return (min_ - 2 * h), (max_ + 2 * h)
def gen_sparse_map(self, ids):
arr_size = len(ids)
local_ids = np.arange(arr_size).astype(dtype=np.int64)
sparse_map = Dict.empty(
key_type=types.int64,
value_type=types.int64
)
sparse_map = self._gen_sparse_map(sparse_map, ids, local_ids)
return sparse_map
@staticmethod
@nb.njit
def _gen_sparse_map(sp_map, global_ids, local_ids):
for i in range(len(global_ids)):
sp_map[global_ids[i]] = local_ids[i]
return sp_map
@staticmethod
@nb.njit
def _index(ids1, ids2):
"""ids1: sparse encoding,
ids2: fluid ids"""
idx_map = []
cursor = 0
for i, id1 in enumerate(ids1):
id2 = ids2[cursor]
if id2 == id1:
idx_map.append(i)
cursor += 1
if cursor == len(ids2):
break
return idx_map
@staticmethod
def find_idx(to_find_arr, key):
"""
Copied from
https://stackoverflow.com/questions/8251541/numpy-for-every-element-in-one-array-find-the-index-in-another-array
"""
xsorted_idx = np.argsort(to_find_arr)
ypos = np.searchsorted(to_find_arr[xsorted_idx], key)
indices = xsorted_idx[ypos]
return indices | 0.345768 | 0.463566 |
import os
from collections import defaultdict
from ctypes import c_float
from itertools import chain
from typing import List, Tuple
import pyglet
from pyglet.gl import *
from pyglet.graphics.vertexdomain import create_domain, create_attribute_usage
from .wavefront_parsers import ObjectParser, WavefrontObjectFactory
from .wavefront_parsers import WaveFrontObject, Face, TexturedFace, Material
class Drawable(object):
__abstract__ = True
def draw(self):
pass
def set_double_sided(self, state):
if state:
self._configure_cull_face = self._disable_cull_face
else:
self._configure_cull_face = self._enable_cull_face
def _configure_cull_face(self):
pass
def _enable_cull_face(self):
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
def _disable_cull_face(self):
glDisable(GL_CULL_FACE)
def is_transparent(self):
pass
class OpenGLMesh(WaveFrontObject):
def __init__(self, faces: List['OpenGLFace'], textured_faces: List['OpenGLTexturedFace'], name=None, group=None):
assert len(faces) + len(textured_faces) > 0
super().__init__(faces, textured_faces, name, group)
self.materials = {face.material.name: face.material for face in chain(faces, textured_faces)}
self.drawables = set()
self.transparent_drawables = set()
self._render_bundles()
self.animations = set()
self.transmutations = set()
@property
def all_faces(self):
return chain(self._faces, self._textured_faces)
def update_material(self, material_name, material_mode, material_channel, value):
channels = 'rgba'
values = [int(channel not in material_channel) or value for channel in channels]
self.materials[material_name].update(**{material_mode: values})
def __copy__(self):
faces = [face.__copy__() for face in self._faces]
textured_faces = [face.__copy__() for face in self._textured_faces]
materials = {material.name: material.__copy__() for material in self.materials.values()}
for face in chain(faces, textured_faces):
face.material = materials[face.material.name]
copy = self.__class__(faces, textured_faces, name=self.name, group=self.group)
return copy
def _render_bundles(self):
faces_by_material_n_points_draw_mode = defaultdict(list)
for face in self._faces + self._textured_faces:
n_points = min(face.n_vertices, 5)
material_n_points_draw_mode_key = (face.material.name, n_points, face.draw_mode)
faces_by_material_n_points_draw_mode[material_n_points_draw_mode_key].append(face)
for (material_name, n_points, draw_mode), faces in faces_by_material_n_points_draw_mode.items():
material = self.materials[material_name]
bundle = OpenGLFaceBundle(faces, material, n_points, draw_mode)
if bundle.is_transparent():
self.transparent_drawables.add(bundle)
else:
self.drawables.add(bundle)
def set_double_sided(self, state):
for drawable in self.drawables:
drawable.set_double_sided(state)
def add_transmutation(self, transmutation):
self.transmutations.add(transmutation)
def remove_transmutation(self, transmutation):
try:
self.transmutations.remove(transmutation)
except KeyError:
pass
def add_animation(self, animation):
self.animations.add(animation)
def remove_animation(self, animation):
try:
self.animations.remove(animation)
except KeyError:
pass
def timer(self, dt):
for animation in self.animations:
animation(dt)
for transmutation in self.transmutations:
for material in self.materials.values():
transmutation(material, dt)
def add_drawable(self, drawable: Drawable):
if drawable.is_transparent():
self.transparent_drawables.add(drawable)
else:
self.drawables.add(drawable)
def remove_drawable(self, drawable):
try:
self.drawables.remove(drawable)
except KeyError:
pass
def draw(self):
self.push_attributes()
for bundle in self.drawables:
bundle.draw()
self.pop_attributes()
def draw_transparent(self):
self.push_attributes()
for bundle in self.transparent_drawables:
bundle.draw()
self.pop_attributes()
@staticmethod
def push_attributes():
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT)
glDisable(GL_TEXTURE_2D)
@staticmethod
def pop_attributes():
glPopAttrib()
glPopClientAttrib()
def __repr__(self):
return f'Mesh "{self.name}"\n{self.drawables}\n{self.transparent_drawables}'
class OpenGLFace(Face):
draw_mode = GL_N3F_V3F
def __init__(self, vertices: list, normals: list, material: 'OpenGLMaterial'):
super().__init__(vertices, normals, material)
self.draw_data = self._n3f_v3f()
self.n_vertices = len(self._vertices)
def get_draw_data(self):
return self._n3f_v3f()
def _n3f_v3f(self):
n3f_v3f = []
for n, v in zip(self._normals, self._vertices):
n3f_v3f += n
n3f_v3f += v
return n3f_v3f
class OpenGLTexturedFace(TexturedFace):
draw_mode = GL_T2F_N3F_V3F
def __init__(self, vertices: list, texture_coords: list, normals: list, material: 'OpenGLTexturedMaterial'):
super().__init__(vertices, texture_coords, normals, material)
self.draw_data = self._t2f_n3f_v3f()
def get_draw_data(self):
return self._t2f_n3f_v3f()
def _t2f_n3f_v3f(self):
t2f_n3f_v3f = []
for n, t, v in zip(self._normals, self._texture_coords, self._vertices):
t2f_n3f_v3f += t
t2f_n3f_v3f += n
t2f_n3f_v3f += v
return t2f_n3f_v3f
class OpenGLMaterial(Material):
def __init__(self, diffuse: Tuple[float, float, float] = None, ambient: Tuple[float, float, float] = None,
specular: Tuple[float, float, float] = None, emissive: Tuple[float, float, float] = None,
shininess: float = 0.0, name: str = None, alpha: float = 1.0):
diffuse = diffuse or (0, 0, 0)
ambient = ambient or (0, 0, 0)
specular = specular or (0, 0, 0)
emissive = emissive or (0, 0, 0)
name = name or "Unnamed Material"
super().__init__(diffuse, ambient, specular, emissive, shininess, name, alpha)
emissive = [e * d for e, d in zip(emissive, diffuse)]
ambient = [a * d for a, d in zip(ambient, diffuse)]
self.opengl_diffuse = self.to_c_arr(list(diffuse) + [alpha])
self.opengl_ambient = self.to_c_arr(list(ambient) + [alpha])
self.opengl_specular = self.to_c_arr(list(specular) + [alpha])
self.opengl_emissive = self.to_c_arr(list(emissive) + [alpha])
self.opengl_shininess = (shininess / 1000) * 128
self.original_opengl_diffuse = self.opengl_diffuse
self.original_opengl_ambient = self.opengl_ambient
self.original_opengl_specular = self.opengl_specular
self.original_opengl_emissive = self.opengl_emissive
self.original_opengl_shininess = self.opengl_shininess
def update(self, **kwargs):
ones = (1, 1, 1, kwargs.get('alpha', 1))
opengl_diffuse = [a * b for a, b in zip(kwargs.get('diffuse', ones), self.original_opengl_diffuse)]
self.opengl_diffuse = self.to_c_arr(opengl_diffuse)
self.opengl_ambient = self.to_c_arr((a * b for a, b in zip(kwargs.get('ambient', ones), self.original_opengl_ambient)))
self.opengl_specular = self.to_c_arr((a * b for a, b in zip(kwargs.get('specular', ones), self.original_opengl_specular)))
self.opengl_emissive = self.to_c_arr((a * b for a, b in zip(kwargs.get('emissive', ones), self.original_opengl_emissive)))
self.opengl_shininess = (kwargs.get('shininess', self.original_opengl_shininess) / 1000) * 128
def __getstate__(self):
d = {}
for k, val in self.__dict__.items():
if 'opengl' in k and 'opengl_shininess' not in k:
d[k] = list(val)
else:
d[k] = val
return d
def __setstate__(self, state):
d = {}
for k, val in state.items():
if 'opengl' in k and 'opengl_shininess' not in k:
d[k] = self.to_c_arr(val)
else:
d[k] = val
self.__dict__.update(d)
@staticmethod
def to_c_arr(values) -> List[c_float]:
c_arr = (c_float * 4)
return c_arr(*values)
@staticmethod
def _revert_from_c_float_arr(values):
return list(values)
@staticmethod
def _convert_zero_to_one_values_into_minus_one_to_one_values(value: float) -> float:
return value # * 2 - 1
def set_material(self):
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, self.opengl_diffuse)
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, self.opengl_ambient)
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, self.opengl_specular)
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, self.opengl_emissive)
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, self.opengl_shininess)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
class OpenGLTexturedMaterial(OpenGLMaterial):
textures = {}
def __init__(self, texture_file_name: str, diffuse: Tuple[float, float, float] = None,
ambient: Tuple[float, float, float] = None, specular: Tuple[float, float, float] = None,
emissive: Tuple[float, float, float] = None, shininess: float = 0.0, name: str = None,
alpha: float = 1.0):
super().__init__(diffuse, ambient, specular, emissive, shininess, name, alpha)
self.texture_file_name = texture_file_name
self.texture = self.load_texture()
def load_texture(self):
try:
texture = self.textures[self.texture_file_name]
except:
try:
image = pyglet.image.load(self.texture_file_name)
except FileNotFoundError:
file_name = os.path.split(self.texture_file_name)[-1]
local_path = os.path.join("objects", file_name)
image = pyglet.image.load(local_path)
texture = image.get_texture()
self.textures[self.texture_file_name] = texture
assert self._value_is_a_power_of_two(image.width)
assert self._value_is_a_power_of_two(image.height)
return texture
def __copy__(self):
return self.__class__(diffuse=self.diffuse, ambient=self.ambient, specular=self.specular,
emissive=self.emissive, shininess=self.shininess,
texture_file_name=self.texture_file_name, name=self.name, alpha=self.alpha)
def __getstate__(self):
d = super(OpenGLTexturedMaterial, self).__getstate__()
d['texture'] = None
return d
def __setstate__(self, state):
super(OpenGLTexturedMaterial, self).__setstate__(state)
self.texture = self.load_texture()
@staticmethod
def _value_is_a_power_of_two(value):
return ((value & (value - 1)) == 0) and value != 0
def set_material(self):
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.texture.id)
gl.glTexParameterf(GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
gl.glTexParameterf(GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
super(OpenGLTexturedMaterial, self).set_material()
class OpenGLFaceBundle(Drawable):
shape_by_n_points = {3: GL_TRIANGLES, 4: GL_QUADS}
def __init__(self, faces: List[OpenGLTexturedFace], material=None, n_points=None, draw_mode=None, **config):
self.faces = faces
self.material = material or faces[0].material
self.n_points = n_points or min(faces[0].n_vertices, 5)
self._n_vertices = len(faces) * self.n_points
self.draw_mode = draw_mode or faces[0].draw_mode
self.shape = self.shape_by_n_points[self.n_points]
self.draw_data = []
self._vertices = []
self._normals = []
self._tex_coords = []
self._face_data_index = {}
self._face_vertex_index = {}
self._face_normal_index = {}
self._face_tex_coord_index = {}
for face in faces:
self._face_data_index[face] = len(self.draw_data)
face.observe(self._update_c_draw_data, "vertices")
self.draw_data += face.draw_data
self._face_vertex_index[face] = len(self._vertices)
self._vertices += face._vertices
face.observe(self._update_vertices, "vertices")
self._face_normal_index[face] = len(self._normals)
self._normals += face._normals
if face._texture_coords:
self._face_tex_coord_index[face] = len(self._tex_coords)
self._tex_coords += face._texture_coords
self.vertex_list = self.create_vertexlist()
self.data_length = len(self.draw_data)
self.c_arr = c_float * self.data_length
self.c_draw_data = self.c_arr(*self.draw_data)
if config.get('double_sided', False):
self._configure_cull_face = self._disable_cull_face
else:
self._configure_cull_face = self._enable_cull_face
def create_vertexlist(self):
usage = create_attribute_usage(f'{self.draw_mode}/dynamic')
vd = create_domain(usage)
vertex_list = vd.create(self._n_vertices)
if self._tex_coords:
vertex_list.tex_coords = self._tex_coords
vertex_list.vertices = self._vertices
vertex_list.normals = self._normals
return vertex_list
def _update_c_draw_data(self, caller: OpenGLTexturedFace):
data = caller.draw_data
start = self._face_data_index[caller]
end = start + len(data)
self.c_draw_data[start:end] = data
def _update_vertices(self, caller: OpenGLTexturedFace):
data = caller._vertices
start = self._face_vertex_index[caller]
end = start + len(data)
self._vertices[start:end] = data
self.vertex_list.vertices = self._vertices
def __getstate__(self):
d = {k: val for k, val in self.__dict__.items()}
del d['c_arr']
del d['c_draw_data']
return d
def __setstate__(self, state):
state["c_arr"] = c_float * state['data_length']
state["c_draw_data"] = state['c_arr'](*state['draw_data'])
self.__dict__.update(state)
def draw(self):
self._configure_cull_face()
self.material.set_material()
glInterleavedArrays(self.draw_mode, 0, self.c_draw_data)
glDrawArrays(self.shape, 0, self._n_vertices)
def is_transparent(self):
return self.material.alpha < 1.0
def __repr__(self):
return "{} {}-gons of {}".format(len(self.faces), self.n_points, self.material.name)
class OpenGLWaveFrontParser(ObjectParser):
def __init__(self, object_class=OpenGLMesh):
super().__init__(object_class=object_class, face_class=OpenGLFace, textured_face_class=OpenGLTexturedFace,
material_class=OpenGLMaterial, textured_material_class=OpenGLTexturedMaterial)
class OpenGLWaveFrontFactory(WavefrontObjectFactory):
def __init__(self, files_to_load: List[str]):
super().__init__(files_to_load, object_parser_class=OpenGLWaveFrontParser) | engine/views/opengl_mesh.py | import os
from collections import defaultdict
from ctypes import c_float
from itertools import chain
from typing import List, Tuple
import pyglet
from pyglet.gl import *
from pyglet.graphics.vertexdomain import create_domain, create_attribute_usage
from .wavefront_parsers import ObjectParser, WavefrontObjectFactory
from .wavefront_parsers import WaveFrontObject, Face, TexturedFace, Material
class Drawable(object):
__abstract__ = True
def draw(self):
pass
def set_double_sided(self, state):
if state:
self._configure_cull_face = self._disable_cull_face
else:
self._configure_cull_face = self._enable_cull_face
def _configure_cull_face(self):
pass
def _enable_cull_face(self):
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
def _disable_cull_face(self):
glDisable(GL_CULL_FACE)
def is_transparent(self):
pass
class OpenGLMesh(WaveFrontObject):
def __init__(self, faces: List['OpenGLFace'], textured_faces: List['OpenGLTexturedFace'], name=None, group=None):
assert len(faces) + len(textured_faces) > 0
super().__init__(faces, textured_faces, name, group)
self.materials = {face.material.name: face.material for face in chain(faces, textured_faces)}
self.drawables = set()
self.transparent_drawables = set()
self._render_bundles()
self.animations = set()
self.transmutations = set()
@property
def all_faces(self):
return chain(self._faces, self._textured_faces)
def update_material(self, material_name, material_mode, material_channel, value):
channels = 'rgba'
values = [int(channel not in material_channel) or value for channel in channels]
self.materials[material_name].update(**{material_mode: values})
def __copy__(self):
faces = [face.__copy__() for face in self._faces]
textured_faces = [face.__copy__() for face in self._textured_faces]
materials = {material.name: material.__copy__() for material in self.materials.values()}
for face in chain(faces, textured_faces):
face.material = materials[face.material.name]
copy = self.__class__(faces, textured_faces, name=self.name, group=self.group)
return copy
def _render_bundles(self):
faces_by_material_n_points_draw_mode = defaultdict(list)
for face in self._faces + self._textured_faces:
n_points = min(face.n_vertices, 5)
material_n_points_draw_mode_key = (face.material.name, n_points, face.draw_mode)
faces_by_material_n_points_draw_mode[material_n_points_draw_mode_key].append(face)
for (material_name, n_points, draw_mode), faces in faces_by_material_n_points_draw_mode.items():
material = self.materials[material_name]
bundle = OpenGLFaceBundle(faces, material, n_points, draw_mode)
if bundle.is_transparent():
self.transparent_drawables.add(bundle)
else:
self.drawables.add(bundle)
def set_double_sided(self, state):
for drawable in self.drawables:
drawable.set_double_sided(state)
def add_transmutation(self, transmutation):
self.transmutations.add(transmutation)
def remove_transmutation(self, transmutation):
try:
self.transmutations.remove(transmutation)
except KeyError:
pass
def add_animation(self, animation):
self.animations.add(animation)
def remove_animation(self, animation):
try:
self.animations.remove(animation)
except KeyError:
pass
def timer(self, dt):
for animation in self.animations:
animation(dt)
for transmutation in self.transmutations:
for material in self.materials.values():
transmutation(material, dt)
def add_drawable(self, drawable: Drawable):
if drawable.is_transparent():
self.transparent_drawables.add(drawable)
else:
self.drawables.add(drawable)
def remove_drawable(self, drawable):
try:
self.drawables.remove(drawable)
except KeyError:
pass
def draw(self):
self.push_attributes()
for bundle in self.drawables:
bundle.draw()
self.pop_attributes()
def draw_transparent(self):
self.push_attributes()
for bundle in self.transparent_drawables:
bundle.draw()
self.pop_attributes()
@staticmethod
def push_attributes():
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT)
glDisable(GL_TEXTURE_2D)
@staticmethod
def pop_attributes():
glPopAttrib()
glPopClientAttrib()
def __repr__(self):
return f'Mesh "{self.name}"\n{self.drawables}\n{self.transparent_drawables}'
class OpenGLFace(Face):
draw_mode = GL_N3F_V3F
def __init__(self, vertices: list, normals: list, material: 'OpenGLMaterial'):
super().__init__(vertices, normals, material)
self.draw_data = self._n3f_v3f()
self.n_vertices = len(self._vertices)
def get_draw_data(self):
return self._n3f_v3f()
def _n3f_v3f(self):
n3f_v3f = []
for n, v in zip(self._normals, self._vertices):
n3f_v3f += n
n3f_v3f += v
return n3f_v3f
class OpenGLTexturedFace(TexturedFace):
draw_mode = GL_T2F_N3F_V3F
def __init__(self, vertices: list, texture_coords: list, normals: list, material: 'OpenGLTexturedMaterial'):
super().__init__(vertices, texture_coords, normals, material)
self.draw_data = self._t2f_n3f_v3f()
def get_draw_data(self):
return self._t2f_n3f_v3f()
def _t2f_n3f_v3f(self):
t2f_n3f_v3f = []
for n, t, v in zip(self._normals, self._texture_coords, self._vertices):
t2f_n3f_v3f += t
t2f_n3f_v3f += n
t2f_n3f_v3f += v
return t2f_n3f_v3f
class OpenGLMaterial(Material):
def __init__(self, diffuse: Tuple[float, float, float] = None, ambient: Tuple[float, float, float] = None,
specular: Tuple[float, float, float] = None, emissive: Tuple[float, float, float] = None,
shininess: float = 0.0, name: str = None, alpha: float = 1.0):
diffuse = diffuse or (0, 0, 0)
ambient = ambient or (0, 0, 0)
specular = specular or (0, 0, 0)
emissive = emissive or (0, 0, 0)
name = name or "Unnamed Material"
super().__init__(diffuse, ambient, specular, emissive, shininess, name, alpha)
emissive = [e * d for e, d in zip(emissive, diffuse)]
ambient = [a * d for a, d in zip(ambient, diffuse)]
self.opengl_diffuse = self.to_c_arr(list(diffuse) + [alpha])
self.opengl_ambient = self.to_c_arr(list(ambient) + [alpha])
self.opengl_specular = self.to_c_arr(list(specular) + [alpha])
self.opengl_emissive = self.to_c_arr(list(emissive) + [alpha])
self.opengl_shininess = (shininess / 1000) * 128
self.original_opengl_diffuse = self.opengl_diffuse
self.original_opengl_ambient = self.opengl_ambient
self.original_opengl_specular = self.opengl_specular
self.original_opengl_emissive = self.opengl_emissive
self.original_opengl_shininess = self.opengl_shininess
def update(self, **kwargs):
ones = (1, 1, 1, kwargs.get('alpha', 1))
opengl_diffuse = [a * b for a, b in zip(kwargs.get('diffuse', ones), self.original_opengl_diffuse)]
self.opengl_diffuse = self.to_c_arr(opengl_diffuse)
self.opengl_ambient = self.to_c_arr((a * b for a, b in zip(kwargs.get('ambient', ones), self.original_opengl_ambient)))
self.opengl_specular = self.to_c_arr((a * b for a, b in zip(kwargs.get('specular', ones), self.original_opengl_specular)))
self.opengl_emissive = self.to_c_arr((a * b for a, b in zip(kwargs.get('emissive', ones), self.original_opengl_emissive)))
self.opengl_shininess = (kwargs.get('shininess', self.original_opengl_shininess) / 1000) * 128
def __getstate__(self):
d = {}
for k, val in self.__dict__.items():
if 'opengl' in k and 'opengl_shininess' not in k:
d[k] = list(val)
else:
d[k] = val
return d
def __setstate__(self, state):
d = {}
for k, val in state.items():
if 'opengl' in k and 'opengl_shininess' not in k:
d[k] = self.to_c_arr(val)
else:
d[k] = val
self.__dict__.update(d)
@staticmethod
def to_c_arr(values) -> List[c_float]:
c_arr = (c_float * 4)
return c_arr(*values)
@staticmethod
def _revert_from_c_float_arr(values):
return list(values)
@staticmethod
def _convert_zero_to_one_values_into_minus_one_to_one_values(value: float) -> float:
return value # * 2 - 1
def set_material(self):
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, self.opengl_diffuse)
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, self.opengl_ambient)
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, self.opengl_specular)
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, self.opengl_emissive)
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, self.opengl_shininess)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
class OpenGLTexturedMaterial(OpenGLMaterial):
textures = {}
def __init__(self, texture_file_name: str, diffuse: Tuple[float, float, float] = None,
ambient: Tuple[float, float, float] = None, specular: Tuple[float, float, float] = None,
emissive: Tuple[float, float, float] = None, shininess: float = 0.0, name: str = None,
alpha: float = 1.0):
super().__init__(diffuse, ambient, specular, emissive, shininess, name, alpha)
self.texture_file_name = texture_file_name
self.texture = self.load_texture()
def load_texture(self):
try:
texture = self.textures[self.texture_file_name]
except:
try:
image = pyglet.image.load(self.texture_file_name)
except FileNotFoundError:
file_name = os.path.split(self.texture_file_name)[-1]
local_path = os.path.join("objects", file_name)
image = pyglet.image.load(local_path)
texture = image.get_texture()
self.textures[self.texture_file_name] = texture
assert self._value_is_a_power_of_two(image.width)
assert self._value_is_a_power_of_two(image.height)
return texture
def __copy__(self):
return self.__class__(diffuse=self.diffuse, ambient=self.ambient, specular=self.specular,
emissive=self.emissive, shininess=self.shininess,
texture_file_name=self.texture_file_name, name=self.name, alpha=self.alpha)
def __getstate__(self):
d = super(OpenGLTexturedMaterial, self).__getstate__()
d['texture'] = None
return d
def __setstate__(self, state):
super(OpenGLTexturedMaterial, self).__setstate__(state)
self.texture = self.load_texture()
@staticmethod
def _value_is_a_power_of_two(value):
return ((value & (value - 1)) == 0) and value != 0
def set_material(self):
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.texture.id)
gl.glTexParameterf(GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
gl.glTexParameterf(GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
super(OpenGLTexturedMaterial, self).set_material()
class OpenGLFaceBundle(Drawable):
shape_by_n_points = {3: GL_TRIANGLES, 4: GL_QUADS}
def __init__(self, faces: List[OpenGLTexturedFace], material=None, n_points=None, draw_mode=None, **config):
self.faces = faces
self.material = material or faces[0].material
self.n_points = n_points or min(faces[0].n_vertices, 5)
self._n_vertices = len(faces) * self.n_points
self.draw_mode = draw_mode or faces[0].draw_mode
self.shape = self.shape_by_n_points[self.n_points]
self.draw_data = []
self._vertices = []
self._normals = []
self._tex_coords = []
self._face_data_index = {}
self._face_vertex_index = {}
self._face_normal_index = {}
self._face_tex_coord_index = {}
for face in faces:
self._face_data_index[face] = len(self.draw_data)
face.observe(self._update_c_draw_data, "vertices")
self.draw_data += face.draw_data
self._face_vertex_index[face] = len(self._vertices)
self._vertices += face._vertices
face.observe(self._update_vertices, "vertices")
self._face_normal_index[face] = len(self._normals)
self._normals += face._normals
if face._texture_coords:
self._face_tex_coord_index[face] = len(self._tex_coords)
self._tex_coords += face._texture_coords
self.vertex_list = self.create_vertexlist()
self.data_length = len(self.draw_data)
self.c_arr = c_float * self.data_length
self.c_draw_data = self.c_arr(*self.draw_data)
if config.get('double_sided', False):
self._configure_cull_face = self._disable_cull_face
else:
self._configure_cull_face = self._enable_cull_face
def create_vertexlist(self):
usage = create_attribute_usage(f'{self.draw_mode}/dynamic')
vd = create_domain(usage)
vertex_list = vd.create(self._n_vertices)
if self._tex_coords:
vertex_list.tex_coords = self._tex_coords
vertex_list.vertices = self._vertices
vertex_list.normals = self._normals
return vertex_list
def _update_c_draw_data(self, caller: OpenGLTexturedFace):
data = caller.draw_data
start = self._face_data_index[caller]
end = start + len(data)
self.c_draw_data[start:end] = data
def _update_vertices(self, caller: OpenGLTexturedFace):
data = caller._vertices
start = self._face_vertex_index[caller]
end = start + len(data)
self._vertices[start:end] = data
self.vertex_list.vertices = self._vertices
def __getstate__(self):
d = {k: val for k, val in self.__dict__.items()}
del d['c_arr']
del d['c_draw_data']
return d
def __setstate__(self, state):
state["c_arr"] = c_float * state['data_length']
state["c_draw_data"] = state['c_arr'](*state['draw_data'])
self.__dict__.update(state)
def draw(self):
self._configure_cull_face()
self.material.set_material()
glInterleavedArrays(self.draw_mode, 0, self.c_draw_data)
glDrawArrays(self.shape, 0, self._n_vertices)
def is_transparent(self):
return self.material.alpha < 1.0
def __repr__(self):
return "{} {}-gons of {}".format(len(self.faces), self.n_points, self.material.name)
class OpenGLWaveFrontParser(ObjectParser):
def __init__(self, object_class=OpenGLMesh):
super().__init__(object_class=object_class, face_class=OpenGLFace, textured_face_class=OpenGLTexturedFace,
material_class=OpenGLMaterial, textured_material_class=OpenGLTexturedMaterial)
class OpenGLWaveFrontFactory(WavefrontObjectFactory):
def __init__(self, files_to_load: List[str]):
super().__init__(files_to_load, object_parser_class=OpenGLWaveFrontParser) | 0.731634 | 0.211641 |
import re
import requests
from bs4 import BeautifulSoup
#re = \(?0?([1-9]{2})[ \-\.\)]{0,2}(9[ \-\.]?\d{4})[ \-\.]?(\d{4})
#soup.prettify() faz o parsing do html
dominio = 'https://django-anuncios.solyd.com.br'
url = 'https://django-anuncios.solyd.com.br/automoveis/'
def GET(url):
try:
resposta = requests.get(url)
if resposta.status_code == 200:
return resposta.text
except Exception as erro:
print('Houve um erro inesperado, desculpe.')
print(erro)
def parsing(resposta_html):
try:
soup = BeautifulSoup(resposta_html, 'html.parser')
return soup
except Exception as erro:
print('Erro no parsing.')
print(erro)
def find_link(soup):
card_pai = soup.find('div', class_='ui three doubling link cards')
cards = card_pai.find_all('a')
links = []
for card in cards:
try:
link = card['href']
links.append(link)
except:
pass
return links
def play_find_link(url):
resposta = GET(url)
if resposta:
soup = parsing(resposta)
if soup:
links_found = find_link(soup)
if links_found:
full_link = []
for link in links_found:
dir = dominio + link
full_link.append(dir)
return full_link
def find_cell(full_link):
for link in full_link:
resposta = GET(link)
if resposta:
soup = parsing(resposta)
if soup:
try:
descricao = soup.find_all('div', class_='sixteen wide column')[2].p.get_text().strip()
except:
print('Erro ao incontrar descrição')
return None
regex = re.findall(r"\(?0?([1-9]{2})[ \-\.\)]{0,2}(9[ \-\.]?\d{4})[ \-\.]?(\d{4})", descricao)
if regex:
print(f'\n{link}:\nnumero: {regex}')
if __name__ == "__main__":
links = play_find_link(url)
if links:
find_cell(links) | random designs-python/crawler/crawler.py | import re
import requests
from bs4 import BeautifulSoup
#re = \(?0?([1-9]{2})[ \-\.\)]{0,2}(9[ \-\.]?\d{4})[ \-\.]?(\d{4})
#soup.prettify() faz o parsing do html
dominio = 'https://django-anuncios.solyd.com.br'
url = 'https://django-anuncios.solyd.com.br/automoveis/'
def GET(url):
try:
resposta = requests.get(url)
if resposta.status_code == 200:
return resposta.text
except Exception as erro:
print('Houve um erro inesperado, desculpe.')
print(erro)
def parsing(resposta_html):
try:
soup = BeautifulSoup(resposta_html, 'html.parser')
return soup
except Exception as erro:
print('Erro no parsing.')
print(erro)
def find_link(soup):
card_pai = soup.find('div', class_='ui three doubling link cards')
cards = card_pai.find_all('a')
links = []
for card in cards:
try:
link = card['href']
links.append(link)
except:
pass
return links
def play_find_link(url):
resposta = GET(url)
if resposta:
soup = parsing(resposta)
if soup:
links_found = find_link(soup)
if links_found:
full_link = []
for link in links_found:
dir = dominio + link
full_link.append(dir)
return full_link
def find_cell(full_link):
for link in full_link:
resposta = GET(link)
if resposta:
soup = parsing(resposta)
if soup:
try:
descricao = soup.find_all('div', class_='sixteen wide column')[2].p.get_text().strip()
except:
print('Erro ao incontrar descrição')
return None
regex = re.findall(r"\(?0?([1-9]{2})[ \-\.\)]{0,2}(9[ \-\.]?\d{4})[ \-\.]?(\d{4})", descricao)
if regex:
print(f'\n{link}:\nnumero: {regex}')
if __name__ == "__main__":
links = play_find_link(url)
if links:
find_cell(links) | 0.181916 | 0.140543 |
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from neutron.common import exceptions as n_exc
from oslo_log import log
from neutron_dynamic_routing._i18n import _
from neutron_dynamic_routing.extensions import bgp as bgp_ext
LOG = log.getLogger(__name__)
# Regular expression to validate Route Target list format
# ["<asn1>:<nn1>","<asn2>:<nn2>", ...] with asn and nn in range 0-65535
RT_REGEX = (r'^((?:0|[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]'
r'\d|6553[0-5]):(?:0|[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d'
r'{2}|655[0-2]\d|6553[0-5]))$')
BGPVRF_RESOURCE_NAME = 'vrf'
BGPVRF_BODY_KEY_NAME = 'vrf'
BGPVRF_TYPE_EVPN = 'evpn'
BGPVRF_EXT_ALIAS = 'vrf'
class BGPVRFNotFound(n_exc.NotFound):
message = _("BGP VRF %(id)s could not be found")
class BGPVRFRouterAssocNotFound(n_exc.NotFound):
message = _("BGP VRF %(vrf_id)s router %(router_id)s "
"association could not be found ")
class BGPVRFRDNotSupported(n_exc.BadRequest):
message = _("BGP VRF %(driver)s driver does not support to manually set "
"route distinguisher")
class BGPVRFRouterAssociationNotSupported(n_exc.BadRequest):
message = _("BGP VRF %(driver)s driver does not support router "
"associations")
class BGPVRFRouterAssocAlreadyExists(n_exc.BadRequest):
message = _("router %(router_id)s is already associated to "
"BGP VRF %(vrf_id)s")
class BGPVRFMultipleRouterAssocNotSupported(n_exc.BadRequest):
message = _("BGP VRF %(driver)s driver does not support multiple "
"router association with a bgp vrf")
class BGPVRFDriverError(n_exc.NeutronException):
message = _("%(method)s failed.")
class BGPVRFSpeakerAssocNotFound(n_exc.NotFound):
message = _("BGP VRF %(vrf_id)s speaker %(speaker_id)s "
"association could not be found ")
class BGPVRFSpeakerAssocAlreadyExists(n_exc.BadRequest):
message = _("Speaker %(speaker_id)s is already associated to "
"BGP VRF %(vrf_id)s")
def _validate_rt_list(data, valid_values=None):
if data is None or data is "":
return
if not isinstance(data, list):
msg = _("'%s' is not a list") % data
LOG.debug(msg)
return msg
for item in data:
msg = attr._validate_regex(item, RT_REGEX)
if msg:
LOG.debug(msg)
return msg
if len(set(data)) != len(data):
msg = _("Duplicate items in the list: '%s'") % ', '.join(data)
LOG.debug(msg)
return msg
validators = {'type:route_target_list': _validate_rt_list}
attr.validators.update(validators)
RESOURCE_ATTRIBUTE_MAP = {
BGPVRF_RESOURCE_NAME + 's': {
'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None},
'is_visible': True,
'primary_key': True,
'enforce_policy': True},
'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None},
'required_by_policy': False,
'is_visible': True,
'enforce_policy': True},
'name': {'allow_post': True, 'allow_put': True,
'default': '',
'validate': {'type:string': None},
'is_visible': True,
'enforce_policy': True},
'type': {'allow_post': True, 'allow_put': False,
'default': BGPVRF_TYPE_EVPN,
'validate': {'type:values': [BGPVRF_TYPE_EVPN]},
'is_visible': True,
'enforce_policy': True},
'import_targets': {'allow_post': True, 'allow_put': True,
'default': [],
'convert_to': attr.convert_to_list,
'validate': {'type:route_target_list': None},
'is_visible': True,
'enforce_policy': True},
'export_targets': {'allow_post': True, 'allow_put': True,
'default': [],
'convert_to': attr.convert_to_list,
'validate': {'type:route_target_list': None},
'is_visible': True,
'enforce_policy': True},
'route_distinguishers': {'allow_post': True, 'allow_put': True,
'default': [],
'convert_to': attr.convert_to_list,
'validate': {'type:route_target_list': None},
'is_visible': True,
'enforce_policy': True},
'routers': {'allow_post': False, 'allow_put': False,
'is_visible': True,
'enforce_policy': True},
'segmentation_id': {'allow_post': True, 'allow_put': True,
'is_visible': True,
'enforce_policy': True}
},
}
class Vrf(extensions.ExtensionDescriptor):
@classmethod
def get_name(cls):
return "Neutron BGP Dynamic Routing Extension"
@classmethod
def get_alias(cls):
return BGPVRF_EXT_ALIAS
@classmethod
def get_description(cls):
return("BGP VRF")
@classmethod
def get_updated(cls):
return "2016-05-10T15:37:00-00:00"
@classmethod
def get_resources(cls):
plural_mappings = resource_helper.build_plural_mappings(
{}, RESOURCE_ATTRIBUTE_MAP)
plural_mappings['import_targets'] = 'import_target'
plural_mappings['export_targets'] = 'export_target'
plural_mappings['route_distinguishers'] = 'route_distinguishers'
plural_mappings['router_associations'] = 'router_association'
attr.PLURALS.update(plural_mappings)
action_map = {BGPVRF_RESOURCE_NAME:
{'add_vrf_speaker_assoc': 'PUT',
'remove_vrf_speaker_assoc': 'PUT',
'add_vrf_router_assoc': 'PUT',
'remove_vrf_router_assoc': 'PUT'}}
exts = resource_helper.build_resource_info(plural_mappings,
RESOURCE_ATTRIBUTE_MAP,
bgp_ext.BGP_EXT_ALIAS,
action_map=action_map)
return exts | neutron_dynamic_routing/extensions/vrf.py |
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from neutron.common import exceptions as n_exc
from oslo_log import log
from neutron_dynamic_routing._i18n import _
from neutron_dynamic_routing.extensions import bgp as bgp_ext
LOG = log.getLogger(__name__)
# Regular expression to validate Route Target list format
# ["<asn1>:<nn1>","<asn2>:<nn2>", ...] with asn and nn in range 0-65535
RT_REGEX = (r'^((?:0|[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]'
r'\d|6553[0-5]):(?:0|[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d'
r'{2}|655[0-2]\d|6553[0-5]))$')
BGPVRF_RESOURCE_NAME = 'vrf'
BGPVRF_BODY_KEY_NAME = 'vrf'
BGPVRF_TYPE_EVPN = 'evpn'
BGPVRF_EXT_ALIAS = 'vrf'
class BGPVRFNotFound(n_exc.NotFound):
message = _("BGP VRF %(id)s could not be found")
class BGPVRFRouterAssocNotFound(n_exc.NotFound):
message = _("BGP VRF %(vrf_id)s router %(router_id)s "
"association could not be found ")
class BGPVRFRDNotSupported(n_exc.BadRequest):
message = _("BGP VRF %(driver)s driver does not support to manually set "
"route distinguisher")
class BGPVRFRouterAssociationNotSupported(n_exc.BadRequest):
message = _("BGP VRF %(driver)s driver does not support router "
"associations")
class BGPVRFRouterAssocAlreadyExists(n_exc.BadRequest):
message = _("router %(router_id)s is already associated to "
"BGP VRF %(vrf_id)s")
class BGPVRFMultipleRouterAssocNotSupported(n_exc.BadRequest):
message = _("BGP VRF %(driver)s driver does not support multiple "
"router association with a bgp vrf")
class BGPVRFDriverError(n_exc.NeutronException):
message = _("%(method)s failed.")
class BGPVRFSpeakerAssocNotFound(n_exc.NotFound):
message = _("BGP VRF %(vrf_id)s speaker %(speaker_id)s "
"association could not be found ")
class BGPVRFSpeakerAssocAlreadyExists(n_exc.BadRequest):
message = _("Speaker %(speaker_id)s is already associated to "
"BGP VRF %(vrf_id)s")
def _validate_rt_list(data, valid_values=None):
if data is None or data is "":
return
if not isinstance(data, list):
msg = _("'%s' is not a list") % data
LOG.debug(msg)
return msg
for item in data:
msg = attr._validate_regex(item, RT_REGEX)
if msg:
LOG.debug(msg)
return msg
if len(set(data)) != len(data):
msg = _("Duplicate items in the list: '%s'") % ', '.join(data)
LOG.debug(msg)
return msg
validators = {'type:route_target_list': _validate_rt_list}
attr.validators.update(validators)
RESOURCE_ATTRIBUTE_MAP = {
BGPVRF_RESOURCE_NAME + 's': {
'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None},
'is_visible': True,
'primary_key': True,
'enforce_policy': True},
'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None},
'required_by_policy': False,
'is_visible': True,
'enforce_policy': True},
'name': {'allow_post': True, 'allow_put': True,
'default': '',
'validate': {'type:string': None},
'is_visible': True,
'enforce_policy': True},
'type': {'allow_post': True, 'allow_put': False,
'default': BGPVRF_TYPE_EVPN,
'validate': {'type:values': [BGPVRF_TYPE_EVPN]},
'is_visible': True,
'enforce_policy': True},
'import_targets': {'allow_post': True, 'allow_put': True,
'default': [],
'convert_to': attr.convert_to_list,
'validate': {'type:route_target_list': None},
'is_visible': True,
'enforce_policy': True},
'export_targets': {'allow_post': True, 'allow_put': True,
'default': [],
'convert_to': attr.convert_to_list,
'validate': {'type:route_target_list': None},
'is_visible': True,
'enforce_policy': True},
'route_distinguishers': {'allow_post': True, 'allow_put': True,
'default': [],
'convert_to': attr.convert_to_list,
'validate': {'type:route_target_list': None},
'is_visible': True,
'enforce_policy': True},
'routers': {'allow_post': False, 'allow_put': False,
'is_visible': True,
'enforce_policy': True},
'segmentation_id': {'allow_post': True, 'allow_put': True,
'is_visible': True,
'enforce_policy': True}
},
}
class Vrf(extensions.ExtensionDescriptor):
@classmethod
def get_name(cls):
return "Neutron BGP Dynamic Routing Extension"
@classmethod
def get_alias(cls):
return BGPVRF_EXT_ALIAS
@classmethod
def get_description(cls):
return("BGP VRF")
@classmethod
def get_updated(cls):
return "2016-05-10T15:37:00-00:00"
@classmethod
def get_resources(cls):
plural_mappings = resource_helper.build_plural_mappings(
{}, RESOURCE_ATTRIBUTE_MAP)
plural_mappings['import_targets'] = 'import_target'
plural_mappings['export_targets'] = 'export_target'
plural_mappings['route_distinguishers'] = 'route_distinguishers'
plural_mappings['router_associations'] = 'router_association'
attr.PLURALS.update(plural_mappings)
action_map = {BGPVRF_RESOURCE_NAME:
{'add_vrf_speaker_assoc': 'PUT',
'remove_vrf_speaker_assoc': 'PUT',
'add_vrf_router_assoc': 'PUT',
'remove_vrf_router_assoc': 'PUT'}}
exts = resource_helper.build_resource_info(plural_mappings,
RESOURCE_ATTRIBUTE_MAP,
bgp_ext.BGP_EXT_ALIAS,
action_map=action_map)
return exts | 0.636466 | 0.09611 |
from functools import wraps
import os.path
import click
import ndef
version_message = '%%(prog)s %%(version)s (ndeflib %s)' % ndef.__version__
command_plugins = os.path.join(os.path.dirname(__file__), 'commands')
def echo(*args, **kwargs):
click.echo(*args, **kwargs)
def info(*args):
if click.get_current_context().meta['output-logmsg'] != 'silent':
click.secho(*args, err=True, fg='green')
def dmsg(*args):
if click.get_current_context().meta['output-logmsg'] == 'debug':
click.secho(*args, err=True, fg='yellow')
def warn(*args):
click.secho(*args, err=True, fg='red')
class CommandGroup(click.Group):
def list_commands(self, ctx):
command_list = []
# All commands are separate Python files within the
# command_plugins folder.
for filename in sorted(os.listdir(command_plugins)):
basename, extension = os.path.splitext(filename)
if extension == '.py' and basename != '__init__':
command_list.append(basename)
return command_list
def get_command(self, ctx, name):
name = name.lower() # all commands treated case insensitive
# From list_commands() we get the command file names without
# extension. We use the upper case letters to construct the
# abbreviated name and import the module if the requested
# command name matches either the lower case full or short
# name.
for cmd_name in self.list_commands(ctx):
cmd_abbr = ''.join(x for x in cmd_name if 'A' <= x <= 'Z')
if name in (cmd_name.lower(), cmd_abbr.lower()):
module = 'ndeftool.commands.' + cmd_name
return __import__(module, None, None, ['cmd']).cmd
def format_commands(self, ctx, formatter):
rows = []
# From list_commands() we get the command file names without
# extension. We use the upper case letters to construct the
# abbreviated name and store lower case versions of short and
# long command name.
for cmd_name in self.list_commands(ctx):
cmd_abbr = ''.join(x for x in cmd_name if 'A' <= x <= 'Z')
cmd_help = self.get_command(ctx, cmd_name).short_help or ''
rows.append((cmd_abbr.lower(), cmd_name.lower(), cmd_help))
# We want the command list to be sorted by abbreviated command
# name with the shortest names first.
rows = sorted(rows, key=lambda x: '%02d %s' % (len(x[0]), x[0]))
rows = [('%s, %s' % (a, n) if a != n else a, h) for a, n, h in rows]
with formatter.section('Commands'):
formatter.write_dl(rows)
@click.command(cls=CommandGroup, chain=True)
@click.version_option(message=version_message)
@click.option('--relax', 'errors', flag_value='relax',
help='Ignore some errors when decoding.')
@click.option('--ignore', 'errors', flag_value='ignore',
help='Ignore all errors when decoding.')
@click.option('--silent', 'logmsg', flag_value='silent',
help='Suppress all progress information.')
@click.option('--debug', 'logmsg', flag_value='debug',
help='Output debug progress information.')
@click.pass_context
def main(ctx, **kwargs):
"""Create or inspect NFC Data Exchange Format messages.
The ndeftool provides a number of commands to create or inspect
NDEF messages. All commands can be chained to an internal
processing pipeline and the whole fit into a command shell
pipeline.
\b
ndeftool load FILE1 load FILE2 save FILE3
ndeftool load - load FILE2 < FILE1 > FILE3
cat FILE1 | ndeftool load - load FILE2 | hexdump -Cv
The ndeftool processing pipeline builds an NDEF message from left
to right, each command adds some NDEF record(s) to the message
until it is either send to standard output or consumed by an
ndeftool command (unless the --keep option is given to a command
that would otherwise consume the message).
\b
ndeftool text 'one' text 'two' print --keep > two_text_records.ndef
ndeftool text 'one' text 'two' save --keep two_text_records.ndef print
A new pipeline is started after ndeftool command that consumed the
current message. This can be used to generate or inspect multiple
messages.
\b
ndeftool text 'one' save text_1.ndef text 'two' save text_2.ndef
ndeftool load text_1.ndef print load text_2.ndef print
Each command has it's own help page: 'ndeftool <cmd> --help'
"""
ctx.meta['decode-errors'] = kwargs['errors'] or 'strict'
ctx.meta['output-logmsg'] = kwargs['logmsg'] or 'normal'
@main.resultcallback()
def process_commands(processors, **kwargs):
message = None
for processor in processors:
message = processor(message)
dmsg('records = ' + str(message))
echo(b''.join(ndef.message_encoder(message)), nl=False)
def command_processor(func):
@wraps(func)
def wrapper(*args, **kwargs):
def processor(message):
return func(message, *args, **kwargs)
return processor
return wrapper | src/ndeftool/cli.py |
from functools import wraps
import os.path
import click
import ndef
version_message = '%%(prog)s %%(version)s (ndeflib %s)' % ndef.__version__
command_plugins = os.path.join(os.path.dirname(__file__), 'commands')
def echo(*args, **kwargs):
click.echo(*args, **kwargs)
def info(*args):
if click.get_current_context().meta['output-logmsg'] != 'silent':
click.secho(*args, err=True, fg='green')
def dmsg(*args):
if click.get_current_context().meta['output-logmsg'] == 'debug':
click.secho(*args, err=True, fg='yellow')
def warn(*args):
click.secho(*args, err=True, fg='red')
class CommandGroup(click.Group):
def list_commands(self, ctx):
command_list = []
# All commands are separate Python files within the
# command_plugins folder.
for filename in sorted(os.listdir(command_plugins)):
basename, extension = os.path.splitext(filename)
if extension == '.py' and basename != '__init__':
command_list.append(basename)
return command_list
def get_command(self, ctx, name):
name = name.lower() # all commands treated case insensitive
# From list_commands() we get the command file names without
# extension. We use the upper case letters to construct the
# abbreviated name and import the module if the requested
# command name matches either the lower case full or short
# name.
for cmd_name in self.list_commands(ctx):
cmd_abbr = ''.join(x for x in cmd_name if 'A' <= x <= 'Z')
if name in (cmd_name.lower(), cmd_abbr.lower()):
module = 'ndeftool.commands.' + cmd_name
return __import__(module, None, None, ['cmd']).cmd
def format_commands(self, ctx, formatter):
rows = []
# From list_commands() we get the command file names without
# extension. We use the upper case letters to construct the
# abbreviated name and store lower case versions of short and
# long command name.
for cmd_name in self.list_commands(ctx):
cmd_abbr = ''.join(x for x in cmd_name if 'A' <= x <= 'Z')
cmd_help = self.get_command(ctx, cmd_name).short_help or ''
rows.append((cmd_abbr.lower(), cmd_name.lower(), cmd_help))
# We want the command list to be sorted by abbreviated command
# name with the shortest names first.
rows = sorted(rows, key=lambda x: '%02d %s' % (len(x[0]), x[0]))
rows = [('%s, %s' % (a, n) if a != n else a, h) for a, n, h in rows]
with formatter.section('Commands'):
formatter.write_dl(rows)
@click.command(cls=CommandGroup, chain=True)
@click.version_option(message=version_message)
@click.option('--relax', 'errors', flag_value='relax',
help='Ignore some errors when decoding.')
@click.option('--ignore', 'errors', flag_value='ignore',
help='Ignore all errors when decoding.')
@click.option('--silent', 'logmsg', flag_value='silent',
help='Suppress all progress information.')
@click.option('--debug', 'logmsg', flag_value='debug',
help='Output debug progress information.')
@click.pass_context
def main(ctx, **kwargs):
"""Create or inspect NFC Data Exchange Format messages.
The ndeftool provides a number of commands to create or inspect
NDEF messages. All commands can be chained to an internal
processing pipeline and the whole fit into a command shell
pipeline.
\b
ndeftool load FILE1 load FILE2 save FILE3
ndeftool load - load FILE2 < FILE1 > FILE3
cat FILE1 | ndeftool load - load FILE2 | hexdump -Cv
The ndeftool processing pipeline builds an NDEF message from left
to right, each command adds some NDEF record(s) to the message
until it is either send to standard output or consumed by an
ndeftool command (unless the --keep option is given to a command
that would otherwise consume the message).
\b
ndeftool text 'one' text 'two' print --keep > two_text_records.ndef
ndeftool text 'one' text 'two' save --keep two_text_records.ndef print
A new pipeline is started after ndeftool command that consumed the
current message. This can be used to generate or inspect multiple
messages.
\b
ndeftool text 'one' save text_1.ndef text 'two' save text_2.ndef
ndeftool load text_1.ndef print load text_2.ndef print
Each command has it's own help page: 'ndeftool <cmd> --help'
"""
ctx.meta['decode-errors'] = kwargs['errors'] or 'strict'
ctx.meta['output-logmsg'] = kwargs['logmsg'] or 'normal'
@main.resultcallback()
def process_commands(processors, **kwargs):
message = None
for processor in processors:
message = processor(message)
dmsg('records = ' + str(message))
echo(b''.join(ndef.message_encoder(message)), nl=False)
def command_processor(func):
@wraps(func)
def wrapper(*args, **kwargs):
def processor(message):
return func(message, *args, **kwargs)
return processor
return wrapper | 0.474144 | 0.098382 |
import time, urllib, urllib2
from Adafruit_MCP230xx import *
import RPi.GPIO as GPIO
# Raspberry Pi Pin Usage
APPLIANCE0_RPI_PIN = 18
# MCP23017 I2C Port Expander Pin Usage
APPLIANCE0_LED_PIN = 10
APPLIANCE1_LED_PIN = 11
APPLIANCE2_LED_PIN = 12
APPLIANCE3_LED_PIN = 13
APPLIANCE4_LED_PIN = 14
APPLIANCE0_BUTTON_PIN = 4
APPLIANCE1_BUTTON_PIN = 5
APPLIANCE2_BUTTON_PIN = 6
APPLIANCE3_BUTTON_PIN = 7
APPLIANCE4_BUTTON_PIN = 8
APPLIANCE1_MOSFET_PIN = 0
APPLIANCE2_MOSFET_PIN = 1
APPLIANCE3_MOSFET_PIN = 15
APPLIANCE4_MOSFET_PIN = 3
# Appliance state is either 0 or 1 once setup is finished
APPLIANCE0_STATE = -1
APPLIANCE1_STATE = -1
APPLIANCE2_STATE = -1
APPLIANCE3_STATE = -1
APPLIANCE4_STATE = -1
# Set up Raspberry PI GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(APPLIANCE0_RPI_PIN, GPIO.OUT)
# URLs for sending/receiving appliance data
get_url = 'http://localhost/get_data.php'
send_url = 'http://localhost/send_data.php'
# Function called during setup or after main power supply is turned on
def setup_mcp():
global mcp
# Use busnum = 1 for new Raspberry Pi's (512MB with mounting holes)
mcp = Adafruit_MCP230XX(busnum = 1, address = 0x20, num_gpios = 16)
# Set LED and MOSFET pins to outputs
mcp.config(APPLIANCE0_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE1_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE2_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE3_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE4_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE1_MOSFET_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE2_MOSFET_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE3_MOSFET_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE4_MOSFET_PIN, mcp.OUTPUT)
# Set button pins to input with the pullup resistor enabled
mcp.pullup(APPLIANCE0_BUTTON_PIN, 1)
mcp.pullup(APPLIANCE1_BUTTON_PIN, 1)
mcp.pullup(APPLIANCE2_BUTTON_PIN, 1)
mcp.pullup(APPLIANCE3_BUTTON_PIN, 1)
mcp.pullup(APPLIANCE4_BUTTON_PIN, 1)
# Function called when changes to appliance states occur
def update_all_appliances():
mcp.output(APPLIANCE0_LED_PIN, APPLIANCE0_STATE)
mcp.output(APPLIANCE1_LED_PIN, APPLIANCE1_STATE)
mcp.output(APPLIANCE2_LED_PIN, APPLIANCE2_STATE)
mcp.output(APPLIANCE3_LED_PIN, APPLIANCE3_STATE)
mcp.output(APPLIANCE4_LED_PIN, APPLIANCE4_STATE)
mcp.output(APPLIANCE1_MOSFET_PIN, 1 - APPLIANCE1_STATE)
mcp.output(APPLIANCE2_MOSFET_PIN, 1 - APPLIANCE2_STATE)
mcp.output(APPLIANCE3_MOSFET_PIN, 1 - APPLIANCE3_STATE)
mcp.output(APPLIANCE4_MOSFET_PIN, 1 - APPLIANCE4_STATE)
# Function called to get appliance data from MySQL database
def get_data():
values = {'username' : 'sender', # Key/value pairs
'p' : '<KEY>',
}
try:
data = urllib.urlencode(values)
req = urllib2.Request(get_url, data)
response = urllib2.urlopen(req)
return response.read()
except Exception, detail:
print "Err ", detail
# Function called to send appliance data to MySQL database when there is a change (a button is pressed)
def send_data():
values = {'username' : 'sender', # Key/value pairs
'p' : '<KEY>',
'appliance0' : APPLIANCE0_STATE,
'appliance1' : APPLIANCE1_STATE,
'appliance2' : APPLIANCE2_STATE,
'appliance3' : APPLIANCE3_STATE,
'appliance4' : APPLIANCE4_STATE,
}
try:
data = urllib.urlencode(values)
req = urllib2.Request(send_url, data)
response = urllib2.urlopen(req)
return response.read()
except Exception, detail:
print "Err ", detail
def verify_database_integrity(): # Error will be thrown if any appliances are set to on when Python program starts
# This function sets all appliances to off just to be safe
values = {'username' : 'sender', # Key/value pairs
'p' : '<KEY>',
'appliance0' : 0,
'appliance1' : 0,
'appliance2' : 0,
'appliance3' : 0,
'appliance4' : 0,
}
try:
data = urllib.urlencode(values)
req = urllib2.Request(send_url, data)
response = urllib2.urlopen(req)
return response.read()
except Exception, detail:
print "Err ", detail
def turn_appliance0_on(): # Turning on main power supply resets I2C Port Expander - so this function fixes that issue
global APPLIANCE0_STATE
APPLIANCE0_STATE = 1
GPIO.output(APPLIANCE0_RPI_PIN, True)
time.sleep(.25)
setup_mcp()
update_all_appliances()
def turn_appliance0_off(): # When main power supply is turned off, all other appliances need to be shut as well
global APPLIANCE0_STATE, APPLIANCE1_STATE, APPLIANCE2_STATE, APPLIANCE3_STATE, APPLIANCE4_STATE
APPLIANCE0_STATE = 0
APPLIANCE1_STATE = 0
APPLIANCE2_STATE = 0
APPLIANCE3_STATE = 0
APPLIANCE4_STATE = 0
update_all_appliances()
GPIO.output(APPLIANCE0_RPI_PIN, False)
# Main part of program running
print "Setting up MCP23017 port expander"
setup_mcp()
print "Verifying database integrity"
verify_database_integrity()
print "Main loop of program running"
while True:
try:
page = get_data() # Get appliance data
print page
# React if state of appliance has changed
if page.find('!0@0#') != -1 and APPLIANCE0_STATE != 0:
turn_appliance0_off()
elif page.find('!0@1#') != -1 and APPLIANCE0_STATE != 1:
turn_appliance0_on()
if page.find('!1@0#') != -1 and APPLIANCE1_STATE != 0:
APPLIANCE1_STATE = 0
mcp.output(APPLIANCE1_MOSFET_PIN, 1 - APPLIANCE1_STATE)
mcp.output(APPLIANCE1_LED_PIN, APPLIANCE1_STATE)
elif page.find('!1@1#') != -1 and APPLIANCE1_STATE != 1:
APPLIANCE1_STATE = 1
mcp.output(APPLIANCE1_MOSFET_PIN, 1 - APPLIANCE1_STATE)
mcp.output(APPLIANCE1_LED_PIN, APPLIANCE1_STATE)
if page.find('!2@0#') != -1 and APPLIANCE2_STATE != 0:
APPLIANCE2_STATE = 0
mcp.output(APPLIANCE2_MOSFET_PIN, 1 - APPLIANCE2_STATE)
mcp.output(APPLIANCE2_LED_PIN, APPLIANCE2_STATE)
elif page.find('!2@1#') != -1 and APPLIANCE2_STATE != 1:
APPLIANCE2_STATE = 1
mcp.output(APPLIANCE2_MOSFET_PIN, 1 - APPLIANCE2_STATE)
mcp.output(APPLIANCE2_LED_PIN, APPLIANCE2_STATE)
if page.find('!3@0#') != -1 and APPLIANCE3_STATE != 0:
APPLIANCE3_STATE = 0
mcp.output(APPLIANCE3_MOSFET_PIN, 1 - APPLIANCE3_STATE)
mcp.output(APPLIANCE3_LED_PIN, APPLIANCE3_STATE)
elif page.find('!3@1#') != -1 and APPLIANCE3_STATE != 1:
APPLIANCE3_STATE = 1
mcp.output(APPLIANCE3_MOSFET_PIN, 1 - APPLIANCE3_STATE)
mcp.output(APPLIANCE3_LED_PIN, APPLIANCE3_STATE)
if page.find('!4@0#') != -1 and APPLIANCE4_STATE != 0:
APPLIANCE4_STATE = 0
mcp.output(APPLIANCE4_MOSFET_PIN, 1 - APPLIANCE4_STATE)
mcp.output(APPLIANCE4_LED_PIN, APPLIANCE4_STATE)
elif page.find('!4@1#') != -1 and APPLIANCE4_STATE != 1:
APPLIANCE4_STATE = 1
mcp.output(APPLIANCE4_MOSFET_PIN, 1 - APPLIANCE4_STATE)
mcp.output(APPLIANCE4_LED_PIN, APPLIANCE4_STATE)
button_pressed = False
if mcp.input(APPLIANCE0_BUTTON_PIN) == 0: # Check if Appliance 0's button was pressed
if APPLIANCE0_STATE == 0:
turn_appliance0_on()
else:
turn_appliance0_off()
button_pressed = True
else:
if mcp.input(APPLIANCE1_BUTTON_PIN) == 0 and APPLIANCE0_STATE == 1: # Check if Appliance 1's button was pressed
if APPLIANCE1_STATE == 0: # Only act if power supply is on
APPLIANCE1_STATE = 1
else:
APPLIANCE1_STATE = 0
button_pressed = True
elif mcp.input(APPLIANCE2_BUTTON_PIN) == 0 and APPLIANCE0_STATE == 1: # Check if Appliance 2's button was pressed
if APPLIANCE2_STATE == 0: # Only act if power supply is on
APPLIANCE2_STATE = 1
else:
APPLIANCE2_STATE = 0
button_pressed = True
elif mcp.input(APPLIANCE3_BUTTON_PIN) == 0 and APPLIANCE0_STATE == 1: # Check if Appliance 3's button was pressed
if APPLIANCE3_STATE == 0: # Only act if power supply is on
APPLIANCE3_STATE = 1
else:
APPLIANCE3_STATE = 0
button_pressed = True
elif mcp.input(APPLIANCE4_BUTTON_PIN) == 0 and APPLIANCE0_STATE == 1: # Check if Appliance 4's button was pressed
if APPLIANCE4_STATE == 0: # Only act if power supply is on
APPLIANCE4_STATE = 1
else:
APPLIANCE4_STATE = 0
button_pressed = True
if button_pressed:
print send_data()
update_all_appliances()
time.sleep(2)
except KeyboardInterrupt: # User presses Ctrl-C to stop the program
print "\n\nShutting down power supply and appliances..."
turn_appliance0_off()
print send_data()
print "Exiting program..."
exit() | power_manager.py | import time, urllib, urllib2
from Adafruit_MCP230xx import *
import RPi.GPIO as GPIO
# Raspberry Pi Pin Usage
APPLIANCE0_RPI_PIN = 18
# MCP23017 I2C Port Expander Pin Usage
APPLIANCE0_LED_PIN = 10
APPLIANCE1_LED_PIN = 11
APPLIANCE2_LED_PIN = 12
APPLIANCE3_LED_PIN = 13
APPLIANCE4_LED_PIN = 14
APPLIANCE0_BUTTON_PIN = 4
APPLIANCE1_BUTTON_PIN = 5
APPLIANCE2_BUTTON_PIN = 6
APPLIANCE3_BUTTON_PIN = 7
APPLIANCE4_BUTTON_PIN = 8
APPLIANCE1_MOSFET_PIN = 0
APPLIANCE2_MOSFET_PIN = 1
APPLIANCE3_MOSFET_PIN = 15
APPLIANCE4_MOSFET_PIN = 3
# Appliance state is either 0 or 1 once setup is finished
APPLIANCE0_STATE = -1
APPLIANCE1_STATE = -1
APPLIANCE2_STATE = -1
APPLIANCE3_STATE = -1
APPLIANCE4_STATE = -1
# Set up Raspberry PI GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(APPLIANCE0_RPI_PIN, GPIO.OUT)
# URLs for sending/receiving appliance data
get_url = 'http://localhost/get_data.php'
send_url = 'http://localhost/send_data.php'
# Function called during setup or after main power supply is turned on
def setup_mcp():
global mcp
# Use busnum = 1 for new Raspberry Pi's (512MB with mounting holes)
mcp = Adafruit_MCP230XX(busnum = 1, address = 0x20, num_gpios = 16)
# Set LED and MOSFET pins to outputs
mcp.config(APPLIANCE0_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE1_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE2_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE3_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE4_LED_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE1_MOSFET_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE2_MOSFET_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE3_MOSFET_PIN, mcp.OUTPUT)
mcp.config(APPLIANCE4_MOSFET_PIN, mcp.OUTPUT)
# Set button pins to input with the pullup resistor enabled
mcp.pullup(APPLIANCE0_BUTTON_PIN, 1)
mcp.pullup(APPLIANCE1_BUTTON_PIN, 1)
mcp.pullup(APPLIANCE2_BUTTON_PIN, 1)
mcp.pullup(APPLIANCE3_BUTTON_PIN, 1)
mcp.pullup(APPLIANCE4_BUTTON_PIN, 1)
# Function called when changes to appliance states occur
def update_all_appliances():
mcp.output(APPLIANCE0_LED_PIN, APPLIANCE0_STATE)
mcp.output(APPLIANCE1_LED_PIN, APPLIANCE1_STATE)
mcp.output(APPLIANCE2_LED_PIN, APPLIANCE2_STATE)
mcp.output(APPLIANCE3_LED_PIN, APPLIANCE3_STATE)
mcp.output(APPLIANCE4_LED_PIN, APPLIANCE4_STATE)
mcp.output(APPLIANCE1_MOSFET_PIN, 1 - APPLIANCE1_STATE)
mcp.output(APPLIANCE2_MOSFET_PIN, 1 - APPLIANCE2_STATE)
mcp.output(APPLIANCE3_MOSFET_PIN, 1 - APPLIANCE3_STATE)
mcp.output(APPLIANCE4_MOSFET_PIN, 1 - APPLIANCE4_STATE)
# Function called to get appliance data from MySQL database
def get_data():
values = {'username' : 'sender', # Key/value pairs
'p' : '<KEY>',
}
try:
data = urllib.urlencode(values)
req = urllib2.Request(get_url, data)
response = urllib2.urlopen(req)
return response.read()
except Exception, detail:
print "Err ", detail
# Function called to send appliance data to MySQL database when there is a change (a button is pressed)
def send_data():
values = {'username' : 'sender', # Key/value pairs
'p' : '<KEY>',
'appliance0' : APPLIANCE0_STATE,
'appliance1' : APPLIANCE1_STATE,
'appliance2' : APPLIANCE2_STATE,
'appliance3' : APPLIANCE3_STATE,
'appliance4' : APPLIANCE4_STATE,
}
try:
data = urllib.urlencode(values)
req = urllib2.Request(send_url, data)
response = urllib2.urlopen(req)
return response.read()
except Exception, detail:
print "Err ", detail
def verify_database_integrity(): # Error will be thrown if any appliances are set to on when Python program starts
# This function sets all appliances to off just to be safe
values = {'username' : 'sender', # Key/value pairs
'p' : '<KEY>',
'appliance0' : 0,
'appliance1' : 0,
'appliance2' : 0,
'appliance3' : 0,
'appliance4' : 0,
}
try:
data = urllib.urlencode(values)
req = urllib2.Request(send_url, data)
response = urllib2.urlopen(req)
return response.read()
except Exception, detail:
print "Err ", detail
def turn_appliance0_on(): # Turning on main power supply resets I2C Port Expander - so this function fixes that issue
global APPLIANCE0_STATE
APPLIANCE0_STATE = 1
GPIO.output(APPLIANCE0_RPI_PIN, True)
time.sleep(.25)
setup_mcp()
update_all_appliances()
def turn_appliance0_off(): # When main power supply is turned off, all other appliances need to be shut as well
global APPLIANCE0_STATE, APPLIANCE1_STATE, APPLIANCE2_STATE, APPLIANCE3_STATE, APPLIANCE4_STATE
APPLIANCE0_STATE = 0
APPLIANCE1_STATE = 0
APPLIANCE2_STATE = 0
APPLIANCE3_STATE = 0
APPLIANCE4_STATE = 0
update_all_appliances()
GPIO.output(APPLIANCE0_RPI_PIN, False)
# Main part of program running
print "Setting up MCP23017 port expander"
setup_mcp()
print "Verifying database integrity"
verify_database_integrity()
print "Main loop of program running"
while True:
try:
page = get_data() # Get appliance data
print page
# React if state of appliance has changed
if page.find('!0@0#') != -1 and APPLIANCE0_STATE != 0:
turn_appliance0_off()
elif page.find('!0@1#') != -1 and APPLIANCE0_STATE != 1:
turn_appliance0_on()
if page.find('!1@0#') != -1 and APPLIANCE1_STATE != 0:
APPLIANCE1_STATE = 0
mcp.output(APPLIANCE1_MOSFET_PIN, 1 - APPLIANCE1_STATE)
mcp.output(APPLIANCE1_LED_PIN, APPLIANCE1_STATE)
elif page.find('!1@1#') != -1 and APPLIANCE1_STATE != 1:
APPLIANCE1_STATE = 1
mcp.output(APPLIANCE1_MOSFET_PIN, 1 - APPLIANCE1_STATE)
mcp.output(APPLIANCE1_LED_PIN, APPLIANCE1_STATE)
if page.find('!2@0#') != -1 and APPLIANCE2_STATE != 0:
APPLIANCE2_STATE = 0
mcp.output(APPLIANCE2_MOSFET_PIN, 1 - APPLIANCE2_STATE)
mcp.output(APPLIANCE2_LED_PIN, APPLIANCE2_STATE)
elif page.find('!2@1#') != -1 and APPLIANCE2_STATE != 1:
APPLIANCE2_STATE = 1
mcp.output(APPLIANCE2_MOSFET_PIN, 1 - APPLIANCE2_STATE)
mcp.output(APPLIANCE2_LED_PIN, APPLIANCE2_STATE)
if page.find('!3@0#') != -1 and APPLIANCE3_STATE != 0:
APPLIANCE3_STATE = 0
mcp.output(APPLIANCE3_MOSFET_PIN, 1 - APPLIANCE3_STATE)
mcp.output(APPLIANCE3_LED_PIN, APPLIANCE3_STATE)
elif page.find('!3@1#') != -1 and APPLIANCE3_STATE != 1:
APPLIANCE3_STATE = 1
mcp.output(APPLIANCE3_MOSFET_PIN, 1 - APPLIANCE3_STATE)
mcp.output(APPLIANCE3_LED_PIN, APPLIANCE3_STATE)
if page.find('!4@0#') != -1 and APPLIANCE4_STATE != 0:
APPLIANCE4_STATE = 0
mcp.output(APPLIANCE4_MOSFET_PIN, 1 - APPLIANCE4_STATE)
mcp.output(APPLIANCE4_LED_PIN, APPLIANCE4_STATE)
elif page.find('!4@1#') != -1 and APPLIANCE4_STATE != 1:
APPLIANCE4_STATE = 1
mcp.output(APPLIANCE4_MOSFET_PIN, 1 - APPLIANCE4_STATE)
mcp.output(APPLIANCE4_LED_PIN, APPLIANCE4_STATE)
button_pressed = False
if mcp.input(APPLIANCE0_BUTTON_PIN) == 0: # Check if Appliance 0's button was pressed
if APPLIANCE0_STATE == 0:
turn_appliance0_on()
else:
turn_appliance0_off()
button_pressed = True
else:
if mcp.input(APPLIANCE1_BUTTON_PIN) == 0 and APPLIANCE0_STATE == 1: # Check if Appliance 1's button was pressed
if APPLIANCE1_STATE == 0: # Only act if power supply is on
APPLIANCE1_STATE = 1
else:
APPLIANCE1_STATE = 0
button_pressed = True
elif mcp.input(APPLIANCE2_BUTTON_PIN) == 0 and APPLIANCE0_STATE == 1: # Check if Appliance 2's button was pressed
if APPLIANCE2_STATE == 0: # Only act if power supply is on
APPLIANCE2_STATE = 1
else:
APPLIANCE2_STATE = 0
button_pressed = True
elif mcp.input(APPLIANCE3_BUTTON_PIN) == 0 and APPLIANCE0_STATE == 1: # Check if Appliance 3's button was pressed
if APPLIANCE3_STATE == 0: # Only act if power supply is on
APPLIANCE3_STATE = 1
else:
APPLIANCE3_STATE = 0
button_pressed = True
elif mcp.input(APPLIANCE4_BUTTON_PIN) == 0 and APPLIANCE0_STATE == 1: # Check if Appliance 4's button was pressed
if APPLIANCE4_STATE == 0: # Only act if power supply is on
APPLIANCE4_STATE = 1
else:
APPLIANCE4_STATE = 0
button_pressed = True
if button_pressed:
print send_data()
update_all_appliances()
time.sleep(2)
except KeyboardInterrupt: # User presses Ctrl-C to stop the program
print "\n\nShutting down power supply and appliances..."
turn_appliance0_off()
print send_data()
print "Exiting program..."
exit() | 0.258045 | 0.10697 |
import datetime as dt
import rasterio
import geopandas as gpd
from det_tool import functions as fun
from det_tool import classes as cls
from pre_processor import functions as pfun
from config import cityModel_path, foot_height_shp, roof_raster, facade_solar_energy, updated_JSON, report_path
def process(model_path, shp_path, raster_path, facade_file):
print("Reading config file ...")
print("Reading and loading input data ...")
shapefile_foot = gpd.read_file(shp_path)
data = pfun.read_json(model_path)
obj_id = pfun.get_obj_ids(data)
print("3D City model contains {} city objects ...\n".format(len(obj_id)))
print("Initializing InitialRaster Object Class ...")
img = rasterio.open(raster_path)
ini_rast = cls.InitialRaster(img)
print("Initializing and processing FacadeFile Object Class ...")
facadeFile = cls.FacadeData(facade_file)
facadeFile.process_input()
print("Initializing and processing Voxel Object Class ...")
voxels = []
i = 0
for voxel_entry in facadeFile.file_data:
voxel = cls.Voxel(voxel_entry['column'], voxel_entry['row'], voxel_entry['data'], i)
voxel.define_coordinates(ini_rast)
i += 1
voxels.append(voxel)
print("Initializing and processing Building Object Classes ...\n")
build_obj_list = []
build_irr_values = []
stat_data = {}
i = 0
for key in obj_id:
b_start = dt.datetime.now()
print("Building {} in being processed ...".format(key))
building = cls.Building(key, i, fun.extract_footprints(key, shapefile_foot), int(shapefile_foot.height[i]), fun.get_surfaces_info(data, key))
fun.process_building(building, voxels)
for facade in building.facade_list:
facadeRaster = cls.FacadeRaster(facade.feature_id, facade.height, facade.start, facade.end, facade.facade_index)
fun.process_fac_raster(facadeRaster, building, facade)
win_geom, wind_bound_id = fun.extract_window_geometry(data['CityObjects'][key], data)
for n in range(len(win_geom)):
win_obj = cls.Window(win_geom[n], key, n, wind_bound_id[n])
for facade in building.facade_list:
fun.process_window(win_obj, facade, building)
facade.getFacadeIrradiance()
#build_irr_values.append(win_obj.total_irradiance)
stat_data['{}'.format(key)] = {'win_assigned': len(building.windows_geometry)}
roof = cls.Roof(key)
fun.process_roof(roof, data['CityObjects'][key], data, ini_rast)
building.roof = roof
end_time = dt.datetime.now()
dif = end_time - b_start
print("The processing time of building {a} is: {b}\n".format(a=key, b=end_time - b_start))
stat_data['{}'.format(key)]['proc_time'] = float(dif.total_seconds())
build_obj_list.append(building)
uni_ver = []
bound = data['CityObjects'][key]['geometry'][0]['boundaries'][0]
for ver_list in bound:
for element in ver_list:
if element not in uni_ver:
uni_ver.append(element)
stat_data['{}'.format(key)]['n_vertices'] = len(uni_ver)
i += 1
for building in build_obj_list:
for window in building.windows_geometry:
build_irr_values.append(window.total_irradiance)
return build_obj_list, build_irr_values
def main():
start = dt.datetime.now()
build_obj_list, irr_values = process(cityModel_path, foot_height_shp, roof_raster, facade_solar_energy)
process_end = dt.datetime.now()
fun.update_CityModel(build_obj_list, cityModel_path, updated_JSON, irr_values)
fun.generate_report(build_obj_list, report_path)
print("Done!\nProcessing time of the whole dataset: {a}\n"
"The running time of the tool, including the user interaction: {b}"
.format(a=process_end-start, b=dt.datetime.now() - start)) | det_tool/process.py | import datetime as dt
import rasterio
import geopandas as gpd
from det_tool import functions as fun
from det_tool import classes as cls
from pre_processor import functions as pfun
from config import cityModel_path, foot_height_shp, roof_raster, facade_solar_energy, updated_JSON, report_path
def process(model_path, shp_path, raster_path, facade_file):
print("Reading config file ...")
print("Reading and loading input data ...")
shapefile_foot = gpd.read_file(shp_path)
data = pfun.read_json(model_path)
obj_id = pfun.get_obj_ids(data)
print("3D City model contains {} city objects ...\n".format(len(obj_id)))
print("Initializing InitialRaster Object Class ...")
img = rasterio.open(raster_path)
ini_rast = cls.InitialRaster(img)
print("Initializing and processing FacadeFile Object Class ...")
facadeFile = cls.FacadeData(facade_file)
facadeFile.process_input()
print("Initializing and processing Voxel Object Class ...")
voxels = []
i = 0
for voxel_entry in facadeFile.file_data:
voxel = cls.Voxel(voxel_entry['column'], voxel_entry['row'], voxel_entry['data'], i)
voxel.define_coordinates(ini_rast)
i += 1
voxels.append(voxel)
print("Initializing and processing Building Object Classes ...\n")
build_obj_list = []
build_irr_values = []
stat_data = {}
i = 0
for key in obj_id:
b_start = dt.datetime.now()
print("Building {} in being processed ...".format(key))
building = cls.Building(key, i, fun.extract_footprints(key, shapefile_foot), int(shapefile_foot.height[i]), fun.get_surfaces_info(data, key))
fun.process_building(building, voxels)
for facade in building.facade_list:
facadeRaster = cls.FacadeRaster(facade.feature_id, facade.height, facade.start, facade.end, facade.facade_index)
fun.process_fac_raster(facadeRaster, building, facade)
win_geom, wind_bound_id = fun.extract_window_geometry(data['CityObjects'][key], data)
for n in range(len(win_geom)):
win_obj = cls.Window(win_geom[n], key, n, wind_bound_id[n])
for facade in building.facade_list:
fun.process_window(win_obj, facade, building)
facade.getFacadeIrradiance()
#build_irr_values.append(win_obj.total_irradiance)
stat_data['{}'.format(key)] = {'win_assigned': len(building.windows_geometry)}
roof = cls.Roof(key)
fun.process_roof(roof, data['CityObjects'][key], data, ini_rast)
building.roof = roof
end_time = dt.datetime.now()
dif = end_time - b_start
print("The processing time of building {a} is: {b}\n".format(a=key, b=end_time - b_start))
stat_data['{}'.format(key)]['proc_time'] = float(dif.total_seconds())
build_obj_list.append(building)
uni_ver = []
bound = data['CityObjects'][key]['geometry'][0]['boundaries'][0]
for ver_list in bound:
for element in ver_list:
if element not in uni_ver:
uni_ver.append(element)
stat_data['{}'.format(key)]['n_vertices'] = len(uni_ver)
i += 1
for building in build_obj_list:
for window in building.windows_geometry:
build_irr_values.append(window.total_irradiance)
return build_obj_list, build_irr_values
def main():
start = dt.datetime.now()
build_obj_list, irr_values = process(cityModel_path, foot_height_shp, roof_raster, facade_solar_energy)
process_end = dt.datetime.now()
fun.update_CityModel(build_obj_list, cityModel_path, updated_JSON, irr_values)
fun.generate_report(build_obj_list, report_path)
print("Done!\nProcessing time of the whole dataset: {a}\n"
"The running time of the tool, including the user interaction: {b}"
.format(a=process_end-start, b=dt.datetime.now() - start)) | 0.31363 | 0.260766 |
import csv
import os
import shutil
from glob import glob
import pytest
import xlsxwriter
from cliboa.conf import env
from cliboa.scenario.transform.file import CsvHeaderConvert, CsvMerge, ExcelConvert, FileConvert
from cliboa.util.exception import InvalidCount, InvalidFormat
from cliboa.util.helper import Helper
from cliboa.util.lisboa_log import LisboaLog
class TestFileTransform(object):
def setup_method(self, method):
self._data_dir = os.path.join(env.BASE_DIR, "data")
class TestExcelConvert(TestFileTransform):
def test_execute_ng_invalid_extension(self):
with pytest.raises(InvalidFormat) as execinfo:
try:
# create test file
os.makedirs(self._data_dir)
excel_file = os.path.join(self._data_dir, "test.xlxs")
open(excel_file, "w").close()
excel_file2 = os.path.join(self._data_dir, "test.xlxs.bk")
open(excel_file2, "w").close()
# set the essential attributes
instance = ExcelConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", "test.xlxs")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.xlxs")
instance.execute()
finally:
shutil.rmtree(self._data_dir)
assert "not supported" in str(execinfo.value)
def test_excute_ng_multiple_src(self):
with pytest.raises(InvalidCount) as execinfo:
try:
# create test file
os.makedirs(self._data_dir)
excel_file = os.path.join(self._data_dir, "test1.xlxs")
open(excel_file, "w").close()
excel_file2 = os.path.join(self._data_dir, "test2.xlxs")
open(excel_file2, "w").close()
# set the essential attributes
instance = ExcelConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test(.*)\.xlxs")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", r"test(.*).xlxs")
instance.execute()
finally:
shutil.rmtree(self._data_dir)
assert "must be only one" in str(execinfo.value)
def test_execute_ok(self):
try:
# create test file
os.makedirs(self._data_dir)
excel_file = os.path.join(self._data_dir, "test.xlxs")
workbook = xlsxwriter.Workbook(excel_file)
workbook.close()
# set the essential attributes
instance = ExcelConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.xlxs")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
exists_csv = glob(os.path.join(self._data_dir, "test.csv"))
finally:
shutil.rmtree(self._data_dir)
assert "test.csv" in exists_csv[0]
class TestCsvMerge(TestFileTransform):
def test_execute_ok(self):
try:
# create test file
csv_list1 = [["key", "data"], ["1", "spam"], ["2", "spam"], ["3", "spam"]]
os.makedirs(self._data_dir)
test_csv1 = os.path.join(self._data_dir, "test1.csv")
with open(test_csv1, "w") as t1:
writer = csv.writer(t1)
writer.writerows(csv_list1)
csv_list2 = [
["key", "address"],
["1", "spam"],
["2", "spam"],
["3", "spam"],
]
test_csv2 = os.path.join(self._data_dir, "test2.csv")
with open(test_csv2, "w") as t2:
writer = csv.writer(t2)
writer.writerows(csv_list2)
# set the essential attributes
instance = CsvMerge()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src1_pattern", r"test1\.csv")
Helper.set_property(instance, "src2_pattern", r"test2\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
exists_csv = glob(os.path.join(self._data_dir, "test.csv"))
finally:
shutil.rmtree(self._data_dir)
assert "test.csv" in exists_csv[0]
def test_execute_ok_with_unnamed(self):
try:
# create test file
csv_list1 = [["key", "data"], ["1", "spam"], ["2", "spam"], ["3", "spam"]]
os.makedirs(self._data_dir)
test_csv1 = os.path.join(self._data_dir, "test1.csv")
with open(test_csv1, "w") as t1:
writer = csv.writer(t1)
writer.writerows(csv_list1)
csv_list2 = [
["key", "Unnamed: 0"],
["1", "spam"],
["2", "spam"],
["3", "spam"],
]
test_csv2 = os.path.join(self._data_dir, "test2.csv")
with open(test_csv2, "w") as t2:
writer = csv.writer(t2)
writer.writerows(csv_list2)
# set the essential attributes
instance = CsvMerge()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src1_pattern", r"test1\.csv")
Helper.set_property(instance, "src2_pattern", r"test2\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
exists_csv = glob(os.path.join(self._data_dir, "test.csv"))
finally:
shutil.rmtree(self._data_dir)
assert "test.csv" in exists_csv[0]
def test_excute_ng_multiple_target1(self):
with pytest.raises(InvalidCount) as execinfo:
try:
# create test file
os.makedirs(self._data_dir)
target1_file = os.path.join(self._data_dir, "test11.csv")
open(target1_file, "w").close()
target1_file = os.path.join(self._data_dir, "test111.csv")
open(target1_file, "w").close()
target2_file = os.path.join(self._data_dir, "test2.csv")
open(target2_file, "w").close()
# set the essential attributes
instance = CsvMerge()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src1_pattern", "test1(.*).csv")
Helper.set_property(instance, "src2_pattern", "test2.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
finally:
shutil.rmtree(self._data_dir)
assert "must be only one" in str(execinfo.value)
def test_excute_ng_multiple_target2(self):
with pytest.raises(InvalidCount) as execinfo:
try:
# create test file
os.makedirs(self._data_dir)
target1_file = os.path.join(self._data_dir, "test1.csv")
open(target1_file, "w").close()
target2_file = os.path.join(self._data_dir, "test22.csv")
open(target2_file, "w").close()
target2_file = os.path.join(self._data_dir, "test222.csv")
open(target2_file, "w").close()
# set the essential attributes
instance = CsvMerge()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src1_pattern", "test1.csv")
Helper.set_property(instance, "src2_pattern", "test2(.*).csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
finally:
shutil.rmtree(self._data_dir)
assert "must be only one" in str(execinfo.value)
class TestCsvHeaderConvert(TestFileTransform):
def test_execute_ok(self):
try:
# create test file
csv_list = [["key", "data"], ["1", "spam"], ["2", "spam"], ["3", "spam"]]
os.makedirs(self._data_dir)
test_csv = os.path.join(self._data_dir, "test.csv")
with open(test_csv, "w") as t:
writer = csv.writer(t)
writer.writerows(csv_list)
# set the essential attributes
instance = CsvHeaderConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test_new.csv")
Helper.set_property(
instance, "headers", [{"key": "new_key"}, {"data": "new_data"}]
)
instance.execute()
test_new_csv = os.path.join(self._data_dir, "test_new.csv")
with open(test_new_csv, "r") as t:
reader = csv.reader(t)
line = next(reader)
finally:
shutil.rmtree(self._data_dir)
assert line == ["new_key", "new_data"]
def test_execute_ok_2(self):
try:
# create test file
csv_list = [["key", "data"], ["1", "spam"], ["2", "spam"], ["3", "spam"]]
os.makedirs(self._data_dir)
test_csv = os.path.join(self._data_dir, "test.csv")
with open(test_csv, "w") as t:
writer = csv.writer(t)
writer.writerows(csv_list)
# set the essential attributes
instance = CsvHeaderConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test_new.csv")
Helper.set_property(instance, "headers", [{"key": "new_key"}])
instance.execute()
test_new_csv = os.path.join(self._data_dir, "test_new.csv")
with open(test_new_csv, "r") as t:
reader = csv.reader(t)
line = next(reader)
finally:
shutil.rmtree(self._data_dir)
assert line == ["new_key", "data"]
def test_execute_ng_no_src_file(self):
os.makedirs(self._data_dir)
with pytest.raises(InvalidCount) as execinfo:
# set the essential attributes
instance = CsvHeaderConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test_new.csv")
Helper.set_property(
instance, "headers", [{"key": "new_key"}, {"data": "new_data"}]
)
instance.execute()
shutil.rmtree(self._data_dir)
assert "not exist" in str(execinfo.value)
def test_execute_ng_no_multiple_files(self):
# create test files
os.makedirs(self._data_dir)
test1_csv = os.path.join(self._data_dir, "test1.csv")
test2_csv = os.path.join(self._data_dir, "test2.csv")
open(test1_csv, "w").close
open(test2_csv, "w").close
with pytest.raises(InvalidCount) as execinfo:
# set the essential attributes
instance = CsvHeaderConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test(.*)\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test_new.csv")
Helper.set_property(
instance, "headers", [{"key": "new_key"}, {"data": "new_data"}]
)
instance.execute()
shutil.rmtree(self._data_dir)
assert "only one" in str(execinfo.value)
class TestFileConvert(TestFileTransform):
def test_execute(self):
STR_UTF8 = "いろはにほへと"
try:
# create test file
os.makedirs(self._data_dir)
test_file = os.path.join(self._data_dir, "test.txt")
with open(test_file, "w") as t:
t.write(STR_UTF8)
# set the essential attributes
instance = FileConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.txt")
Helper.set_property(instance, "encoding_from", "utf-8")
Helper.set_property(instance, "encoding_to", "utf-16")
instance.execute()
with open(test_file, errors="ignore") as t:
str_utf16 = t.read()
assert str_utf16 != STR_UTF8
# set the essential attributes
instance = FileConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.txt")
Helper.set_property(instance, "encoding_from", "utf-16")
Helper.set_property(instance, "encoding_to", "utf-8")
instance.execute()
with open(test_file) as t:
str_utf8 = t.read()
assert str_utf8 == STR_UTF8
finally:
shutil.rmtree(self._data_dir) | tests/scenario/transform/test_file.py | import csv
import os
import shutil
from glob import glob
import pytest
import xlsxwriter
from cliboa.conf import env
from cliboa.scenario.transform.file import CsvHeaderConvert, CsvMerge, ExcelConvert, FileConvert
from cliboa.util.exception import InvalidCount, InvalidFormat
from cliboa.util.helper import Helper
from cliboa.util.lisboa_log import LisboaLog
class TestFileTransform(object):
def setup_method(self, method):
self._data_dir = os.path.join(env.BASE_DIR, "data")
class TestExcelConvert(TestFileTransform):
def test_execute_ng_invalid_extension(self):
with pytest.raises(InvalidFormat) as execinfo:
try:
# create test file
os.makedirs(self._data_dir)
excel_file = os.path.join(self._data_dir, "test.xlxs")
open(excel_file, "w").close()
excel_file2 = os.path.join(self._data_dir, "test.xlxs.bk")
open(excel_file2, "w").close()
# set the essential attributes
instance = ExcelConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", "test.xlxs")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.xlxs")
instance.execute()
finally:
shutil.rmtree(self._data_dir)
assert "not supported" in str(execinfo.value)
def test_excute_ng_multiple_src(self):
with pytest.raises(InvalidCount) as execinfo:
try:
# create test file
os.makedirs(self._data_dir)
excel_file = os.path.join(self._data_dir, "test1.xlxs")
open(excel_file, "w").close()
excel_file2 = os.path.join(self._data_dir, "test2.xlxs")
open(excel_file2, "w").close()
# set the essential attributes
instance = ExcelConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test(.*)\.xlxs")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", r"test(.*).xlxs")
instance.execute()
finally:
shutil.rmtree(self._data_dir)
assert "must be only one" in str(execinfo.value)
def test_execute_ok(self):
try:
# create test file
os.makedirs(self._data_dir)
excel_file = os.path.join(self._data_dir, "test.xlxs")
workbook = xlsxwriter.Workbook(excel_file)
workbook.close()
# set the essential attributes
instance = ExcelConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.xlxs")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
exists_csv = glob(os.path.join(self._data_dir, "test.csv"))
finally:
shutil.rmtree(self._data_dir)
assert "test.csv" in exists_csv[0]
class TestCsvMerge(TestFileTransform):
def test_execute_ok(self):
try:
# create test file
csv_list1 = [["key", "data"], ["1", "spam"], ["2", "spam"], ["3", "spam"]]
os.makedirs(self._data_dir)
test_csv1 = os.path.join(self._data_dir, "test1.csv")
with open(test_csv1, "w") as t1:
writer = csv.writer(t1)
writer.writerows(csv_list1)
csv_list2 = [
["key", "address"],
["1", "spam"],
["2", "spam"],
["3", "spam"],
]
test_csv2 = os.path.join(self._data_dir, "test2.csv")
with open(test_csv2, "w") as t2:
writer = csv.writer(t2)
writer.writerows(csv_list2)
# set the essential attributes
instance = CsvMerge()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src1_pattern", r"test1\.csv")
Helper.set_property(instance, "src2_pattern", r"test2\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
exists_csv = glob(os.path.join(self._data_dir, "test.csv"))
finally:
shutil.rmtree(self._data_dir)
assert "test.csv" in exists_csv[0]
def test_execute_ok_with_unnamed(self):
try:
# create test file
csv_list1 = [["key", "data"], ["1", "spam"], ["2", "spam"], ["3", "spam"]]
os.makedirs(self._data_dir)
test_csv1 = os.path.join(self._data_dir, "test1.csv")
with open(test_csv1, "w") as t1:
writer = csv.writer(t1)
writer.writerows(csv_list1)
csv_list2 = [
["key", "Unnamed: 0"],
["1", "spam"],
["2", "spam"],
["3", "spam"],
]
test_csv2 = os.path.join(self._data_dir, "test2.csv")
with open(test_csv2, "w") as t2:
writer = csv.writer(t2)
writer.writerows(csv_list2)
# set the essential attributes
instance = CsvMerge()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src1_pattern", r"test1\.csv")
Helper.set_property(instance, "src2_pattern", r"test2\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
exists_csv = glob(os.path.join(self._data_dir, "test.csv"))
finally:
shutil.rmtree(self._data_dir)
assert "test.csv" in exists_csv[0]
def test_excute_ng_multiple_target1(self):
with pytest.raises(InvalidCount) as execinfo:
try:
# create test file
os.makedirs(self._data_dir)
target1_file = os.path.join(self._data_dir, "test11.csv")
open(target1_file, "w").close()
target1_file = os.path.join(self._data_dir, "test111.csv")
open(target1_file, "w").close()
target2_file = os.path.join(self._data_dir, "test2.csv")
open(target2_file, "w").close()
# set the essential attributes
instance = CsvMerge()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src1_pattern", "test1(.*).csv")
Helper.set_property(instance, "src2_pattern", "test2.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
finally:
shutil.rmtree(self._data_dir)
assert "must be only one" in str(execinfo.value)
def test_excute_ng_multiple_target2(self):
with pytest.raises(InvalidCount) as execinfo:
try:
# create test file
os.makedirs(self._data_dir)
target1_file = os.path.join(self._data_dir, "test1.csv")
open(target1_file, "w").close()
target2_file = os.path.join(self._data_dir, "test22.csv")
open(target2_file, "w").close()
target2_file = os.path.join(self._data_dir, "test222.csv")
open(target2_file, "w").close()
# set the essential attributes
instance = CsvMerge()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src1_pattern", "test1.csv")
Helper.set_property(instance, "src2_pattern", "test2(.*).csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test.csv")
instance.execute()
finally:
shutil.rmtree(self._data_dir)
assert "must be only one" in str(execinfo.value)
class TestCsvHeaderConvert(TestFileTransform):
def test_execute_ok(self):
try:
# create test file
csv_list = [["key", "data"], ["1", "spam"], ["2", "spam"], ["3", "spam"]]
os.makedirs(self._data_dir)
test_csv = os.path.join(self._data_dir, "test.csv")
with open(test_csv, "w") as t:
writer = csv.writer(t)
writer.writerows(csv_list)
# set the essential attributes
instance = CsvHeaderConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test_new.csv")
Helper.set_property(
instance, "headers", [{"key": "new_key"}, {"data": "new_data"}]
)
instance.execute()
test_new_csv = os.path.join(self._data_dir, "test_new.csv")
with open(test_new_csv, "r") as t:
reader = csv.reader(t)
line = next(reader)
finally:
shutil.rmtree(self._data_dir)
assert line == ["new_key", "new_data"]
def test_execute_ok_2(self):
try:
# create test file
csv_list = [["key", "data"], ["1", "spam"], ["2", "spam"], ["3", "spam"]]
os.makedirs(self._data_dir)
test_csv = os.path.join(self._data_dir, "test.csv")
with open(test_csv, "w") as t:
writer = csv.writer(t)
writer.writerows(csv_list)
# set the essential attributes
instance = CsvHeaderConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test_new.csv")
Helper.set_property(instance, "headers", [{"key": "new_key"}])
instance.execute()
test_new_csv = os.path.join(self._data_dir, "test_new.csv")
with open(test_new_csv, "r") as t:
reader = csv.reader(t)
line = next(reader)
finally:
shutil.rmtree(self._data_dir)
assert line == ["new_key", "data"]
def test_execute_ng_no_src_file(self):
os.makedirs(self._data_dir)
with pytest.raises(InvalidCount) as execinfo:
# set the essential attributes
instance = CsvHeaderConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test_new.csv")
Helper.set_property(
instance, "headers", [{"key": "new_key"}, {"data": "new_data"}]
)
instance.execute()
shutil.rmtree(self._data_dir)
assert "not exist" in str(execinfo.value)
def test_execute_ng_no_multiple_files(self):
# create test files
os.makedirs(self._data_dir)
test1_csv = os.path.join(self._data_dir, "test1.csv")
test2_csv = os.path.join(self._data_dir, "test2.csv")
open(test1_csv, "w").close
open(test2_csv, "w").close
with pytest.raises(InvalidCount) as execinfo:
# set the essential attributes
instance = CsvHeaderConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test(.*)\.csv")
Helper.set_property(instance, "dest_dir", self._data_dir)
Helper.set_property(instance, "dest_pattern", "test_new.csv")
Helper.set_property(
instance, "headers", [{"key": "new_key"}, {"data": "new_data"}]
)
instance.execute()
shutil.rmtree(self._data_dir)
assert "only one" in str(execinfo.value)
class TestFileConvert(TestFileTransform):
def test_execute(self):
STR_UTF8 = "いろはにほへと"
try:
# create test file
os.makedirs(self._data_dir)
test_file = os.path.join(self._data_dir, "test.txt")
with open(test_file, "w") as t:
t.write(STR_UTF8)
# set the essential attributes
instance = FileConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.txt")
Helper.set_property(instance, "encoding_from", "utf-8")
Helper.set_property(instance, "encoding_to", "utf-16")
instance.execute()
with open(test_file, errors="ignore") as t:
str_utf16 = t.read()
assert str_utf16 != STR_UTF8
# set the essential attributes
instance = FileConvert()
Helper.set_property(instance, "logger", LisboaLog.get_logger(__name__))
Helper.set_property(instance, "src_dir", self._data_dir)
Helper.set_property(instance, "src_pattern", r"test\.txt")
Helper.set_property(instance, "encoding_from", "utf-16")
Helper.set_property(instance, "encoding_to", "utf-8")
instance.execute()
with open(test_file) as t:
str_utf8 = t.read()
assert str_utf8 == STR_UTF8
finally:
shutil.rmtree(self._data_dir) | 0.299822 | 0.256523 |
from neuralnetwork.FeedForward import FeedForward
from neuralnetwork.Sigmoid import Sigmoid
from neuralnetwork.Backpropagation import Backpropagation
from utils import preprocess, feature_engineer
import pandas as pd
import numpy as np
from numpy import argmax
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import scale
from datetime import datetime
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
df = pd.read_csv('NYC_taxi.csv', parse_dates=['pickup_datetime'], nrows=500000)
# Perform preprocessing and feature engineering
df = preprocess(df)
df = feature_engineer(df)
# Scale the features
df_prescaled = df.copy()
df_scaled = df.copy()
df_scaled = df.drop(['fare_amount'], axis=1)
targets = df.fare_amount.values.reshape(-1, 1)
min_max_scaler = MinMaxScaler()
df_scaled[df_scaled.columns] = min_max_scaler.fit_transform(df_scaled[df_scaled.columns])
target_scaler = MinMaxScaler()
target_scaler.fit(targets)
targets_scaled = target_scaler.transform(targets)
df_scaled["targets_scaled"] = targets_scaled
train, test = train_test_split(df_scaled, test_size=0.2)
sigmoid = Sigmoid()
networkLayer = [17,34,17,1]
feedForward = FeedForward(networkLayer, sigmoid)
backpropagation = Backpropagation(feedForward,0.7,0.8, 0.05, 1)
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Start Time =", current_time)
backpropagation.initialise()
result = backpropagation.train(train.values)
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("End Time =", current_time)
print("Training time {} minutes".format(backpropagation.getTrainingTime()/60))
feedForward.save('./network.txt')
feedForward = FeedForward.load('./network.txt')
train_pred = []
train_actual_fares = []
train_total_rows = train.shape[0]
count = 0
for num,row in train.iterrows():
actual_fare = df_prescaled.loc[num,'fare_amount']
feedForward.activate(row[0:17].values)
outputs = feedForward.getOutputs()
predicted_fare = float(outputs[0])
predicted_fare_original = target_scaler.inverse_transform([[predicted_fare]])[0][0]
train_pred.append(predicted_fare_original)
train_actual_fares.append(actual_fare)
# print("Inside Training Set")
# print("{} of {}, Actual fare: {:0.2f}, Predicated fare: {:0.2f}".format(count, train_total_rows, actual_fare, predicted_fare_original))
count = count + 1
test_pred = []
test_actual_fares = []
test_total_rows = test.shape[0]
count = 0
for num,row in test.iterrows():
actual_fare = df_prescaled.loc[num,'fare_amount']
feedForward.activate(row[0:17].values)
outputs = feedForward.getOutputs()
predicted_fare = float(outputs[0])
predicted_fare_original = target_scaler.inverse_transform([[predicted_fare]])[0][0]
test_pred.append(predicted_fare_original)
test_actual_fares.append(actual_fare)
# print("Inside Testing Set")
# print("{} of {}, Actual fare: {:0.2f}, Predicated fare: {:0.2f}".format(count, test_total_rows, actual_fare, predicted_fare_original))
count = count + 1
train_rmse = np.sqrt(mean_squared_error(train_actual_fares, train_pred))
test_rmse = np.sqrt(mean_squared_error(test_actual_fares, test_pred))
print("Train RMSE: {:0.2f}".format(train_rmse))
print("Test RMSE: {:0.2f}".format(test_rmse))
print('------------------------')
def predict_random(df_prescaled, X_test, model, target_scaler):
sample = X_test.sample(n=1, random_state=np.random.randint(low=0, high=10000))
idx = sample.index[0]
actual_fare = df_prescaled.loc[idx,'fare_amount']
day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
day_of_week = day_names[df_prescaled.loc[idx,'day_of_week']]
hour = df_prescaled.loc[idx,'hour']
model.activate(sample.values[0][0:17])
outputs = feedForward.getOutputs()
predicted_fare = float(outputs[0])
predicted_fare_original = target_scaler.inverse_transform([[predicted_fare]])[0][0]
rmse = np.sqrt(np.square(predicted_fare_original-actual_fare))
print("Trip Details: {}, {}:00hrs".format(day_of_week, hour))
print("Actual fare: ${:0.2f}".format(actual_fare))
print("Predicted fare: ${:0.2f}".format(predicted_fare_original))
print("RMSE: ${:0.2f}".format(rmse))
predict_random(df_prescaled, test, feedForward, target_scaler) | predicting-taxi-fares/train.py | from neuralnetwork.FeedForward import FeedForward
from neuralnetwork.Sigmoid import Sigmoid
from neuralnetwork.Backpropagation import Backpropagation
from utils import preprocess, feature_engineer
import pandas as pd
import numpy as np
from numpy import argmax
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import scale
from datetime import datetime
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
df = pd.read_csv('NYC_taxi.csv', parse_dates=['pickup_datetime'], nrows=500000)
# Perform preprocessing and feature engineering
df = preprocess(df)
df = feature_engineer(df)
# Scale the features
df_prescaled = df.copy()
df_scaled = df.copy()
df_scaled = df.drop(['fare_amount'], axis=1)
targets = df.fare_amount.values.reshape(-1, 1)
min_max_scaler = MinMaxScaler()
df_scaled[df_scaled.columns] = min_max_scaler.fit_transform(df_scaled[df_scaled.columns])
target_scaler = MinMaxScaler()
target_scaler.fit(targets)
targets_scaled = target_scaler.transform(targets)
df_scaled["targets_scaled"] = targets_scaled
train, test = train_test_split(df_scaled, test_size=0.2)
sigmoid = Sigmoid()
networkLayer = [17,34,17,1]
feedForward = FeedForward(networkLayer, sigmoid)
backpropagation = Backpropagation(feedForward,0.7,0.8, 0.05, 1)
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Start Time =", current_time)
backpropagation.initialise()
result = backpropagation.train(train.values)
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("End Time =", current_time)
print("Training time {} minutes".format(backpropagation.getTrainingTime()/60))
feedForward.save('./network.txt')
feedForward = FeedForward.load('./network.txt')
train_pred = []
train_actual_fares = []
train_total_rows = train.shape[0]
count = 0
for num,row in train.iterrows():
actual_fare = df_prescaled.loc[num,'fare_amount']
feedForward.activate(row[0:17].values)
outputs = feedForward.getOutputs()
predicted_fare = float(outputs[0])
predicted_fare_original = target_scaler.inverse_transform([[predicted_fare]])[0][0]
train_pred.append(predicted_fare_original)
train_actual_fares.append(actual_fare)
# print("Inside Training Set")
# print("{} of {}, Actual fare: {:0.2f}, Predicated fare: {:0.2f}".format(count, train_total_rows, actual_fare, predicted_fare_original))
count = count + 1
test_pred = []
test_actual_fares = []
test_total_rows = test.shape[0]
count = 0
for num,row in test.iterrows():
actual_fare = df_prescaled.loc[num,'fare_amount']
feedForward.activate(row[0:17].values)
outputs = feedForward.getOutputs()
predicted_fare = float(outputs[0])
predicted_fare_original = target_scaler.inverse_transform([[predicted_fare]])[0][0]
test_pred.append(predicted_fare_original)
test_actual_fares.append(actual_fare)
# print("Inside Testing Set")
# print("{} of {}, Actual fare: {:0.2f}, Predicated fare: {:0.2f}".format(count, test_total_rows, actual_fare, predicted_fare_original))
count = count + 1
train_rmse = np.sqrt(mean_squared_error(train_actual_fares, train_pred))
test_rmse = np.sqrt(mean_squared_error(test_actual_fares, test_pred))
print("Train RMSE: {:0.2f}".format(train_rmse))
print("Test RMSE: {:0.2f}".format(test_rmse))
print('------------------------')
def predict_random(df_prescaled, X_test, model, target_scaler):
sample = X_test.sample(n=1, random_state=np.random.randint(low=0, high=10000))
idx = sample.index[0]
actual_fare = df_prescaled.loc[idx,'fare_amount']
day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
day_of_week = day_names[df_prescaled.loc[idx,'day_of_week']]
hour = df_prescaled.loc[idx,'hour']
model.activate(sample.values[0][0:17])
outputs = feedForward.getOutputs()
predicted_fare = float(outputs[0])
predicted_fare_original = target_scaler.inverse_transform([[predicted_fare]])[0][0]
rmse = np.sqrt(np.square(predicted_fare_original-actual_fare))
print("Trip Details: {}, {}:00hrs".format(day_of_week, hour))
print("Actual fare: ${:0.2f}".format(actual_fare))
print("Predicted fare: ${:0.2f}".format(predicted_fare_original))
print("RMSE: ${:0.2f}".format(rmse))
predict_random(df_prescaled, test, feedForward, target_scaler) | 0.49292 | 0.324169 |
import hashlib
import hmac
import time
import uuid
import requests
from celery import states
from celery.task import Task
from celery.exceptions import Ignore
from vigil.celery import app
class OverwatchTask(Task):
"""
Report the given error to overwatch
"""
expected_data = {
'bot_name': '',
'exchange': '',
'title': '',
'message': ''
}
business_logic_data = {
'api_user': '',
'api_secret': ''
}
action_type = 'logic'
def check_data(self, data):
for key in self.expected_data:
if key not in data:
self.update_state(
state=states.FAILURE,
meta='A value for \'{}\' was not present in the passed data'.format(key)
)
return False
return True
def check_business_logic_data(self, data):
for key in self.business_logic_data:
if key not in data:
self.update_state(
state=states.FAILURE,
meta='A value for \'{}\' was not present in the saved business logic data'.format(key)
)
return False
return True
@staticmethod
def generate_hash(api_user, api_secret):
nonce = int(time.time() * 1000)
# calculate the hash from supplied data
return nonce, hmac.new(
uuid.UUID(api_secret).bytes,
'{}{}'.format(
uuid.UUID(api_user).hex.lower(),
nonce
).encode('utf-8'),
hashlib.sha256
).hexdigest()
def handle_response(self, r):
if r.status_code != requests.codes.ok:
self.update_state(
state=states.FAILURE,
meta='overwatch gave a bad response code: {} {}'.format(r.status_code, r.text)
)
return False
try:
response = r.json()
except ValueError:
self.update_state(
state=states.FAILURE,
meta='overwatch did not return valid JSON: {}'.format(r.text)
)
return False
if not response.get('success', True):
self.update_state(
state=states.FAILURE,
meta='overwatch reported a failure: {}'.format(response)
)
return False
return response
def run(self, *args, **kwargs):
data = kwargs.get('data', {})
if not self.check_data(data):
raise Ignore()
business_logic_data = kwargs.get('business_logic_data', 'Nope')
if not self.check_business_logic_data(business_logic_data):
raise Ignore()
api_user = business_logic_data.get('api_user')
api_secret = business_logic_data.get('api_secret')
nonce, generated_hash = self.generate_hash(
api_user,
api_secret
)
name = data.get('bot_name')
exchange = data.get('exchange')
response = self.handle_response(
requests.post(
url='https://overwatch.crypto-daio.co.uk/bot/report_error',
data={
'name': name,
'exchange': exchange,
'api_user': api_user,
'n': nonce,
'h': generated_hash,
'title': data.get('title'),
'message': data.get('message')
}
)
)
if not response:
raise Ignore()
return response
Overwatch = app.register_task(OverwatchTask()) | vigil/tasks/logic/overwatch.py | import hashlib
import hmac
import time
import uuid
import requests
from celery import states
from celery.task import Task
from celery.exceptions import Ignore
from vigil.celery import app
class OverwatchTask(Task):
"""
Report the given error to overwatch
"""
expected_data = {
'bot_name': '',
'exchange': '',
'title': '',
'message': ''
}
business_logic_data = {
'api_user': '',
'api_secret': ''
}
action_type = 'logic'
def check_data(self, data):
for key in self.expected_data:
if key not in data:
self.update_state(
state=states.FAILURE,
meta='A value for \'{}\' was not present in the passed data'.format(key)
)
return False
return True
def check_business_logic_data(self, data):
for key in self.business_logic_data:
if key not in data:
self.update_state(
state=states.FAILURE,
meta='A value for \'{}\' was not present in the saved business logic data'.format(key)
)
return False
return True
@staticmethod
def generate_hash(api_user, api_secret):
nonce = int(time.time() * 1000)
# calculate the hash from supplied data
return nonce, hmac.new(
uuid.UUID(api_secret).bytes,
'{}{}'.format(
uuid.UUID(api_user).hex.lower(),
nonce
).encode('utf-8'),
hashlib.sha256
).hexdigest()
def handle_response(self, r):
if r.status_code != requests.codes.ok:
self.update_state(
state=states.FAILURE,
meta='overwatch gave a bad response code: {} {}'.format(r.status_code, r.text)
)
return False
try:
response = r.json()
except ValueError:
self.update_state(
state=states.FAILURE,
meta='overwatch did not return valid JSON: {}'.format(r.text)
)
return False
if not response.get('success', True):
self.update_state(
state=states.FAILURE,
meta='overwatch reported a failure: {}'.format(response)
)
return False
return response
def run(self, *args, **kwargs):
data = kwargs.get('data', {})
if not self.check_data(data):
raise Ignore()
business_logic_data = kwargs.get('business_logic_data', 'Nope')
if not self.check_business_logic_data(business_logic_data):
raise Ignore()
api_user = business_logic_data.get('api_user')
api_secret = business_logic_data.get('api_secret')
nonce, generated_hash = self.generate_hash(
api_user,
api_secret
)
name = data.get('bot_name')
exchange = data.get('exchange')
response = self.handle_response(
requests.post(
url='https://overwatch.crypto-daio.co.uk/bot/report_error',
data={
'name': name,
'exchange': exchange,
'api_user': api_user,
'n': nonce,
'h': generated_hash,
'title': data.get('title'),
'message': data.get('message')
}
)
)
if not response:
raise Ignore()
return response
Overwatch = app.register_task(OverwatchTask()) | 0.477311 | 0.163312 |
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
county_name = "Alameda County"
df_population = pd.read_csv("population_all.csv")
df_population = df_population[["Year", county_name]]
X = df_population
df_demand = pd.read_csv("demand_all.csv")
y = df_demand[[county_name]]
linear_regression = LinearRegression()
linear_regression.fit(X, y)
y_pred = linear_regression.predict(X)
def get_slopes():
slopes_list = linear_regression.coef_.tolist()
slopes_str = []
for element in slopes_list[0]:
slopes_str.append(str(element))
for element in slopes_str[0]:
slopes_str.extend(element.split(','))
return slopes_str
intercept = linear_regression.intercept_
slopes = get_slopes()
print("y = ", slopes[0], "x1 + ", slopes[1], "x2 + ", intercept[0])
slopes = linear_regression.coef_.tolist()
year_slope = slopes[0][0]
pop_slope = slopes[0][1]
xdata = X.iloc[:, 0].values
ydata = X.iloc[:, 1].values
zdata = y.values
zdata_pred = np.arange(30, dtype=float)
for i in range(0, 30):
zdata_pred[i] = year_slope*xdata[i] + pop_slope*ydata[i] + intercept[0]
fig = plt.figure()
fig.suptitle(f"Multivariate Regression of Power Demand in {county_name}")
ax = plt.axes(projection='3d')
plt.xlabel("Year")
plt.ylabel("Population")
ax.set_zlabel("Power Demand (MW)")
ax.scatter3D(xdata, ydata, zdata, color="blue", label="Actual Demand")
ax.scatter3D(xdata, ydata, zdata_pred, color="black", label="Predicted Demand")
def plot_chart(feature_name, feature, target, target_pred, county):
figure = plt.figure()
figure.suptitle(f"Multivariate Regression of Power Demand in {county}")
plt.scatter(x=feature, y=target, color="blue", label="Actual Demand")
plt.scatter(x=feature, y=target_pred, color="black", label="Predicted Demand")
plt.xlabel(feature_name)
plt.ylabel("Power Demand (MW)")
plt.legend(loc="upper left")
features_list = ["Year", "Population"]
for i in range(len(features_list)):
plot_chart(features_list[i], X.iloc[:, i], y, y_pred, county_name)
plt.show() | modules/module8/extra/predict_3d_demand.py | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
county_name = "Alameda County"
df_population = pd.read_csv("population_all.csv")
df_population = df_population[["Year", county_name]]
X = df_population
df_demand = pd.read_csv("demand_all.csv")
y = df_demand[[county_name]]
linear_regression = LinearRegression()
linear_regression.fit(X, y)
y_pred = linear_regression.predict(X)
def get_slopes():
slopes_list = linear_regression.coef_.tolist()
slopes_str = []
for element in slopes_list[0]:
slopes_str.append(str(element))
for element in slopes_str[0]:
slopes_str.extend(element.split(','))
return slopes_str
intercept = linear_regression.intercept_
slopes = get_slopes()
print("y = ", slopes[0], "x1 + ", slopes[1], "x2 + ", intercept[0])
slopes = linear_regression.coef_.tolist()
year_slope = slopes[0][0]
pop_slope = slopes[0][1]
xdata = X.iloc[:, 0].values
ydata = X.iloc[:, 1].values
zdata = y.values
zdata_pred = np.arange(30, dtype=float)
for i in range(0, 30):
zdata_pred[i] = year_slope*xdata[i] + pop_slope*ydata[i] + intercept[0]
fig = plt.figure()
fig.suptitle(f"Multivariate Regression of Power Demand in {county_name}")
ax = plt.axes(projection='3d')
plt.xlabel("Year")
plt.ylabel("Population")
ax.set_zlabel("Power Demand (MW)")
ax.scatter3D(xdata, ydata, zdata, color="blue", label="Actual Demand")
ax.scatter3D(xdata, ydata, zdata_pred, color="black", label="Predicted Demand")
def plot_chart(feature_name, feature, target, target_pred, county):
figure = plt.figure()
figure.suptitle(f"Multivariate Regression of Power Demand in {county}")
plt.scatter(x=feature, y=target, color="blue", label="Actual Demand")
plt.scatter(x=feature, y=target_pred, color="black", label="Predicted Demand")
plt.xlabel(feature_name)
plt.ylabel("Power Demand (MW)")
plt.legend(loc="upper left")
features_list = ["Year", "Population"]
for i in range(len(features_list)):
plot_chart(features_list[i], X.iloc[:, i], y, y_pred, county_name)
plt.show() | 0.663124 | 0.664064 |
from flask import Flask, jsonify, redirect, render_template, session, url_for, request
from flaskext.mysql import MySQL
app = Flask(__name__, static_url_path = "")
from myprojectprototype.script import dataAnalytic
import functools
from sqlalchemy import create_engine
import pandas as pd
import simplejson as json
def get_db():
engine = create_engine("mysql+mysqldb://root:1234qwer@ucdgroup18.ck04mjz0uhn8.us-west-2.rds.amazonaws.com:3306/bike")
return engine
@app.after_request
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=0'
return response
@app.route('/stations/')
@functools.lru_cache(maxsize=128)
def get_stations():
engine = get_db()
sql = "select * from BikeStation;"
rows = engine.execute(sql).fetchall()
print('#found {} stations', len(rows))
return jsonify(stations=[dict(row.items()) for row in rows])
get_stations.cache_clear()
@app.route('/mychart/')
def mychart():
return render_template("chart.html")
@app.route('/test/')
def test():
return render_template("test.html")
@app.route("/occupancy/<int:station_id>")
def get_occupancy(station_id):
engine = get_db()
df = pd.read_sql_query("select * from BikeStationHistory where number = %(number)s", engine, params={"number": station_id})
df.Last_update = df.Last_update.str.replace('\'', '')
#df.to_csv("out.csv")
df['last_update_date'] = pd.to_datetime(df.Last_update, unit='ms')
df.set_index('last_update_date', inplace=True)
res = df['Available_bike_stands'].resample('1d').mean()
res = res.dropna(axis=0,how='any')
res = res.fillna(value=0)
print(res)
return jsonify(data=json.dumps(list(zip(map(lambda x:x.isoformat(), res.index), res.values))))
@app.route('/lodash/')
def lodash():
return render_template("lodash.html")
@app.route('/bikeReview/')
def bikeReview():
return render_template("bikeReview.html")
@app.route('/weather/icons/<name>')
def icon(name):
return render_template("{}".format(name))
@app.route('/')
def index():
return render_template("index.html")
@app.route('/bike5json/')
def bike5json():
return app.send_static_file("Dublin_bike_updated.json")
@app.route('/markers.js/')
def markers():
return app.send_static_file("markers.js")
@app.route('/charts.js/')
def chartsjs():
return app.send_static_file("Chart.js")
@app.route('/chart1.js/')
def chart1():
return app.send_static_file("chart1.js")
@app.route('/chart2.js/')
def chart2():
return app.send_static_file("chart2.js")
@app.route('/chart6.js/')
def chart6():
return app.send_static_file("chart6.js")
@app.route('/weather.js/')
def wheather():
return app.send_static_file("weather.js")
@app.route('/bikeCss.css/')
def bikeCss():
return app.send_static_file("bikeCss.css")
@app.route('/bootstrap.min.css/')
def bootstrapmincss():
return app.send_static_file("bootstrap.min.css")
@app.route('/font-awesome.css/')
def fontawesomecss():
return app.send_static_file("font-awesome.css")
@app.route('/style.css/')
def stylecss():
return app.send_static_file("style.css")
@app.route('/modernizr.custom.js/')
def modernizrcustomjs():
return app.send_static_file("modernizr.custom.js")
@app.route('/jquery-1.11.2.min.js/')
def jquery1112minjs():
return app.send_static_file("jquery-1.11.2.min.js")
@app.route('/wow.min.js/')
def wowminjs():
return app.send_static_file("wow.min.js")
@app.route('/owl-carousel.js/')
def owlcarouseljs():
return app.send_static_file("owl-carousel.js")
@app.route('/nivo-lightbox.min.js/')
def nivolightboxminjs():
return app.send_static_file("nivo-lightbox.min.js")
@app.route('/smoothscroll.js/')
def smoothscrolljs():
return app.send_static_file("smoothscroll.js")
@app.route('/bootstrap.min.js/')
def bootstrapminjs():
return app.send_static_file("bootstrap.min.js")
@app.route('/classie.js/')
def classiejs():
return app.send_static_file("classie.js")
@app.route('/script.js/')
def cscriptjs():
return app.send_static_file("script.js")
@app.route('/bike.jpg/')
def bikejpg():
return app.send_static_file("bike.jpg")
@app.route('/charts.min.js/')
def chartsminjs():
return app.send_static_file("Chart.min.js")
@app.route('/charts.bundle.js/')
def chartsbundlejs():
return app.send_static_file("Chart.bundle.js")
@app.route('/charts.bundle.min.js/')
def chartsbundleminjs():
return app.send_static_file("Chart.bundle.min.js")
@app.route('/station_chart6/')
def stationChart6():
return app.send_static_file("Dublin_Chart_6.json")
@app.route('/station_chart7/')
def chart7():
return app.send_static_file("Dublin_Chart_7.json")
@app.route('/analyze', methods=['GET', 'POST'])
def server():
if request.method == 'POST':
returnDict = {}
#'{{ number }}', '{{ location }}', '{{ usedBikes}}', '{{ bikeStands }}
# Then get the data from the form
if len(request.form['Number']) == 0 or \
len(request.form['Temp']) == 0 or len(request.form['Humi']) == 0 or \
len(request.form['Weat']) == 0 or len(request.form['Wind']) == 0 \
or int(request.form['Number']) == 20:
return render_template('index.html')
number = int(request.form['Number'])
temp = float(request.form['Temp'])
humidity = int(request.form['Humi'])
weather = request.form['Weat']
windspeed = float(request.form['Wind'])
myAnalytic = dataAnalytic.dataAnalytic()
returnDict['location'] = myAnalytic.getBikeStations()[int(number)]
returnDict['number'] = number
returnDict['usedBikes'], returnDict['bikeStands'] = \
myAnalytic.getPredictionOnStation(temp=temp,humidity=humidity,weather=weather,\
windSpeed=windspeed,stationNumber=number)
# Generate just a boring response
return render_template('index.html', **returnDict)
# Otherwise this was a normal GET request
else:
return render_template('index.html') | src/myprojectprototype/app/views.py | from flask import Flask, jsonify, redirect, render_template, session, url_for, request
from flaskext.mysql import MySQL
app = Flask(__name__, static_url_path = "")
from myprojectprototype.script import dataAnalytic
import functools
from sqlalchemy import create_engine
import pandas as pd
import simplejson as json
def get_db():
engine = create_engine("mysql+mysqldb://root:1234qwer@ucdgroup18.ck04mjz0uhn8.us-west-2.rds.amazonaws.com:3306/bike")
return engine
@app.after_request
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=0'
return response
@app.route('/stations/')
@functools.lru_cache(maxsize=128)
def get_stations():
engine = get_db()
sql = "select * from BikeStation;"
rows = engine.execute(sql).fetchall()
print('#found {} stations', len(rows))
return jsonify(stations=[dict(row.items()) for row in rows])
get_stations.cache_clear()
@app.route('/mychart/')
def mychart():
return render_template("chart.html")
@app.route('/test/')
def test():
return render_template("test.html")
@app.route("/occupancy/<int:station_id>")
def get_occupancy(station_id):
engine = get_db()
df = pd.read_sql_query("select * from BikeStationHistory where number = %(number)s", engine, params={"number": station_id})
df.Last_update = df.Last_update.str.replace('\'', '')
#df.to_csv("out.csv")
df['last_update_date'] = pd.to_datetime(df.Last_update, unit='ms')
df.set_index('last_update_date', inplace=True)
res = df['Available_bike_stands'].resample('1d').mean()
res = res.dropna(axis=0,how='any')
res = res.fillna(value=0)
print(res)
return jsonify(data=json.dumps(list(zip(map(lambda x:x.isoformat(), res.index), res.values))))
@app.route('/lodash/')
def lodash():
return render_template("lodash.html")
@app.route('/bikeReview/')
def bikeReview():
return render_template("bikeReview.html")
@app.route('/weather/icons/<name>')
def icon(name):
return render_template("{}".format(name))
@app.route('/')
def index():
return render_template("index.html")
@app.route('/bike5json/')
def bike5json():
return app.send_static_file("Dublin_bike_updated.json")
@app.route('/markers.js/')
def markers():
return app.send_static_file("markers.js")
@app.route('/charts.js/')
def chartsjs():
return app.send_static_file("Chart.js")
@app.route('/chart1.js/')
def chart1():
return app.send_static_file("chart1.js")
@app.route('/chart2.js/')
def chart2():
return app.send_static_file("chart2.js")
@app.route('/chart6.js/')
def chart6():
return app.send_static_file("chart6.js")
@app.route('/weather.js/')
def wheather():
return app.send_static_file("weather.js")
@app.route('/bikeCss.css/')
def bikeCss():
return app.send_static_file("bikeCss.css")
@app.route('/bootstrap.min.css/')
def bootstrapmincss():
return app.send_static_file("bootstrap.min.css")
@app.route('/font-awesome.css/')
def fontawesomecss():
return app.send_static_file("font-awesome.css")
@app.route('/style.css/')
def stylecss():
return app.send_static_file("style.css")
@app.route('/modernizr.custom.js/')
def modernizrcustomjs():
return app.send_static_file("modernizr.custom.js")
@app.route('/jquery-1.11.2.min.js/')
def jquery1112minjs():
return app.send_static_file("jquery-1.11.2.min.js")
@app.route('/wow.min.js/')
def wowminjs():
return app.send_static_file("wow.min.js")
@app.route('/owl-carousel.js/')
def owlcarouseljs():
return app.send_static_file("owl-carousel.js")
@app.route('/nivo-lightbox.min.js/')
def nivolightboxminjs():
return app.send_static_file("nivo-lightbox.min.js")
@app.route('/smoothscroll.js/')
def smoothscrolljs():
return app.send_static_file("smoothscroll.js")
@app.route('/bootstrap.min.js/')
def bootstrapminjs():
return app.send_static_file("bootstrap.min.js")
@app.route('/classie.js/')
def classiejs():
return app.send_static_file("classie.js")
@app.route('/script.js/')
def cscriptjs():
return app.send_static_file("script.js")
@app.route('/bike.jpg/')
def bikejpg():
return app.send_static_file("bike.jpg")
@app.route('/charts.min.js/')
def chartsminjs():
return app.send_static_file("Chart.min.js")
@app.route('/charts.bundle.js/')
def chartsbundlejs():
return app.send_static_file("Chart.bundle.js")
@app.route('/charts.bundle.min.js/')
def chartsbundleminjs():
return app.send_static_file("Chart.bundle.min.js")
@app.route('/station_chart6/')
def stationChart6():
return app.send_static_file("Dublin_Chart_6.json")
@app.route('/station_chart7/')
def chart7():
return app.send_static_file("Dublin_Chart_7.json")
@app.route('/analyze', methods=['GET', 'POST'])
def server():
if request.method == 'POST':
returnDict = {}
#'{{ number }}', '{{ location }}', '{{ usedBikes}}', '{{ bikeStands }}
# Then get the data from the form
if len(request.form['Number']) == 0 or \
len(request.form['Temp']) == 0 or len(request.form['Humi']) == 0 or \
len(request.form['Weat']) == 0 or len(request.form['Wind']) == 0 \
or int(request.form['Number']) == 20:
return render_template('index.html')
number = int(request.form['Number'])
temp = float(request.form['Temp'])
humidity = int(request.form['Humi'])
weather = request.form['Weat']
windspeed = float(request.form['Wind'])
myAnalytic = dataAnalytic.dataAnalytic()
returnDict['location'] = myAnalytic.getBikeStations()[int(number)]
returnDict['number'] = number
returnDict['usedBikes'], returnDict['bikeStands'] = \
myAnalytic.getPredictionOnStation(temp=temp,humidity=humidity,weather=weather,\
windSpeed=windspeed,stationNumber=number)
# Generate just a boring response
return render_template('index.html', **returnDict)
# Otherwise this was a normal GET request
else:
return render_template('index.html') | 0.415254 | 0.069038 |
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from pretix.api.serializers.i18n import I18nAwareModelSerializer
from pretix.base.models import Seat, Voucher
class VoucherListSerializer(serializers.ListSerializer):
def create(self, validated_data):
codes = set()
seats = set()
errs = []
err = False
for voucher_data in validated_data:
if voucher_data.get('seat') and (voucher_data.get('seat'), voucher_data.get('subevent')) in seats:
err = True
errs.append({'code': ['Duplicate seat ID in request.']})
continue
else:
seats.add((voucher_data.get('seat'), voucher_data.get('subevent')))
if voucher_data['code'] in codes:
err = True
errs.append({'code': ['Duplicate voucher code in request.']})
else:
codes.add(voucher_data['code'])
errs.append({})
if err:
raise ValidationError(errs)
return super().create(validated_data)
class SeatGuidField(serializers.CharField):
def to_representation(self, val: Seat):
return val.seat_guid
class VoucherSerializer(I18nAwareModelSerializer):
seat = SeatGuidField(allow_null=True, required=False)
class Meta:
model = Voucher
fields = ('id', 'code', 'max_usages', 'redeemed', 'valid_until', 'block_quota',
'allow_ignore_quota', 'price_mode', 'value', 'item', 'variation', 'quota',
'tag', 'comment', 'subevent', 'show_hidden_items', 'seat')
read_only_fields = ('id', 'redeemed')
list_serializer_class = VoucherListSerializer
def validate(self, data):
data = super().validate(data)
full_data = self.to_internal_value(self.to_representation(self.instance)) if self.instance else {}
full_data.update(data)
Voucher.clean_item_properties(
full_data, self.context.get('event'),
full_data.get('quota'), full_data.get('item'), full_data.get('variation'),
block_quota=full_data.get('block_quota')
)
Voucher.clean_subevent(
full_data, self.context.get('event')
)
Voucher.clean_max_usages(full_data, self.instance.redeemed if self.instance else 0)
check_quota = Voucher.clean_quota_needs_checking(
full_data, self.instance,
item_changed=self.instance and (
full_data.get('item') != self.instance.item or
full_data.get('variation') != self.instance.variation or
full_data.get('quota') != self.instance.quota
),
creating=not self.instance
)
if check_quota:
Voucher.clean_quota_check(
full_data, 1, self.instance, self.context.get('event'),
full_data.get('quota'), full_data.get('item'), full_data.get('variation')
)
Voucher.clean_voucher_code(full_data, self.context.get('event'), self.instance.pk if self.instance else None)
if full_data.get('seat'):
data['seat'] = Voucher.clean_seat_id(
full_data, full_data.get('item'), full_data.get('quota'), self.context.get('event'),
self.instance.pk if self.instance else None
)
return data | src/pretix/api/serializers/voucher.py | from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from pretix.api.serializers.i18n import I18nAwareModelSerializer
from pretix.base.models import Seat, Voucher
class VoucherListSerializer(serializers.ListSerializer):
def create(self, validated_data):
codes = set()
seats = set()
errs = []
err = False
for voucher_data in validated_data:
if voucher_data.get('seat') and (voucher_data.get('seat'), voucher_data.get('subevent')) in seats:
err = True
errs.append({'code': ['Duplicate seat ID in request.']})
continue
else:
seats.add((voucher_data.get('seat'), voucher_data.get('subevent')))
if voucher_data['code'] in codes:
err = True
errs.append({'code': ['Duplicate voucher code in request.']})
else:
codes.add(voucher_data['code'])
errs.append({})
if err:
raise ValidationError(errs)
return super().create(validated_data)
class SeatGuidField(serializers.CharField):
def to_representation(self, val: Seat):
return val.seat_guid
class VoucherSerializer(I18nAwareModelSerializer):
seat = SeatGuidField(allow_null=True, required=False)
class Meta:
model = Voucher
fields = ('id', 'code', 'max_usages', 'redeemed', 'valid_until', 'block_quota',
'allow_ignore_quota', 'price_mode', 'value', 'item', 'variation', 'quota',
'tag', 'comment', 'subevent', 'show_hidden_items', 'seat')
read_only_fields = ('id', 'redeemed')
list_serializer_class = VoucherListSerializer
def validate(self, data):
data = super().validate(data)
full_data = self.to_internal_value(self.to_representation(self.instance)) if self.instance else {}
full_data.update(data)
Voucher.clean_item_properties(
full_data, self.context.get('event'),
full_data.get('quota'), full_data.get('item'), full_data.get('variation'),
block_quota=full_data.get('block_quota')
)
Voucher.clean_subevent(
full_data, self.context.get('event')
)
Voucher.clean_max_usages(full_data, self.instance.redeemed if self.instance else 0)
check_quota = Voucher.clean_quota_needs_checking(
full_data, self.instance,
item_changed=self.instance and (
full_data.get('item') != self.instance.item or
full_data.get('variation') != self.instance.variation or
full_data.get('quota') != self.instance.quota
),
creating=not self.instance
)
if check_quota:
Voucher.clean_quota_check(
full_data, 1, self.instance, self.context.get('event'),
full_data.get('quota'), full_data.get('item'), full_data.get('variation')
)
Voucher.clean_voucher_code(full_data, self.context.get('event'), self.instance.pk if self.instance else None)
if full_data.get('seat'):
data['seat'] = Voucher.clean_seat_id(
full_data, full_data.get('item'), full_data.get('quota'), self.context.get('event'),
self.instance.pk if self.instance else None
)
return data | 0.447702 | 0.105902 |
import pytest
import numpy as np
from mikeio import Dfs0
from datetime import datetime
import fmskill
from fmskill.observation import PointObservation
@pytest.fixture
def fn_mod():
return "tests/testdata/SW/ts_storm_4.dfs0"
@pytest.fixture
def fn_obs():
return "tests/testdata/SW/eur_Hm0.dfs0"
def test_compare(fn_obs, fn_mod):
df_mod = Dfs0(fn_mod).read(items=0).to_dataframe()
c = fmskill.compare(fn_obs, df_mod)
assert c.n_points == 67
assert c.start == datetime(2017, 10, 27, 0, 0, 0)
assert c.end == datetime(2017, 10, 29, 18, 0, 0)
def test_compare_mod_item(fn_obs, fn_mod):
c = fmskill.compare(fn_obs, fn_mod, mod_item=0)
dfs = Dfs0(fn_mod)
assert c.mod_names[0] == dfs.items[0].name
def test_compare_fn(fn_obs):
c = fmskill.compare(fn_obs, fn_obs)
assert c.n_points == 95
def test_compare_df(fn_obs, fn_mod):
df_obs = Dfs0(fn_obs).read().to_dataframe()
df_mod = Dfs0(fn_mod).read(items=0).to_dataframe()
c = fmskill.compare(df_obs, df_mod)
assert c.n_points == 67
assert c.start == datetime(2017, 10, 27, 0, 0, 0)
assert c.end == datetime(2017, 10, 29, 18, 0, 0)
def test_compare_point_obs(fn_obs, fn_mod):
obs = fmskill.PointObservation(fn_obs, name="EPL")
df_mod = Dfs0(fn_mod).read(items=0).to_dataframe()
c = fmskill.compare(obs, df_mod)
assert c.n_points == 67
def test_compare_fail(fn_obs, fn_mod):
df_mod = Dfs0(fn_mod).read(items=[0, 1, 2]).to_dataframe()
with pytest.raises(ValueError):
# multiple items in model df -> ambigous
fmskill.compare(fn_obs, df_mod)
df_obs2, fn_mod2 = df_mod, fn_obs
with pytest.raises(ValueError):
# multiple items in obs df -> ambigous
fmskill.compare(df_obs2, fn_mod2)
def test_compare_obs_item(fn_mod):
c = fmskill.compare(
"tests/testdata/SW/eur_Hm0.dfs0", fn_mod, mod_item=0
) # obs file has only 1 item, not necessary to specify obs_item
assert c.n_points == 67
with pytest.raises(ValueError):
fmskill.compare(
"tests/testdata/SW/eur_Hm0.dfs0", fn_mod, mod_item=0, obs_item=1
) # file has only 1 item
c = fmskill.compare(
"tests/testdata/SW/eur_Hm0_Quality.dfs0", fn_mod, mod_item=0, obs_item=0
)
assert c.n_points == 67
with pytest.raises(ValueError):
fmskill.compare(
"tests/testdata/SW/eur_Hm0_Quality.dfs0", fn_mod
) # Obs file has multiple items, but we did not specify one
def test_compare_obs_item_pointobs(fn_mod):
o1 = PointObservation("tests/testdata/SW/eur_Hm0_Quality.dfs0", item=0)
c = fmskill.compare(o1, fn_mod, mod_item=0)
assert c.n_points == 67
def test_compare_obs_item_pointobs_inconsistent_item_error(fn_mod):
o1 = PointObservation("tests/testdata/SW/eur_Hm0_Quality.dfs0", item=0)
with pytest.raises(ValueError):
fmskill.compare(o1, fn_mod, mod_item=0, obs_item=1) # item=0 != obs_item==1
def test_compare_mod_item(fn_obs, fn_mod):
df_mod = Dfs0(fn_mod).read(items=[0, 1, 2]).to_dataframe()
c = fmskill.compare(fn_obs, df_mod, mod_item=0)
assert c.n_points > 0
def test_force_keyword_args(fn_obs, fn_mod):
with pytest.raises(TypeError):
fmskill.compare(fn_obs, fn_mod, 0, 0) | tests/test_simple_compare.py | import pytest
import numpy as np
from mikeio import Dfs0
from datetime import datetime
import fmskill
from fmskill.observation import PointObservation
@pytest.fixture
def fn_mod():
return "tests/testdata/SW/ts_storm_4.dfs0"
@pytest.fixture
def fn_obs():
return "tests/testdata/SW/eur_Hm0.dfs0"
def test_compare(fn_obs, fn_mod):
df_mod = Dfs0(fn_mod).read(items=0).to_dataframe()
c = fmskill.compare(fn_obs, df_mod)
assert c.n_points == 67
assert c.start == datetime(2017, 10, 27, 0, 0, 0)
assert c.end == datetime(2017, 10, 29, 18, 0, 0)
def test_compare_mod_item(fn_obs, fn_mod):
c = fmskill.compare(fn_obs, fn_mod, mod_item=0)
dfs = Dfs0(fn_mod)
assert c.mod_names[0] == dfs.items[0].name
def test_compare_fn(fn_obs):
c = fmskill.compare(fn_obs, fn_obs)
assert c.n_points == 95
def test_compare_df(fn_obs, fn_mod):
df_obs = Dfs0(fn_obs).read().to_dataframe()
df_mod = Dfs0(fn_mod).read(items=0).to_dataframe()
c = fmskill.compare(df_obs, df_mod)
assert c.n_points == 67
assert c.start == datetime(2017, 10, 27, 0, 0, 0)
assert c.end == datetime(2017, 10, 29, 18, 0, 0)
def test_compare_point_obs(fn_obs, fn_mod):
obs = fmskill.PointObservation(fn_obs, name="EPL")
df_mod = Dfs0(fn_mod).read(items=0).to_dataframe()
c = fmskill.compare(obs, df_mod)
assert c.n_points == 67
def test_compare_fail(fn_obs, fn_mod):
df_mod = Dfs0(fn_mod).read(items=[0, 1, 2]).to_dataframe()
with pytest.raises(ValueError):
# multiple items in model df -> ambigous
fmskill.compare(fn_obs, df_mod)
df_obs2, fn_mod2 = df_mod, fn_obs
with pytest.raises(ValueError):
# multiple items in obs df -> ambigous
fmskill.compare(df_obs2, fn_mod2)
def test_compare_obs_item(fn_mod):
c = fmskill.compare(
"tests/testdata/SW/eur_Hm0.dfs0", fn_mod, mod_item=0
) # obs file has only 1 item, not necessary to specify obs_item
assert c.n_points == 67
with pytest.raises(ValueError):
fmskill.compare(
"tests/testdata/SW/eur_Hm0.dfs0", fn_mod, mod_item=0, obs_item=1
) # file has only 1 item
c = fmskill.compare(
"tests/testdata/SW/eur_Hm0_Quality.dfs0", fn_mod, mod_item=0, obs_item=0
)
assert c.n_points == 67
with pytest.raises(ValueError):
fmskill.compare(
"tests/testdata/SW/eur_Hm0_Quality.dfs0", fn_mod
) # Obs file has multiple items, but we did not specify one
def test_compare_obs_item_pointobs(fn_mod):
o1 = PointObservation("tests/testdata/SW/eur_Hm0_Quality.dfs0", item=0)
c = fmskill.compare(o1, fn_mod, mod_item=0)
assert c.n_points == 67
def test_compare_obs_item_pointobs_inconsistent_item_error(fn_mod):
o1 = PointObservation("tests/testdata/SW/eur_Hm0_Quality.dfs0", item=0)
with pytest.raises(ValueError):
fmskill.compare(o1, fn_mod, mod_item=0, obs_item=1) # item=0 != obs_item==1
def test_compare_mod_item(fn_obs, fn_mod):
df_mod = Dfs0(fn_mod).read(items=[0, 1, 2]).to_dataframe()
c = fmskill.compare(fn_obs, df_mod, mod_item=0)
assert c.n_points > 0
def test_force_keyword_args(fn_obs, fn_mod):
with pytest.raises(TypeError):
fmskill.compare(fn_obs, fn_mod, 0, 0) | 0.472927 | 0.572603 |
from django.http import HttpResponse
import cv2
import numpy as np
import requests
import datetime
import hashlib
import base64
import hmac
import json
import os
import glob
def uploadImg(request):
'''
上传图片并保存到当前目录下,便于后续处理;同时返回该图片数据,便于在页面上显示已经上传的图片
'''
if request.method == 'POST':
file_list = request.FILES.getlist('file')
file = file_list[0]
img_dir = "./backend/Data/origin.jpg"
data = file.file.read()
with open(img_dir, 'wb') as f:
f.write(data)
return HttpResponse(data, content_type='image/png')
def Formula_Recognition(request):
'''
接受前端请求,进行公式识别
'''
img_dir = "./backend/Data/origin.jpg"
cropAndStore(img_dir) # 裁剪图片并储存
str_all = "\\begin{align} "
for paths in glob.glob("./backend/Data/cropped/*"):
gClass = XunFeiAPI(paths) # 初始化科大讯飞公式识别API
str = gClass.call_url()
str_all += str
str_all += "\\\\"
str_all += " \\end{align}"
return HttpResponse(str_all, content_type='text/plain')
def cropAndStore(img_dir):
img = cv2.imread(img_dir)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 读取图片灰度值
ret, th = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY) # 针对不同图需要调整阈值
h_h = hProject(th) # 获取图片水平投影
start = 0 # 当前区域开始标志
h_start, h_end = [], [] # 记录遍历结果,每个区域起始点记录在h_start中,结束点记录在h_end中
# 根据水平投影获取分割
zero_cnt = 0 # 记录像素点为0的连续行数
for i in range(len(h_h)): # 遍历各行像素值
if h_h[i] > 0 and start == 0: # 如果当前行投影不为0,并且没有开始一个新的区域
h_start.append(max(0, i - 5)) # 进入有效区域,开始行留有余量,此处设置为5行
start = 1
zero_cnt = 0
if h_h[i] == 0: # 当前行投影为0,zero_cnt计数
zero_cnt += 1
if zero_cnt > 10 and start == 1: # 如果在有效区域中,像素点为0的连续行数达到一定阈值(此处设置为10),结束当前区域,保存结束点
h_end.append(i)
start = 0
cropped_dir = "./backend/Data/cropped/"
if os.path.exists(cropped_dir):
for path in glob.glob("./backend/Data/cropped/*"):
os.remove(path)
else:
os.makedirs(cropped_dir)
for i in range(len(h_start)):
crop = img[h_start[i]: h_end[i]]
# cv2.imshow('crop_%d' % i, crop)
cv2.imwrite(os.path.join(cropped_dir, 'crop_%d.jpg' % i), crop)
def hProject(binary):
'''获取图片水平方向投影'''
h, w = binary.shape
hprojection = np.zeros(binary.shape, dtype=np.uint8)
h_h = [0] * h
for j in range(h):
for i in range(w):
if binary[j, i] == 0:
h_h[j] += 1
for j in range(h):
for i in range(h_h[j]):
hprojection[j, i] = 255
return h_h
class XunFeiAPI(object):
'''科大讯飞公式识别API'''
def __init__(self, AudioPath, host="rest-api.xfyun.cn"):
# 应用ID(到控制台获取)
self.APPID = "1258fd12"
# 接口APISercet(到控制台公式识别服务页面获取)
self.Secret = "<KEY>"
# 接口APIKey(到控制台公式识别服务页面获取)
self.APIKey = "<KEY>"
# POST请求
self.Host = host
self.RequestUri = "/v2/itr"
# 设置url
self.url = "https://" + host + self.RequestUri
self.HttpMethod = "POST"
self.Algorithm = "hmac-sha256"
self.HttpProto = "HTTP/1.1"
# 设置当前时间
curTime_utc = datetime.datetime.utcnow()
self.Date = self.httpdate(curTime_utc)
# 设置测试图片文件
self.AudioPath = AudioPath
self.BusinessArgs = {
"ent": "teach-photo-print",
"aue": "raw",
}
def imgRead(self, path):
with open(path, 'rb') as fo:
return fo.read()
def hashlib_256(self, res):
m = hashlib.sha256(bytes(res.encode(encoding='utf-8'))).digest()
result = "SHA-256=" + base64.b64encode(m).decode(encoding='utf-8')
return result
def httpdate(self, dt):
"""
Return a string representation of a date according to RFC 1123
(HTTP/1.1).
The supplied date must be in UTC.
"""
weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"][dt.month - 1]
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
dt.year, dt.hour, dt.minute, dt.second)
def generateSignature(self, digest):
signatureStr = "host: " + self.Host + "\n"
signatureStr += "date: " + self.Date + "\n"
signatureStr += self.HttpMethod + " " + self.RequestUri \
+ " " + self.HttpProto + "\n"
signatureStr += "digest: " + digest
signature = hmac.new(bytes(self.Secret.encode(encoding='utf-8')),
bytes(signatureStr.encode(encoding='utf-8')),
digestmod=hashlib.sha256).digest()
result = base64.b64encode(signature)
return result.decode(encoding='utf-8')
def init_header(self, data):
digest = self.hashlib_256(data)
sign = self.generateSignature(digest)
authHeader = 'api_key="%s", algorithm="%s", ' \
'headers="host date request-line digest", ' \
'signature="%s"' \
% (self.APIKey, self.Algorithm, sign)
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Method": "POST",
"Host": self.Host,
"Date": self.Date,
"Digest": digest,
"Authorization": authHeader
}
return headers
def get_body(self):
audioData = self.imgRead((self.AudioPath))
content = base64.b64encode(audioData).decode(encoding='utf-8')
postdata = {
"common": {"app_id": self.APPID},
"business": self.BusinessArgs,
"data": {
"image": content,
}
}
body = json.dumps(postdata)
return body
def get_content(self, respData):
# 处理识别结果中的字符串,包括整合各个区域识别出的字符、去掉标识latex代码的前后缀等
str = ""
try:
for i in range(len(respData['data']['region'])):
str += respData['data']['region'][i]['recog']['content'] + "\n"
except:
return "Error!"
s1 = 'ifly-latex-begin'
flag = 1
while flag == 1: # 若无子字符串在内则跳出循环
flag = 0
if s1 in str:
str = str.replace(s1, '')
flag = 1
s1 = 'ifly-latex-end'
flag = 1
while flag == 1:
flag = 0
if s1 in str:
str = str.replace(s1, '')
flag = 1
s1 = ' '
flag = 1
while flag == 1:
flag = 0
if s1 in str:
str = str.replace(s1, '')
flag = 1
return str
def call_url(self):
body = self.get_body()
headers = self.init_header(body)
# print(self.url)
response = requests.post(self.url, data=body, headers=headers, timeout=8)
status_code = response.status_code
str_default = "Error!"
if status_code != 200:
# 鉴权失败
print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html")
else:
# 鉴权成功
respData = json.loads(response.text)
str_default = self.get_content(respData)
return str_default | backend/views.py | from django.http import HttpResponse
import cv2
import numpy as np
import requests
import datetime
import hashlib
import base64
import hmac
import json
import os
import glob
def uploadImg(request):
'''
上传图片并保存到当前目录下,便于后续处理;同时返回该图片数据,便于在页面上显示已经上传的图片
'''
if request.method == 'POST':
file_list = request.FILES.getlist('file')
file = file_list[0]
img_dir = "./backend/Data/origin.jpg"
data = file.file.read()
with open(img_dir, 'wb') as f:
f.write(data)
return HttpResponse(data, content_type='image/png')
def Formula_Recognition(request):
'''
接受前端请求,进行公式识别
'''
img_dir = "./backend/Data/origin.jpg"
cropAndStore(img_dir) # 裁剪图片并储存
str_all = "\\begin{align} "
for paths in glob.glob("./backend/Data/cropped/*"):
gClass = XunFeiAPI(paths) # 初始化科大讯飞公式识别API
str = gClass.call_url()
str_all += str
str_all += "\\\\"
str_all += " \\end{align}"
return HttpResponse(str_all, content_type='text/plain')
def cropAndStore(img_dir):
img = cv2.imread(img_dir)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 读取图片灰度值
ret, th = cv2.threshold(gray, 80, 255, cv2.THRESH_BINARY) # 针对不同图需要调整阈值
h_h = hProject(th) # 获取图片水平投影
start = 0 # 当前区域开始标志
h_start, h_end = [], [] # 记录遍历结果,每个区域起始点记录在h_start中,结束点记录在h_end中
# 根据水平投影获取分割
zero_cnt = 0 # 记录像素点为0的连续行数
for i in range(len(h_h)): # 遍历各行像素值
if h_h[i] > 0 and start == 0: # 如果当前行投影不为0,并且没有开始一个新的区域
h_start.append(max(0, i - 5)) # 进入有效区域,开始行留有余量,此处设置为5行
start = 1
zero_cnt = 0
if h_h[i] == 0: # 当前行投影为0,zero_cnt计数
zero_cnt += 1
if zero_cnt > 10 and start == 1: # 如果在有效区域中,像素点为0的连续行数达到一定阈值(此处设置为10),结束当前区域,保存结束点
h_end.append(i)
start = 0
cropped_dir = "./backend/Data/cropped/"
if os.path.exists(cropped_dir):
for path in glob.glob("./backend/Data/cropped/*"):
os.remove(path)
else:
os.makedirs(cropped_dir)
for i in range(len(h_start)):
crop = img[h_start[i]: h_end[i]]
# cv2.imshow('crop_%d' % i, crop)
cv2.imwrite(os.path.join(cropped_dir, 'crop_%d.jpg' % i), crop)
def hProject(binary):
'''获取图片水平方向投影'''
h, w = binary.shape
hprojection = np.zeros(binary.shape, dtype=np.uint8)
h_h = [0] * h
for j in range(h):
for i in range(w):
if binary[j, i] == 0:
h_h[j] += 1
for j in range(h):
for i in range(h_h[j]):
hprojection[j, i] = 255
return h_h
class XunFeiAPI(object):
'''科大讯飞公式识别API'''
def __init__(self, AudioPath, host="rest-api.xfyun.cn"):
# 应用ID(到控制台获取)
self.APPID = "1258fd12"
# 接口APISercet(到控制台公式识别服务页面获取)
self.Secret = "<KEY>"
# 接口APIKey(到控制台公式识别服务页面获取)
self.APIKey = "<KEY>"
# POST请求
self.Host = host
self.RequestUri = "/v2/itr"
# 设置url
self.url = "https://" + host + self.RequestUri
self.HttpMethod = "POST"
self.Algorithm = "hmac-sha256"
self.HttpProto = "HTTP/1.1"
# 设置当前时间
curTime_utc = datetime.datetime.utcnow()
self.Date = self.httpdate(curTime_utc)
# 设置测试图片文件
self.AudioPath = AudioPath
self.BusinessArgs = {
"ent": "teach-photo-print",
"aue": "raw",
}
def imgRead(self, path):
with open(path, 'rb') as fo:
return fo.read()
def hashlib_256(self, res):
m = hashlib.sha256(bytes(res.encode(encoding='utf-8'))).digest()
result = "SHA-256=" + base64.b64encode(m).decode(encoding='utf-8')
return result
def httpdate(self, dt):
"""
Return a string representation of a date according to RFC 1123
(HTTP/1.1).
The supplied date must be in UTC.
"""
weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"][dt.month - 1]
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
dt.year, dt.hour, dt.minute, dt.second)
def generateSignature(self, digest):
signatureStr = "host: " + self.Host + "\n"
signatureStr += "date: " + self.Date + "\n"
signatureStr += self.HttpMethod + " " + self.RequestUri \
+ " " + self.HttpProto + "\n"
signatureStr += "digest: " + digest
signature = hmac.new(bytes(self.Secret.encode(encoding='utf-8')),
bytes(signatureStr.encode(encoding='utf-8')),
digestmod=hashlib.sha256).digest()
result = base64.b64encode(signature)
return result.decode(encoding='utf-8')
def init_header(self, data):
digest = self.hashlib_256(data)
sign = self.generateSignature(digest)
authHeader = 'api_key="%s", algorithm="%s", ' \
'headers="host date request-line digest", ' \
'signature="%s"' \
% (self.APIKey, self.Algorithm, sign)
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Method": "POST",
"Host": self.Host,
"Date": self.Date,
"Digest": digest,
"Authorization": authHeader
}
return headers
def get_body(self):
audioData = self.imgRead((self.AudioPath))
content = base64.b64encode(audioData).decode(encoding='utf-8')
postdata = {
"common": {"app_id": self.APPID},
"business": self.BusinessArgs,
"data": {
"image": content,
}
}
body = json.dumps(postdata)
return body
def get_content(self, respData):
# 处理识别结果中的字符串,包括整合各个区域识别出的字符、去掉标识latex代码的前后缀等
str = ""
try:
for i in range(len(respData['data']['region'])):
str += respData['data']['region'][i]['recog']['content'] + "\n"
except:
return "Error!"
s1 = 'ifly-latex-begin'
flag = 1
while flag == 1: # 若无子字符串在内则跳出循环
flag = 0
if s1 in str:
str = str.replace(s1, '')
flag = 1
s1 = 'ifly-latex-end'
flag = 1
while flag == 1:
flag = 0
if s1 in str:
str = str.replace(s1, '')
flag = 1
s1 = ' '
flag = 1
while flag == 1:
flag = 0
if s1 in str:
str = str.replace(s1, '')
flag = 1
return str
def call_url(self):
body = self.get_body()
headers = self.init_header(body)
# print(self.url)
response = requests.post(self.url, data=body, headers=headers, timeout=8)
status_code = response.status_code
str_default = "Error!"
if status_code != 200:
# 鉴权失败
print("Http请求失败,状态码:" + str(status_code) + ",错误信息:" + response.text)
print("请根据错误信息检查代码,接口文档:https://www.xfyun.cn/doc/words/formula-discern/API.html")
else:
# 鉴权成功
respData = json.loads(response.text)
str_default = self.get_content(respData)
return str_default | 0.318909 | 0.160595 |
import re
class Token:
def __init__(self, t, v):
self.type = t
self.value = v
def __str__(self):
return 'Token = `{}\' : `{}\''.format(self.type, self.value)
class Lexer:
_keyword = ['let', 'def', 'if', 'elsif', 'else', 'end']
_literal = ['nil', 'true', 'false']
def __init__(self, program):
self._program = program
self._index = 0
self._len = len(program)
def get_token(self):
while True:
if self._index >= self._len:
raise StopIteration
curr_char = self._program[self._index]
# skip space
if curr_char.isspace():
self._index += 1
continue
r_identifier = r'[_a-zA-Z][_a-zA-Z0-9]*'
match = re.match(r_identifier, self._program[self._index:])
if match is not None:
self._index += match.end()
identifier = match.group()
if identifier in self._keyword:
return Token(identifier, identifier)
return Token('Identifier', identifier)
r_number = r'[-+]?[0-9]*\.?[0-9]+'
match = re.match(r_number, self._program[self._index:])
if match is not None:
self._index += match.end()
number = match.group()
return Token('Number', float(number))
r_arrow = r'=>'
match = re.match(r_arrow, self._program[self._index:])
if match is not None:
self._index += match.end()
number = match.group()
return Token('Arrow', '=>')
r_arrow = r':='
match = re.match(r_arrow, self._program[self._index:])
if match is not None:
self._index += match.end()
number = match.group()
return Token('Assign', ':=')
self._index += 1
return Token(curr_char, curr_char)
def __iter__(self):
return self
def __next__(self):
return self.get_token()
program = '''
let a = 5
a := 6
def do_0(x)
x * 2
end
if true
do_1()
elsif false
do_2()
else
do_3()
end
'''
lexer = Lexer(program)
for token in lexer:
print(token) | lexer.py | import re
class Token:
def __init__(self, t, v):
self.type = t
self.value = v
def __str__(self):
return 'Token = `{}\' : `{}\''.format(self.type, self.value)
class Lexer:
_keyword = ['let', 'def', 'if', 'elsif', 'else', 'end']
_literal = ['nil', 'true', 'false']
def __init__(self, program):
self._program = program
self._index = 0
self._len = len(program)
def get_token(self):
while True:
if self._index >= self._len:
raise StopIteration
curr_char = self._program[self._index]
# skip space
if curr_char.isspace():
self._index += 1
continue
r_identifier = r'[_a-zA-Z][_a-zA-Z0-9]*'
match = re.match(r_identifier, self._program[self._index:])
if match is not None:
self._index += match.end()
identifier = match.group()
if identifier in self._keyword:
return Token(identifier, identifier)
return Token('Identifier', identifier)
r_number = r'[-+]?[0-9]*\.?[0-9]+'
match = re.match(r_number, self._program[self._index:])
if match is not None:
self._index += match.end()
number = match.group()
return Token('Number', float(number))
r_arrow = r'=>'
match = re.match(r_arrow, self._program[self._index:])
if match is not None:
self._index += match.end()
number = match.group()
return Token('Arrow', '=>')
r_arrow = r':='
match = re.match(r_arrow, self._program[self._index:])
if match is not None:
self._index += match.end()
number = match.group()
return Token('Assign', ':=')
self._index += 1
return Token(curr_char, curr_char)
def __iter__(self):
return self
def __next__(self):
return self.get_token()
program = '''
let a = 5
a := 6
def do_0(x)
x * 2
end
if true
do_1()
elsif false
do_2()
else
do_3()
end
'''
lexer = Lexer(program)
for token in lexer:
print(token) | 0.359701 | 0.158793 |
import random
import math
import time
import threading
from PyQt5.QtChart import (QAreaSeries, QBarSet, QChart, QChartView,
QLineSeries, QPieSeries, QScatterSeries, QSplineSeries,
QStackedBarSeries, QValueAxis)
from PyQt5.QtCore import (
pyqtSlot, QPoint, QPointF, Qt
)
from PyQt5.Qt import (QApplication, QWidget, QPushButton,
QThread, QMutex, pyqtSignal)
from PyQt5.QtGui import QColor, QPainter, QPalette
from PyQt5.QtWidgets import (QCheckBox, QComboBox, QGridLayout, QHBoxLayout,
QLabel, QSizePolicy, QWidget, QPushButton)
class TestChart(QChart):
def __init__(self, parent=None):
super(TestChart, self).__init__(parent)
self.xRange = 500
self.sampleRate = 1
self.counter = 0
self.seriesList = []
self.temp_y = []
# self.legend().show()
self.legend().setVisible(False)
self.axisX = QValueAxis()
self.axisX.setRange(0, self.xRange)
self.addAxis(self.axisX, Qt.AlignBottom)
# self.setAxisX(self.axisX, series)
self.axisY = QValueAxis()
self.axisY.setRange(0,1)
self.addAxis(self.axisY, Qt.AlignLeft)
# self.setAxisY(self.axisY, series)
self.series = QLineSeries()
# self.series.setName("生成300~1000随机数")
# self.series.setUseOpenGL(True)
self.addSeries(self.series)
self.series.attachAxis(self.axisX)
self.series.attachAxis(self.axisY)
def handleUpdate(self, ydata):
if (self.counter < self.xRange):
for i in range(self.sampleRate):
self.series.append(self.counter + i, ydata)
self.temp_y.append(ydata)
self.axisY.setRange(min(self.temp_y), max(self.temp_y))
else:
points = self.series.pointsVector()
print(points[0])
y_temp = [0] * (len(points) - self.sampleRate)
for i in range(len(points) - self.sampleRate):
points[i].setY(points[i + self.sampleRate].y())
y_temp[i] = points[i + self.sampleRate].y()
for i in range(self.sampleRate):
points[len(points) - (self.sampleRate - i)].setY(ydata)
self.series.replace(points)
# self.axisY.setRange(min(y_temp), max(y_temp))
# self.series.setUseOpenGL(True)
self.counter += self.sampleRate
class WorkThread(QThread):
_signal_updateUI = pyqtSignal()
def __init__(self, parent=None):
super(WorkThread, self).__init__(parent)
self.qmut = QMutex()
self.isexit = False
def run(self):
while (True):
self.qmut.lock()
if (self.isexit):
break
self.qmut.unlock()
self._signal_updateUI.emit()
time.sleep(0.01)
self.qmut.unlock()
def stop(self):
# 改变线程状态与终止
self.qmut.lock()
self.isexit = True
self.qmut.unlock()
self.wait()
class MyWidget(QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.mythread = WorkThread()
self.label = QLabel()
# self.m_charts = []
self.pushubutton = QPushButton()
self.pushubutton.setText('start')
self.pushubutton_stop = QPushButton()
self.pushubutton_stop.setText('stop')
self.connectSignals()
# Create the layout.
baseLayout = QGridLayout()
settingsLayout = QHBoxLayout()
settingsLayout.addWidget(self.pushubutton)
settingsLayout.addWidget(self.pushubutton_stop)
settingsLayout.addStretch()
baseLayout.addLayout(settingsLayout, 0, 0, 1, 3)
self.myChart = TestChart()
chartView = QChartView(self.myChart)
chartView.setRenderHint(QPainter.Antialiasing) # 抗锯齿
baseLayout.addWidget(chartView)
# self.m_charts.append(chartView)
self.setLayout(baseLayout)
self.pushubutton_stop.setEnabled(False)
def pushubutton_clicked(self):
self.mythread.start()
self.pushubutton.setEnabled(False)
self.pushubutton_stop.setEnabled(True)
def pushubutton_stop_clicked(self):
self.mythread.stop()
self.mythread.isexit = False
self.pushubutton.setEnabled(True)
self.pushubutton_stop.setEnabled(False)
def connectSignals(self):
self.pushubutton.clicked.connect(self.pushubutton_clicked)
self.pushubutton_stop.clicked.connect(self.pushubutton_stop_clicked)
self.mythread._signal_updateUI.connect(self.threading_slot)
def threading_slot(self):
yint = 0 #random.randint(300, 1000)
self.myChart.handleUpdate(yint)
# 实时刷新界面
self.myChart.update()
# QApplication.processEvents()
if __name__ == '__main__':
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
app = QApplication(sys.argv)
window = QMainWindow()
widget = MyWidget()
window.setCentralWidget(widget)
window.resize(900, 600)
window.show()
sys.exit(app.exec_()) | no_use_files/test.py |
import random
import math
import time
import threading
from PyQt5.QtChart import (QAreaSeries, QBarSet, QChart, QChartView,
QLineSeries, QPieSeries, QScatterSeries, QSplineSeries,
QStackedBarSeries, QValueAxis)
from PyQt5.QtCore import (
pyqtSlot, QPoint, QPointF, Qt
)
from PyQt5.Qt import (QApplication, QWidget, QPushButton,
QThread, QMutex, pyqtSignal)
from PyQt5.QtGui import QColor, QPainter, QPalette
from PyQt5.QtWidgets import (QCheckBox, QComboBox, QGridLayout, QHBoxLayout,
QLabel, QSizePolicy, QWidget, QPushButton)
class TestChart(QChart):
def __init__(self, parent=None):
super(TestChart, self).__init__(parent)
self.xRange = 500
self.sampleRate = 1
self.counter = 0
self.seriesList = []
self.temp_y = []
# self.legend().show()
self.legend().setVisible(False)
self.axisX = QValueAxis()
self.axisX.setRange(0, self.xRange)
self.addAxis(self.axisX, Qt.AlignBottom)
# self.setAxisX(self.axisX, series)
self.axisY = QValueAxis()
self.axisY.setRange(0,1)
self.addAxis(self.axisY, Qt.AlignLeft)
# self.setAxisY(self.axisY, series)
self.series = QLineSeries()
# self.series.setName("生成300~1000随机数")
# self.series.setUseOpenGL(True)
self.addSeries(self.series)
self.series.attachAxis(self.axisX)
self.series.attachAxis(self.axisY)
def handleUpdate(self, ydata):
if (self.counter < self.xRange):
for i in range(self.sampleRate):
self.series.append(self.counter + i, ydata)
self.temp_y.append(ydata)
self.axisY.setRange(min(self.temp_y), max(self.temp_y))
else:
points = self.series.pointsVector()
print(points[0])
y_temp = [0] * (len(points) - self.sampleRate)
for i in range(len(points) - self.sampleRate):
points[i].setY(points[i + self.sampleRate].y())
y_temp[i] = points[i + self.sampleRate].y()
for i in range(self.sampleRate):
points[len(points) - (self.sampleRate - i)].setY(ydata)
self.series.replace(points)
# self.axisY.setRange(min(y_temp), max(y_temp))
# self.series.setUseOpenGL(True)
self.counter += self.sampleRate
class WorkThread(QThread):
_signal_updateUI = pyqtSignal()
def __init__(self, parent=None):
super(WorkThread, self).__init__(parent)
self.qmut = QMutex()
self.isexit = False
def run(self):
while (True):
self.qmut.lock()
if (self.isexit):
break
self.qmut.unlock()
self._signal_updateUI.emit()
time.sleep(0.01)
self.qmut.unlock()
def stop(self):
# 改变线程状态与终止
self.qmut.lock()
self.isexit = True
self.qmut.unlock()
self.wait()
class MyWidget(QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.mythread = WorkThread()
self.label = QLabel()
# self.m_charts = []
self.pushubutton = QPushButton()
self.pushubutton.setText('start')
self.pushubutton_stop = QPushButton()
self.pushubutton_stop.setText('stop')
self.connectSignals()
# Create the layout.
baseLayout = QGridLayout()
settingsLayout = QHBoxLayout()
settingsLayout.addWidget(self.pushubutton)
settingsLayout.addWidget(self.pushubutton_stop)
settingsLayout.addStretch()
baseLayout.addLayout(settingsLayout, 0, 0, 1, 3)
self.myChart = TestChart()
chartView = QChartView(self.myChart)
chartView.setRenderHint(QPainter.Antialiasing) # 抗锯齿
baseLayout.addWidget(chartView)
# self.m_charts.append(chartView)
self.setLayout(baseLayout)
self.pushubutton_stop.setEnabled(False)
def pushubutton_clicked(self):
self.mythread.start()
self.pushubutton.setEnabled(False)
self.pushubutton_stop.setEnabled(True)
def pushubutton_stop_clicked(self):
self.mythread.stop()
self.mythread.isexit = False
self.pushubutton.setEnabled(True)
self.pushubutton_stop.setEnabled(False)
def connectSignals(self):
self.pushubutton.clicked.connect(self.pushubutton_clicked)
self.pushubutton_stop.clicked.connect(self.pushubutton_stop_clicked)
self.mythread._signal_updateUI.connect(self.threading_slot)
def threading_slot(self):
yint = 0 #random.randint(300, 1000)
self.myChart.handleUpdate(yint)
# 实时刷新界面
self.myChart.update()
# QApplication.processEvents()
if __name__ == '__main__':
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
app = QApplication(sys.argv)
window = QMainWindow()
widget = MyWidget()
window.setCentralWidget(widget)
window.resize(900, 600)
window.show()
sys.exit(app.exec_()) | 0.325199 | 0.273526 |
import numpy as np
from ..cy.lib import maxDist,minDist
from copy import deepcopy
class molecule(object):
'''
Base molecule class. All molecules should inherit from this class
and call the stron
'''
def __init__(self):
self.placed=False
self.natoms=0
self.positions=[]
self.names=[]
self.types=[]
self.masses=[]
self.residue_numbers=[]
self.residue_types=[]
self.diameters=[]
self.bonds=[]
self.angles=[]
self.dihedrals=[]
self.bodies=[]
self.charges=[]
self.moleculeIDs=None
self.moleculeNames=[]
self.name='BaseClass'
def shiftBondIDs(self,shiftVal):
newBondCount = 0
newAngleCount = 0
newDihedralCount = 0
bondTypeSet = set()
angleTypeSet = set()
dihedralTypeSet = set()
newBonds=[]
for bond in self.bonds:
newBonds.append([bond[0], bond[1]+shiftVal, bond[2]+shiftVal])
bondTypeSet.add(bond[0])
newBondCount+=1
newAngles = []
for angle in self.angles:
newAngles.append([angle[0], angle[1]+shiftVal, angle[2]+shiftVal, angle[3]+shiftVal])
angleTypeSet.add(angle[0])
newAngleCount+=1
newDihedrals = []
for dihedral in self.dihedrals:
newDihedrals.append([dihedral[0], dihedral[1]+shiftVal, dihedral[2]+shiftVal, dihedral[3]+shiftVal, dihedral[4]+shiftVal])
dihedralTypeSet.add(dihedral[0])
newDihedralCount+=1
self.bonds=newBonds
self.angles=newAngles
self.dihedrals=newDihedrals
counts = {'bond':newBondCount,'angle':newAngleCount,'dihedral':newDihedralCount}
types = {'bond':bondTypeSet,'angle':angleTypeSet,'dihedral':dihedralTypeSet}
return {'counts':counts,'types':types}
def shiftBody(self,bodyCount):
newBodies = np.max(self.bodies)+1
for i,bval in enumerate(self.bodies):
if bval!=-1:
self.bodies[i]+=bodyCount
return newBodies
def translateCOM(self,newCOM, L=1e5):
diff = newCOM - self.COM[0]
self.positions = self.positions + diff
self.COM = np.array([newCOM])
def calcCOM(self):
self.COM = np.array([np.mean(self.positions,axis=0)])
def calcMaxR(self):
self.maxR = maxDist(self.COM,self.positions,0,False)[2]
def addMolecule(self,newMol):
newMol = deepcopy(newMol)
newMol.shiftBondIDs(self.natoms)
self.positions.extend(newMol.positions)
self.types.extend(deepcopy(newMol.types))
self.residue_types.extend(deepcopy(newMol.residue_types))
self.diameters.extend(deepcopy(newMol.diameters))
self.bonds.extend(deepcopy(newMol.bonds))
self.angles.extend(deepcopy(newMol.angles))
self.dihedrals.extend(deepcopy(newMol.dihedrals))
self.bodies.extend(deepcopy(newMol.bodies))
self.charges.extend(deepcopy(newMol.charges))
self.natoms+=newMol.natoms
for d in newMol.diameters:
self.beadVol += (4.0/3.0) * np.pi * (d/2.0)**(3.0)
if newMol.moleculeIDs is not None:
if self.moleculeIDs is None:
self.moleculeIDs = []
self.moleculeIDs.extend(deepcopy(newMol.moleculeIDs))
#self.moleculeNames.extend([newMol.name]*newMol.natoms)
def toXYZ(self,fname):
with open(fname,'w') as f:
f.write('{}\n'.format(self.natoms))
f.write('TYPY generated XYZ file for molecule: {}\n'.format(self.name))
for i in range(self.natoms):
t = str(self.types[i])
x = self.positions[i,0]
y = self.positions[i,1]
z = self.positions[i,2]
f.write('{:>3s} {:10.5f} {:10.5f} {:10.5f}\n'.format(t,x,y,z)) | molecules/molecule.py | import numpy as np
from ..cy.lib import maxDist,minDist
from copy import deepcopy
class molecule(object):
'''
Base molecule class. All molecules should inherit from this class
and call the stron
'''
def __init__(self):
self.placed=False
self.natoms=0
self.positions=[]
self.names=[]
self.types=[]
self.masses=[]
self.residue_numbers=[]
self.residue_types=[]
self.diameters=[]
self.bonds=[]
self.angles=[]
self.dihedrals=[]
self.bodies=[]
self.charges=[]
self.moleculeIDs=None
self.moleculeNames=[]
self.name='BaseClass'
def shiftBondIDs(self,shiftVal):
newBondCount = 0
newAngleCount = 0
newDihedralCount = 0
bondTypeSet = set()
angleTypeSet = set()
dihedralTypeSet = set()
newBonds=[]
for bond in self.bonds:
newBonds.append([bond[0], bond[1]+shiftVal, bond[2]+shiftVal])
bondTypeSet.add(bond[0])
newBondCount+=1
newAngles = []
for angle in self.angles:
newAngles.append([angle[0], angle[1]+shiftVal, angle[2]+shiftVal, angle[3]+shiftVal])
angleTypeSet.add(angle[0])
newAngleCount+=1
newDihedrals = []
for dihedral in self.dihedrals:
newDihedrals.append([dihedral[0], dihedral[1]+shiftVal, dihedral[2]+shiftVal, dihedral[3]+shiftVal, dihedral[4]+shiftVal])
dihedralTypeSet.add(dihedral[0])
newDihedralCount+=1
self.bonds=newBonds
self.angles=newAngles
self.dihedrals=newDihedrals
counts = {'bond':newBondCount,'angle':newAngleCount,'dihedral':newDihedralCount}
types = {'bond':bondTypeSet,'angle':angleTypeSet,'dihedral':dihedralTypeSet}
return {'counts':counts,'types':types}
def shiftBody(self,bodyCount):
newBodies = np.max(self.bodies)+1
for i,bval in enumerate(self.bodies):
if bval!=-1:
self.bodies[i]+=bodyCount
return newBodies
def translateCOM(self,newCOM, L=1e5):
diff = newCOM - self.COM[0]
self.positions = self.positions + diff
self.COM = np.array([newCOM])
def calcCOM(self):
self.COM = np.array([np.mean(self.positions,axis=0)])
def calcMaxR(self):
self.maxR = maxDist(self.COM,self.positions,0,False)[2]
def addMolecule(self,newMol):
newMol = deepcopy(newMol)
newMol.shiftBondIDs(self.natoms)
self.positions.extend(newMol.positions)
self.types.extend(deepcopy(newMol.types))
self.residue_types.extend(deepcopy(newMol.residue_types))
self.diameters.extend(deepcopy(newMol.diameters))
self.bonds.extend(deepcopy(newMol.bonds))
self.angles.extend(deepcopy(newMol.angles))
self.dihedrals.extend(deepcopy(newMol.dihedrals))
self.bodies.extend(deepcopy(newMol.bodies))
self.charges.extend(deepcopy(newMol.charges))
self.natoms+=newMol.natoms
for d in newMol.diameters:
self.beadVol += (4.0/3.0) * np.pi * (d/2.0)**(3.0)
if newMol.moleculeIDs is not None:
if self.moleculeIDs is None:
self.moleculeIDs = []
self.moleculeIDs.extend(deepcopy(newMol.moleculeIDs))
#self.moleculeNames.extend([newMol.name]*newMol.natoms)
def toXYZ(self,fname):
with open(fname,'w') as f:
f.write('{}\n'.format(self.natoms))
f.write('TYPY generated XYZ file for molecule: {}\n'.format(self.name))
for i in range(self.natoms):
t = str(self.types[i])
x = self.positions[i,0]
y = self.positions[i,1]
z = self.positions[i,2]
f.write('{:>3s} {:10.5f} {:10.5f} {:10.5f}\n'.format(t,x,y,z)) | 0.417628 | 0.179261 |
import json
from http import HTTPStatus
import tornado.gen as gen
from jupyterlab_pullrequests.manager import PullRequestsManager
from notebook.utils import url_path_join
from tornado.httpclient import AsyncHTTPClient, HTTPClientError, HTTPRequest
from tornado.httputil import url_concat
from tornado.web import HTTPError
GITHUB_API_BASE_URL = "https://api.github.com"
class PullRequestsGithubManager(PullRequestsManager):
# -----------------------------------------------------------------------------
# /pullrequests/prs/user Handler
# -----------------------------------------------------------------------------
@gen.coroutine
def get_current_user(self):
if not self.access_token:
raise HTTPError(
status_code=HTTPStatus.BAD_REQUEST,
reason="No Github access token specified."
)
git_url = url_path_join(GITHUB_API_BASE_URL, "user")
data = yield self.call_github(git_url)
return {'username': data["login"]}
def get_search_filter(self, username, pr_filter):
if pr_filter == "created":
search_filter = "+author:"
elif pr_filter == "assigned":
search_filter = "+assignee:"
return search_filter + username
@gen.coroutine
def list_prs(self, username, pr_filter):
search_filter = self.get_search_filter(username, pr_filter)
# Use search API to find matching PRs and return
git_url = url_path_join(
GITHUB_API_BASE_URL, "/search/issues?q=+state:open+type:pr" + search_filter
)
results = yield self.call_github(git_url)
data = []
for result in results["items"]:
data.append({
'id': result["pull_request"]["url"],
'title': result["title"],
'body': result["body"],
'internal_id': result["id"],
'url': result["html_url"]
})
return data
# -----------------------------------------------------------------------------
# /pullrequests/prs/files Handler
# -----------------------------------------------------------------------------
@gen.coroutine
def list_files(self, pr_id):
git_url = url_path_join(pr_id, "/files")
results = yield self.call_github(git_url)
data = []
for result in results:
data.append({
'name': result["filename"],
'status': result["status"],
'additions': result["additions"],
'deletions': result["deletions"]
})
return data
# -----------------------------------------------------------------------------
# /pullrequests/files/content Handler
# -----------------------------------------------------------------------------
@gen.coroutine
def get_pr_links(self, pr_id, filename):
data = yield self.call_github(pr_id)
base_url = url_concat(url_path_join(data["base"]["repo"]["url"],"contents",filename), {"ref": data["base"]["ref"]})
head_url = url_concat(url_path_join(data["head"]["repo"]["url"],"contents",filename), {"ref": data["head"]["ref"]})
commit_id = data["head"]["sha"]
return {'base_url':base_url, 'head_url':head_url, 'commit_id':commit_id}
@gen.coroutine
def validate_pr_link(self, link):
try:
data = yield self.call_github(link)
return data["download_url"]
except HTTPError as e:
if e.status_code == 404:
return ""
else:
raise e
@gen.coroutine
def get_link_content(self, file_url):
if (file_url == ""):
return ""
result = yield self.call_github(file_url, False)
return result
@gen.coroutine
def get_file_content(self, pr_id, filename):
links = yield self.get_pr_links(pr_id, filename)
base_raw_url = yield self.validate_pr_link(links["base_url"])
head_raw_url = yield self.validate_pr_link(links["head_url"])
base_content = yield self.get_link_content(base_raw_url)
head_content = yield self.get_link_content(head_raw_url)
return {'base_content':base_content, 'head_content':head_content, 'commit_id':links["commit_id"]}
# -----------------------------------------------------------------------------
# /pullrequests/files/comments Handler
# -----------------------------------------------------------------------------
def file_comment_response(self, result):
data = {
'id': result["id"],
'line_number': result["position"],
'text': result["body"],
'updated_at': result["updated_at"],
'user_name': result["user"]["login"],
'user_pic': result["user"]["avatar_url"]
}
if 'in_reply_to_id' in result:
data['in_reply_to_id'] = result["in_reply_to_id"]
return data
@gen.coroutine
def get_file_comments(self, pr_id, filename):
git_url = url_path_join(pr_id, "/comments")
results = yield self.call_github(git_url)
return [self.file_comment_response(result) for result in results if result["path"] == filename]
@gen.coroutine
def post_file_comment(self, pr_id, filename, body):
if type(body).__name__ == 'PRCommentReply':
body = {"body": body.text, "in_reply_to": body.in_reply_to}
else:
body = {"body": body.text, "commit_id": body.commit_id, "path": body.filename, "position": body.position}
git_url = url_path_join(pr_id,"comments")
response = yield self.call_github(git_url, method="POST", body=body)
return self.file_comment_response(response)
# -----------------------------------------------------------------------------
# Handler utilities
# -----------------------------------------------------------------------------
@gen.coroutine
def call_github(self, git_url, load_json=True, method="GET", body=None):
params = {"Accept": "application/vnd.github.v3+json", "access_token": self.access_token}
# User agents required for Github API, see https://developer.github.com/v3/#user-agent-required
try:
if method.lower() == "get":
request = HTTPRequest(
url_concat(git_url, params), validate_cert=True, user_agent="JupyterLab Pull Requests"
)
elif method.lower() == "post":
request = HTTPRequest(
url_concat(git_url, params), validate_cert=True, user_agent="JupyterLab Pull Requests", method="POST", body=json.dumps(body)
)
else:
raise ValueError()
except:
HTTPError(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
reason=f"Invalid call_github '{method}': {e}"
)
try:
response = yield self.client.fetch(request)
result = response.body.decode("utf-8")
if load_json:
return json.loads(result)
else:
return result
except HTTPClientError as e:
raise HTTPError(
status_code=e.code,
reason=f"Invalid response in '{git_url}': {e}"
)
except ValueError as e:
raise HTTPError(
status_code=HTTPStatus.BAD_REQUEST,
reason=f"Invalid response in '{git_url}': {e}"
)
except Exception as e:
raise HTTPError(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
reason=f"Unknown error in '{git_url}': {e}"
) | jupyterlab_pullrequests/github_manager.py | import json
from http import HTTPStatus
import tornado.gen as gen
from jupyterlab_pullrequests.manager import PullRequestsManager
from notebook.utils import url_path_join
from tornado.httpclient import AsyncHTTPClient, HTTPClientError, HTTPRequest
from tornado.httputil import url_concat
from tornado.web import HTTPError
GITHUB_API_BASE_URL = "https://api.github.com"
class PullRequestsGithubManager(PullRequestsManager):
# -----------------------------------------------------------------------------
# /pullrequests/prs/user Handler
# -----------------------------------------------------------------------------
@gen.coroutine
def get_current_user(self):
if not self.access_token:
raise HTTPError(
status_code=HTTPStatus.BAD_REQUEST,
reason="No Github access token specified."
)
git_url = url_path_join(GITHUB_API_BASE_URL, "user")
data = yield self.call_github(git_url)
return {'username': data["login"]}
def get_search_filter(self, username, pr_filter):
if pr_filter == "created":
search_filter = "+author:"
elif pr_filter == "assigned":
search_filter = "+assignee:"
return search_filter + username
@gen.coroutine
def list_prs(self, username, pr_filter):
search_filter = self.get_search_filter(username, pr_filter)
# Use search API to find matching PRs and return
git_url = url_path_join(
GITHUB_API_BASE_URL, "/search/issues?q=+state:open+type:pr" + search_filter
)
results = yield self.call_github(git_url)
data = []
for result in results["items"]:
data.append({
'id': result["pull_request"]["url"],
'title': result["title"],
'body': result["body"],
'internal_id': result["id"],
'url': result["html_url"]
})
return data
# -----------------------------------------------------------------------------
# /pullrequests/prs/files Handler
# -----------------------------------------------------------------------------
@gen.coroutine
def list_files(self, pr_id):
git_url = url_path_join(pr_id, "/files")
results = yield self.call_github(git_url)
data = []
for result in results:
data.append({
'name': result["filename"],
'status': result["status"],
'additions': result["additions"],
'deletions': result["deletions"]
})
return data
# -----------------------------------------------------------------------------
# /pullrequests/files/content Handler
# -----------------------------------------------------------------------------
@gen.coroutine
def get_pr_links(self, pr_id, filename):
data = yield self.call_github(pr_id)
base_url = url_concat(url_path_join(data["base"]["repo"]["url"],"contents",filename), {"ref": data["base"]["ref"]})
head_url = url_concat(url_path_join(data["head"]["repo"]["url"],"contents",filename), {"ref": data["head"]["ref"]})
commit_id = data["head"]["sha"]
return {'base_url':base_url, 'head_url':head_url, 'commit_id':commit_id}
@gen.coroutine
def validate_pr_link(self, link):
try:
data = yield self.call_github(link)
return data["download_url"]
except HTTPError as e:
if e.status_code == 404:
return ""
else:
raise e
@gen.coroutine
def get_link_content(self, file_url):
if (file_url == ""):
return ""
result = yield self.call_github(file_url, False)
return result
@gen.coroutine
def get_file_content(self, pr_id, filename):
links = yield self.get_pr_links(pr_id, filename)
base_raw_url = yield self.validate_pr_link(links["base_url"])
head_raw_url = yield self.validate_pr_link(links["head_url"])
base_content = yield self.get_link_content(base_raw_url)
head_content = yield self.get_link_content(head_raw_url)
return {'base_content':base_content, 'head_content':head_content, 'commit_id':links["commit_id"]}
# -----------------------------------------------------------------------------
# /pullrequests/files/comments Handler
# -----------------------------------------------------------------------------
def file_comment_response(self, result):
data = {
'id': result["id"],
'line_number': result["position"],
'text': result["body"],
'updated_at': result["updated_at"],
'user_name': result["user"]["login"],
'user_pic': result["user"]["avatar_url"]
}
if 'in_reply_to_id' in result:
data['in_reply_to_id'] = result["in_reply_to_id"]
return data
@gen.coroutine
def get_file_comments(self, pr_id, filename):
git_url = url_path_join(pr_id, "/comments")
results = yield self.call_github(git_url)
return [self.file_comment_response(result) for result in results if result["path"] == filename]
@gen.coroutine
def post_file_comment(self, pr_id, filename, body):
if type(body).__name__ == 'PRCommentReply':
body = {"body": body.text, "in_reply_to": body.in_reply_to}
else:
body = {"body": body.text, "commit_id": body.commit_id, "path": body.filename, "position": body.position}
git_url = url_path_join(pr_id,"comments")
response = yield self.call_github(git_url, method="POST", body=body)
return self.file_comment_response(response)
# -----------------------------------------------------------------------------
# Handler utilities
# -----------------------------------------------------------------------------
@gen.coroutine
def call_github(self, git_url, load_json=True, method="GET", body=None):
params = {"Accept": "application/vnd.github.v3+json", "access_token": self.access_token}
# User agents required for Github API, see https://developer.github.com/v3/#user-agent-required
try:
if method.lower() == "get":
request = HTTPRequest(
url_concat(git_url, params), validate_cert=True, user_agent="JupyterLab Pull Requests"
)
elif method.lower() == "post":
request = HTTPRequest(
url_concat(git_url, params), validate_cert=True, user_agent="JupyterLab Pull Requests", method="POST", body=json.dumps(body)
)
else:
raise ValueError()
except:
HTTPError(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
reason=f"Invalid call_github '{method}': {e}"
)
try:
response = yield self.client.fetch(request)
result = response.body.decode("utf-8")
if load_json:
return json.loads(result)
else:
return result
except HTTPClientError as e:
raise HTTPError(
status_code=e.code,
reason=f"Invalid response in '{git_url}': {e}"
)
except ValueError as e:
raise HTTPError(
status_code=HTTPStatus.BAD_REQUEST,
reason=f"Invalid response in '{git_url}': {e}"
)
except Exception as e:
raise HTTPError(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
reason=f"Unknown error in '{git_url}': {e}"
) | 0.344554 | 0.076857 |
import os
import sys
import time
import codecs
from logging import FileHandler
import logging.config
basedir = os.path.abspath(os.path.dirname(__file__))
logdir = os.path.join(basedir, 'logs')
logini_path = os.path.join(basedir, 'log.ini')
if not os.path.exists(logdir):
os.mkdir(logdir)
class SafeFileHandler(FileHandler):
def __init__(self, filename, mode, encoding=None, delay=0):
"""
Use the specified filename for streamed logging
"""
if codecs is None:
encoding = None
FileHandler.__init__(self, filename, mode, encoding, delay)
self.mode = mode
self.encoding = encoding
self.suffix = "%Y-%m-%d"
self.suffix_time = ""
self.delay = delay
def emit(self, record):
"""
Emit a record.
Always check time
"""
try:
if self.check_baseFilename(record):
self.build_baseFilename()
FileHandler.emit(self, record)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def check_baseFilename(self, record):
"""
Determine if builder should occur.
record is not used, as we are just comparing times,
but it is needed so the method signatures are the same
"""
timeTuple = time.localtime()
if (self.suffix_time != time.strftime(self.suffix, timeTuple) or not
os.path.exists(self.baseFilename+'.'+self.suffix_time)):
return 1
else:
return 0
def build_baseFilename(self):
"""
do builder; in this case,
old time stamp is removed from filename and
a new time stamp is append to the filename
"""
if self.stream:
self.stream.close()
self.stream = None
# remove old suffix
if self.suffix_time != "":
index = self.baseFilename.find("."+self.suffix_time)
if index == -1:
index = self.baseFilename.rfind(".")
self.baseFilename = self.baseFilename[:index]
# add new suffix
currentTimeTuple = time.localtime()
self.suffix_time = time.strftime(self.suffix, currentTimeTuple)
self.baseFilename = self.baseFilename + "." + self.suffix_time
self.mode = 'a'
if not self.delay:
self.stream = self._open()
logging.config.fileConfig(logini_path)
logger = logging.getLogger('metadataserver')
# taken from https://stackoverflow.com/questions/6234405/logging-uncaught-exceptions-in-python
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
else:
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
sys.excepthook = handle_exception | wait/autotest.2020.03.16/log.py |
import os
import sys
import time
import codecs
from logging import FileHandler
import logging.config
basedir = os.path.abspath(os.path.dirname(__file__))
logdir = os.path.join(basedir, 'logs')
logini_path = os.path.join(basedir, 'log.ini')
if not os.path.exists(logdir):
os.mkdir(logdir)
class SafeFileHandler(FileHandler):
def __init__(self, filename, mode, encoding=None, delay=0):
"""
Use the specified filename for streamed logging
"""
if codecs is None:
encoding = None
FileHandler.__init__(self, filename, mode, encoding, delay)
self.mode = mode
self.encoding = encoding
self.suffix = "%Y-%m-%d"
self.suffix_time = ""
self.delay = delay
def emit(self, record):
"""
Emit a record.
Always check time
"""
try:
if self.check_baseFilename(record):
self.build_baseFilename()
FileHandler.emit(self, record)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def check_baseFilename(self, record):
"""
Determine if builder should occur.
record is not used, as we are just comparing times,
but it is needed so the method signatures are the same
"""
timeTuple = time.localtime()
if (self.suffix_time != time.strftime(self.suffix, timeTuple) or not
os.path.exists(self.baseFilename+'.'+self.suffix_time)):
return 1
else:
return 0
def build_baseFilename(self):
"""
do builder; in this case,
old time stamp is removed from filename and
a new time stamp is append to the filename
"""
if self.stream:
self.stream.close()
self.stream = None
# remove old suffix
if self.suffix_time != "":
index = self.baseFilename.find("."+self.suffix_time)
if index == -1:
index = self.baseFilename.rfind(".")
self.baseFilename = self.baseFilename[:index]
# add new suffix
currentTimeTuple = time.localtime()
self.suffix_time = time.strftime(self.suffix, currentTimeTuple)
self.baseFilename = self.baseFilename + "." + self.suffix_time
self.mode = 'a'
if not self.delay:
self.stream = self._open()
logging.config.fileConfig(logini_path)
logger = logging.getLogger('metadataserver')
# taken from https://stackoverflow.com/questions/6234405/logging-uncaught-exceptions-in-python
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
else:
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
sys.excepthook = handle_exception | 0.342242 | 0.051106 |
from bs4 import BeautifulSoup
import logging
import time
import tweepy
import requests
from conf import settings
from services.twitter import config
log = logging.getLogger()
def send_tweets(tweets, delay):
"""
:param tweets:
:param delay:
:return:
"""
twitter_api = config.create_api()
for tweet in tweets:
try:
if twitter_api.update_status(tweet):
log.info('Tweet posted')
except tweepy.error.TweepError as e:
log.exception(e)
time.sleep(delay)
def get_twitter_element(url, element):
"""
:return:
"""
headers = requests.utils.default_headers()
headers.update(
{ 'User-Agent': settings.USER_AGENT,
}
)
session = requests.Session()
response = session.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
element_class = soup.find_all('meta', attrs={"name": element})
if not element_class:
logging.error('No Twitter image found in {}'.format(url))
return
twitter_element = element_class[0].get('content')
if not twitter_element:
logging.warning('Element: {} not found'.format(element))
return twitter_element
def add_hash_tags(tweet, entities):
"""For all entities add hashtags to words.
Example:
tweet: Thai startup Lightnet, which aims to provide remittance services in Southeast Asia through its Stellar based blockchain network, raises $31.2M Series A
entities: return {'persons': [], 'organizations': ['Lightnet', 'Stellar', 'blockchain']}
for _,
:param tweet:
:param entities:
:return:
"""
if tweet is None:
raise ValueError('No tweet defined')
if entities is None:
raise ValueError('No entities defined')
persons = list(entities.values())[0] or []
organizations = list(entities.values())[1] or []
for person in persons:
tweet = tweet.replace(person, '#{}'.format(person))
for organization in organizations:
tweet = tweet.replace(organization, '#{}'.format(organization))
return tweet | services/twitter/utils.py |
from bs4 import BeautifulSoup
import logging
import time
import tweepy
import requests
from conf import settings
from services.twitter import config
log = logging.getLogger()
def send_tweets(tweets, delay):
"""
:param tweets:
:param delay:
:return:
"""
twitter_api = config.create_api()
for tweet in tweets:
try:
if twitter_api.update_status(tweet):
log.info('Tweet posted')
except tweepy.error.TweepError as e:
log.exception(e)
time.sleep(delay)
def get_twitter_element(url, element):
"""
:return:
"""
headers = requests.utils.default_headers()
headers.update(
{ 'User-Agent': settings.USER_AGENT,
}
)
session = requests.Session()
response = session.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
element_class = soup.find_all('meta', attrs={"name": element})
if not element_class:
logging.error('No Twitter image found in {}'.format(url))
return
twitter_element = element_class[0].get('content')
if not twitter_element:
logging.warning('Element: {} not found'.format(element))
return twitter_element
def add_hash_tags(tweet, entities):
"""For all entities add hashtags to words.
Example:
tweet: Thai startup Lightnet, which aims to provide remittance services in Southeast Asia through its Stellar based blockchain network, raises $31.2M Series A
entities: return {'persons': [], 'organizations': ['Lightnet', 'Stellar', 'blockchain']}
for _,
:param tweet:
:param entities:
:return:
"""
if tweet is None:
raise ValueError('No tweet defined')
if entities is None:
raise ValueError('No entities defined')
persons = list(entities.values())[0] or []
organizations = list(entities.values())[1] or []
for person in persons:
tweet = tweet.replace(person, '#{}'.format(person))
for organization in organizations:
tweet = tweet.replace(organization, '#{}'.format(organization))
return tweet | 0.380183 | 0.081337 |
from django.conf import settings
from django.contrib import admin
from django.db.models import JSONField
from django import forms
from django.utils.html import mark_safe
from django_json_widget.widgets import JSONEditorWidget
from worlds.models import Pipeline, Job, StreamLog, CompletedLog, Cluster, NodePool
class PoolInline(admin.StackedInline):
model = NodePool
extra = 0
@admin.register(Cluster)
class ClusterAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
search_fields = ('name', 'slug')
save_as = True
inlines = [PoolInline]
@admin.register(Pipeline)
class PipelineAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'workers')
search_fields = ('name', 'slug', 'worker_command')
save_as = True
raw_id_fields = ('cluster',)
formfield_overrides = {
JSONField: {'widget': JSONEditorWidget()},
}
@admin.register(Job)
class JobAdmin(admin.ModelAdmin):
list_display = ('name', '_image', 'parallelism', 'succeeded', 'failed', 'status', 'created', '_actions')
list_filter = ('status', 'modified', 'created')
search_fields = ('command', 'image', 'job_name')
formfield_overrides = {
JSONField: {'widget': JSONEditorWidget(options={'mode': 'view'})},
}
raw_id_fields = ('pipeline',)
readonly_fields = ('succeeded', 'failed', 'status')
def _actions(self, obj):
if obj:
return mark_safe(f'<a href="/worlds/job/{obj.id}/" target="_blank">view</a>')
def _image(self, obj):
img = obj.image
if settings.CONTAINER_REPO:
img = img.replace(settings.CONTAINER_REPO + '/', '')
img = img.split(':')
if len(img) > 1:
img[-1] = img[-1][:8]
return ":".join(img)
@admin.register(CompletedLog)
class CompletedLogAdmin(admin.ModelAdmin):
list_display= ('name', 'job', 'created')
search_fields = ('pod', 'job__job_name')
date_hierarchy = 'created'
raw_id_fields = ('job',)
@admin.register(StreamLog)
class StreamLogAdmin(admin.ModelAdmin):
list_display= ('pod', 'job', 'lines', 'status', 'modified')
search_fields = ('pod', 'job__job_name')
date_hierarchy = 'modified'
raw_id_fields = ('job',) | worlds/admin.py | from django.conf import settings
from django.contrib import admin
from django.db.models import JSONField
from django import forms
from django.utils.html import mark_safe
from django_json_widget.widgets import JSONEditorWidget
from worlds.models import Pipeline, Job, StreamLog, CompletedLog, Cluster, NodePool
class PoolInline(admin.StackedInline):
model = NodePool
extra = 0
@admin.register(Cluster)
class ClusterAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
search_fields = ('name', 'slug')
save_as = True
inlines = [PoolInline]
@admin.register(Pipeline)
class PipelineAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'workers')
search_fields = ('name', 'slug', 'worker_command')
save_as = True
raw_id_fields = ('cluster',)
formfield_overrides = {
JSONField: {'widget': JSONEditorWidget()},
}
@admin.register(Job)
class JobAdmin(admin.ModelAdmin):
list_display = ('name', '_image', 'parallelism', 'succeeded', 'failed', 'status', 'created', '_actions')
list_filter = ('status', 'modified', 'created')
search_fields = ('command', 'image', 'job_name')
formfield_overrides = {
JSONField: {'widget': JSONEditorWidget(options={'mode': 'view'})},
}
raw_id_fields = ('pipeline',)
readonly_fields = ('succeeded', 'failed', 'status')
def _actions(self, obj):
if obj:
return mark_safe(f'<a href="/worlds/job/{obj.id}/" target="_blank">view</a>')
def _image(self, obj):
img = obj.image
if settings.CONTAINER_REPO:
img = img.replace(settings.CONTAINER_REPO + '/', '')
img = img.split(':')
if len(img) > 1:
img[-1] = img[-1][:8]
return ":".join(img)
@admin.register(CompletedLog)
class CompletedLogAdmin(admin.ModelAdmin):
list_display= ('name', 'job', 'created')
search_fields = ('pod', 'job__job_name')
date_hierarchy = 'created'
raw_id_fields = ('job',)
@admin.register(StreamLog)
class StreamLogAdmin(admin.ModelAdmin):
list_display= ('pod', 'job', 'lines', 'status', 'modified')
search_fields = ('pod', 'job__job_name')
date_hierarchy = 'modified'
raw_id_fields = ('job',) | 0.361277 | 0.075142 |
import os
from keystoneauth1.identity import v2
from keystoneauth1.identity import v3
from keystoneauth1 import session
# Assumes openrc file is sourced.
class Credentials(object):
def __init__(self):
self.password = None
self.username = None
self.tenant_name = None
self.auth_url = None
self.cacert = None
self.region_name = None
self.user_domain_name = None
self.project_domain_name = None
self.project_name = None
self.identity_api_version = 2
success = True
if 'OS_IDENTITY_API_VERSION' in os.environ:
self.identity_api_version = int(os.environ['OS_IDENTITY_API_VERSION'])
if self.identity_api_version == 2:
for varname in ['OS_USERNAME', 'OS_AUTH_URL', 'OS_TENANT_NAME']:
if varname not in os.environ:
success = False
if success:
self.username = os.environ['OS_USERNAME']
self.auth_url = os.environ['OS_AUTH_URL']
self.tenant_name = os.environ['OS_TENANT_NAME']
if 'OS_REGION_NAME' in os.environ:
self.region_name = os.environ['OS_REGION_NAME']
elif self.identity_api_version == 3:
self.username = os.environ['OS_USERNAME']
self.auth_url = os.environ['OS_AUTH_URL']
self.project_name = os.environ['OS_PROJECT_NAME']
self.project_domain_name = os.environ['OS_PROJECT_DOMAIN_NAME']
self.user_domain_name = os.environ['OS_USER_DOMAIN_NAME']
if 'OS_CACERT' in os.environ:
self.cacert = os.environ['OS_CACERT']
if 'OS_PASSWORD' in os.environ:
self.password = os.environ['OS_PASSWORD']
def get_session(self):
dct = {
'username': self.username,
'password': <PASSWORD>,
'auth_url': self.auth_url
}
auth = None
if self.identity_api_version == 3:
dct.update({
'project_name': self.project_name,
'project_domain_name': self.project_domain_name,
'user_domain_name': self.user_domain_name
})
auth = v3.Password(**dct)
else:
dct.update({
'tenant_name': self.tenant_name
})
auth = v2.Password(**dct)
return session.Session(auth=auth, verify=self.cacert) | openstack_client/cloud_orchestrator/credentials.py |
import os
from keystoneauth1.identity import v2
from keystoneauth1.identity import v3
from keystoneauth1 import session
# Assumes openrc file is sourced.
class Credentials(object):
def __init__(self):
self.password = None
self.username = None
self.tenant_name = None
self.auth_url = None
self.cacert = None
self.region_name = None
self.user_domain_name = None
self.project_domain_name = None
self.project_name = None
self.identity_api_version = 2
success = True
if 'OS_IDENTITY_API_VERSION' in os.environ:
self.identity_api_version = int(os.environ['OS_IDENTITY_API_VERSION'])
if self.identity_api_version == 2:
for varname in ['OS_USERNAME', 'OS_AUTH_URL', 'OS_TENANT_NAME']:
if varname not in os.environ:
success = False
if success:
self.username = os.environ['OS_USERNAME']
self.auth_url = os.environ['OS_AUTH_URL']
self.tenant_name = os.environ['OS_TENANT_NAME']
if 'OS_REGION_NAME' in os.environ:
self.region_name = os.environ['OS_REGION_NAME']
elif self.identity_api_version == 3:
self.username = os.environ['OS_USERNAME']
self.auth_url = os.environ['OS_AUTH_URL']
self.project_name = os.environ['OS_PROJECT_NAME']
self.project_domain_name = os.environ['OS_PROJECT_DOMAIN_NAME']
self.user_domain_name = os.environ['OS_USER_DOMAIN_NAME']
if 'OS_CACERT' in os.environ:
self.cacert = os.environ['OS_CACERT']
if 'OS_PASSWORD' in os.environ:
self.password = os.environ['OS_PASSWORD']
def get_session(self):
dct = {
'username': self.username,
'password': <PASSWORD>,
'auth_url': self.auth_url
}
auth = None
if self.identity_api_version == 3:
dct.update({
'project_name': self.project_name,
'project_domain_name': self.project_domain_name,
'user_domain_name': self.user_domain_name
})
auth = v3.Password(**dct)
else:
dct.update({
'tenant_name': self.tenant_name
})
auth = v2.Password(**dct)
return session.Session(auth=auth, verify=self.cacert) | 0.247351 | 0.048677 |
from spectre.readers import get_chromophore_peex_data
def test_m0_reader():
filename = "test/m0"
erg1, trd1, trm1, mo = get_chromophore_peex_data(filename, False)
assert type(erg1) == list
assert len(erg1) == 4
assert len(erg1) == len(trd1)
assert type(trm1) == dict
assert mo == -1 # no moments
assert abs(trd1[3][2] - 2.08899512e-02) < 1.0e-9 # checking on the last item in the list of transition dipoles
# now read again, but this time read the m0 moments too
erg2, trd2, trm2, mo = get_chromophore_peex_data(filename, True)
assert len(erg2) == len(erg1)
for e1, e2 in zip(erg1, erg2):
assert abs(e2 - e1) < 1.0e-9
assert type(trm2) == dict
assert mo == 0 # charges
assert "charges" in trm2
tr_q = trm2["charges"]
assert len(tr_q) == len(erg2)
assert abs(tr_q[2][0] - (-0.566597)) < 1.0e-9 # the 3rd excitation first charge
def test_m1_reader():
filename = "test/m1"
erg1, trd1, trm1, mo = get_chromophore_peex_data(filename, False)
assert type(erg1) == list
assert len(erg1) == 4
assert len(erg1) == len(trd1)
assert type(trm1) == dict
assert mo == -1 # no moments
assert abs(trd1[0][0] - 1.50505287e-02) < 1.0e-9 # checking on the first item in the list of transition dipoles
# now read again, but this time read the m0 and m1 moments too
erg2, trd2, trm2, mo = get_chromophore_peex_data(filename, True)
assert mo == 1 # dipoles
assert "charges" in trm2
tr_q = trm2["charges"]
assert len(tr_q) == len(erg2)
assert abs(tr_q[0][1] - 0.003357) < 1.0e-9 # the 1st excitation, 2nd atom charge
assert "dipoles" in trm2
tr_d = trm2["dipoles"]
assert len(tr_d) == len(erg2)
for i in range(len(tr_d)):
assert len(tr_d[i]) == 3 # number of atoms
for j in range(len(tr_d[i])):
assert len(tr_d[i][j]) == 3
assert abs(tr_d[1][1][1] - 0.013144) < 1.0e-9 # 2nd excitation, 2nd atom, 2nd element of dipole
def test_m2_reader():
filename = "test/m2"
erg1, trd1, trm1, mo = get_chromophore_peex_data(filename, False)
assert type(erg1) == list
assert len(erg1) == 4
assert len(erg1) == len(trd1)
assert type(trm1) == dict
assert mo == -1 # no moments
assert abs(trd1[2][1] - 6.28123166e-02) < 1.0e-9 # checking on the first item in the list of transition dipoles
# now read again, but this time read the m0 and m1 moments too
erg2, trd2, trm2, mo = get_chromophore_peex_data(filename, True)
assert mo == 2 # quadrupoles
assert "charges" in trm2
tr_q = trm2["charges"]
assert len(tr_q) == len(erg2)
assert abs(tr_q[0][1] - (-0.473546)) < 1.0e-9 # the 1st excitation, 2nd atom charge
assert "dipoles" in trm2
tr_d = trm2["dipoles"]
assert len(tr_d) == len(erg2)
assert abs(tr_d[1][2][2] - 0.163796) < 1.0e-9 # 2nd excitation, 3nd atom, 3nd element of dipole
assert "quadrupoles" in trm2
tr_quad = trm2["quadrupoles"]
assert len(tr_quad) == len(erg2)
for i in range(len(tr_quad)):
assert len(tr_quad[i]) == 3 # number of atoms
for j in range(len(tr_quad[i])):
assert len(tr_quad[i][j]) == 6
assert abs(tr_quad[2][0][5] - (-0.279883)) < 1.0e-9 # 3rd excitation, 1st atom, 6th element of quad tensor
assert abs(tr_quad[3][0][0] - 0.266974) < 1.0e-9 # 3rd excitation, 1st atom, 6th element of quad tensor | test/test_readers.py | from spectre.readers import get_chromophore_peex_data
def test_m0_reader():
filename = "test/m0"
erg1, trd1, trm1, mo = get_chromophore_peex_data(filename, False)
assert type(erg1) == list
assert len(erg1) == 4
assert len(erg1) == len(trd1)
assert type(trm1) == dict
assert mo == -1 # no moments
assert abs(trd1[3][2] - 2.08899512e-02) < 1.0e-9 # checking on the last item in the list of transition dipoles
# now read again, but this time read the m0 moments too
erg2, trd2, trm2, mo = get_chromophore_peex_data(filename, True)
assert len(erg2) == len(erg1)
for e1, e2 in zip(erg1, erg2):
assert abs(e2 - e1) < 1.0e-9
assert type(trm2) == dict
assert mo == 0 # charges
assert "charges" in trm2
tr_q = trm2["charges"]
assert len(tr_q) == len(erg2)
assert abs(tr_q[2][0] - (-0.566597)) < 1.0e-9 # the 3rd excitation first charge
def test_m1_reader():
filename = "test/m1"
erg1, trd1, trm1, mo = get_chromophore_peex_data(filename, False)
assert type(erg1) == list
assert len(erg1) == 4
assert len(erg1) == len(trd1)
assert type(trm1) == dict
assert mo == -1 # no moments
assert abs(trd1[0][0] - 1.50505287e-02) < 1.0e-9 # checking on the first item in the list of transition dipoles
# now read again, but this time read the m0 and m1 moments too
erg2, trd2, trm2, mo = get_chromophore_peex_data(filename, True)
assert mo == 1 # dipoles
assert "charges" in trm2
tr_q = trm2["charges"]
assert len(tr_q) == len(erg2)
assert abs(tr_q[0][1] - 0.003357) < 1.0e-9 # the 1st excitation, 2nd atom charge
assert "dipoles" in trm2
tr_d = trm2["dipoles"]
assert len(tr_d) == len(erg2)
for i in range(len(tr_d)):
assert len(tr_d[i]) == 3 # number of atoms
for j in range(len(tr_d[i])):
assert len(tr_d[i][j]) == 3
assert abs(tr_d[1][1][1] - 0.013144) < 1.0e-9 # 2nd excitation, 2nd atom, 2nd element of dipole
def test_m2_reader():
filename = "test/m2"
erg1, trd1, trm1, mo = get_chromophore_peex_data(filename, False)
assert type(erg1) == list
assert len(erg1) == 4
assert len(erg1) == len(trd1)
assert type(trm1) == dict
assert mo == -1 # no moments
assert abs(trd1[2][1] - 6.28123166e-02) < 1.0e-9 # checking on the first item in the list of transition dipoles
# now read again, but this time read the m0 and m1 moments too
erg2, trd2, trm2, mo = get_chromophore_peex_data(filename, True)
assert mo == 2 # quadrupoles
assert "charges" in trm2
tr_q = trm2["charges"]
assert len(tr_q) == len(erg2)
assert abs(tr_q[0][1] - (-0.473546)) < 1.0e-9 # the 1st excitation, 2nd atom charge
assert "dipoles" in trm2
tr_d = trm2["dipoles"]
assert len(tr_d) == len(erg2)
assert abs(tr_d[1][2][2] - 0.163796) < 1.0e-9 # 2nd excitation, 3nd atom, 3nd element of dipole
assert "quadrupoles" in trm2
tr_quad = trm2["quadrupoles"]
assert len(tr_quad) == len(erg2)
for i in range(len(tr_quad)):
assert len(tr_quad[i]) == 3 # number of atoms
for j in range(len(tr_quad[i])):
assert len(tr_quad[i][j]) == 6
assert abs(tr_quad[2][0][5] - (-0.279883)) < 1.0e-9 # 3rd excitation, 1st atom, 6th element of quad tensor
assert abs(tr_quad[3][0][0] - 0.266974) < 1.0e-9 # 3rd excitation, 1st atom, 6th element of quad tensor | 0.545044 | 0.803135 |
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib
class ParameterScan (object):
def __init__(self, rr):
self.startTime = 0
self.endTime = 20
self.numberOfPoints = 50
self.polyNumber = 10
self.startValue = None
self.endValue = None
self.value = None
self.independent = None
self.selection = None
self.dependent = None
self.integrator = "cvode"
self.rr = rr
self.color = None
self.width = 2.5
self.alpha = 0.7
self.title = None
self.xlabel = 'toSet'
self.ylabel = 'toSet'
self.zlabel = 'toSet'
self.colormap = "seismic"
self.colorbar = True
self.antialias = True
self.sameColor = False
self.legend = True
def sim(self):
"""Runs a simulation and returns the result for a plotting function. Not intended to
be called by user."""
mdl = self.rr.model
if self.selection is None:
result = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints, integrator = self.integrator)
else:
if not isinstance(self.selection, list):
self.selection = [self.selection]
if 'time' not in [item.lower() for item in self.selection]:
self.selection = ['time'] + self.selection
for item in self.selection:
if item not in mdl.getFloatingSpeciesIds() and item not in mdl.getBoundarySpeciesIds():
if item.lower() != 'time':
raise ValueError('"{0}" is not a valid species in loaded model'.format(item))
result = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
self.selection, integrator = self.integrator)
return result
def plotArray(self):
"""Plots result of simulation with options for linewdith and line color.
p.plotArray()"""
result = self.sim()
if self.color is None:
for species in self.rr.timeCourseSelections[1:]:
plt.plot(result[:,0], result[species], linewidth = self.width, label = species)
else:
if len(self.color) != result.shape[1]:
self.color = self.colorCycle()
for i in range(result.shape[1] - 1):
plt.plot(result[:,0], result[:,i+1], color = self.color[i],
linewidth = self.width, label = self.rr.timeCourseSelections[i+1])
if self.xlabel == 'toSet':
plt.xlabel('time')
elif self.xlabel:
plt.xlabel(self.xlabel)
if self.ylabel == 'toSet':
plt.ylabel('concentration')
elif self.ylabel:
plt.ylabel(self.ylabel)
if self.title is not None:
plt.suptitle(self.title)
if self.legend:
plt.legend()
plt.show()
def graduatedSim(self):
"""Runs successive simulations with incremental changes in one species, and returns
results for a plotting function. Not intended to be called by user."""
mdl = self.rr.model
if self.value is None:
self.value = mdl.getFloatingSpeciesIds()[0]
print 'Warning: self.value not set. Using self.value = {0}'.format(self.value)
elif not isinstance(self.value, str):
raise ValueError('self.value must be a string')
elif self.value not in mdl.getFloatingSpeciesIds() and self.value not in mdl.getBoundarySpeciesIds():
if self.value not in mdl.getGlobalParameterIds():
raise ValueError('self.value "{0}" cannot be found in loaded model'.format(self.value))
if self.startValue is None:
self.startValue = mdl[self.value]
else:
self.startValue = float(self.startValue)
if self.endValue is None:
self.endValue = self.startValue + 5
else:
self.endValue = float(self.endValue)
if self.selection is None:
self.selection = [mdl.getFloatingSpeciesIds()[0]]
else:
if not isinstance(self.selection, list):
self.selection = [self.selection]
for item in self.selection:
if item.lower() == 'time':
self.selection.remove(item)
if not isinstance(item, str) or (item not in mdl.getFloatingSpeciesIds() and item not in mdl.getBoundarySpeciesIds()):
if item.lower() != 'time':
raise ValueError('{0} cannot be found in loaded model'.format(item))
self.selection = ['time'] + self.selection
polyNumber = float(self.polyNumber)
mdl[self.value] = self.startValue
m = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
self.selection, integrator = self.integrator)
interval = ((self.endValue - self.startValue) / (polyNumber - 1))
start = self.startValue
while start < self.endValue - .00001:
self.rr.reset()
start += interval
mdl[self.value] = start
m1 = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
self.selection, integrator = self.integrator)
m1 = np.delete(m1, 0, 1)
m = np.hstack((m, m1))
return m
def plotGraduatedArray(self):
"""Plots array with either default multiple colors or user sepcified colors using
results from graduatedSim().
p.plotGraduatedArray()"""
result = self.graduatedSim()
interval = ((self.endValue - self.startValue) / (self.polyNumber - 1))
numSp = len(self.selection) - 1
if self.color is None and self.sameColor is True:
count = 1
for species in self.selection[1:]:
for i in range(self.polyNumber):
if numSp > 1:
lbl = "{0}, {1} = {2}".format(species, self.value, round((self.startValue + (interval * i)), 2))
else:
lbl = "{0} = {1}".format(self.value, round((self.startValue + (interval * i)), 2))
plt.plot(result[:,0], result[:,numSp*i+count], linewidth = self.width, color = 'b', label = lbl)
count += 1
elif self.color is None:
count = 1
for species in self.selection[1:]:
for i in range(self.polyNumber):
if numSp > 1:
lbl = "{0}, {1} = {2}".format(species, self.value, round((self.startValue + (interval * i)), 2))
else:
lbl = "{0} = {1}".format(self.value, round((self.startValue + (interval * i)), 2))
plt.plot(result[:,0], result[:,numSp*i+count], linewidth = self.width, label = lbl)
count += 1
else:
if len(self.color) != self.polyNumber:
self.color = self.colorCycle()
count = 1
for species in self.selection[1:]:
for i in range(self.polyNumber):
if numSp > 1:
lbl = "{0}, {1} = {2}".format(species, self.value, round((self.startValue + (interval * i)), 2))
else:
lbl = "{0} = {1}".format(self.value, round((self.startValue + (interval * i)), 2))
plt.plot(result[:,0], result[:,numSp*i+count], color = self.color[i],
linewidth = self.width, label = lbl)
count += 1
if self.title is not None:
plt.suptitle(self.title)
if self.xlabel == 'toSet':
plt.xlabel('time')
elif self.xlabel:
plt.xlabel(self.xlabel)
if self.ylabel == 'toSet':
plt.ylabel('concentration')
elif self.ylabel:
plt.ylabel(self.ylabel)
if self.legend:
plt.legend()
plt.show()
def plotPolyArray(self):
"""Plots results as individual graphs parallel to each other in 3D space using results
from graduatedSim().
p.plotPolyArray()"""
result = self.graduatedSim()
interval = ((self.endValue - self.startValue) / (self.polyNumber - 1))
self.rr.reset()
fig = plt.figure()
ax = fig.gca(projection='3d')
if self.startValue is None:
self.startValue = self.rr.model[self.value]
columnNumber = self.polyNumber + 1
lastPoint = [self.endTime]
firstPoint = [self.startTime]
for i in range(int(columnNumber) - 1):
lastPoint.append(0)
firstPoint.append(0)
lastPoint = np.array(lastPoint)
firstPoint = np.array(firstPoint)
zresult = np.vstack((result, lastPoint))
zresult = np.vstack((firstPoint, zresult))
zs = []
result = []
for i in range(int(columnNumber)-1):
zs.append(i)
result.append(zip(zresult[:,0], zresult[:,(i+1)]))
if self.color is None:
poly = PolyCollection(result)
else:
if len(self.color) != self.polyNumber:
self.color = self.colorCycle()
poly = PolyCollection(result, facecolors = self.color, closed = False)
poly.set_alpha(self.alpha)
ax.add_collection3d(poly, zs=zs, zdir='y')
ax.set_xlim3d(0, self.endTime)
ax.set_ylim3d(0, (columnNumber - 1))
ax.set_zlim3d(0, (self.endValue + interval))
if self.xlabel == 'toSet':
ax.set_xlabel('Time')
elif self.xlabel:
ax.set_xlabel(self.xlabel)
if self.ylabel == 'toSet':
ax.set_ylabel('Trial Number')
elif self.ylabel:
ax.set_ylabel(self.ylabel)
if self.zlabel == 'toSet':
ax.set_zlabel(self.value)
elif self.zlabel:
ax.set_zlabel(self.zlabel)
# ax.set_xlabel('Time') if self.xlabel is None else ax.set_xlabel(self.xlabel)
# ax.set_ylabel('Trial Number') if self.ylabel is None else ax.set_ylabel(self.ylabel)
# ax.set_zlabel(self.value) if self.zlabel is None else ax.set_zlabel(self.zlabel)
if self.title is not None:
ax.set_title(self.title)
plt.show()
def plotSurface(self):
""" Plots results of simulation as a colored surface. Takes three variables, two
independent and one dependent. Legal colormap names can be found at
http://matplotlib.org/examples/color/colormaps_reference.html.
p.plotSurface()"""
try:
# if self.independent is None and self.dependent is None:
# self.independent = ['Time']
# defaultParameter = self.rr.model.getGlobalParameterIds()[0]
# self.independent.append(defaultParameter)
# defaultSpecies = self.rr.model.getFloatingSpeciesIds()[0]
# self.dependent = [defaultSpecies]
# print 'Warning: self.independent and self.dependent not set. Using' \
# ' self.independent = %s and self.dependent = %s' % (self.independent, self.dependent)
if self.independent is None:
self.independent = ['Time']
defaultParameter = self.rr.model.getGlobalParameterIds()[0]
self.independent.append(defaultParameter)
print 'Warning: self.independent not set. Using: {0}'.format(self.independent)
if self.dependent is None:
defaultSpecies = self.rr.model.getFloatingSpeciesIds()[0]
self.dependent = defaultSpecies
print 'Warning: self.dependent not set. Using: {0}'.format(self.dependent)
if len(self.independent) < 2:
raise ValueError('self.independent must contain two independent variables')
if not isinstance(self.independent, list):
raise ValueError('self.independent must be a list of strings')
if not isinstance(self.dependent, str):
raise ValueError('self.dependent must be a string')
if self.startValue is None:
if self.independent[0].lower() != 'time':
self.startValue = self.rr.model[self.independent[0]]
else:
self.startValue = self.rr.model[self.independent[1]]
if self.endValue is None:
self.endValue = self.startValue + 5
fig = plt.figure()
ax = fig.gca(projection='3d')
interval = (self.endTime - self.startTime) / float(self.numberOfPoints - 1)
X = np.arange(self.startTime, (self.endTime + (interval - 0.001)), interval)
interval = (self.endValue - self.startValue) / float(self.numberOfPoints - 1)
Y = np.arange(self.startValue, (self.endValue + (interval - 0.001)), interval)
X, Y = np.meshgrid(X, Y)
self.rr.reset()
self.rr.model[self.independent[1]] = self.startValue
Z = self.rr.simulate(self.startTime, self.endTime, (self.numberOfPoints),
[self.dependent], integrator = self.integrator)
Z = Z.T
for i in range(self.numberOfPoints - 1):
self.rr.reset()
self.rr.model[self.independent[1]] = self.startValue + ((i + 1) * interval)
Z1 = self.rr.simulate(self.startTime, self.endTime, (self.numberOfPoints),
[self.dependent], integrator = self.integrator)
Z1 = Z1.T
Z = np.concatenate ((Z, Z1))
if self.antialias is False:
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap = self.colormap,
antialiased = False, linewidth=0)
else:
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap = self.colormap,
linewidth=0)
ax.yaxis.set_major_locator(LinearLocator((6)))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
if self.xlabel == 'toSet':
ax.set_xlabel(self.independent[0])
elif self.xlabel:
ax.set_xlabel(self.xlabel)
if self.ylabel == 'toSet':
ax.set_ylabel(self.independent[1])
elif self.ylabel:
ax.set_ylabel(self.ylabel)
if self.zlabel == 'toSet':
ax.set_zlabel(self.dependent)
elif self.zlabel:
ax.set_zlabel(self.zlabel)
if self.title is not None:
ax.set_title(self.title)
if self.colorbar:
fig.colorbar(surf, shrink=0.5, aspect=4)
plt.show()
except Exception as e:
print 'error: {0}'.format(e.message)
def plotMultiArray(self, param1, param1Range, param2, param2Range):
"""Plots separate arrays for each possible combination of the contents of param1range and
param2range as an array of subplots. The ranges are lists of values that determine the
initial conditions of each simulation.
p.multiArrayPlot('S1', [1, 2, 3], 'S2', [1, 2])"""
mdl = self.rr.model
f, axarr = plt.subplots(
len(param1Range),
len(param2Range),
sharex='col',
sharey='row')
if self.color is None:
self.color = ['b', 'g', 'r', 'k']
for i, k1 in enumerate(param1Range):
for j, k2 in enumerate(param2Range):
self.rr.reset()
mdl[param1], mdl[param2] = k1, k2
if self.selection is None:
result = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
integrator = self.integrator)
else:
if 'time' not in [item.lower() for item in self.selection]:
self.selection = ['time'] + self.selection
for item in self.selection:
if item not in mdl.getFloatingSpeciesIds() and item not in mdl.getBoundarySpeciesIds():
if item.lower() != 'time':
raise ValueError('"{0}" is not a valid species in loaded model'.format(item))
result = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
self.selection, integrator = self.integrator)
columns = result.shape[1]
legendItems = self.rr.timeCourseSelections[1:]
if columns-1 != len(legendItems):
raise Exception('Legend list must match result array')
for c in range(columns-1):
axarr[i, j].plot(
result[:, 0],
result[:, c+1],
linewidth = self.width,
label = legendItems[c])
if (self.legend):
plt.legend(loc= 3, bbox_to_anchor=(0.5, 0.5))
if (i == (len(param1Range) - 1)):
axarr[i, j].set_xlabel('%s = %.2f' % (param2, k2))
if (j == 0):
axarr[i, j].set_ylabel('%s = %.2f' % (param1, k1))
if self.title is not None:
plt.suptitle(self.title)
def createColormap(self, color1, color2):
"""Creates a color map for plotSurface using two colors as RGB tuplets, standard color
names, e.g. 'aqua'; or hex strings.
p.colormap = p.createColorMap([0,0,0], [1,1,1])"""
if isinstance(color1, str) is True:
try:
color1 = matplotlib.colors.colorConverter.to_rgb('%s' % color1)
except ValueError:
print '"{0}" is not a valid color name, using default "blue" instead'.format(color1)
color1 = matplotlib.colors.colorConverter.to_rgb('blue')
if isinstance(color2, str) is True:
try:
color2 = matplotlib.colors.colorConverter.to_rgb('%s' % color2)
except ValueError:
print '"{0}" is not a valid color name, using default "blue" instead'.format(color2)
color2 = matplotlib.colors.colorConverter.to_rgb('blue')
cdict = {'red': ((0., 0., color1[0]),
(1., color2[0], 0.)),
'green': ((0., 0., color1[1]),
(1., color2[1], 0.)),
'blue': ((0., 0., color1[2]),
(1., color2[2], 0.))}
my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)
return my_cmap
def colorCycle(self):
"""Adjusts contents of self.color as needed for plotting methods."""
if len(self.color) < self.polyNumber:
for i in range(self.polyNumber - len(self.color)):
self.color.append(self.color[i])
else:
for i in range(len(self.color) - self.polyNumber):
del self.color[-(i+1)]
return self.color
def createColorPoints(self):
"""Sets self.color to a set of values that allow plotPolyArray, plotArray,
or plotGraduatedArray to take on colors from a colormap. The colormap can either
be user-defined using createColormap or one of the standard colormaps.
p.createColorPoints() """
color = []
interval = 1.0 / self.polyNumber
count = 0
if isinstance(self.colormap, str) is True:
for i in range(self.polyNumber):
color.append(eval('matplotlib.pylab.cm.%s(%s)' % (self.colormap, count)))
count += interval
else:
for i in range(self.polyNumber):
color.append(self.colormap(count))
count += interval
self.color = color
class SteadyStateScan (object):
def __init__(self, rr):
self.startTime = 0
self.endTime = 20
self.numberOfPoints = 50
self.polyNumber = 10
self.startValue = None
self.endValue = None
self.value = None
self.independent = None
self.selection = None
self.dependent = None
self.integrator = "cvode"
self.rr = rr
self.color = None
self.width = 2.5
self.alpha = 0.7
self.title = None
self.xlabel = None
self.ylabel = None
self.zlabel = None
self.colormap = "seismic"
self.colorbar = True
self.antialias = True
self.sameColor = False
def steadyStateSim(self):
if self.value is None:
self.value = self.rr.model.getFloatingSpeciesIds()[0]
print 'Warning: self.value not set. Using self.value = %s' % self.value
if self.startValue is None:
self.startValue = self.rr.model[self.value]
if self.endValue is None:
self.endValue = self.startValue + 5
interval = (float(self.endValue - self.startValue) / float(self.numberOfPoints - 1))
a = []
for i in range(len(self.selection) + 1):
a.append(0.)
result = np.array(a)
start = self.startValue
for i in range(self.numberOfPoints):
self.rr.reset()
start += interval
self.rr.model[self.value] = start
self.rr.steadyState()
b = [self.rr.model[self.value]]
for i in range(len(self.selection)):
b.append(self.rr.model[self.selection[i]])
result = np.vstack((result, b))
result = np.delete(result, 0, 0)
return result
def plotArray(self):
result = self.steadyStateSim()
print result
if self.color is None:
plt.plot(result[:,0], result[:,1:], linewidth = self.width)
else:
if len(self.color) != result.shape[1]:
self.color = self.colorCycle()
for i in range(result.shape[1] - 1):
plt.plot(result[:,0], result[:,i], color = self.color[i], linewidth = self.width) | tellurium/ParameterScan/ParameterScan.py | import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib
class ParameterScan (object):
def __init__(self, rr):
self.startTime = 0
self.endTime = 20
self.numberOfPoints = 50
self.polyNumber = 10
self.startValue = None
self.endValue = None
self.value = None
self.independent = None
self.selection = None
self.dependent = None
self.integrator = "cvode"
self.rr = rr
self.color = None
self.width = 2.5
self.alpha = 0.7
self.title = None
self.xlabel = 'toSet'
self.ylabel = 'toSet'
self.zlabel = 'toSet'
self.colormap = "seismic"
self.colorbar = True
self.antialias = True
self.sameColor = False
self.legend = True
def sim(self):
"""Runs a simulation and returns the result for a plotting function. Not intended to
be called by user."""
mdl = self.rr.model
if self.selection is None:
result = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints, integrator = self.integrator)
else:
if not isinstance(self.selection, list):
self.selection = [self.selection]
if 'time' not in [item.lower() for item in self.selection]:
self.selection = ['time'] + self.selection
for item in self.selection:
if item not in mdl.getFloatingSpeciesIds() and item not in mdl.getBoundarySpeciesIds():
if item.lower() != 'time':
raise ValueError('"{0}" is not a valid species in loaded model'.format(item))
result = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
self.selection, integrator = self.integrator)
return result
def plotArray(self):
"""Plots result of simulation with options for linewdith and line color.
p.plotArray()"""
result = self.sim()
if self.color is None:
for species in self.rr.timeCourseSelections[1:]:
plt.plot(result[:,0], result[species], linewidth = self.width, label = species)
else:
if len(self.color) != result.shape[1]:
self.color = self.colorCycle()
for i in range(result.shape[1] - 1):
plt.plot(result[:,0], result[:,i+1], color = self.color[i],
linewidth = self.width, label = self.rr.timeCourseSelections[i+1])
if self.xlabel == 'toSet':
plt.xlabel('time')
elif self.xlabel:
plt.xlabel(self.xlabel)
if self.ylabel == 'toSet':
plt.ylabel('concentration')
elif self.ylabel:
plt.ylabel(self.ylabel)
if self.title is not None:
plt.suptitle(self.title)
if self.legend:
plt.legend()
plt.show()
def graduatedSim(self):
"""Runs successive simulations with incremental changes in one species, and returns
results for a plotting function. Not intended to be called by user."""
mdl = self.rr.model
if self.value is None:
self.value = mdl.getFloatingSpeciesIds()[0]
print 'Warning: self.value not set. Using self.value = {0}'.format(self.value)
elif not isinstance(self.value, str):
raise ValueError('self.value must be a string')
elif self.value not in mdl.getFloatingSpeciesIds() and self.value not in mdl.getBoundarySpeciesIds():
if self.value not in mdl.getGlobalParameterIds():
raise ValueError('self.value "{0}" cannot be found in loaded model'.format(self.value))
if self.startValue is None:
self.startValue = mdl[self.value]
else:
self.startValue = float(self.startValue)
if self.endValue is None:
self.endValue = self.startValue + 5
else:
self.endValue = float(self.endValue)
if self.selection is None:
self.selection = [mdl.getFloatingSpeciesIds()[0]]
else:
if not isinstance(self.selection, list):
self.selection = [self.selection]
for item in self.selection:
if item.lower() == 'time':
self.selection.remove(item)
if not isinstance(item, str) or (item not in mdl.getFloatingSpeciesIds() and item not in mdl.getBoundarySpeciesIds()):
if item.lower() != 'time':
raise ValueError('{0} cannot be found in loaded model'.format(item))
self.selection = ['time'] + self.selection
polyNumber = float(self.polyNumber)
mdl[self.value] = self.startValue
m = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
self.selection, integrator = self.integrator)
interval = ((self.endValue - self.startValue) / (polyNumber - 1))
start = self.startValue
while start < self.endValue - .00001:
self.rr.reset()
start += interval
mdl[self.value] = start
m1 = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
self.selection, integrator = self.integrator)
m1 = np.delete(m1, 0, 1)
m = np.hstack((m, m1))
return m
def plotGraduatedArray(self):
"""Plots array with either default multiple colors or user sepcified colors using
results from graduatedSim().
p.plotGraduatedArray()"""
result = self.graduatedSim()
interval = ((self.endValue - self.startValue) / (self.polyNumber - 1))
numSp = len(self.selection) - 1
if self.color is None and self.sameColor is True:
count = 1
for species in self.selection[1:]:
for i in range(self.polyNumber):
if numSp > 1:
lbl = "{0}, {1} = {2}".format(species, self.value, round((self.startValue + (interval * i)), 2))
else:
lbl = "{0} = {1}".format(self.value, round((self.startValue + (interval * i)), 2))
plt.plot(result[:,0], result[:,numSp*i+count], linewidth = self.width, color = 'b', label = lbl)
count += 1
elif self.color is None:
count = 1
for species in self.selection[1:]:
for i in range(self.polyNumber):
if numSp > 1:
lbl = "{0}, {1} = {2}".format(species, self.value, round((self.startValue + (interval * i)), 2))
else:
lbl = "{0} = {1}".format(self.value, round((self.startValue + (interval * i)), 2))
plt.plot(result[:,0], result[:,numSp*i+count], linewidth = self.width, label = lbl)
count += 1
else:
if len(self.color) != self.polyNumber:
self.color = self.colorCycle()
count = 1
for species in self.selection[1:]:
for i in range(self.polyNumber):
if numSp > 1:
lbl = "{0}, {1} = {2}".format(species, self.value, round((self.startValue + (interval * i)), 2))
else:
lbl = "{0} = {1}".format(self.value, round((self.startValue + (interval * i)), 2))
plt.plot(result[:,0], result[:,numSp*i+count], color = self.color[i],
linewidth = self.width, label = lbl)
count += 1
if self.title is not None:
plt.suptitle(self.title)
if self.xlabel == 'toSet':
plt.xlabel('time')
elif self.xlabel:
plt.xlabel(self.xlabel)
if self.ylabel == 'toSet':
plt.ylabel('concentration')
elif self.ylabel:
plt.ylabel(self.ylabel)
if self.legend:
plt.legend()
plt.show()
def plotPolyArray(self):
"""Plots results as individual graphs parallel to each other in 3D space using results
from graduatedSim().
p.plotPolyArray()"""
result = self.graduatedSim()
interval = ((self.endValue - self.startValue) / (self.polyNumber - 1))
self.rr.reset()
fig = plt.figure()
ax = fig.gca(projection='3d')
if self.startValue is None:
self.startValue = self.rr.model[self.value]
columnNumber = self.polyNumber + 1
lastPoint = [self.endTime]
firstPoint = [self.startTime]
for i in range(int(columnNumber) - 1):
lastPoint.append(0)
firstPoint.append(0)
lastPoint = np.array(lastPoint)
firstPoint = np.array(firstPoint)
zresult = np.vstack((result, lastPoint))
zresult = np.vstack((firstPoint, zresult))
zs = []
result = []
for i in range(int(columnNumber)-1):
zs.append(i)
result.append(zip(zresult[:,0], zresult[:,(i+1)]))
if self.color is None:
poly = PolyCollection(result)
else:
if len(self.color) != self.polyNumber:
self.color = self.colorCycle()
poly = PolyCollection(result, facecolors = self.color, closed = False)
poly.set_alpha(self.alpha)
ax.add_collection3d(poly, zs=zs, zdir='y')
ax.set_xlim3d(0, self.endTime)
ax.set_ylim3d(0, (columnNumber - 1))
ax.set_zlim3d(0, (self.endValue + interval))
if self.xlabel == 'toSet':
ax.set_xlabel('Time')
elif self.xlabel:
ax.set_xlabel(self.xlabel)
if self.ylabel == 'toSet':
ax.set_ylabel('Trial Number')
elif self.ylabel:
ax.set_ylabel(self.ylabel)
if self.zlabel == 'toSet':
ax.set_zlabel(self.value)
elif self.zlabel:
ax.set_zlabel(self.zlabel)
# ax.set_xlabel('Time') if self.xlabel is None else ax.set_xlabel(self.xlabel)
# ax.set_ylabel('Trial Number') if self.ylabel is None else ax.set_ylabel(self.ylabel)
# ax.set_zlabel(self.value) if self.zlabel is None else ax.set_zlabel(self.zlabel)
if self.title is not None:
ax.set_title(self.title)
plt.show()
def plotSurface(self):
""" Plots results of simulation as a colored surface. Takes three variables, two
independent and one dependent. Legal colormap names can be found at
http://matplotlib.org/examples/color/colormaps_reference.html.
p.plotSurface()"""
try:
# if self.independent is None and self.dependent is None:
# self.independent = ['Time']
# defaultParameter = self.rr.model.getGlobalParameterIds()[0]
# self.independent.append(defaultParameter)
# defaultSpecies = self.rr.model.getFloatingSpeciesIds()[0]
# self.dependent = [defaultSpecies]
# print 'Warning: self.independent and self.dependent not set. Using' \
# ' self.independent = %s and self.dependent = %s' % (self.independent, self.dependent)
if self.independent is None:
self.independent = ['Time']
defaultParameter = self.rr.model.getGlobalParameterIds()[0]
self.independent.append(defaultParameter)
print 'Warning: self.independent not set. Using: {0}'.format(self.independent)
if self.dependent is None:
defaultSpecies = self.rr.model.getFloatingSpeciesIds()[0]
self.dependent = defaultSpecies
print 'Warning: self.dependent not set. Using: {0}'.format(self.dependent)
if len(self.independent) < 2:
raise ValueError('self.independent must contain two independent variables')
if not isinstance(self.independent, list):
raise ValueError('self.independent must be a list of strings')
if not isinstance(self.dependent, str):
raise ValueError('self.dependent must be a string')
if self.startValue is None:
if self.independent[0].lower() != 'time':
self.startValue = self.rr.model[self.independent[0]]
else:
self.startValue = self.rr.model[self.independent[1]]
if self.endValue is None:
self.endValue = self.startValue + 5
fig = plt.figure()
ax = fig.gca(projection='3d')
interval = (self.endTime - self.startTime) / float(self.numberOfPoints - 1)
X = np.arange(self.startTime, (self.endTime + (interval - 0.001)), interval)
interval = (self.endValue - self.startValue) / float(self.numberOfPoints - 1)
Y = np.arange(self.startValue, (self.endValue + (interval - 0.001)), interval)
X, Y = np.meshgrid(X, Y)
self.rr.reset()
self.rr.model[self.independent[1]] = self.startValue
Z = self.rr.simulate(self.startTime, self.endTime, (self.numberOfPoints),
[self.dependent], integrator = self.integrator)
Z = Z.T
for i in range(self.numberOfPoints - 1):
self.rr.reset()
self.rr.model[self.independent[1]] = self.startValue + ((i + 1) * interval)
Z1 = self.rr.simulate(self.startTime, self.endTime, (self.numberOfPoints),
[self.dependent], integrator = self.integrator)
Z1 = Z1.T
Z = np.concatenate ((Z, Z1))
if self.antialias is False:
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap = self.colormap,
antialiased = False, linewidth=0)
else:
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap = self.colormap,
linewidth=0)
ax.yaxis.set_major_locator(LinearLocator((6)))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
if self.xlabel == 'toSet':
ax.set_xlabel(self.independent[0])
elif self.xlabel:
ax.set_xlabel(self.xlabel)
if self.ylabel == 'toSet':
ax.set_ylabel(self.independent[1])
elif self.ylabel:
ax.set_ylabel(self.ylabel)
if self.zlabel == 'toSet':
ax.set_zlabel(self.dependent)
elif self.zlabel:
ax.set_zlabel(self.zlabel)
if self.title is not None:
ax.set_title(self.title)
if self.colorbar:
fig.colorbar(surf, shrink=0.5, aspect=4)
plt.show()
except Exception as e:
print 'error: {0}'.format(e.message)
def plotMultiArray(self, param1, param1Range, param2, param2Range):
"""Plots separate arrays for each possible combination of the contents of param1range and
param2range as an array of subplots. The ranges are lists of values that determine the
initial conditions of each simulation.
p.multiArrayPlot('S1', [1, 2, 3], 'S2', [1, 2])"""
mdl = self.rr.model
f, axarr = plt.subplots(
len(param1Range),
len(param2Range),
sharex='col',
sharey='row')
if self.color is None:
self.color = ['b', 'g', 'r', 'k']
for i, k1 in enumerate(param1Range):
for j, k2 in enumerate(param2Range):
self.rr.reset()
mdl[param1], mdl[param2] = k1, k2
if self.selection is None:
result = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
integrator = self.integrator)
else:
if 'time' not in [item.lower() for item in self.selection]:
self.selection = ['time'] + self.selection
for item in self.selection:
if item not in mdl.getFloatingSpeciesIds() and item not in mdl.getBoundarySpeciesIds():
if item.lower() != 'time':
raise ValueError('"{0}" is not a valid species in loaded model'.format(item))
result = self.rr.simulate(self.startTime, self.endTime, self.numberOfPoints,
self.selection, integrator = self.integrator)
columns = result.shape[1]
legendItems = self.rr.timeCourseSelections[1:]
if columns-1 != len(legendItems):
raise Exception('Legend list must match result array')
for c in range(columns-1):
axarr[i, j].plot(
result[:, 0],
result[:, c+1],
linewidth = self.width,
label = legendItems[c])
if (self.legend):
plt.legend(loc= 3, bbox_to_anchor=(0.5, 0.5))
if (i == (len(param1Range) - 1)):
axarr[i, j].set_xlabel('%s = %.2f' % (param2, k2))
if (j == 0):
axarr[i, j].set_ylabel('%s = %.2f' % (param1, k1))
if self.title is not None:
plt.suptitle(self.title)
def createColormap(self, color1, color2):
"""Creates a color map for plotSurface using two colors as RGB tuplets, standard color
names, e.g. 'aqua'; or hex strings.
p.colormap = p.createColorMap([0,0,0], [1,1,1])"""
if isinstance(color1, str) is True:
try:
color1 = matplotlib.colors.colorConverter.to_rgb('%s' % color1)
except ValueError:
print '"{0}" is not a valid color name, using default "blue" instead'.format(color1)
color1 = matplotlib.colors.colorConverter.to_rgb('blue')
if isinstance(color2, str) is True:
try:
color2 = matplotlib.colors.colorConverter.to_rgb('%s' % color2)
except ValueError:
print '"{0}" is not a valid color name, using default "blue" instead'.format(color2)
color2 = matplotlib.colors.colorConverter.to_rgb('blue')
cdict = {'red': ((0., 0., color1[0]),
(1., color2[0], 0.)),
'green': ((0., 0., color1[1]),
(1., color2[1], 0.)),
'blue': ((0., 0., color1[2]),
(1., color2[2], 0.))}
my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)
return my_cmap
def colorCycle(self):
"""Adjusts contents of self.color as needed for plotting methods."""
if len(self.color) < self.polyNumber:
for i in range(self.polyNumber - len(self.color)):
self.color.append(self.color[i])
else:
for i in range(len(self.color) - self.polyNumber):
del self.color[-(i+1)]
return self.color
def createColorPoints(self):
"""Sets self.color to a set of values that allow plotPolyArray, plotArray,
or plotGraduatedArray to take on colors from a colormap. The colormap can either
be user-defined using createColormap or one of the standard colormaps.
p.createColorPoints() """
color = []
interval = 1.0 / self.polyNumber
count = 0
if isinstance(self.colormap, str) is True:
for i in range(self.polyNumber):
color.append(eval('matplotlib.pylab.cm.%s(%s)' % (self.colormap, count)))
count += interval
else:
for i in range(self.polyNumber):
color.append(self.colormap(count))
count += interval
self.color = color
class SteadyStateScan (object):
def __init__(self, rr):
self.startTime = 0
self.endTime = 20
self.numberOfPoints = 50
self.polyNumber = 10
self.startValue = None
self.endValue = None
self.value = None
self.independent = None
self.selection = None
self.dependent = None
self.integrator = "cvode"
self.rr = rr
self.color = None
self.width = 2.5
self.alpha = 0.7
self.title = None
self.xlabel = None
self.ylabel = None
self.zlabel = None
self.colormap = "seismic"
self.colorbar = True
self.antialias = True
self.sameColor = False
def steadyStateSim(self):
if self.value is None:
self.value = self.rr.model.getFloatingSpeciesIds()[0]
print 'Warning: self.value not set. Using self.value = %s' % self.value
if self.startValue is None:
self.startValue = self.rr.model[self.value]
if self.endValue is None:
self.endValue = self.startValue + 5
interval = (float(self.endValue - self.startValue) / float(self.numberOfPoints - 1))
a = []
for i in range(len(self.selection) + 1):
a.append(0.)
result = np.array(a)
start = self.startValue
for i in range(self.numberOfPoints):
self.rr.reset()
start += interval
self.rr.model[self.value] = start
self.rr.steadyState()
b = [self.rr.model[self.value]]
for i in range(len(self.selection)):
b.append(self.rr.model[self.selection[i]])
result = np.vstack((result, b))
result = np.delete(result, 0, 0)
return result
def plotArray(self):
result = self.steadyStateSim()
print result
if self.color is None:
plt.plot(result[:,0], result[:,1:], linewidth = self.width)
else:
if len(self.color) != result.shape[1]:
self.color = self.colorCycle()
for i in range(result.shape[1] - 1):
plt.plot(result[:,0], result[:,i], color = self.color[i], linewidth = self.width) | 0.688678 | 0.413803 |
import pytest
from mergify_engine import context
from mergify_engine import github_types
from mergify_engine import subscription
from mergify_engine import utils
from mergify_engine.clients import github
@pytest.mark.asyncio
async def test_user_permission_cache(redis_cache: utils.RedisCache) -> None:
class FakeClient(github.AsyncGithubInstallationClient):
called: int
def __init__(self, owner, repo):
super().__init__(auth=None)
self.owner = owner
self.repo = repo
self.called = 0
async def item(self, url, *args, **kwargs):
self.called += 1
if self.repo == "test":
if (
url
== f"/repos/{self.owner}/{self.repo}/collaborators/foo/permission"
):
return {"permission": "admin"}
elif url.startswith(f"/repos/{self.owner}/{self.repo}/collaborators/"):
return {"permission": "loser"}
elif self.repo == "test2":
if (
url
== f"/repos/{self.owner}/{self.repo}/collaborators/bar/permission"
):
return {"permission": "admin"}
elif url.startswith(f"/repos/{self.owner}/{self.repo}/collaborators/"):
return {"permission": "loser"}
raise ValueError(f"Unknown test URL `{url}` for repo {self.repo}")
gh_owner = github_types.GitHubAccount(
{
"id": github_types.GitHubAccountIdType(123),
"login": github_types.GitHubLogin("jd"),
"type": "User",
}
)
gh_repo = github_types.GitHubRepository(
{
"id": github_types.GitHubRepositoryIdType(0),
"owner": gh_owner,
"full_name": "",
"archived": False,
"url": "",
"default_branch": github_types.GitHubRefType(""),
"name": github_types.GitHubRepositoryName("test"),
"private": False,
}
)
def make_pr(
gh_repo: github_types.GitHubRepository, gh_owner: github_types.GitHubAccount
) -> github_types.GitHubPullRequest:
return github_types.GitHubPullRequest(
{
"title": "",
"id": github_types.GitHubPullRequestId(0),
"maintainer_can_modify": False,
"head": {
"user": gh_owner,
"label": "",
"ref": github_types.GitHubRefType(""),
"sha": github_types.SHAType(""),
"repo": gh_repo,
},
"user": gh_owner,
"number": github_types.GitHubPullRequestNumber(0),
"rebaseable": False,
"draft": False,
"merge_commit_sha": None,
"html_url": "",
"state": "closed",
"mergeable_state": "unknown",
"merged_by": None,
"merged": False,
"merged_at": None,
"labels": [],
"base": {
"ref": github_types.GitHubRefType("main"),
"sha": github_types.SHAType(""),
"label": "",
"repo": gh_repo,
"user": gh_owner,
},
}
)
user_1 = github_types.GitHubAccount(
{
"id": github_types.GitHubAccountIdType(1),
"login": github_types.GitHubLogin("foo"),
"type": "User",
}
)
user_2 = github_types.GitHubAccount(
{
"id": github_types.GitHubAccountIdType(2),
"login": github_types.GitHubLogin("bar"),
"type": "User",
}
)
user_3 = github_types.GitHubAccount(
{
"id": github_types.GitHubAccountIdType(3),
"login": github_types.GitHubLogin("baz"),
"type": "User",
}
)
sub = subscription.Subscription(redis_cache, 0, False, "", {}, frozenset())
client = FakeClient(gh_owner["login"], gh_repo["name"])
installation = context.Installation(
gh_owner["id"], gh_owner["login"], sub, client, redis_cache
)
repository = context.Repository(installation, gh_repo["name"])
c = await context.Context.create(repository, make_pr(gh_repo, gh_owner))
assert client.called == 0
assert await c.has_write_permission(user_1)
assert client.called == 1
assert await c.has_write_permission(user_1)
assert client.called == 1
assert not await c.has_write_permission(user_2)
assert client.called == 2
assert not await c.has_write_permission(user_2)
assert client.called == 2
assert not await c.has_write_permission(user_3)
assert client.called == 3
gh_repo = github_types.GitHubRepository(
{
"id": github_types.GitHubRepositoryIdType(1),
"owner": gh_owner,
"full_name": "",
"archived": False,
"url": "",
"default_branch": github_types.GitHubRefType(""),
"name": github_types.GitHubRepositoryName("test2"),
"private": False,
}
)
client = FakeClient(gh_owner["login"], gh_repo["name"])
installation = context.Installation(
gh_owner["id"], gh_owner["login"], sub, client, redis_cache
)
repository = context.Repository(installation, gh_repo["name"])
c = await context.Context.create(repository, make_pr(gh_repo, gh_owner))
assert client.called == 0
assert await c.has_write_permission(user_2)
assert client.called == 1
assert await c.has_write_permission(user_2)
assert client.called == 1
assert not await c.has_write_permission(user_1)
assert client.called == 2
await context.Context.clear_user_permission_cache_for_repo(
redis_cache, gh_owner, gh_repo
)
assert not await c.has_write_permission(user_1)
assert client.called == 3
assert not await c.has_write_permission(user_3)
assert client.called == 4
await context.Context.clear_user_permission_cache_for_org(redis_cache, gh_owner)
assert not await c.has_write_permission(user_3)
assert client.called == 5
assert await c.has_write_permission(user_2)
assert client.called == 6
assert await c.has_write_permission(user_2)
assert client.called == 6
await context.Context.clear_user_permission_cache_for_user(
redis_cache, gh_owner, gh_repo, user_2
)
assert await c.has_write_permission(user_2)
assert client.called == 7 | mergify_engine/tests/unit/test_context.py | import pytest
from mergify_engine import context
from mergify_engine import github_types
from mergify_engine import subscription
from mergify_engine import utils
from mergify_engine.clients import github
@pytest.mark.asyncio
async def test_user_permission_cache(redis_cache: utils.RedisCache) -> None:
class FakeClient(github.AsyncGithubInstallationClient):
called: int
def __init__(self, owner, repo):
super().__init__(auth=None)
self.owner = owner
self.repo = repo
self.called = 0
async def item(self, url, *args, **kwargs):
self.called += 1
if self.repo == "test":
if (
url
== f"/repos/{self.owner}/{self.repo}/collaborators/foo/permission"
):
return {"permission": "admin"}
elif url.startswith(f"/repos/{self.owner}/{self.repo}/collaborators/"):
return {"permission": "loser"}
elif self.repo == "test2":
if (
url
== f"/repos/{self.owner}/{self.repo}/collaborators/bar/permission"
):
return {"permission": "admin"}
elif url.startswith(f"/repos/{self.owner}/{self.repo}/collaborators/"):
return {"permission": "loser"}
raise ValueError(f"Unknown test URL `{url}` for repo {self.repo}")
gh_owner = github_types.GitHubAccount(
{
"id": github_types.GitHubAccountIdType(123),
"login": github_types.GitHubLogin("jd"),
"type": "User",
}
)
gh_repo = github_types.GitHubRepository(
{
"id": github_types.GitHubRepositoryIdType(0),
"owner": gh_owner,
"full_name": "",
"archived": False,
"url": "",
"default_branch": github_types.GitHubRefType(""),
"name": github_types.GitHubRepositoryName("test"),
"private": False,
}
)
def make_pr(
gh_repo: github_types.GitHubRepository, gh_owner: github_types.GitHubAccount
) -> github_types.GitHubPullRequest:
return github_types.GitHubPullRequest(
{
"title": "",
"id": github_types.GitHubPullRequestId(0),
"maintainer_can_modify": False,
"head": {
"user": gh_owner,
"label": "",
"ref": github_types.GitHubRefType(""),
"sha": github_types.SHAType(""),
"repo": gh_repo,
},
"user": gh_owner,
"number": github_types.GitHubPullRequestNumber(0),
"rebaseable": False,
"draft": False,
"merge_commit_sha": None,
"html_url": "",
"state": "closed",
"mergeable_state": "unknown",
"merged_by": None,
"merged": False,
"merged_at": None,
"labels": [],
"base": {
"ref": github_types.GitHubRefType("main"),
"sha": github_types.SHAType(""),
"label": "",
"repo": gh_repo,
"user": gh_owner,
},
}
)
user_1 = github_types.GitHubAccount(
{
"id": github_types.GitHubAccountIdType(1),
"login": github_types.GitHubLogin("foo"),
"type": "User",
}
)
user_2 = github_types.GitHubAccount(
{
"id": github_types.GitHubAccountIdType(2),
"login": github_types.GitHubLogin("bar"),
"type": "User",
}
)
user_3 = github_types.GitHubAccount(
{
"id": github_types.GitHubAccountIdType(3),
"login": github_types.GitHubLogin("baz"),
"type": "User",
}
)
sub = subscription.Subscription(redis_cache, 0, False, "", {}, frozenset())
client = FakeClient(gh_owner["login"], gh_repo["name"])
installation = context.Installation(
gh_owner["id"], gh_owner["login"], sub, client, redis_cache
)
repository = context.Repository(installation, gh_repo["name"])
c = await context.Context.create(repository, make_pr(gh_repo, gh_owner))
assert client.called == 0
assert await c.has_write_permission(user_1)
assert client.called == 1
assert await c.has_write_permission(user_1)
assert client.called == 1
assert not await c.has_write_permission(user_2)
assert client.called == 2
assert not await c.has_write_permission(user_2)
assert client.called == 2
assert not await c.has_write_permission(user_3)
assert client.called == 3
gh_repo = github_types.GitHubRepository(
{
"id": github_types.GitHubRepositoryIdType(1),
"owner": gh_owner,
"full_name": "",
"archived": False,
"url": "",
"default_branch": github_types.GitHubRefType(""),
"name": github_types.GitHubRepositoryName("test2"),
"private": False,
}
)
client = FakeClient(gh_owner["login"], gh_repo["name"])
installation = context.Installation(
gh_owner["id"], gh_owner["login"], sub, client, redis_cache
)
repository = context.Repository(installation, gh_repo["name"])
c = await context.Context.create(repository, make_pr(gh_repo, gh_owner))
assert client.called == 0
assert await c.has_write_permission(user_2)
assert client.called == 1
assert await c.has_write_permission(user_2)
assert client.called == 1
assert not await c.has_write_permission(user_1)
assert client.called == 2
await context.Context.clear_user_permission_cache_for_repo(
redis_cache, gh_owner, gh_repo
)
assert not await c.has_write_permission(user_1)
assert client.called == 3
assert not await c.has_write_permission(user_3)
assert client.called == 4
await context.Context.clear_user_permission_cache_for_org(redis_cache, gh_owner)
assert not await c.has_write_permission(user_3)
assert client.called == 5
assert await c.has_write_permission(user_2)
assert client.called == 6
assert await c.has_write_permission(user_2)
assert client.called == 6
await context.Context.clear_user_permission_cache_for_user(
redis_cache, gh_owner, gh_repo, user_2
)
assert await c.has_write_permission(user_2)
assert client.called == 7 | 0.456652 | 0.295916 |
import logging
from pymultimatic.model import (
Device,
Error,
OperatingModes,
QuickModes,
Room,
SettingModes,
SystemInfo,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_LOCK,
DEVICE_CLASS_POWER,
DEVICE_CLASS_PROBLEM,
DEVICE_CLASS_WINDOW,
DOMAIN,
BinarySensorEntity,
)
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.event import async_call_later, async_track_time_interval
from homeassistant.util import slugify
from . import ApiHub
from .const import DOMAIN as VAILLANT, HUB, REMOVE_ERROR_HANDLER
from .entities import VaillantEntity
from .utils import get_scan_interval
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Vaillant binary sensor platform."""
sensors = []
hub: ApiHub = hass.data[VAILLANT][entry.unique_id][HUB]
if hub.system:
if hub.system.dhw and hub.system.dhw.circulation:
sensors.append(CirculationSensor(hub))
if hub.system.boiler_status:
sensors.append(BoilerError(hub))
if hub.system.info:
sensors.append(BoxOnline(hub, hub.system.info))
sensors.append(BoxUpdate(hub, hub.system.info))
for room in hub.system.rooms:
sensors.append(RoomWindow(hub, room))
for device in room.devices:
if device.device_type == "VALVE":
sensors.append(RoomDeviceChildLock(hub, device, room))
sensors.append(RoomDeviceBattery(hub, device, room))
sensors.append(RoomDeviceConnectivity(hub, device, room))
entity = HolidayModeSensor(hub)
sensors.append(entity)
entity = QuickModeSensor(hub)
sensors.append(entity)
handler = SystemErrorHandler(hub, hass, async_add_entities)
remove_handler = async_track_time_interval(
hass, handler.update, get_scan_interval(entry)
)
hass.data[VAILLANT][entry.unique_id][REMOVE_ERROR_HANDLER] = remove_handler
await handler.update(None)
_LOGGER.info("Adding %s binary sensor entities", len(sensors))
async_add_entities(sensors, True)
return True
class CirculationSensor(VaillantEntity, BinarySensorEntity):
"""Binary sensor for circulation running on or not."""
def __init__(self, hub: ApiHub):
"""Initialize entity."""
self._circulation = hub.system.dhw.circulation
super().__init__(
hub,
DOMAIN,
self._circulation.id,
self._circulation.name,
DEVICE_CLASS_POWER,
False,
)
self._active_mode = None
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return (
self._active_mode.current == OperatingModes.ON
or self._active_mode.sub == SettingModes.ON
or self._active_mode.current == QuickModes.HOTWATER_BOOST
)
@property
def available(self):
"""Return True if entity is available."""
return self._circulation is not None
async def vaillant_update(self):
"""Update specific for vaillant."""
self._circulation = self.coordinator.system.dhw.circulation
self._active_mode = self.coordinator.system.get_active_mode_circulation()
class RoomWindow(VaillantEntity, BinarySensorEntity):
"""Vaillant window binary sensor."""
def __init__(self, hub: ApiHub, room: Room):
"""Initialize entity."""
super().__init__(hub, DOMAIN, room.name, room.name, DEVICE_CLASS_WINDOW)
self._room = room
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._room.window_open
@property
def available(self):
"""Return True if entity is available."""
return self._room is not None
async def vaillant_update(self):
"""Update specific for vaillant."""
new_room: Room = self.coordinator.find_component(self._room)
if new_room:
_LOGGER.debug(
"New / old state: %s / %s", new_room.child_lock, self._room.child_lock
)
else:
_LOGGER.debug("Room %s doesn't exist anymore", self._room.id)
self._room = new_room
class RoomDeviceEntity(VaillantEntity, BinarySensorEntity):
"""Base class for ambisense device."""
def __init__(self, hub: ApiHub, device: Device, room: Room, device_class) -> None:
"""Initialize device."""
VaillantEntity.__init__(
self, hub, DOMAIN, device.sgtin, device.name, device_class
)
self.room = room
self.device = device
@property
def device_info(self):
"""Return device specific attributes."""
return {
"identifiers": {(VAILLANT, self.device.sgtin)},
"name": self.device.name,
"manufacturer": "Vaillant",
"model": self.device.device_type,
}
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
"device_id": self.device.sgtin,
"battery_low": self.device.battery_low,
"connected": not self.device.radio_out_of_reach,
}
# pylint: disable=no-self-use
def _find_device(self, new_room: Room, sgtin: str):
"""Find a device in a room."""
if new_room:
for device in new_room.devices:
if device.sgtin == sgtin:
return device
@property
def available(self):
"""Return True if entity is available."""
return self.device is not None
async def vaillant_update(self):
"""Update specific for vaillant."""
new_room: Room = self.coordinator.find_component(self.room)
new_device: Device = self._find_device(new_room, self.device.sgtin)
if new_room:
if new_device:
_LOGGER.debug(
"New / old state: %s / %s",
new_device.battery_low,
self.device.battery_low,
)
else:
_LOGGER.debug("Device %s doesn't exist anymore", self.device.sgtin)
else:
_LOGGER.debug("Room %s doesn't exist anymore", self.room.id)
self.room = new_room
self.device = new_device
class RoomDeviceChildLock(RoomDeviceEntity):
"""Binary sensor for valve child lock.
At vaillant API, the lock is set at a room level, but it applies to all
devices inside a room.
"""
def __init__(self, hub: ApiHub, device: Device, room: Room):
"""Initialize entity."""
super().__init__(hub, device, room, DEVICE_CLASS_LOCK)
@property
def is_on(self):
"""According to the doc, true means unlock, false lock."""
return not self.room.child_lock
class RoomDeviceBattery(RoomDeviceEntity):
"""Represent a device battery."""
def __init__(self, hub: ApiHub, device: Device, room: Room):
"""Initialize entity."""
super().__init__(hub, device, room, DEVICE_CLASS_BATTERY)
@property
def is_on(self):
"""According to the doc, true means normal, false low."""
return self.device.battery_low
class RoomDeviceConnectivity(RoomDeviceEntity):
"""Device in room is out of reach or not."""
def __init__(self, hub: ApiHub, device: Device, room: Room):
"""Initialize entity."""
super().__init__(hub, device, room, DEVICE_CLASS_CONNECTIVITY)
@property
def is_on(self):
"""According to the doc, true means connected, false disconnected."""
return not self.device.radio_out_of_reach
class VRBoxEntity(VaillantEntity, BinarySensorEntity):
"""Vaillant gateway device (ex: VR920)."""
def __init__(self, hub: ApiHub, info: SystemInfo, device_class, name, comp_id):
"""Initialize entity."""
VaillantEntity.__init__(self, hub, DOMAIN, comp_id, name, device_class, False)
self.system_info = info
@property
def device_info(self):
"""Return device specific attributes."""
return {
"identifiers": {(VAILLANT, self.system_info.serial_number)},
"connections": {(CONNECTION_NETWORK_MAC, self.system_info.mac_ethernet)},
"name": self.system_info.gateway,
"manufacturer": "Vaillant",
"model": self.system_info.gateway,
"sw_version": self.system_info.firmware,
}
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
"serial_number": self.system_info.serial_number,
"connected": self.system_info.is_online,
"up_to_date": self.system_info.is_up_to_date,
}
@property
def available(self):
"""Return True if entity is available."""
return self.system_info is not None
async def vaillant_update(self):
"""Update specific for vaillant."""
system_info: SystemInfo = self.coordinator.system.info
if system_info:
_LOGGER.debug(
"Found new system status " "online? %s, up to date? %s",
system_info.is_online,
system_info.is_up_to_date,
)
else:
_LOGGER.debug("System status doesn't exist anymore")
self.system_info = system_info
class BoxUpdate(VRBoxEntity):
"""Update binary sensor."""
def __init__(self, hub: ApiHub, info: SystemInfo):
"""Init."""
super().__init__(
hub, info, DEVICE_CLASS_POWER, "System update", "system_update"
)
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return not self.system_info.is_up_to_date
class BoxOnline(VRBoxEntity):
"""Check if box is online."""
def __init__(self, hub: ApiHub, info: SystemInfo):
"""Init."""
super().__init__(
hub, info, DEVICE_CLASS_CONNECTIVITY, "System Online", "system_online"
)
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self.system_info.is_online
class BoilerError(VaillantEntity, BinarySensorEntity):
"""Check if there is some error."""
def __init__(self, hub: ApiHub):
"""Initialize entity."""
self._boiler_status = hub.system.boiler_status
VaillantEntity.__init__(
self,
hub,
DOMAIN,
self._boiler_status.device_name,
self._boiler_status.device_name,
DEVICE_CLASS_PROBLEM,
False,
)
self._boiler_id = slugify(self._boiler_status.device_name)
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._boiler_status is not None and self._boiler_status.is_error
@property
def state_attributes(self):
"""Return the state attributes."""
if self._boiler_status is not None:
return {
"status_code": self._boiler_status.status_code,
"title": self._boiler_status.title,
"timestamp": self._boiler_status.timestamp,
}
return None
async def vaillant_update(self):
"""Update specific for vaillant."""
_LOGGER.debug("new boiler status is %s", self.coordinator.system.boiler_status)
self._boiler_status = self.coordinator.system.boiler_status
@property
def device_info(self):
"""Return device specific attributes."""
if self._boiler_status is not None:
return {
"identifiers": {(VAILLANT, self._boiler_id)},
"name": self._boiler_status.device_name,
"manufacturer": "Vaillant",
"model": self._boiler_status.device_name,
}
return None
@property
def device_state_attributes(self):
"""Return the state attributes."""
if self._boiler_status is not None:
return {"device_id": self._boiler_id, "error": self._boiler_status.is_error}
return None
class SystemErrorHandler:
"""Handler responsible for creating dynamically error binary sensor."""
def __init__(self, hub: ApiHub, hass, async_add_entities) -> None:
"""Init."""
self.hub = hub
self._hass = hass
self._async_add_entities = async_add_entities
async def update(self, time):
"""Check for error. It doesn't do IO."""
if self.hub.system.errors:
reg = await self._hass.helpers.entity_registry.async_get_registry()
sensors = []
for error in self.hub.system.errors:
binary_sensor = VaillantSystemError(self.hub, error)
if not reg.async_is_registered(binary_sensor.entity_id):
sensors.append(binary_sensor)
if sensors:
self._async_add_entities(sensors)
class VaillantSystemError(VaillantEntity, BinarySensorEntity):
"""Check if there is any error message from system."""
def __init__(self, hub: ApiHub, error: Error):
"""Init."""
self._error = error
super().__init__(
hub,
DOMAIN,
"error_" + error.status_code,
error.title,
DEVICE_CLASS_PROBLEM,
False,
)
@property
def state_attributes(self):
"""Return the state attributes."""
return {
"status_code": self._error.status_code,
"title": self._error.title,
"timestamp": self._error.timestamp,
"description": self._error.description,
"device_name": self._error.device_name,
}
async def vaillant_update(self):
"""Update specific for vaillant.
Special attention during the update, the entity can remove itself
from registry if the error disappear from vaillant system.
"""
errors = {e.status_code: e for e in self.coordinator.system.errors}
if self._error.status_code in [e.status_code for e in list(errors.values())]:
self._error = errors.get(self._error.status_code)
else:
async_call_later(self.hass, 0.1, self._remove)
async def _remove(self, *_):
"""Remove entity itself."""
await self.async_remove()
reg = await self.hass.helpers.entity_registry.async_get_registry()
entity_id = reg.async_get_entity_id(DOMAIN, VAILLANT, self.unique_id)
if entity_id:
reg.async_remove(entity_id)
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return True
class HolidayModeSensor(VaillantEntity, BinarySensorEntity):
"""Binary sensor for holiday mode."""
def __init__(self, hub: ApiHub):
"""Init."""
super().__init__(hub, DOMAIN, "holiday", "holiday", DEVICE_CLASS_POWER, False)
self._holiday = hub.system.holiday
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._holiday is not None and self._holiday.is_applied
@property
def state_attributes(self):
"""Return the state attributes."""
if self.is_on:
return {
"start_date": self._holiday.start_date.isoformat(),
"end_date": self._holiday.end_date.isoformat(),
"temperature": self._holiday.target,
}
return {}
async def vaillant_update(self):
"""Update specific for vaillant."""
self._holiday = self.coordinator.system.holiday
@property
def listening(self):
"""Return whether this entity is listening for system changes or not."""
return True
class QuickModeSensor(VaillantEntity, BinarySensorEntity):
"""Binary sensor for holiday mode."""
def __init__(self, hub: ApiHub):
"""Init."""
super().__init__(
hub, DOMAIN, "quick_mode", "quick_mode", DEVICE_CLASS_POWER, False
)
self._quick_mode = hub.system.quick_mode
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._quick_mode is not None
@property
def state_attributes(self):
"""Return the state attributes."""
if self.is_on:
return {"quick_mode": self._quick_mode.name}
return {}
async def vaillant_update(self):
"""Update specific for vaillant."""
self._quick_mode = self.coordinator.system.quick_mode
@property
def listening(self):
"""Return whether this entity is listening for system changes or not."""
return True | homeassistant/components/vaillant/binary_sensor.py |
import logging
from pymultimatic.model import (
Device,
Error,
OperatingModes,
QuickModes,
Room,
SettingModes,
SystemInfo,
)
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_CONNECTIVITY,
DEVICE_CLASS_LOCK,
DEVICE_CLASS_POWER,
DEVICE_CLASS_PROBLEM,
DEVICE_CLASS_WINDOW,
DOMAIN,
BinarySensorEntity,
)
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.event import async_call_later, async_track_time_interval
from homeassistant.util import slugify
from . import ApiHub
from .const import DOMAIN as VAILLANT, HUB, REMOVE_ERROR_HANDLER
from .entities import VaillantEntity
from .utils import get_scan_interval
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Vaillant binary sensor platform."""
sensors = []
hub: ApiHub = hass.data[VAILLANT][entry.unique_id][HUB]
if hub.system:
if hub.system.dhw and hub.system.dhw.circulation:
sensors.append(CirculationSensor(hub))
if hub.system.boiler_status:
sensors.append(BoilerError(hub))
if hub.system.info:
sensors.append(BoxOnline(hub, hub.system.info))
sensors.append(BoxUpdate(hub, hub.system.info))
for room in hub.system.rooms:
sensors.append(RoomWindow(hub, room))
for device in room.devices:
if device.device_type == "VALVE":
sensors.append(RoomDeviceChildLock(hub, device, room))
sensors.append(RoomDeviceBattery(hub, device, room))
sensors.append(RoomDeviceConnectivity(hub, device, room))
entity = HolidayModeSensor(hub)
sensors.append(entity)
entity = QuickModeSensor(hub)
sensors.append(entity)
handler = SystemErrorHandler(hub, hass, async_add_entities)
remove_handler = async_track_time_interval(
hass, handler.update, get_scan_interval(entry)
)
hass.data[VAILLANT][entry.unique_id][REMOVE_ERROR_HANDLER] = remove_handler
await handler.update(None)
_LOGGER.info("Adding %s binary sensor entities", len(sensors))
async_add_entities(sensors, True)
return True
class CirculationSensor(VaillantEntity, BinarySensorEntity):
"""Binary sensor for circulation running on or not."""
def __init__(self, hub: ApiHub):
"""Initialize entity."""
self._circulation = hub.system.dhw.circulation
super().__init__(
hub,
DOMAIN,
self._circulation.id,
self._circulation.name,
DEVICE_CLASS_POWER,
False,
)
self._active_mode = None
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return (
self._active_mode.current == OperatingModes.ON
or self._active_mode.sub == SettingModes.ON
or self._active_mode.current == QuickModes.HOTWATER_BOOST
)
@property
def available(self):
"""Return True if entity is available."""
return self._circulation is not None
async def vaillant_update(self):
"""Update specific for vaillant."""
self._circulation = self.coordinator.system.dhw.circulation
self._active_mode = self.coordinator.system.get_active_mode_circulation()
class RoomWindow(VaillantEntity, BinarySensorEntity):
"""Vaillant window binary sensor."""
def __init__(self, hub: ApiHub, room: Room):
"""Initialize entity."""
super().__init__(hub, DOMAIN, room.name, room.name, DEVICE_CLASS_WINDOW)
self._room = room
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._room.window_open
@property
def available(self):
"""Return True if entity is available."""
return self._room is not None
async def vaillant_update(self):
"""Update specific for vaillant."""
new_room: Room = self.coordinator.find_component(self._room)
if new_room:
_LOGGER.debug(
"New / old state: %s / %s", new_room.child_lock, self._room.child_lock
)
else:
_LOGGER.debug("Room %s doesn't exist anymore", self._room.id)
self._room = new_room
class RoomDeviceEntity(VaillantEntity, BinarySensorEntity):
"""Base class for ambisense device."""
def __init__(self, hub: ApiHub, device: Device, room: Room, device_class) -> None:
"""Initialize device."""
VaillantEntity.__init__(
self, hub, DOMAIN, device.sgtin, device.name, device_class
)
self.room = room
self.device = device
@property
def device_info(self):
"""Return device specific attributes."""
return {
"identifiers": {(VAILLANT, self.device.sgtin)},
"name": self.device.name,
"manufacturer": "Vaillant",
"model": self.device.device_type,
}
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
"device_id": self.device.sgtin,
"battery_low": self.device.battery_low,
"connected": not self.device.radio_out_of_reach,
}
# pylint: disable=no-self-use
def _find_device(self, new_room: Room, sgtin: str):
"""Find a device in a room."""
if new_room:
for device in new_room.devices:
if device.sgtin == sgtin:
return device
@property
def available(self):
"""Return True if entity is available."""
return self.device is not None
async def vaillant_update(self):
"""Update specific for vaillant."""
new_room: Room = self.coordinator.find_component(self.room)
new_device: Device = self._find_device(new_room, self.device.sgtin)
if new_room:
if new_device:
_LOGGER.debug(
"New / old state: %s / %s",
new_device.battery_low,
self.device.battery_low,
)
else:
_LOGGER.debug("Device %s doesn't exist anymore", self.device.sgtin)
else:
_LOGGER.debug("Room %s doesn't exist anymore", self.room.id)
self.room = new_room
self.device = new_device
class RoomDeviceChildLock(RoomDeviceEntity):
"""Binary sensor for valve child lock.
At vaillant API, the lock is set at a room level, but it applies to all
devices inside a room.
"""
def __init__(self, hub: ApiHub, device: Device, room: Room):
"""Initialize entity."""
super().__init__(hub, device, room, DEVICE_CLASS_LOCK)
@property
def is_on(self):
"""According to the doc, true means unlock, false lock."""
return not self.room.child_lock
class RoomDeviceBattery(RoomDeviceEntity):
"""Represent a device battery."""
def __init__(self, hub: ApiHub, device: Device, room: Room):
"""Initialize entity."""
super().__init__(hub, device, room, DEVICE_CLASS_BATTERY)
@property
def is_on(self):
"""According to the doc, true means normal, false low."""
return self.device.battery_low
class RoomDeviceConnectivity(RoomDeviceEntity):
"""Device in room is out of reach or not."""
def __init__(self, hub: ApiHub, device: Device, room: Room):
"""Initialize entity."""
super().__init__(hub, device, room, DEVICE_CLASS_CONNECTIVITY)
@property
def is_on(self):
"""According to the doc, true means connected, false disconnected."""
return not self.device.radio_out_of_reach
class VRBoxEntity(VaillantEntity, BinarySensorEntity):
"""Vaillant gateway device (ex: VR920)."""
def __init__(self, hub: ApiHub, info: SystemInfo, device_class, name, comp_id):
"""Initialize entity."""
VaillantEntity.__init__(self, hub, DOMAIN, comp_id, name, device_class, False)
self.system_info = info
@property
def device_info(self):
"""Return device specific attributes."""
return {
"identifiers": {(VAILLANT, self.system_info.serial_number)},
"connections": {(CONNECTION_NETWORK_MAC, self.system_info.mac_ethernet)},
"name": self.system_info.gateway,
"manufacturer": "Vaillant",
"model": self.system_info.gateway,
"sw_version": self.system_info.firmware,
}
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
"serial_number": self.system_info.serial_number,
"connected": self.system_info.is_online,
"up_to_date": self.system_info.is_up_to_date,
}
@property
def available(self):
"""Return True if entity is available."""
return self.system_info is not None
async def vaillant_update(self):
"""Update specific for vaillant."""
system_info: SystemInfo = self.coordinator.system.info
if system_info:
_LOGGER.debug(
"Found new system status " "online? %s, up to date? %s",
system_info.is_online,
system_info.is_up_to_date,
)
else:
_LOGGER.debug("System status doesn't exist anymore")
self.system_info = system_info
class BoxUpdate(VRBoxEntity):
"""Update binary sensor."""
def __init__(self, hub: ApiHub, info: SystemInfo):
"""Init."""
super().__init__(
hub, info, DEVICE_CLASS_POWER, "System update", "system_update"
)
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return not self.system_info.is_up_to_date
class BoxOnline(VRBoxEntity):
"""Check if box is online."""
def __init__(self, hub: ApiHub, info: SystemInfo):
"""Init."""
super().__init__(
hub, info, DEVICE_CLASS_CONNECTIVITY, "System Online", "system_online"
)
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self.system_info.is_online
class BoilerError(VaillantEntity, BinarySensorEntity):
"""Check if there is some error."""
def __init__(self, hub: ApiHub):
"""Initialize entity."""
self._boiler_status = hub.system.boiler_status
VaillantEntity.__init__(
self,
hub,
DOMAIN,
self._boiler_status.device_name,
self._boiler_status.device_name,
DEVICE_CLASS_PROBLEM,
False,
)
self._boiler_id = slugify(self._boiler_status.device_name)
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._boiler_status is not None and self._boiler_status.is_error
@property
def state_attributes(self):
"""Return the state attributes."""
if self._boiler_status is not None:
return {
"status_code": self._boiler_status.status_code,
"title": self._boiler_status.title,
"timestamp": self._boiler_status.timestamp,
}
return None
async def vaillant_update(self):
"""Update specific for vaillant."""
_LOGGER.debug("new boiler status is %s", self.coordinator.system.boiler_status)
self._boiler_status = self.coordinator.system.boiler_status
@property
def device_info(self):
"""Return device specific attributes."""
if self._boiler_status is not None:
return {
"identifiers": {(VAILLANT, self._boiler_id)},
"name": self._boiler_status.device_name,
"manufacturer": "Vaillant",
"model": self._boiler_status.device_name,
}
return None
@property
def device_state_attributes(self):
"""Return the state attributes."""
if self._boiler_status is not None:
return {"device_id": self._boiler_id, "error": self._boiler_status.is_error}
return None
class SystemErrorHandler:
"""Handler responsible for creating dynamically error binary sensor."""
def __init__(self, hub: ApiHub, hass, async_add_entities) -> None:
"""Init."""
self.hub = hub
self._hass = hass
self._async_add_entities = async_add_entities
async def update(self, time):
"""Check for error. It doesn't do IO."""
if self.hub.system.errors:
reg = await self._hass.helpers.entity_registry.async_get_registry()
sensors = []
for error in self.hub.system.errors:
binary_sensor = VaillantSystemError(self.hub, error)
if not reg.async_is_registered(binary_sensor.entity_id):
sensors.append(binary_sensor)
if sensors:
self._async_add_entities(sensors)
class VaillantSystemError(VaillantEntity, BinarySensorEntity):
"""Check if there is any error message from system."""
def __init__(self, hub: ApiHub, error: Error):
"""Init."""
self._error = error
super().__init__(
hub,
DOMAIN,
"error_" + error.status_code,
error.title,
DEVICE_CLASS_PROBLEM,
False,
)
@property
def state_attributes(self):
"""Return the state attributes."""
return {
"status_code": self._error.status_code,
"title": self._error.title,
"timestamp": self._error.timestamp,
"description": self._error.description,
"device_name": self._error.device_name,
}
async def vaillant_update(self):
"""Update specific for vaillant.
Special attention during the update, the entity can remove itself
from registry if the error disappear from vaillant system.
"""
errors = {e.status_code: e for e in self.coordinator.system.errors}
if self._error.status_code in [e.status_code for e in list(errors.values())]:
self._error = errors.get(self._error.status_code)
else:
async_call_later(self.hass, 0.1, self._remove)
async def _remove(self, *_):
"""Remove entity itself."""
await self.async_remove()
reg = await self.hass.helpers.entity_registry.async_get_registry()
entity_id = reg.async_get_entity_id(DOMAIN, VAILLANT, self.unique_id)
if entity_id:
reg.async_remove(entity_id)
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return True
class HolidayModeSensor(VaillantEntity, BinarySensorEntity):
"""Binary sensor for holiday mode."""
def __init__(self, hub: ApiHub):
"""Init."""
super().__init__(hub, DOMAIN, "holiday", "holiday", DEVICE_CLASS_POWER, False)
self._holiday = hub.system.holiday
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._holiday is not None and self._holiday.is_applied
@property
def state_attributes(self):
"""Return the state attributes."""
if self.is_on:
return {
"start_date": self._holiday.start_date.isoformat(),
"end_date": self._holiday.end_date.isoformat(),
"temperature": self._holiday.target,
}
return {}
async def vaillant_update(self):
"""Update specific for vaillant."""
self._holiday = self.coordinator.system.holiday
@property
def listening(self):
"""Return whether this entity is listening for system changes or not."""
return True
class QuickModeSensor(VaillantEntity, BinarySensorEntity):
"""Binary sensor for holiday mode."""
def __init__(self, hub: ApiHub):
"""Init."""
super().__init__(
hub, DOMAIN, "quick_mode", "quick_mode", DEVICE_CLASS_POWER, False
)
self._quick_mode = hub.system.quick_mode
@property
def is_on(self):
"""Return true if the binary sensor is on."""
return self._quick_mode is not None
@property
def state_attributes(self):
"""Return the state attributes."""
if self.is_on:
return {"quick_mode": self._quick_mode.name}
return {}
async def vaillant_update(self):
"""Update specific for vaillant."""
self._quick_mode = self.coordinator.system.quick_mode
@property
def listening(self):
"""Return whether this entity is listening for system changes or not."""
return True | 0.799599 | 0.126947 |
"""Align trajectories to their average structure."""
import logging.config
import time
from pathlib import Path
from typing import Any
from typing import List
import click
import mdtraj as md
import numpy as np
from mdtraj.utils import in_units_of
from nptyping import Float
from nptyping import NDArray
from .. import _MASK
from .. import create_logging_dict
from .. import PathLike
from ..libs.align import align_trajectory
from ..libs.utils import get_average_structure
from ..libs.utils import get_positions
@click.command("align", short_help="Align trajectory to a reference")
@click.option(
"-s",
"--top",
"topology",
metavar="FILE",
default=Path.cwd().joinpath("input.top").as_posix(),
show_default=True,
type=click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True),
help="Topology",
)
@click.option(
"-f",
"--traj",
"trajectory",
metavar="FILE",
default=[
Path.cwd().joinpath("input.nc").as_posix(),
],
show_default=True,
multiple=True,
type=click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True),
help="Trajectory",
)
@click.option(
"-r",
"--ref",
"reference",
metavar="FILE",
default=Path.cwd().joinpath("average.pdb").as_posix(),
show_default=True,
type=click.Path(exists=False, file_okay=True, dir_okay=False, resolve_path=True),
help="Average structure of trajectory",
)
@click.option(
"-o",
"--outfile",
metavar="FILE",
default=Path.cwd().joinpath("aligned.nc").as_posix(),
show_default=True,
type=click.Path(exists=False, file_okay=True, dir_okay=False, resolve_path=True),
help="Aligned trajectory",
)
@click.option(
"-l",
"--logfile",
metavar="LOG",
show_default=True,
default=Path.cwd().joinpath("align_traj.log").as_posix(),
type=click.Path(exists=False, file_okay=True, dir_okay=False, resolve_path=True),
help="Log file",
)
@click.option(
"--dt",
"step",
metavar="OFFSET",
default=0,
show_default=True,
type=click.IntRange(min=0, clamp=True),
help="Trajectory output offset (0 = single step)",
)
@click.option(
"-m",
"--mask",
default="ca",
show_default=True,
type=click.Choice(_MASK.keys()),
help="Atom selection",
)
@click.option(
"--tol",
type=click.FloatRange(min=0.0, max=1.0),
default=0.001,
show_default=True,
help="Error tolerance",
)
@click.option("-v", "--verbose", is_flag=True, help="Noisy output")
def cli(
topology: PathLike,
trajectory: List[str],
reference: PathLike,
outfile: PathLike,
logfile: PathLike,
step: int,
mask: str,
tol: float,
verbose: bool,
) -> None:
"""Align a trajectory to average structure using Kabsch fitting."""
start_time: float = time.perf_counter()
# Setup logging
logging.config.dictConfig(create_logging_dict(logfile))
logger: logging.Logger = logging.getLogger(__name__)
step = step if step > 0 else 1
logger.info("Loading %s and %s", topology, trajectory)
positions: NDArray[(Any, ...), Float] = get_positions(
topology, trajectory, mask=_MASK[mask], stride=step
)
# Calculate average structure
ref_traj: md.Trajectory = get_average_structure(
topology, trajectory, mask=_MASK[mask], stride=step
)
logger.info("Saving average structure to %s", reference)
ref_traj.save(reference)
unitcell_angles: NDArray[(Any, ...), Float] = ref_traj.unitcell_angles.copy()
unitcell_lengths: NDArray[(Any, ...), Float] = ref_traj.unitcell_lengths.copy()
unitcell_vectors: NDArray[(Any, ...), Float] = ref_traj.unitcell_vectors.copy()
if not (
".gro" in "".join(trajectory)
or ".xtc" in "".join(trajectory)
or ".trj" in "".join(trajectory)
or ".tng" in "".join(trajectory)
):
in_units_of(ref_traj.xyz, "nanometer", "angstroms", inplace=True)
logger.info("Aligning trajectory to average structures")
ref_traj.xyz = align_trajectory(
positions, ref_traj.xyz[0], tol=tol, verbose=verbose
)
n_frames = ref_traj.n_frames
ref_traj.time = np.arange(n_frames)
ref_traj.unitcell_angles = np.repeat(unitcell_angles, n_frames, axis=0)
ref_traj.unitcell_lengths = np.repeat(unitcell_lengths, n_frames, axis=0)
ref_traj.unitcell_vectors = np.repeat(unitcell_vectors, n_frames, axis=0)
if not (
".gro" in "".join(trajectory)
or ".xtc" in "".join(trajectory)
or ".trj" in "".join(trajectory)
or ".tng" in "".join(trajectory)
):
in_units_of(ref_traj.xyz, "angstroms", "nanometer", inplace=True)
logger.info("Saving aligned trajectory to %s}", outfile)
ref_traj.save(outfile)
stop_time: float = time.perf_counter()
dt: float = stop_time - start_time
struct_time: time.struct_time = time.gmtime(dt)
if verbose:
output: str = time.strftime("%H:%M:%S", struct_time)
logger.info(f"Total execution time: {output}") | src/qaa/commands/cmd_align.py | """Align trajectories to their average structure."""
import logging.config
import time
from pathlib import Path
from typing import Any
from typing import List
import click
import mdtraj as md
import numpy as np
from mdtraj.utils import in_units_of
from nptyping import Float
from nptyping import NDArray
from .. import _MASK
from .. import create_logging_dict
from .. import PathLike
from ..libs.align import align_trajectory
from ..libs.utils import get_average_structure
from ..libs.utils import get_positions
@click.command("align", short_help="Align trajectory to a reference")
@click.option(
"-s",
"--top",
"topology",
metavar="FILE",
default=Path.cwd().joinpath("input.top").as_posix(),
show_default=True,
type=click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True),
help="Topology",
)
@click.option(
"-f",
"--traj",
"trajectory",
metavar="FILE",
default=[
Path.cwd().joinpath("input.nc").as_posix(),
],
show_default=True,
multiple=True,
type=click.Path(exists=True, file_okay=True, dir_okay=False, resolve_path=True),
help="Trajectory",
)
@click.option(
"-r",
"--ref",
"reference",
metavar="FILE",
default=Path.cwd().joinpath("average.pdb").as_posix(),
show_default=True,
type=click.Path(exists=False, file_okay=True, dir_okay=False, resolve_path=True),
help="Average structure of trajectory",
)
@click.option(
"-o",
"--outfile",
metavar="FILE",
default=Path.cwd().joinpath("aligned.nc").as_posix(),
show_default=True,
type=click.Path(exists=False, file_okay=True, dir_okay=False, resolve_path=True),
help="Aligned trajectory",
)
@click.option(
"-l",
"--logfile",
metavar="LOG",
show_default=True,
default=Path.cwd().joinpath("align_traj.log").as_posix(),
type=click.Path(exists=False, file_okay=True, dir_okay=False, resolve_path=True),
help="Log file",
)
@click.option(
"--dt",
"step",
metavar="OFFSET",
default=0,
show_default=True,
type=click.IntRange(min=0, clamp=True),
help="Trajectory output offset (0 = single step)",
)
@click.option(
"-m",
"--mask",
default="ca",
show_default=True,
type=click.Choice(_MASK.keys()),
help="Atom selection",
)
@click.option(
"--tol",
type=click.FloatRange(min=0.0, max=1.0),
default=0.001,
show_default=True,
help="Error tolerance",
)
@click.option("-v", "--verbose", is_flag=True, help="Noisy output")
def cli(
topology: PathLike,
trajectory: List[str],
reference: PathLike,
outfile: PathLike,
logfile: PathLike,
step: int,
mask: str,
tol: float,
verbose: bool,
) -> None:
"""Align a trajectory to average structure using Kabsch fitting."""
start_time: float = time.perf_counter()
# Setup logging
logging.config.dictConfig(create_logging_dict(logfile))
logger: logging.Logger = logging.getLogger(__name__)
step = step if step > 0 else 1
logger.info("Loading %s and %s", topology, trajectory)
positions: NDArray[(Any, ...), Float] = get_positions(
topology, trajectory, mask=_MASK[mask], stride=step
)
# Calculate average structure
ref_traj: md.Trajectory = get_average_structure(
topology, trajectory, mask=_MASK[mask], stride=step
)
logger.info("Saving average structure to %s", reference)
ref_traj.save(reference)
unitcell_angles: NDArray[(Any, ...), Float] = ref_traj.unitcell_angles.copy()
unitcell_lengths: NDArray[(Any, ...), Float] = ref_traj.unitcell_lengths.copy()
unitcell_vectors: NDArray[(Any, ...), Float] = ref_traj.unitcell_vectors.copy()
if not (
".gro" in "".join(trajectory)
or ".xtc" in "".join(trajectory)
or ".trj" in "".join(trajectory)
or ".tng" in "".join(trajectory)
):
in_units_of(ref_traj.xyz, "nanometer", "angstroms", inplace=True)
logger.info("Aligning trajectory to average structures")
ref_traj.xyz = align_trajectory(
positions, ref_traj.xyz[0], tol=tol, verbose=verbose
)
n_frames = ref_traj.n_frames
ref_traj.time = np.arange(n_frames)
ref_traj.unitcell_angles = np.repeat(unitcell_angles, n_frames, axis=0)
ref_traj.unitcell_lengths = np.repeat(unitcell_lengths, n_frames, axis=0)
ref_traj.unitcell_vectors = np.repeat(unitcell_vectors, n_frames, axis=0)
if not (
".gro" in "".join(trajectory)
or ".xtc" in "".join(trajectory)
or ".trj" in "".join(trajectory)
or ".tng" in "".join(trajectory)
):
in_units_of(ref_traj.xyz, "angstroms", "nanometer", inplace=True)
logger.info("Saving aligned trajectory to %s}", outfile)
ref_traj.save(outfile)
stop_time: float = time.perf_counter()
dt: float = stop_time - start_time
struct_time: time.struct_time = time.gmtime(dt)
if verbose:
output: str = time.strftime("%H:%M:%S", struct_time)
logger.info(f"Total execution time: {output}") | 0.878301 | 0.334997 |
import sys
import Queue
from threading import Thread
__all__ = ['TasksRunner']
DEFAULT_WORKERS_NUMBER = 20
QUEUE_GET_TIMEOUT = 3
class TasksRunner(object):
def __init__(self, task_executor=None, max_workers=None, verbose=None,
daemonic_workers=True):
self._executor = task_executor
self._max_workers = (max_workers == None) and DEFAULT_WORKERS_NUMBER \
or int(max_workers)
self._verbose = verbose
self.workers = []
self.daemonic_workers = daemonic_workers
self.tasks_queue = Queue.Queue()
# Queue with exceptions from threads.
self.exc_queue = Queue.Queue()
def put_task(self, *args):
self.tasks_queue.put(args, timeout=10)
def run_tasks(self):
ntasks = self.tasks_queue.qsize()
nworkers = (ntasks < self._max_workers) and ntasks or self._max_workers
for _ in range(nworkers):
worker = Worker(self._executor, self.tasks_queue)
thr = ThreadWrapper(target=worker.work, exc_queue=self.exc_queue,
verbose=self._verbose, daemonic=self.daemonic_workers)
self.workers.append(thr)
thr.start()
def wait_tasks_processed(self, ignore_exception=False):
while not self._tasks_finished():
self._process_exc_queue(ignore_exception)
self._process_exc_queue(ignore_exception)
def _tasks_finished(self):
return all(map(lambda w: not w.is_alive(), self.workers))
def _process_exc_queue(self, ignore_exception):
try:
exc_info = self.exc_queue.get(block=True,
timeout=QUEUE_GET_TIMEOUT)
except Queue.Empty:
pass
else:
if not ignore_exception:
self._stop_all_workers()
raise exc_info[0], exc_info[1], exc_info[2]
def _stop_all_workers(self):
for t in self.workers:
t._Thread__stop()
class Worker(object):
def __init__(self, task_executor, tasks_queue):
self._executor = task_executor
self._queue = tasks_queue
def work(self):
while True:
try:
task = self._queue.get(timeout=QUEUE_GET_TIMEOUT)
except Queue.Empty:
break
self._executor(*task)
self._queue.task_done()
class ThreadWrapper(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None, exc_queue=None,
daemonic=True):
if verbose != None and int(verbose) >= 3:
verbose = True
super(ThreadWrapper, self).__init__(group=group, target=target,
name=name, args=args,
kwargs=kwargs, verbose=verbose)
self.daemon = daemonic
if exc_queue and not hasattr(exc_queue, 'put'):
raise TypeError('exc_queue object must support queue interface put()')
self.exc_queue = exc_queue
self.exc_info = None
def run(self):
try:
self._note('Starting run()')
super(ThreadWrapper, self).run()
self._note('Finished run()')
except:
self._note('Exception %s', sys.exc_info())
if self.exc_queue is not None:
self.exc_queue.put(sys.exc_info())
self.exc_info = sys.exc_info()
def get_exc_info(self):
return self.exc_info | client/src/main/python/slipstream/utils/tasksrunner.py | import sys
import Queue
from threading import Thread
__all__ = ['TasksRunner']
DEFAULT_WORKERS_NUMBER = 20
QUEUE_GET_TIMEOUT = 3
class TasksRunner(object):
def __init__(self, task_executor=None, max_workers=None, verbose=None,
daemonic_workers=True):
self._executor = task_executor
self._max_workers = (max_workers == None) and DEFAULT_WORKERS_NUMBER \
or int(max_workers)
self._verbose = verbose
self.workers = []
self.daemonic_workers = daemonic_workers
self.tasks_queue = Queue.Queue()
# Queue with exceptions from threads.
self.exc_queue = Queue.Queue()
def put_task(self, *args):
self.tasks_queue.put(args, timeout=10)
def run_tasks(self):
ntasks = self.tasks_queue.qsize()
nworkers = (ntasks < self._max_workers) and ntasks or self._max_workers
for _ in range(nworkers):
worker = Worker(self._executor, self.tasks_queue)
thr = ThreadWrapper(target=worker.work, exc_queue=self.exc_queue,
verbose=self._verbose, daemonic=self.daemonic_workers)
self.workers.append(thr)
thr.start()
def wait_tasks_processed(self, ignore_exception=False):
while not self._tasks_finished():
self._process_exc_queue(ignore_exception)
self._process_exc_queue(ignore_exception)
def _tasks_finished(self):
return all(map(lambda w: not w.is_alive(), self.workers))
def _process_exc_queue(self, ignore_exception):
try:
exc_info = self.exc_queue.get(block=True,
timeout=QUEUE_GET_TIMEOUT)
except Queue.Empty:
pass
else:
if not ignore_exception:
self._stop_all_workers()
raise exc_info[0], exc_info[1], exc_info[2]
def _stop_all_workers(self):
for t in self.workers:
t._Thread__stop()
class Worker(object):
def __init__(self, task_executor, tasks_queue):
self._executor = task_executor
self._queue = tasks_queue
def work(self):
while True:
try:
task = self._queue.get(timeout=QUEUE_GET_TIMEOUT)
except Queue.Empty:
break
self._executor(*task)
self._queue.task_done()
class ThreadWrapper(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None, exc_queue=None,
daemonic=True):
if verbose != None and int(verbose) >= 3:
verbose = True
super(ThreadWrapper, self).__init__(group=group, target=target,
name=name, args=args,
kwargs=kwargs, verbose=verbose)
self.daemon = daemonic
if exc_queue and not hasattr(exc_queue, 'put'):
raise TypeError('exc_queue object must support queue interface put()')
self.exc_queue = exc_queue
self.exc_info = None
def run(self):
try:
self._note('Starting run()')
super(ThreadWrapper, self).run()
self._note('Finished run()')
except:
self._note('Exception %s', sys.exc_info())
if self.exc_queue is not None:
self.exc_queue.put(sys.exc_info())
self.exc_info = sys.exc_info()
def get_exc_info(self):
return self.exc_info | 0.233881 | 0.098036 |
from __future__ import print_function
import numpy as np
def gen_noise(shape, prob=0.1, seed_layers=0):
"""Generate uniform noise data of requested shape"""
noise = (np.random.random_sample(shape) < prob).astype(np.int8)
noise[:,:seed_layers,:,:] = 0
return noise
def sample_track_params(n, num_det_layers, det_layer_size):
"""Generate track parameters constrained within detector shape"""
# Sample the entry and exit points for tracks
entry_points = np.random.uniform(0, det_layer_size, size=(n, 2))
exit_points = np.random.uniform(0, det_layer_size, size=(n, 2))
# Calculate slope parameters
slopes = (exit_points - entry_points) / float(num_det_layers - 1)
return np.concatenate([slopes, entry_points], axis=1)
def track_hit_coords(params, det_layer_idx=None, num_det_layers=None, as_type=np.int):
"""
Given an array of track params, give the coordinates
of the hits in detector index space
"""
if det_layer_idx is None:
det_layer_idx = np.arange(num_det_layers)
xslope, yslope, xentry, yentry = params
xhits = xslope*det_layer_idx + xentry
yhits = yslope*det_layer_idx + yentry
return xhits.astype(as_type), yhits.astype(as_type)
def gen_straight_tracks(n, num_det_layers, det_layer_size):
"""Generate n straight tracks"""
# Initialize the data
data = np.zeros((n, num_det_layers, det_layer_size, det_layer_size),
dtype=np.float32)
# Sample track parameters
params = sample_track_params(n, num_det_layers, det_layer_size)
# Calculate hit positions and fill hit data
idx = np.arange(num_det_layers)
for ievt in range(n):
xhits, yhits = track_hit_coords(params[ievt], idx)
data[ievt,idx,xhits,yhits] = 1
return data, params
def gen_bkg_tracks(num_event, num_det_layers, det_layer_size,
avg_bkg_tracks=3, seed_layers=0):
"""
Generate background tracks in the non-seed detector layers.
Samples the number of tracks for each event from a poisson
distribution with specified mean avg_bkg_tracks.
"""
num_bkg_tracks = np.random.poisson(avg_bkg_tracks, num_event)
bkg_tracks = np.zeros((num_event, num_det_layers, det_layer_size, det_layer_size),
dtype=np.float32)
for ievt in range(num_event):
ntrk = num_bkg_tracks[ievt]
bkg_tracks[ievt] = sum(gen_straight_tracks(ntrk, num_det_layers, det_layer_size)[0])
bkg_tracks[:,:seed_layers,:,:] = 0
return bkg_tracks
def generate_data(shape, num_seed_layers=3, avg_bkg_tracks=3,
noise_prob=0.01, verbose=True, seed=1234):
"""
Top level function to generate a dataset.
Returns arrays (events, sig_tracks, sig_params)
"""
np.random.seed(seed)
num_event, num_det_layers, det_layer_size, _ = shape
# Signal tracks
sig_tracks, sig_params = gen_straight_tracks(
num_event, num_det_layers, det_layer_size)
# Background tracks
bkg_tracks = gen_bkg_tracks(
num_event, num_det_layers, det_layer_size,
avg_bkg_tracks=avg_bkg_tracks, seed_layers=num_seed_layers)
# Noise
noise = gen_noise(shape, prob=noise_prob, seed_layers=num_seed_layers)
# Full events
events = sig_tracks + bkg_tracks + noise
events[events > 1] = 1
# Print data sizes
if verbose:
print('Sizes of arrays')
print(' events: %g MB' % (events.dtype.itemsize * events.size / 1e6))
print(' sig_tracks: %g MB' % (sig_tracks.dtype.itemsize * sig_tracks.size / 1e6))
print(' bkg_tracks: %g MB' % (bkg_tracks.dtype.itemsize * bkg_tracks.size / 1e6))
print(' noise: %g MB' % (noise.dtype.itemsize * noise.size / 1e6))
print(' sig_params: %g MB' % (sig_params.dtype.itemsize * sig_params.size / 1e6))
return events, sig_tracks, sig_params | src/data_processing/toy3d.py | from __future__ import print_function
import numpy as np
def gen_noise(shape, prob=0.1, seed_layers=0):
"""Generate uniform noise data of requested shape"""
noise = (np.random.random_sample(shape) < prob).astype(np.int8)
noise[:,:seed_layers,:,:] = 0
return noise
def sample_track_params(n, num_det_layers, det_layer_size):
"""Generate track parameters constrained within detector shape"""
# Sample the entry and exit points for tracks
entry_points = np.random.uniform(0, det_layer_size, size=(n, 2))
exit_points = np.random.uniform(0, det_layer_size, size=(n, 2))
# Calculate slope parameters
slopes = (exit_points - entry_points) / float(num_det_layers - 1)
return np.concatenate([slopes, entry_points], axis=1)
def track_hit_coords(params, det_layer_idx=None, num_det_layers=None, as_type=np.int):
"""
Given an array of track params, give the coordinates
of the hits in detector index space
"""
if det_layer_idx is None:
det_layer_idx = np.arange(num_det_layers)
xslope, yslope, xentry, yentry = params
xhits = xslope*det_layer_idx + xentry
yhits = yslope*det_layer_idx + yentry
return xhits.astype(as_type), yhits.astype(as_type)
def gen_straight_tracks(n, num_det_layers, det_layer_size):
"""Generate n straight tracks"""
# Initialize the data
data = np.zeros((n, num_det_layers, det_layer_size, det_layer_size),
dtype=np.float32)
# Sample track parameters
params = sample_track_params(n, num_det_layers, det_layer_size)
# Calculate hit positions and fill hit data
idx = np.arange(num_det_layers)
for ievt in range(n):
xhits, yhits = track_hit_coords(params[ievt], idx)
data[ievt,idx,xhits,yhits] = 1
return data, params
def gen_bkg_tracks(num_event, num_det_layers, det_layer_size,
avg_bkg_tracks=3, seed_layers=0):
"""
Generate background tracks in the non-seed detector layers.
Samples the number of tracks for each event from a poisson
distribution with specified mean avg_bkg_tracks.
"""
num_bkg_tracks = np.random.poisson(avg_bkg_tracks, num_event)
bkg_tracks = np.zeros((num_event, num_det_layers, det_layer_size, det_layer_size),
dtype=np.float32)
for ievt in range(num_event):
ntrk = num_bkg_tracks[ievt]
bkg_tracks[ievt] = sum(gen_straight_tracks(ntrk, num_det_layers, det_layer_size)[0])
bkg_tracks[:,:seed_layers,:,:] = 0
return bkg_tracks
def generate_data(shape, num_seed_layers=3, avg_bkg_tracks=3,
noise_prob=0.01, verbose=True, seed=1234):
"""
Top level function to generate a dataset.
Returns arrays (events, sig_tracks, sig_params)
"""
np.random.seed(seed)
num_event, num_det_layers, det_layer_size, _ = shape
# Signal tracks
sig_tracks, sig_params = gen_straight_tracks(
num_event, num_det_layers, det_layer_size)
# Background tracks
bkg_tracks = gen_bkg_tracks(
num_event, num_det_layers, det_layer_size,
avg_bkg_tracks=avg_bkg_tracks, seed_layers=num_seed_layers)
# Noise
noise = gen_noise(shape, prob=noise_prob, seed_layers=num_seed_layers)
# Full events
events = sig_tracks + bkg_tracks + noise
events[events > 1] = 1
# Print data sizes
if verbose:
print('Sizes of arrays')
print(' events: %g MB' % (events.dtype.itemsize * events.size / 1e6))
print(' sig_tracks: %g MB' % (sig_tracks.dtype.itemsize * sig_tracks.size / 1e6))
print(' bkg_tracks: %g MB' % (bkg_tracks.dtype.itemsize * bkg_tracks.size / 1e6))
print(' noise: %g MB' % (noise.dtype.itemsize * noise.size / 1e6))
print(' sig_params: %g MB' % (sig_params.dtype.itemsize * sig_params.size / 1e6))
return events, sig_tracks, sig_params | 0.754373 | 0.61173 |
from operator import mul
from functools import reduce
import sys
class BitStream:
def __init__(self, string, string_is_hex=True):
if string_is_hex:
nbits = 4 * len(string)
bigint = int(string,base=16)
string = f'{bigint:0{nbits}b}'
self.string = string
self.pos = 0
def length(self):
return len(self.string) - self.pos
def read(self, count=1):
if self.pos >= len(self.string):
return ''
x = self.string[self.pos:self.pos+count]
self.pos += count
return x
def readInt(self):
bits, again = '', True
while again:
again = self.read() == '1'
bits += self.read(4)
return int(bits,2)
class Packet:
def __init__(self, bitstream):
self.version = int(bitstream.read(3),2)
self.type = int(bitstream.read(3),2)
self.value = None
self.subpackets = []
if self.type == 4:
self.value = bitstream.readInt()
else:
if bitstream.read()=='0':
length = int(bitstream.read(15), 2)
substream = BitStream(bitstream.read(length), string_is_hex=False)
while substream.length() > 0:
self.subpackets.append(Packet(substream))
else:
n = int(bitstream.read(11), 2)
for i in range(n):
self.subpackets.append(Packet(bitstream))
def eval(self):
generator = (p.eval() for p in self.subpackets)
if self.type == 0:
return sum(generator)
elif self.type == 1:
return reduce(mul, generator)
elif self.type == 2:
return reduce(min, generator)
elif self.type == 3:
return reduce(max, generator)
elif self.type == 4:
return self.value
elif self.type == 5:
a,b = generator
return 1 if a > b else 0
elif self.type == 6:
a,b = generator
return 1 if a < b else 0
elif self.type == 7:
a,b = generator
return 1 if a == b else 0
else:
raise Exception
def sum_of_packet_versions(hex_string):
packets = [ Packet(BitStream(hex_string)) ]
count = 0
while len(packets)>0:
p = packets.pop(0)
count += p.version
packets.extend(p.subpackets)
return count
if __name__=='__main__':
mode = '1' if len(sys.argv)<2 else sys.argv[1]
hex_string = sys.stdin.readline().strip()
if mode == '1':
print(sum_of_packet_versions(hex_string))
else:
print(Packet(BitStream(hex_string)).eval()) | 16/star.py | from operator import mul
from functools import reduce
import sys
class BitStream:
def __init__(self, string, string_is_hex=True):
if string_is_hex:
nbits = 4 * len(string)
bigint = int(string,base=16)
string = f'{bigint:0{nbits}b}'
self.string = string
self.pos = 0
def length(self):
return len(self.string) - self.pos
def read(self, count=1):
if self.pos >= len(self.string):
return ''
x = self.string[self.pos:self.pos+count]
self.pos += count
return x
def readInt(self):
bits, again = '', True
while again:
again = self.read() == '1'
bits += self.read(4)
return int(bits,2)
class Packet:
def __init__(self, bitstream):
self.version = int(bitstream.read(3),2)
self.type = int(bitstream.read(3),2)
self.value = None
self.subpackets = []
if self.type == 4:
self.value = bitstream.readInt()
else:
if bitstream.read()=='0':
length = int(bitstream.read(15), 2)
substream = BitStream(bitstream.read(length), string_is_hex=False)
while substream.length() > 0:
self.subpackets.append(Packet(substream))
else:
n = int(bitstream.read(11), 2)
for i in range(n):
self.subpackets.append(Packet(bitstream))
def eval(self):
generator = (p.eval() for p in self.subpackets)
if self.type == 0:
return sum(generator)
elif self.type == 1:
return reduce(mul, generator)
elif self.type == 2:
return reduce(min, generator)
elif self.type == 3:
return reduce(max, generator)
elif self.type == 4:
return self.value
elif self.type == 5:
a,b = generator
return 1 if a > b else 0
elif self.type == 6:
a,b = generator
return 1 if a < b else 0
elif self.type == 7:
a,b = generator
return 1 if a == b else 0
else:
raise Exception
def sum_of_packet_versions(hex_string):
packets = [ Packet(BitStream(hex_string)) ]
count = 0
while len(packets)>0:
p = packets.pop(0)
count += p.version
packets.extend(p.subpackets)
return count
if __name__=='__main__':
mode = '1' if len(sys.argv)<2 else sys.argv[1]
hex_string = sys.stdin.readline().strip()
if mode == '1':
print(sum_of_packet_versions(hex_string))
else:
print(Packet(BitStream(hex_string)).eval()) | 0.290981 | 0.295933 |
import numpy
import cv2
from . import structure_block
import os
import csv
import kdtree
import time
import multiprocessing
import datetime
from math import ceil
def video_to_structure(path_to_video: str, destination_folder: str, name_prefix: str, path_to_palette: str = None, ticks_per_frame:int = 2, starting_frame: int = 0, width: int = None, height: int = None, adjust_mode: str = None, optimize = True, processes: int = None, on_progress = None):
path_to_palette = path_to_palette if path_to_palette is not None else os.path.join(os.path.dirname(__file__), "palette.txt")
video = cv2.VideoCapture(path_to_video)
output_fps = 20 / ticks_per_frame
video_fps = video.get(cv2.CAP_PROP_FPS)
frame_skip = video_fps / output_fps
video.set(cv2.CAP_PROP_POS_FRAMES, int(starting_frame * frame_skip) - 1)
success, image = video.read()
size = _get_image_size(image, width, height, adjust_mode)
adjust = _get_adjuster(image, width, height, adjust_mode)
path_to_palette = os.path.abspath(path_to_palette)
processes = processes if processes is not None else multiprocessing.cpu_count()
in_q = multiprocessing.Queue()
out_q = multiprocessing.Queue()
row_processors = [multiprocessing.Process(target=_row_processor, args=(path_to_palette, in_q, out_q)) for _ in range(processes)]
[process.start() for process in row_processors]
if optimize:
x = image.shape[1]
y = image.shape[0]
base = [[None for _ in range(y)] for _ in range(x)]
else:
base = None
total_frames = video.get(cv2.CAP_PROP_FRAME_COUNT) / frame_skip
total_frames = ceil(total_frames)
count = 0
total_time = 0
print("converting video...")
while success:
start = time.time()
image = adjust(image, size)
structure = _array_to_structure(image, in_q, out_q, base)
structure.save(os.path.join(destination_folder, f"{name_prefix}{starting_frame + count}.nbt"))
if on_progress is not None:
on_progress(starting_frame + count)
count += 1
elapsed = time.time() - start
total_time += elapsed
average = total_time / (count)
eta = (total_frames - starting_frame - count) * average
eta = datetime.timedelta(seconds=round(eta))
print(f"{starting_frame + count}/{total_frames} (Elapsed: {datetime.timedelta(seconds=round(total_time, 5))}, Average: {round(average, 5)}s, ETA: {eta})" + " "*10, end="\r")
video.set(cv2.CAP_PROP_POS_FRAMES, int(frame_skip * (starting_frame + count)) - 1)
success, image = video.read()
print("")
print("done!")
[process.terminate() for process in row_processors]
return count
def image_to_structure(path_to_image: str, out_structure: str, path_to_palette: str = None, width: int = None, height: int = None, adjust_mode = None):
path_to_palette = path_to_palette if path_to_palette is not None else os.path.join(os.path.dirname(__file__), "palette.txt")
palette = _get_palette(path_to_palette)
image = cv2.imread(path_to_image)
size = _get_image_size(image, width, height, adjust_mode)
image = _get_adjuster(image, width, height, adjust_mode)(image, size)
structure = array_to_structure(image, palette)
structure.save(out_structure)
def array_to_structure(image: numpy.ndarray, palette: kdtree.KDNode, base = None):
structure = structure_block.StructureBlock((len(image[0]), len(image), 1))
for y, row in enumerate(numpy.flip(image, 0)):
for x, pixel in enumerate(row):
block = palette.search_nn(tuple(numpy.flip(pixel)))[0].data
if base is not None:
if base[x][y] == (block.block_id, block.block_state):
continue
else:
base[x][y] = (block.block_id, block.block_state)
structure.setblock((x,y,0), block.block_id, block.block_state)
return structure
def _array_to_structure(image: numpy.ndarray, in_q, out_q, base = None):
structure = structure_block.StructureBlock((len(image[0]), len(image), 1))
for y, row in enumerate(numpy.flip(image, 0)):
base_row = base[y] if base is not None else None
in_q.put((y, row, base_row))
finished_rows = 0
while True:
if finished_rows == y + 1:
break
result = out_q.get()
if result == "done":
finished_rows += 1
continue
structure.setblock(*result)
if base is not None:
base[result[0][1]][result[0][0]] = result[1:]
return structure
def _row_processor(path_to_palette: str, in_q, out_q):
palette = _get_palette(path_to_palette)
while True:
args = in_q.get()
y, row, base_row = args
for x, pixel in enumerate(row):
block = palette.search_nn(tuple(numpy.flip(pixel)))[0].data
if base_row is not None and base_row[x] == (block.block_id, block.block_state):
continue
out_q.put(((x,y,0), block.block_id, block.block_state))
out_q.put("done")
def _get_adjuster(image: numpy.ndarray, width: str = None, height: str = None, adjust_mode: str = None):
def nop(image: numpy.ndarray, size: tuple) -> numpy.ndarray:
return image
def resize_only(image: numpy.ndarray, size: tuple) -> numpy.ndarray:
return cv2.resize(image, size)
def resize_and_crop(image: numpy.ndarray, size: tuple) -> numpy.ndarray:
image = cv2.resize(image, size)
return _crop(image, width, height)
def resize_and_pad(image: numpy.ndarray, size: tuple) -> numpy.ndarray:
image = cv2.resize(image, size)
return _pad(image, width, height)
img_width = image.shape[1]
img_height = image.shape[0]
if width is None and height is None:
return nop
if width is None or height is None:
if width == img_width or height == img_height:
return nop
else:
return resize_only
if (img_width, img_height) == (width, height):
return nop
if abs(img_width/ img_height - width / height) < 0.01:
return resize_only
if adjust_mode == "fill":
return resize_and_crop
return resize_and_pad
def _crop(image: numpy.ndarray, width: int, height: int):
img_width = image.shape[1]
img_height = image.shape[0]
w_offset = (img_width - width) // 2
h_offset = (img_height - height) // 2
return image[h_offset:h_offset + height, w_offset:w_offset + width]
def _pad(image: numpy.ndarray, width: int, height: int):
img_width = image.shape[1]
img_height = image.shape[0]
w_offset = (width - img_width) // 2
h_offset = (height - img_height) // 2
destination_image = numpy.zeros((height, width, 3))
destination_image[h_offset:h_offset + img_height, w_offset: w_offset + img_width] = image
return destination_image
def _get_image_size(image: numpy.ndarray, width: int = None, height: int = None, adjust_mode: str = None):
img_width = image.shape[1]
img_height = image.shape[0]
if width is not None and height is not None:
dif = img_width / img_height > width / height
if dif and adjust_mode != "fill":
height = None
else:
width = None
if width is None and height is None:
return img_width, img_height
if height is None:
height = img_height / img_width * width
elif width is None:
width = img_width / img_height * height
return int(width), int(height)
def _get_palette(path_to_palette):
palette_file = open(path_to_palette, newline="")
palette_reader = csv.reader(palette_file, dialect="excel", delimiter=";", quotechar='"')
blocks = [_Block(tuple([int(i) for i in block[1:4]]),block[0], block[4] or None) for block in palette_reader]
palette = kdtree.create(blocks)
palette_file.close()
return palette
class _Block:
def __init__(self, color: tuple, block_id: str, block_state: str):
self.color = color
self.block_id = block_id
self.block_state = block_state
def __len__(self):
return len(self.color)
def __getitem__(self, i):
return self.color[i] | minecraft_movie_player/image_converter.py | import numpy
import cv2
from . import structure_block
import os
import csv
import kdtree
import time
import multiprocessing
import datetime
from math import ceil
def video_to_structure(path_to_video: str, destination_folder: str, name_prefix: str, path_to_palette: str = None, ticks_per_frame:int = 2, starting_frame: int = 0, width: int = None, height: int = None, adjust_mode: str = None, optimize = True, processes: int = None, on_progress = None):
path_to_palette = path_to_palette if path_to_palette is not None else os.path.join(os.path.dirname(__file__), "palette.txt")
video = cv2.VideoCapture(path_to_video)
output_fps = 20 / ticks_per_frame
video_fps = video.get(cv2.CAP_PROP_FPS)
frame_skip = video_fps / output_fps
video.set(cv2.CAP_PROP_POS_FRAMES, int(starting_frame * frame_skip) - 1)
success, image = video.read()
size = _get_image_size(image, width, height, adjust_mode)
adjust = _get_adjuster(image, width, height, adjust_mode)
path_to_palette = os.path.abspath(path_to_palette)
processes = processes if processes is not None else multiprocessing.cpu_count()
in_q = multiprocessing.Queue()
out_q = multiprocessing.Queue()
row_processors = [multiprocessing.Process(target=_row_processor, args=(path_to_palette, in_q, out_q)) for _ in range(processes)]
[process.start() for process in row_processors]
if optimize:
x = image.shape[1]
y = image.shape[0]
base = [[None for _ in range(y)] for _ in range(x)]
else:
base = None
total_frames = video.get(cv2.CAP_PROP_FRAME_COUNT) / frame_skip
total_frames = ceil(total_frames)
count = 0
total_time = 0
print("converting video...")
while success:
start = time.time()
image = adjust(image, size)
structure = _array_to_structure(image, in_q, out_q, base)
structure.save(os.path.join(destination_folder, f"{name_prefix}{starting_frame + count}.nbt"))
if on_progress is not None:
on_progress(starting_frame + count)
count += 1
elapsed = time.time() - start
total_time += elapsed
average = total_time / (count)
eta = (total_frames - starting_frame - count) * average
eta = datetime.timedelta(seconds=round(eta))
print(f"{starting_frame + count}/{total_frames} (Elapsed: {datetime.timedelta(seconds=round(total_time, 5))}, Average: {round(average, 5)}s, ETA: {eta})" + " "*10, end="\r")
video.set(cv2.CAP_PROP_POS_FRAMES, int(frame_skip * (starting_frame + count)) - 1)
success, image = video.read()
print("")
print("done!")
[process.terminate() for process in row_processors]
return count
def image_to_structure(path_to_image: str, out_structure: str, path_to_palette: str = None, width: int = None, height: int = None, adjust_mode = None):
path_to_palette = path_to_palette if path_to_palette is not None else os.path.join(os.path.dirname(__file__), "palette.txt")
palette = _get_palette(path_to_palette)
image = cv2.imread(path_to_image)
size = _get_image_size(image, width, height, adjust_mode)
image = _get_adjuster(image, width, height, adjust_mode)(image, size)
structure = array_to_structure(image, palette)
structure.save(out_structure)
def array_to_structure(image: numpy.ndarray, palette: kdtree.KDNode, base = None):
structure = structure_block.StructureBlock((len(image[0]), len(image), 1))
for y, row in enumerate(numpy.flip(image, 0)):
for x, pixel in enumerate(row):
block = palette.search_nn(tuple(numpy.flip(pixel)))[0].data
if base is not None:
if base[x][y] == (block.block_id, block.block_state):
continue
else:
base[x][y] = (block.block_id, block.block_state)
structure.setblock((x,y,0), block.block_id, block.block_state)
return structure
def _array_to_structure(image: numpy.ndarray, in_q, out_q, base = None):
structure = structure_block.StructureBlock((len(image[0]), len(image), 1))
for y, row in enumerate(numpy.flip(image, 0)):
base_row = base[y] if base is not None else None
in_q.put((y, row, base_row))
finished_rows = 0
while True:
if finished_rows == y + 1:
break
result = out_q.get()
if result == "done":
finished_rows += 1
continue
structure.setblock(*result)
if base is not None:
base[result[0][1]][result[0][0]] = result[1:]
return structure
def _row_processor(path_to_palette: str, in_q, out_q):
palette = _get_palette(path_to_palette)
while True:
args = in_q.get()
y, row, base_row = args
for x, pixel in enumerate(row):
block = palette.search_nn(tuple(numpy.flip(pixel)))[0].data
if base_row is not None and base_row[x] == (block.block_id, block.block_state):
continue
out_q.put(((x,y,0), block.block_id, block.block_state))
out_q.put("done")
def _get_adjuster(image: numpy.ndarray, width: str = None, height: str = None, adjust_mode: str = None):
def nop(image: numpy.ndarray, size: tuple) -> numpy.ndarray:
return image
def resize_only(image: numpy.ndarray, size: tuple) -> numpy.ndarray:
return cv2.resize(image, size)
def resize_and_crop(image: numpy.ndarray, size: tuple) -> numpy.ndarray:
image = cv2.resize(image, size)
return _crop(image, width, height)
def resize_and_pad(image: numpy.ndarray, size: tuple) -> numpy.ndarray:
image = cv2.resize(image, size)
return _pad(image, width, height)
img_width = image.shape[1]
img_height = image.shape[0]
if width is None and height is None:
return nop
if width is None or height is None:
if width == img_width or height == img_height:
return nop
else:
return resize_only
if (img_width, img_height) == (width, height):
return nop
if abs(img_width/ img_height - width / height) < 0.01:
return resize_only
if adjust_mode == "fill":
return resize_and_crop
return resize_and_pad
def _crop(image: numpy.ndarray, width: int, height: int):
img_width = image.shape[1]
img_height = image.shape[0]
w_offset = (img_width - width) // 2
h_offset = (img_height - height) // 2
return image[h_offset:h_offset + height, w_offset:w_offset + width]
def _pad(image: numpy.ndarray, width: int, height: int):
img_width = image.shape[1]
img_height = image.shape[0]
w_offset = (width - img_width) // 2
h_offset = (height - img_height) // 2
destination_image = numpy.zeros((height, width, 3))
destination_image[h_offset:h_offset + img_height, w_offset: w_offset + img_width] = image
return destination_image
def _get_image_size(image: numpy.ndarray, width: int = None, height: int = None, adjust_mode: str = None):
img_width = image.shape[1]
img_height = image.shape[0]
if width is not None and height is not None:
dif = img_width / img_height > width / height
if dif and adjust_mode != "fill":
height = None
else:
width = None
if width is None and height is None:
return img_width, img_height
if height is None:
height = img_height / img_width * width
elif width is None:
width = img_width / img_height * height
return int(width), int(height)
def _get_palette(path_to_palette):
palette_file = open(path_to_palette, newline="")
palette_reader = csv.reader(palette_file, dialect="excel", delimiter=";", quotechar='"')
blocks = [_Block(tuple([int(i) for i in block[1:4]]),block[0], block[4] or None) for block in palette_reader]
palette = kdtree.create(blocks)
palette_file.close()
return palette
class _Block:
def __init__(self, color: tuple, block_id: str, block_state: str):
self.color = color
self.block_id = block_id
self.block_state = block_state
def __len__(self):
return len(self.color)
def __getitem__(self, i):
return self.color[i] | 0.38943 | 0.205057 |
import numpy as np
def compute_mean_terr(res, N, d, Σ, g, ε0):
"""Compute mean tracking error from a set of quantum measurements.
Parameters
----------
res: dict
Measurements from a quantum circuit in Qiskit format.
N: int
Number of available stocks.
d: int
Number of chosen stocks.
Σ: 2d array of floats.
Stocks correlation matrix.
g: 1d array of floats.
Stocks correlation with index.
ε0: float.
Correlation of index with itself.
Return
------
terr: float.
Mean tracking error.
"""
terr = 0.0
shots = 0
for k, v in res.items():
state = int(k, 2)
shots += v
# Number of stocks in this state.
ns = 0
# Compute tracking error of this state.
terrs = 0.0
for i in range(N):
ns += (state>>i)&1
terrs += (Σ[i, i] - 2*g[i])*((state>>i)&1)
for j in range(i+1, N):
terrs += 2*Σ[i, j]*((state>>i)&1)*((state>>j)&1)
if ns == d:
terr += terrs*v
terr /= shots
terr += ε0
return terr
def find_min_terr(res, N, d, Σ, g, ε0):
"""Find minimum tracking error from a set of quantum states.
Parameters
----------
res: dict
Measurements from a quantum circuit in Qiskit format.
N: int
Number of available stocks.
d: int
Number of chosen stocks.
Σ: 2d array of floats.
Stocks correlation matrix.
g: 1d array of floats.
Stocks correlation with index.
ε0: float.
Correlation of index with itself.
Return
------
stocks: 1d array of bools.
Vector with True if stock number i is chosen.
terr: float.
Minimum tracking error.
"""
terr = 1e5
stocks = ''
for k, v in res.items():
state = int(k, 2)
# Number of stocks in this state.
ns = 0
# Compute energy of this state.
terrs = 0.0
for i in range(N):
ns += (state>>i)&1
terrs += (Σ[i, i] - 2*g[i])*((state>>i)&1)
for j in range(i+1, N):
terrs += 2*Σ[i, j]*((state>>i)&1)*((state>>j)&1)
if ns == d and terrs < terr:
terr = terrs
stocks = k
return terr, stocks | index_tracking/compute_tracking_error.py |
import numpy as np
def compute_mean_terr(res, N, d, Σ, g, ε0):
"""Compute mean tracking error from a set of quantum measurements.
Parameters
----------
res: dict
Measurements from a quantum circuit in Qiskit format.
N: int
Number of available stocks.
d: int
Number of chosen stocks.
Σ: 2d array of floats.
Stocks correlation matrix.
g: 1d array of floats.
Stocks correlation with index.
ε0: float.
Correlation of index with itself.
Return
------
terr: float.
Mean tracking error.
"""
terr = 0.0
shots = 0
for k, v in res.items():
state = int(k, 2)
shots += v
# Number of stocks in this state.
ns = 0
# Compute tracking error of this state.
terrs = 0.0
for i in range(N):
ns += (state>>i)&1
terrs += (Σ[i, i] - 2*g[i])*((state>>i)&1)
for j in range(i+1, N):
terrs += 2*Σ[i, j]*((state>>i)&1)*((state>>j)&1)
if ns == d:
terr += terrs*v
terr /= shots
terr += ε0
return terr
def find_min_terr(res, N, d, Σ, g, ε0):
"""Find minimum tracking error from a set of quantum states.
Parameters
----------
res: dict
Measurements from a quantum circuit in Qiskit format.
N: int
Number of available stocks.
d: int
Number of chosen stocks.
Σ: 2d array of floats.
Stocks correlation matrix.
g: 1d array of floats.
Stocks correlation with index.
ε0: float.
Correlation of index with itself.
Return
------
stocks: 1d array of bools.
Vector with True if stock number i is chosen.
terr: float.
Minimum tracking error.
"""
terr = 1e5
stocks = ''
for k, v in res.items():
state = int(k, 2)
# Number of stocks in this state.
ns = 0
# Compute energy of this state.
terrs = 0.0
for i in range(N):
ns += (state>>i)&1
terrs += (Σ[i, i] - 2*g[i])*((state>>i)&1)
for j in range(i+1, N):
terrs += 2*Σ[i, j]*((state>>i)&1)*((state>>j)&1)
if ns == d and terrs < terr:
terr = terrs
stocks = k
return terr, stocks | 0.864982 | 0.81119 |
import unittest
import mock
from pyhpecw7.features.switchport import Switchport
from .base_feature_test import BaseFeatureCase
IFACE_INDEX = '9'
IFACE_NAME = 'FortyGigE1/0/3'
class SwitchportTestCase(BaseFeatureCase):
@mock.patch('pyhpecw7.comware.HPCOM7')
@mock.patch('pyhpecw7.features.switchport.Interface')
def setUp(self, mock_iface, mock_device):
self.device = mock_device
mock_iface.return_value.iface_index = IFACE_INDEX
mock_iface.return_value.is_routed = True
mock_iface.return_value.interface_name = IFACE_NAME
self.switchport = Switchport(self.device, IFACE_NAME)
def test_init(self):
self.assertEqual(self.switchport.interface_name, IFACE_NAME)
self.assertEqual(self.switchport.link_type, 'unknown')
def test_get_config(self):
expected_get, get_reply = self.xml_get_and_reply('switchport')
self.device.get.return_value = get_reply
expected = {'pvid': '1', 'link_type': 'access'}
result = self.switchport.get_config()
self.assertEqual(self.switchport.link_type, 'access')
self.assertEqual(result, expected)
self.assert_get_request(expected_get)
def test_get_config_none(self):
expected_get, get_reply = self.xml_get_and_reply('switchport_none')
self.device.get.return_value = get_reply
expected = {}
result = self.switchport.get_config()
self.assertEqual(self.switchport.link_type, 'unknown')
self.assertEqual(result, expected)
self.assert_get_request(expected_get)
@mock.patch.object(Switchport, 'build')
def test_default(self, mock_build):
expected_args = {'pvid': '1', 'link_type': 'access'}
self.switchport.default()
mock_build.assert_called_with(stage=False, **expected_args)
def test_convert_interface_access(self):
expected = self.read_config_xml('switchport_convert_access')
self.switchport.convert_interface('access')
self.assert_config_request(expected)
self.switchport.convert_interface('access', stage=True)
self.assert_stage_request(expected, 'edit_config')
def test_convert_interface_trunk(self):
expected = self.read_config_xml('switchport_convert_trunk')
self.switchport.convert_interface('trunk')
self.assert_config_request(expected)
self.switchport.convert_interface('trunk', stage=True)
self.assert_stage_request(expected, 'edit_config')
def test_build_access(self):
expected = self.read_config_xml('switchport_build_access')
self.switchport.build(link_type='access', pvid='2')
self.assert_config_request(expected)
self.switchport.build(stage=True, link_type='access', pvid='2')
self.assert_stage_request(expected, 'edit_config')
def test_build_trunk(self):
expected = self.read_config_xml('switchport_build_trunk')
self.switchport.build(link_type='trunk', pvid='2')
self.assert_config_request(expected)
self.switchport.build(stage=True, link_type='trunk', pvid='2')
self.assert_stage_request(expected, 'edit_config')
if __name__ == '__main__':
unittest.main() | test/unit/test_features/test_switchport.py | import unittest
import mock
from pyhpecw7.features.switchport import Switchport
from .base_feature_test import BaseFeatureCase
IFACE_INDEX = '9'
IFACE_NAME = 'FortyGigE1/0/3'
class SwitchportTestCase(BaseFeatureCase):
@mock.patch('pyhpecw7.comware.HPCOM7')
@mock.patch('pyhpecw7.features.switchport.Interface')
def setUp(self, mock_iface, mock_device):
self.device = mock_device
mock_iface.return_value.iface_index = IFACE_INDEX
mock_iface.return_value.is_routed = True
mock_iface.return_value.interface_name = IFACE_NAME
self.switchport = Switchport(self.device, IFACE_NAME)
def test_init(self):
self.assertEqual(self.switchport.interface_name, IFACE_NAME)
self.assertEqual(self.switchport.link_type, 'unknown')
def test_get_config(self):
expected_get, get_reply = self.xml_get_and_reply('switchport')
self.device.get.return_value = get_reply
expected = {'pvid': '1', 'link_type': 'access'}
result = self.switchport.get_config()
self.assertEqual(self.switchport.link_type, 'access')
self.assertEqual(result, expected)
self.assert_get_request(expected_get)
def test_get_config_none(self):
expected_get, get_reply = self.xml_get_and_reply('switchport_none')
self.device.get.return_value = get_reply
expected = {}
result = self.switchport.get_config()
self.assertEqual(self.switchport.link_type, 'unknown')
self.assertEqual(result, expected)
self.assert_get_request(expected_get)
@mock.patch.object(Switchport, 'build')
def test_default(self, mock_build):
expected_args = {'pvid': '1', 'link_type': 'access'}
self.switchport.default()
mock_build.assert_called_with(stage=False, **expected_args)
def test_convert_interface_access(self):
expected = self.read_config_xml('switchport_convert_access')
self.switchport.convert_interface('access')
self.assert_config_request(expected)
self.switchport.convert_interface('access', stage=True)
self.assert_stage_request(expected, 'edit_config')
def test_convert_interface_trunk(self):
expected = self.read_config_xml('switchport_convert_trunk')
self.switchport.convert_interface('trunk')
self.assert_config_request(expected)
self.switchport.convert_interface('trunk', stage=True)
self.assert_stage_request(expected, 'edit_config')
def test_build_access(self):
expected = self.read_config_xml('switchport_build_access')
self.switchport.build(link_type='access', pvid='2')
self.assert_config_request(expected)
self.switchport.build(stage=True, link_type='access', pvid='2')
self.assert_stage_request(expected, 'edit_config')
def test_build_trunk(self):
expected = self.read_config_xml('switchport_build_trunk')
self.switchport.build(link_type='trunk', pvid='2')
self.assert_config_request(expected)
self.switchport.build(stage=True, link_type='trunk', pvid='2')
self.assert_stage_request(expected, 'edit_config')
if __name__ == '__main__':
unittest.main() | 0.571288 | 0.30819 |
import sys
import glob
import os
from src import PARAMETERS as PM
import numpy as np
class Carla:
def __init__(self):
sys.path.insert(1, 'D:/Data/GitHub_Repos/carla_dist/WindowsNoEditor/PythonAPI/examples')
try:
sys.path.append(glob.glob
(
'D:/Data/GitHub_Repos/carla_dist/WindowsNoEditor/PythonAPI/carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor, 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
self.actor_list = []
client = carla.Client('127.0.0.1', 2000)
client.set_timeout(2.0)
world = client.get_world()
blueprint_library = world.get_blueprint_library()
# *************************************** Add Vehicle ****************************************
bp = blueprint_library.filter("audi")[2]
spawn_point = world.get_map().get_spawn_points()[30]
vehicle = world.spawn_actor(bp, spawn_point)
vehicle.set_autopilot(True)
# vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0.0))
self.actor_list.append(vehicle)
# *************************************** Add Cameras ****************************************
cam_bp = blueprint_library.find("sensor.camera.rgb")
cam_bp.set_attribute('image_size_x', f'{PM.RESIZED_FRAME_SIZE[0]}')
cam_bp.set_attribute('image_size_y', f'{PM.RESIZED_FRAME_SIZE[1]}')
cam_bp.set_attribute('fov', '50')
spawn_point = carla.Transform(carla.Location(x=0.4, y=-0.5, z=1.5))
self.camera_left = world.spawn_actor(cam_bp, spawn_point, attach_to=vehicle)
self.actor_list.append(self.camera_left)
spawn_point = carla.Transform(carla.Location(x=0.4, y=0.5, z=1.5))
self.camera_right = world.spawn_actor(cam_bp, spawn_point, attach_to=vehicle)
self.actor_list.append(self.camera_right)
self.camera_left.listen(lambda data: self.get_image(data, 'left'))
self.camera_right.listen(lambda data: self.get_image(data, 'right'))
self.left_image = ()
self.right_image = ()
def get_image(self, image, camera):
img = np.array(image.raw_data)
img2 = img.reshape((PM.RESIZED_FRAME_SIZE[1], PM.RESIZED_FRAME_SIZE[0], 4))
img3 = img2[:, :, :3]
if camera == 'left':
self.left_image = img3
if camera == 'right':
self.right_image = img3
def destroy(self):
for actor in self.actor_list:
actor.destroy()
print("All cleaned up!") | src/carla_interface.py | import sys
import glob
import os
from src import PARAMETERS as PM
import numpy as np
class Carla:
def __init__(self):
sys.path.insert(1, 'D:/Data/GitHub_Repos/carla_dist/WindowsNoEditor/PythonAPI/examples')
try:
sys.path.append(glob.glob
(
'D:/Data/GitHub_Repos/carla_dist/WindowsNoEditor/PythonAPI/carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor, 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
self.actor_list = []
client = carla.Client('127.0.0.1', 2000)
client.set_timeout(2.0)
world = client.get_world()
blueprint_library = world.get_blueprint_library()
# *************************************** Add Vehicle ****************************************
bp = blueprint_library.filter("audi")[2]
spawn_point = world.get_map().get_spawn_points()[30]
vehicle = world.spawn_actor(bp, spawn_point)
vehicle.set_autopilot(True)
# vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0.0))
self.actor_list.append(vehicle)
# *************************************** Add Cameras ****************************************
cam_bp = blueprint_library.find("sensor.camera.rgb")
cam_bp.set_attribute('image_size_x', f'{PM.RESIZED_FRAME_SIZE[0]}')
cam_bp.set_attribute('image_size_y', f'{PM.RESIZED_FRAME_SIZE[1]}')
cam_bp.set_attribute('fov', '50')
spawn_point = carla.Transform(carla.Location(x=0.4, y=-0.5, z=1.5))
self.camera_left = world.spawn_actor(cam_bp, spawn_point, attach_to=vehicle)
self.actor_list.append(self.camera_left)
spawn_point = carla.Transform(carla.Location(x=0.4, y=0.5, z=1.5))
self.camera_right = world.spawn_actor(cam_bp, spawn_point, attach_to=vehicle)
self.actor_list.append(self.camera_right)
self.camera_left.listen(lambda data: self.get_image(data, 'left'))
self.camera_right.listen(lambda data: self.get_image(data, 'right'))
self.left_image = ()
self.right_image = ()
def get_image(self, image, camera):
img = np.array(image.raw_data)
img2 = img.reshape((PM.RESIZED_FRAME_SIZE[1], PM.RESIZED_FRAME_SIZE[0], 4))
img3 = img2[:, :, :3]
if camera == 'left':
self.left_image = img3
if camera == 'right':
self.right_image = img3
def destroy(self):
for actor in self.actor_list:
actor.destroy()
print("All cleaned up!") | 0.233357 | 0.128717 |
from intcode import Intcode
with open("../input/day21.txt", 'r') as inputFile:
splitData = inputFile.read().split(",")
data = [int(x) for x in splitData]
runner = Intcode(verbose=False)
isVerbose = False
def runProgram(springscript: list, labels: str):
assert(len(springscript) <= 16)
inputStream = [ord(x) for line in springscript for x in line]
runner.initProgram(data, stallOnOutput=True)
runner.runProgram()
while runner.readOutput:
if isVerbose: print(chr(runner.retVal), end='')
runner.runProgram()
if isVerbose: print("".join([" " + x for x in springscript]))
assert(runner.needsInput)
runner.runProgram(inputStream=inputStream)
assert(runner.readOutput)
pos = 0
x = 0
isFloor = False
while runner.readOutput and not runner.eop:
if runner.retVal > 127:
return runner.retVal
if isVerbose:
print(chr(runner.retVal), end='')
if chr(runner.retVal) == '#':
isFloor = True
if chr(runner.retVal) == '\n':
if isFloor:
for x in range(17):
idx = x - pos + 1
if idx >= 0 and idx < len(labels):
print(labels[idx], end='')
else:
print(' ', end='')
print()
x = 0
isFloor = False
elif chr(runner.retVal) == '@':
pos = x
x += 1
runner.runProgram()
return None
springscript = [
"NOT A T\n",
"NOT D J\n",
"AND T J\n",
"NOT C T\n",
"AND D T\n",
"OR T J\n",
"NOT A T\n",
"OR T J\n",
"WALK\n"
]
part1 = runProgram(springscript, labels='RABCD')
assert(part1 is not None)
print("==============================")
print("Part1:", part1)
print("==============================\n")
springscript = [
"NOT E T\n",
"NOT H J\n",
"AND T J\n",
"NOT J J\n",
"NOT C T\n",
"AND T J\n",
"NOT B T\n",
"OR T J\n",
"NOT A T\n",
"OR T J\n",
"AND D J\n",
"RUN\n"
]
part2 = runProgram(springscript, labels='RABCDEFGHI')
assert(part2 is not None)
print("==============================")
print("Part2:", part2)
print("==============================\n") | 2019/src/day21.py | from intcode import Intcode
with open("../input/day21.txt", 'r') as inputFile:
splitData = inputFile.read().split(",")
data = [int(x) for x in splitData]
runner = Intcode(verbose=False)
isVerbose = False
def runProgram(springscript: list, labels: str):
assert(len(springscript) <= 16)
inputStream = [ord(x) for line in springscript for x in line]
runner.initProgram(data, stallOnOutput=True)
runner.runProgram()
while runner.readOutput:
if isVerbose: print(chr(runner.retVal), end='')
runner.runProgram()
if isVerbose: print("".join([" " + x for x in springscript]))
assert(runner.needsInput)
runner.runProgram(inputStream=inputStream)
assert(runner.readOutput)
pos = 0
x = 0
isFloor = False
while runner.readOutput and not runner.eop:
if runner.retVal > 127:
return runner.retVal
if isVerbose:
print(chr(runner.retVal), end='')
if chr(runner.retVal) == '#':
isFloor = True
if chr(runner.retVal) == '\n':
if isFloor:
for x in range(17):
idx = x - pos + 1
if idx >= 0 and idx < len(labels):
print(labels[idx], end='')
else:
print(' ', end='')
print()
x = 0
isFloor = False
elif chr(runner.retVal) == '@':
pos = x
x += 1
runner.runProgram()
return None
springscript = [
"NOT A T\n",
"NOT D J\n",
"AND T J\n",
"NOT C T\n",
"AND D T\n",
"OR T J\n",
"NOT A T\n",
"OR T J\n",
"WALK\n"
]
part1 = runProgram(springscript, labels='RABCD')
assert(part1 is not None)
print("==============================")
print("Part1:", part1)
print("==============================\n")
springscript = [
"NOT E T\n",
"NOT H J\n",
"AND T J\n",
"NOT J J\n",
"NOT C T\n",
"AND T J\n",
"NOT B T\n",
"OR T J\n",
"NOT A T\n",
"OR T J\n",
"AND D J\n",
"RUN\n"
]
part2 = runProgram(springscript, labels='RABCDEFGHI')
assert(part2 is not None)
print("==============================")
print("Part2:", part2)
print("==============================\n") | 0.31384 | 0.384046 |
import logging
from RouterConfiguration.Cisco.cisco_config_features import *
def get_index_from_args(router, feature, args):
"""
Generates the index (and thereby equivalence class) for parameter values passed to router feature triplets
:param router: Router for the current feature
:param feature: Configuration feature, currently only Cisco configuration features are supported
:param args: Parameter value used
:return: index of args in router.get_possible_args()[feature], if it is not present the "middle" value is used as
default
"""
if args == -1:
return -1
try:
return router.get_possible_args()[feature].index(args)
except ValueError:
if feature == OSPFFeatures.MAX_METRIC:
(ext, stub, summary) = args
if ext not in ['', ' external-lsa 1', ' external-lsa 1000', ' external-lsa 16777215']:
ext = ' external-lsa 1000'
if summary not in ['', ' summary-lsa 1', ' summary-lsa 1000', ' summary-lsa 16777215']:
summary = ' summary-lsa 1000'
return router.get_possible_args()[feature].index((ext, stub, summary))
elif feature == OSPFFeatures.AREA_RANGE:
(net, adv, cost) = args
return router.get_possible_args()[feature].index((net, adv, ' cost 100'))
elif feature == OSPFFeatures.NSSA_DEFAULT_INFORMATION_ORIGINATE:
(metric, t) = args
return router.get_possible_args()[feature].index((' metric 100', t))
elif feature == BGPFeatures.DISTANCE_BGP:
(dist1, dist2, dist3) = args
if dist1 != 1 and dist1 != 255:
dist1 = 100
if dist2 != 1 and dist2 != 255:
dist2 = 100
if dist3 != 1 and dist3 != 255:
dist3 = 100
return router.get_possible_args()[feature].index((dist1, dist2, dist3))
elif feature == RouteMapFeatures.SET_METRIC:
(metric, ) = args
if metric < 0:
return 1
else:
return 2
elif feature == RouteMapFeatures.SET_FEATURE_BGP_IN:
f = args[0]
a = args[1:]
return get_index_from_args(router, f, a)
elif feature == RouteMapFeatures.SET_FEATURE_BGP_OUT:
f = args[0]
a = args[1:]
return get_index_from_args(router, f, a)
else:
return 1
def get_coverage(router_features, rows, possible_args, extra_features=lambda feature: False):
"""
Generates pairwise coverage information for a given set of router feature triplets as well as a list of rows
containing parameter values
:param router_features: List of router feature triplets
:param rows: Rows which each map each router feature triplet to a parameter value
:param possible_args: A dict mapping containing all possible parameter values for a given feature
:param extra_features: function which returns True if the given feature should have an extra value representing
"invalid" configurations. This is used only for the random baseline, in particular to represent for example
using a route-map which is not actually defined on the router
:return: The total number of unique pairs in router_features as well as the number of unique pairs covered by rows
"""
covered_pairs = {(f1, f2): set() for f1 in router_features for f2 in router_features if f1 != f2}
def num_feature_args(feature):
if extra_features(feature):
return len(possible_args[feature]) + 2
else:
return len(possible_args[feature]) + 1
num_pairs = {((r1, f1, arg1), (r2, f2, arg2)): num_feature_args(f1) * num_feature_args(f2)
for (r1, f1, arg1) in router_features for (r2, f2, arg2) in router_features if
(r1, f1, arg1) != (r2, f2, arg2)}
coverage = []
for row in rows:
for f1 in row:
for f2 in row:
if f1 != f2:
covered_pairs[f1, f2].add((row[f1], row[f2]))
covered = 0
for p in covered_pairs:
covered = covered + len(covered_pairs[p])
coverage.append(covered)
total = 0
for p in num_pairs:
total = total + num_pairs[p]
return total, coverage | Evaluation/coverage.py | import logging
from RouterConfiguration.Cisco.cisco_config_features import *
def get_index_from_args(router, feature, args):
"""
Generates the index (and thereby equivalence class) for parameter values passed to router feature triplets
:param router: Router for the current feature
:param feature: Configuration feature, currently only Cisco configuration features are supported
:param args: Parameter value used
:return: index of args in router.get_possible_args()[feature], if it is not present the "middle" value is used as
default
"""
if args == -1:
return -1
try:
return router.get_possible_args()[feature].index(args)
except ValueError:
if feature == OSPFFeatures.MAX_METRIC:
(ext, stub, summary) = args
if ext not in ['', ' external-lsa 1', ' external-lsa 1000', ' external-lsa 16777215']:
ext = ' external-lsa 1000'
if summary not in ['', ' summary-lsa 1', ' summary-lsa 1000', ' summary-lsa 16777215']:
summary = ' summary-lsa 1000'
return router.get_possible_args()[feature].index((ext, stub, summary))
elif feature == OSPFFeatures.AREA_RANGE:
(net, adv, cost) = args
return router.get_possible_args()[feature].index((net, adv, ' cost 100'))
elif feature == OSPFFeatures.NSSA_DEFAULT_INFORMATION_ORIGINATE:
(metric, t) = args
return router.get_possible_args()[feature].index((' metric 100', t))
elif feature == BGPFeatures.DISTANCE_BGP:
(dist1, dist2, dist3) = args
if dist1 != 1 and dist1 != 255:
dist1 = 100
if dist2 != 1 and dist2 != 255:
dist2 = 100
if dist3 != 1 and dist3 != 255:
dist3 = 100
return router.get_possible_args()[feature].index((dist1, dist2, dist3))
elif feature == RouteMapFeatures.SET_METRIC:
(metric, ) = args
if metric < 0:
return 1
else:
return 2
elif feature == RouteMapFeatures.SET_FEATURE_BGP_IN:
f = args[0]
a = args[1:]
return get_index_from_args(router, f, a)
elif feature == RouteMapFeatures.SET_FEATURE_BGP_OUT:
f = args[0]
a = args[1:]
return get_index_from_args(router, f, a)
else:
return 1
def get_coverage(router_features, rows, possible_args, extra_features=lambda feature: False):
"""
Generates pairwise coverage information for a given set of router feature triplets as well as a list of rows
containing parameter values
:param router_features: List of router feature triplets
:param rows: Rows which each map each router feature triplet to a parameter value
:param possible_args: A dict mapping containing all possible parameter values for a given feature
:param extra_features: function which returns True if the given feature should have an extra value representing
"invalid" configurations. This is used only for the random baseline, in particular to represent for example
using a route-map which is not actually defined on the router
:return: The total number of unique pairs in router_features as well as the number of unique pairs covered by rows
"""
covered_pairs = {(f1, f2): set() for f1 in router_features for f2 in router_features if f1 != f2}
def num_feature_args(feature):
if extra_features(feature):
return len(possible_args[feature]) + 2
else:
return len(possible_args[feature]) + 1
num_pairs = {((r1, f1, arg1), (r2, f2, arg2)): num_feature_args(f1) * num_feature_args(f2)
for (r1, f1, arg1) in router_features for (r2, f2, arg2) in router_features if
(r1, f1, arg1) != (r2, f2, arg2)}
coverage = []
for row in rows:
for f1 in row:
for f2 in row:
if f1 != f2:
covered_pairs[f1, f2].add((row[f1], row[f2]))
covered = 0
for p in covered_pairs:
covered = covered + len(covered_pairs[p])
coverage.append(covered)
total = 0
for p in num_pairs:
total = total + num_pairs[p]
return total, coverage | 0.619932 | 0.432723 |
from django.db import models
from filingcabinet.models import (
AbstractDocument,
AbstractDocumentCollection,
DocumentManager as FCDocumentManager,
DocumentCollectionManager as FCDocumentCollectionManager,
get_page_image_filename,
Page,
)
from froide.helper.auth import (
can_read_object_authenticated,
can_write_object,
get_read_queryset,
get_write_queryset,
)
class AuthQuerysetMixin:
def get_authenticated_queryset(self, request):
qs = self.get_queryset()
return get_read_queryset(
qs, request, has_team=True, public_field="public", scope="read:document"
)
class DocumentManager(AuthQuerysetMixin, FCDocumentManager):
pass
class Document(AbstractDocument):
original = models.ForeignKey(
"foirequest.FoiAttachment",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="original_document",
)
foirequest = models.ForeignKey(
"foirequest.FoiRequest", null=True, blank=True, on_delete=models.SET_NULL
)
publicbody = models.ForeignKey(
"publicbody.PublicBody", null=True, blank=True, on_delete=models.SET_NULL
)
team = models.ForeignKey(
"team.Team", null=True, blank=True, on_delete=models.SET_NULL
)
objects = DocumentManager()
def is_public(self):
return self.public
def can_read(self, request):
if self.can_read_unlisted(request):
return True
return can_read_object_authenticated(self, request=request)
def can_write(self, request):
return can_write_object(self, request=request)
@classmethod
def get_annotatable(cls, request):
cond = models.Q(public=True, allow_annotation=True)
return get_write_queryset(
cls.objects.all(),
request,
has_team=True,
user_write_filter=cond,
)
@classmethod
def get_serializer_class(cls, detail=False):
from .api_views import DocumentSerializer, DocumentDetailSerializer
if detail:
return DocumentDetailSerializer
return DocumentSerializer
def get_crossdomain_auth(self, filename=None):
from .auth import DocumentCrossDomainMediaAuth
if filename is None:
filename = self.get_document_filename()
return DocumentCrossDomainMediaAuth({"object": self, "filename": filename})
def get_authorized_file_url(self, filename=None):
if self.public:
return self.get_file_url(filename=filename)
return self.get_crossdomain_auth(filename=filename).get_full_media_url(
authorized=True
)
def get_page_template(self, page="{page}", size="{size}"):
filename = get_page_image_filename(page=page, size=size)
return self.get_authorized_file_url(filename=filename)
def get_cover_image(self):
return self.get_authorized_file_url(
filename=get_page_image_filename(page=1, size="small")
)
@property
def first_page(self):
if not hasattr(self, "_first_page"):
try:
self._first_page = Page.objects.get(number=1, document=self)
except Page.DoesNotExist:
return None
return self._first_page
def get_cover_image_file(self):
if self.first_page:
return self.first_page.image
return None
class DocumentCollectionManager(AuthQuerysetMixin, FCDocumentCollectionManager):
pass
class DocumentCollection(AbstractDocumentCollection):
team = models.ForeignKey(
"team.Team", null=True, blank=True, on_delete=models.SET_NULL
)
objects = DocumentCollectionManager()
def is_public(self):
return self.public
def can_read(self, request):
if self.can_read_unlisted(request):
return True
return can_read_object_authenticated(self, request=request)
def can_write(self, request):
return can_write_object(self, request=request)
@classmethod
def get_serializer_class(cls):
from .api_views import DocumentCollectionSerializer
return DocumentCollectionSerializer | froide/document/models.py | from django.db import models
from filingcabinet.models import (
AbstractDocument,
AbstractDocumentCollection,
DocumentManager as FCDocumentManager,
DocumentCollectionManager as FCDocumentCollectionManager,
get_page_image_filename,
Page,
)
from froide.helper.auth import (
can_read_object_authenticated,
can_write_object,
get_read_queryset,
get_write_queryset,
)
class AuthQuerysetMixin:
def get_authenticated_queryset(self, request):
qs = self.get_queryset()
return get_read_queryset(
qs, request, has_team=True, public_field="public", scope="read:document"
)
class DocumentManager(AuthQuerysetMixin, FCDocumentManager):
pass
class Document(AbstractDocument):
original = models.ForeignKey(
"foirequest.FoiAttachment",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="original_document",
)
foirequest = models.ForeignKey(
"foirequest.FoiRequest", null=True, blank=True, on_delete=models.SET_NULL
)
publicbody = models.ForeignKey(
"publicbody.PublicBody", null=True, blank=True, on_delete=models.SET_NULL
)
team = models.ForeignKey(
"team.Team", null=True, blank=True, on_delete=models.SET_NULL
)
objects = DocumentManager()
def is_public(self):
return self.public
def can_read(self, request):
if self.can_read_unlisted(request):
return True
return can_read_object_authenticated(self, request=request)
def can_write(self, request):
return can_write_object(self, request=request)
@classmethod
def get_annotatable(cls, request):
cond = models.Q(public=True, allow_annotation=True)
return get_write_queryset(
cls.objects.all(),
request,
has_team=True,
user_write_filter=cond,
)
@classmethod
def get_serializer_class(cls, detail=False):
from .api_views import DocumentSerializer, DocumentDetailSerializer
if detail:
return DocumentDetailSerializer
return DocumentSerializer
def get_crossdomain_auth(self, filename=None):
from .auth import DocumentCrossDomainMediaAuth
if filename is None:
filename = self.get_document_filename()
return DocumentCrossDomainMediaAuth({"object": self, "filename": filename})
def get_authorized_file_url(self, filename=None):
if self.public:
return self.get_file_url(filename=filename)
return self.get_crossdomain_auth(filename=filename).get_full_media_url(
authorized=True
)
def get_page_template(self, page="{page}", size="{size}"):
filename = get_page_image_filename(page=page, size=size)
return self.get_authorized_file_url(filename=filename)
def get_cover_image(self):
return self.get_authorized_file_url(
filename=get_page_image_filename(page=1, size="small")
)
@property
def first_page(self):
if not hasattr(self, "_first_page"):
try:
self._first_page = Page.objects.get(number=1, document=self)
except Page.DoesNotExist:
return None
return self._first_page
def get_cover_image_file(self):
if self.first_page:
return self.first_page.image
return None
class DocumentCollectionManager(AuthQuerysetMixin, FCDocumentCollectionManager):
pass
class DocumentCollection(AbstractDocumentCollection):
team = models.ForeignKey(
"team.Team", null=True, blank=True, on_delete=models.SET_NULL
)
objects = DocumentCollectionManager()
def is_public(self):
return self.public
def can_read(self, request):
if self.can_read_unlisted(request):
return True
return can_read_object_authenticated(self, request=request)
def can_write(self, request):
return can_write_object(self, request=request)
@classmethod
def get_serializer_class(cls):
from .api_views import DocumentCollectionSerializer
return DocumentCollectionSerializer | 0.509276 | 0.102305 |
import pandas as pd
import numpy as np
import skimage
from tqdm import tqdm
import utils
class WindTurbinesDataset(utils.Dataset):
def load_samples(self, dataset_dir, subset, config):
"""Return the requested number of images.
count: number of images to generate.
height, width: the size of the generated images.
"""
assert subset in ["train", "validate"]
CSV_FILE = dataset_dir + 'metadata.csv'
frame = pd.read_csv(CSV_FILE)
frame = frame[frame['subset'] == subset]
frame = frame[frame['contains_wind_turbine'] == 'positive']
# Add classes
self.add_class("windturbines", 1, "windturbine")
# Add images
# Images are loaded in load_image().
rows = list(frame.iterrows())
for _, record in tqdm(rows):
offset_x = float(record['offset_x']) / config.RESOLUTION / record['scale']
offset_y = float(record['offset_y']) / config.RESOLUTION / record['scale']
centroid_pixel_x = config.IMAGE_SHAPE[0] / 2 - offset_x
centroid_pixel_y = config.IMAGE_SHAPE[1] / 2 + offset_y
self.add_image("windturbines",
image_id=record['image_file'], path=dataset_dir + record['image_file'],
width=config.IMAGE_SHAPE[0], height=config.IMAGE_SHAPE[1],
centroids=[(round(centroid_pixel_y), round(centroid_pixel_x))], # kinda weird HxW
size=config.OBJECT_SIZE / 2,
geolocation_rd=(float(record['original_rd_x']), float(record['original_rd_y'])),
)
def load_mask(self, image_id):
"""Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# If not a balloon dataset image, delegate to parent class.
image_info = self.image_info[image_id]
if image_info["source"] != "windturbines":
return super(self.__class__, self).load_mask(image_id)
# Convert polygons to a bitmap mask of shape
# [height, width, instance_count]
info = self.image_info[image_id]
mask = np.zeros([info["height"], info["width"], len(info["centroids"])], # prepared for multiple instances
dtype=np.uint8)
for i, centroid in enumerate(info["centroids"]):
# Get indexes of pixels inside the polygon and set them to 1
rr, cc = skimage.draw.circle(centroid[0], centroid[1], 10)
mask[rr, cc, i] = 1
# Return mask, and array of class IDs of each instance. Since we have
# one class ID only, we return an array of 1s
return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
def image_reference(self, image_id):
"""Return the path of the image."""
info = self.image_info[image_id]
if info["source"] == "windturbines":
return info["path"]
else:
super(self.__class__, self).image_reference(image_id) | model/mrcnn/wind_turbines_dataset.py | import pandas as pd
import numpy as np
import skimage
from tqdm import tqdm
import utils
class WindTurbinesDataset(utils.Dataset):
def load_samples(self, dataset_dir, subset, config):
"""Return the requested number of images.
count: number of images to generate.
height, width: the size of the generated images.
"""
assert subset in ["train", "validate"]
CSV_FILE = dataset_dir + 'metadata.csv'
frame = pd.read_csv(CSV_FILE)
frame = frame[frame['subset'] == subset]
frame = frame[frame['contains_wind_turbine'] == 'positive']
# Add classes
self.add_class("windturbines", 1, "windturbine")
# Add images
# Images are loaded in load_image().
rows = list(frame.iterrows())
for _, record in tqdm(rows):
offset_x = float(record['offset_x']) / config.RESOLUTION / record['scale']
offset_y = float(record['offset_y']) / config.RESOLUTION / record['scale']
centroid_pixel_x = config.IMAGE_SHAPE[0] / 2 - offset_x
centroid_pixel_y = config.IMAGE_SHAPE[1] / 2 + offset_y
self.add_image("windturbines",
image_id=record['image_file'], path=dataset_dir + record['image_file'],
width=config.IMAGE_SHAPE[0], height=config.IMAGE_SHAPE[1],
centroids=[(round(centroid_pixel_y), round(centroid_pixel_x))], # kinda weird HxW
size=config.OBJECT_SIZE / 2,
geolocation_rd=(float(record['original_rd_x']), float(record['original_rd_y'])),
)
def load_mask(self, image_id):
"""Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# If not a balloon dataset image, delegate to parent class.
image_info = self.image_info[image_id]
if image_info["source"] != "windturbines":
return super(self.__class__, self).load_mask(image_id)
# Convert polygons to a bitmap mask of shape
# [height, width, instance_count]
info = self.image_info[image_id]
mask = np.zeros([info["height"], info["width"], len(info["centroids"])], # prepared for multiple instances
dtype=np.uint8)
for i, centroid in enumerate(info["centroids"]):
# Get indexes of pixels inside the polygon and set them to 1
rr, cc = skimage.draw.circle(centroid[0], centroid[1], 10)
mask[rr, cc, i] = 1
# Return mask, and array of class IDs of each instance. Since we have
# one class ID only, we return an array of 1s
return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
def image_reference(self, image_id):
"""Return the path of the image."""
info = self.image_info[image_id]
if info["source"] == "windturbines":
return info["path"]
else:
super(self.__class__, self).image_reference(image_id) | 0.716516 | 0.433802 |
import struct
EOL = b"\x00"
# Integer limit unsigned short
STRING_LENGTH_MAX_VALUE = 65535
DATA_TYPE_ENCODERS = {
"float16": (16, struct.Struct("<e")),
"float32": (32, struct.Struct("<f")),
"float64": (64, struct.Struct("<d")),
"int16": (16, struct.Struct("<h")),
"int32": (32, struct.Struct("<i")),
"int64": (64, struct.Struct("<q")),
"uint16": (16, struct.Struct("<H")),
"uint32": (32, struct.Struct("<I")),
"uint64": (64, struct.Struct("<Q"))
}
def encode_string(input_string):
"""Encode the string value in binary using utf-8
as well as its length (valuable info when decoding
later on). Length will be encoded as an unsigned
short (max 65535).
"""
input_string_encoded = input_string.encode("utf-8")
length = len(input_string_encoded)
length_encoded = struct.pack("<H", length)
return length_encoded + input_string_encoded
def encode_presentation_properties(presentation_properties):
"""Encode the presentation properties
Each presentation property has its own binary representation.
This method will be updated as more presentation properties
are supported.
For example the description keyword corresponds to b"\x04"
and the description value will be string encoded, and the whole
will be the description presentation property encoded.
If there are no presentation properties the empty binary string
is returned. Otherwise it's b"\x1e" followed by the binary encoding
of each presentation property key-value pair.
Note: Order matters, description is encoded and then optional in this case.
Args:
presentation_properties (dict): the presentation properties
Returns:
bytes: the binary representation of the presentation
properties.
"""
result = b""
if presentation_properties == {}:
return result
description = presentation_properties.get("description")
if description is not None:
result += b"\x04" + encode_string(description)
optional = presentation_properties.get("optional")
if optional is not None:
result += b"\x05" + (b"\x01" if optional else b"\x00")
return b"\x1e" + result
def decode_number(binary_input, num_type):
precision, dtype_struct = DATA_TYPE_ENCODERS[num_type]
number_of_bytes = int(precision/8)
encoded_number, rest = (binary_input[:number_of_bytes],
binary_input[number_of_bytes:])
return dtype_struct.unpack(encoded_number)[0], rest
def encode_number(value, num_type):
precision, dtype_struct = DATA_TYPE_ENCODERS[num_type]
return dtype_struct.pack(value) | binary/utils.py | import struct
EOL = b"\x00"
# Integer limit unsigned short
STRING_LENGTH_MAX_VALUE = 65535
DATA_TYPE_ENCODERS = {
"float16": (16, struct.Struct("<e")),
"float32": (32, struct.Struct("<f")),
"float64": (64, struct.Struct("<d")),
"int16": (16, struct.Struct("<h")),
"int32": (32, struct.Struct("<i")),
"int64": (64, struct.Struct("<q")),
"uint16": (16, struct.Struct("<H")),
"uint32": (32, struct.Struct("<I")),
"uint64": (64, struct.Struct("<Q"))
}
def encode_string(input_string):
"""Encode the string value in binary using utf-8
as well as its length (valuable info when decoding
later on). Length will be encoded as an unsigned
short (max 65535).
"""
input_string_encoded = input_string.encode("utf-8")
length = len(input_string_encoded)
length_encoded = struct.pack("<H", length)
return length_encoded + input_string_encoded
def encode_presentation_properties(presentation_properties):
"""Encode the presentation properties
Each presentation property has its own binary representation.
This method will be updated as more presentation properties
are supported.
For example the description keyword corresponds to b"\x04"
and the description value will be string encoded, and the whole
will be the description presentation property encoded.
If there are no presentation properties the empty binary string
is returned. Otherwise it's b"\x1e" followed by the binary encoding
of each presentation property key-value pair.
Note: Order matters, description is encoded and then optional in this case.
Args:
presentation_properties (dict): the presentation properties
Returns:
bytes: the binary representation of the presentation
properties.
"""
result = b""
if presentation_properties == {}:
return result
description = presentation_properties.get("description")
if description is not None:
result += b"\x04" + encode_string(description)
optional = presentation_properties.get("optional")
if optional is not None:
result += b"\x05" + (b"\x01" if optional else b"\x00")
return b"\x1e" + result
def decode_number(binary_input, num_type):
precision, dtype_struct = DATA_TYPE_ENCODERS[num_type]
number_of_bytes = int(precision/8)
encoded_number, rest = (binary_input[:number_of_bytes],
binary_input[number_of_bytes:])
return dtype_struct.unpack(encoded_number)[0], rest
def encode_number(value, num_type):
precision, dtype_struct = DATA_TYPE_ENCODERS[num_type]
return dtype_struct.pack(value) | 0.76145 | 0.306903 |
import argparse
import logging
import mimetypes
import os
from pathlib import Path
from typing import Optional, Sequence
from monocat.github import AssetRequest, AssetResponse, GitHubClient, ReleaseRequest, ReleaseResponse
_logger = logging.getLogger(__name__)
class ReleaseError(RuntimeError):
"""A release error"""
class ReleaseManager:
def __init__(self, owner: str, repository: str, interactive: bool):
self.owner = owner
self.repository = repository
self.interactive = interactive
self.client = GitHubClient(owner, repository)
def get_release(self, release_id: str) -> Optional[ReleaseResponse]:
"""Get a GitHub release by release identifier"""
return self.client.get_release(release_id)
def get_release_by_tag(self, tag: str) -> Optional[ReleaseResponse]:
"""Get a GitHub release by tag"""
return self.client.get_release_by_tag(tag)
def create_release(self, request: ReleaseRequest) -> ReleaseResponse:
return self.client.create_release(request)
def update_release(self, request: ReleaseRequest, release_id: int) -> ReleaseResponse:
return self.client.update_release(request, release_id)
def upload_assets(self, release: ReleaseResponse,
artifacts: Sequence[os.PathLike]) -> Sequence[AssetResponse]:
response = []
existing_asset_ids_by_name = {asset.name: asset.id for asset in release.assets}
artifact_paths = [Path(artifact) for artifact in artifacts]
for artifact_path in artifact_paths:
asset = AssetRequest(name=artifact_path.name, label=artifact_path.name)
with open(artifact_path, 'rb') as artifact_file:
asset_id = existing_asset_ids_by_name.get(asset.name)
# TODO: Add a force flag to automatically delete (and thus overwrite) existing assets.
if not asset_id:
response.append(
self.client.upload_asset(
upload_url=release.upload_url, asset=asset, body=artifact_file.read()
)
)
return response | monocat/__init__.py | import argparse
import logging
import mimetypes
import os
from pathlib import Path
from typing import Optional, Sequence
from monocat.github import AssetRequest, AssetResponse, GitHubClient, ReleaseRequest, ReleaseResponse
_logger = logging.getLogger(__name__)
class ReleaseError(RuntimeError):
"""A release error"""
class ReleaseManager:
def __init__(self, owner: str, repository: str, interactive: bool):
self.owner = owner
self.repository = repository
self.interactive = interactive
self.client = GitHubClient(owner, repository)
def get_release(self, release_id: str) -> Optional[ReleaseResponse]:
"""Get a GitHub release by release identifier"""
return self.client.get_release(release_id)
def get_release_by_tag(self, tag: str) -> Optional[ReleaseResponse]:
"""Get a GitHub release by tag"""
return self.client.get_release_by_tag(tag)
def create_release(self, request: ReleaseRequest) -> ReleaseResponse:
return self.client.create_release(request)
def update_release(self, request: ReleaseRequest, release_id: int) -> ReleaseResponse:
return self.client.update_release(request, release_id)
def upload_assets(self, release: ReleaseResponse,
artifacts: Sequence[os.PathLike]) -> Sequence[AssetResponse]:
response = []
existing_asset_ids_by_name = {asset.name: asset.id for asset in release.assets}
artifact_paths = [Path(artifact) for artifact in artifacts]
for artifact_path in artifact_paths:
asset = AssetRequest(name=artifact_path.name, label=artifact_path.name)
with open(artifact_path, 'rb') as artifact_file:
asset_id = existing_asset_ids_by_name.get(asset.name)
# TODO: Add a force flag to automatically delete (and thus overwrite) existing assets.
if not asset_id:
response.append(
self.client.upload_asset(
upload_url=release.upload_url, asset=asset, body=artifact_file.read()
)
)
return response | 0.697918 | 0.050261 |
import argparse
import sys
import os
from collections import deque
from lophi.capture import CaptureReader
def parse_dcap(filename):
reader = CaptureReader(filename)
start = None
end = None
data_size = 0
window_data = deque([])
window_time = deque([])
window_sum = 0
max_throughput = 0
for (ts,data) in reader:
data_size += len(data)
# Keep track of timestamps
if start is None:
start = ts
end = ts
window_sum += len(data)
window_data.append(len(data))
window_time.append(ts)
# Only compute with a certain number of samples
if len(window_data) >= 10000 and window_time[-1] != window_time[0]:
throughput = window_sum/(window_time[-1]-window_time[0])
if throughput > max_throughput:
max_throughput = throughput
while len(window_data) >= 1000 and window_time[-1] != window_time[0]:
data_remove = window_data.popleft()
window_sum -= data_remove
window_time.popleft()
elapsed_time = end-start
print "Time elapsed: ",elapsed_time
print "Bytes Read: ",data_size
print "Avg Rate: ", (data_size/elapsed_time)
print "Max Rate: ", max_throughput
def parse_dcaps(directory):
for (dirpath, dirnames, filenames) in os.walk(directory):
for file in filenames:
# Is this iozone output?
if file.endswith("dcap"):
print "* Parsing %s..."%file
parse_dcap(os.path.join(dirpath, file))
if __name__ == "__main__":
# Import our command line parser
args = argparse.ArgumentParser()
args.add_argument("dcap_dir", action="store", type=str, default=None,
help="Directory containting dcap files.")
# Get arguments
options = args.parse_args()
if options.dcap_dir is None:
print "ERROR: Must provide input directory with dcaps."
sys.exit(0)
parse_dcaps(options.dcap_dir) | experiments/artifacts/disk/parse_dcaps.py | import argparse
import sys
import os
from collections import deque
from lophi.capture import CaptureReader
def parse_dcap(filename):
reader = CaptureReader(filename)
start = None
end = None
data_size = 0
window_data = deque([])
window_time = deque([])
window_sum = 0
max_throughput = 0
for (ts,data) in reader:
data_size += len(data)
# Keep track of timestamps
if start is None:
start = ts
end = ts
window_sum += len(data)
window_data.append(len(data))
window_time.append(ts)
# Only compute with a certain number of samples
if len(window_data) >= 10000 and window_time[-1] != window_time[0]:
throughput = window_sum/(window_time[-1]-window_time[0])
if throughput > max_throughput:
max_throughput = throughput
while len(window_data) >= 1000 and window_time[-1] != window_time[0]:
data_remove = window_data.popleft()
window_sum -= data_remove
window_time.popleft()
elapsed_time = end-start
print "Time elapsed: ",elapsed_time
print "Bytes Read: ",data_size
print "Avg Rate: ", (data_size/elapsed_time)
print "Max Rate: ", max_throughput
def parse_dcaps(directory):
for (dirpath, dirnames, filenames) in os.walk(directory):
for file in filenames:
# Is this iozone output?
if file.endswith("dcap"):
print "* Parsing %s..."%file
parse_dcap(os.path.join(dirpath, file))
if __name__ == "__main__":
# Import our command line parser
args = argparse.ArgumentParser()
args.add_argument("dcap_dir", action="store", type=str, default=None,
help="Directory containting dcap files.")
# Get arguments
options = args.parse_args()
if options.dcap_dir is None:
print "ERROR: Must provide input directory with dcaps."
sys.exit(0)
parse_dcaps(options.dcap_dir) | 0.216342 | 0.188866 |
import copy
from typing import List
from UM.Job import Job
from UM.Operations.GroupedOperation import GroupedOperation
from UM.Message import Message
from UM.Scene.SceneNode import SceneNode
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("cura")
from cura.Arranging.Arrange import Arrange
from cura.Arranging.ShapeArray import ShapeArray
from UM.Application import Application
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.SetTransformOperation import SetTransformOperation
from UM.Math.Vector import Vector
class MultiplyObjectsJob(Job):
def __init__(self, objects, count, min_offset = 8,shape_type = False):
super().__init__()
self._objects = objects
self._count = count
self._min_offset = min_offset
self._type = shape_type
self._moveo_move = None
self._save_x = 0
self._save_y = 0
self._save_z = 0
def run(self) -> None:
# If type is moveo, move to origin
if self._type:
for node in self._objects:
if self._moveo_move == None:
self._save_x = node.getPosition().x
self._save_y = node.getPosition().y
self._save_z = node.getPosition().z
op = GroupedOperation()
op.addOperation(SetTransformOperation(node, Vector(node.getPosition().x - self._save_x, node.getWorldPosition().y, node.getPosition().z - self._save_z)))
op.push()
status_message = Message(i18n_catalog.i18nc("@info:status", "Multiplying and placing objects"), lifetime=0,
dismissable=False, progress=0, title = i18n_catalog.i18nc("@info:title", "Placing Objects"))
status_message.show()
scene = Application.getInstance().getController().getScene()
total_progress = len(self._objects) * self._count
current_progress = 0
global_container_stack = Application.getInstance().getGlobalContainerStack()
if global_container_stack is None:
return # We can't do anything in this case.
machine_width = global_container_stack.getProperty("machine_width", "value")
machine_depth = global_container_stack.getProperty("machine_depth", "value")
root = scene.getRoot()
scale = 0.5
arranger = Arrange.create(x = machine_width, y = machine_depth, scene_root = root, scale = scale, min_offset = self._min_offset)
processed_nodes = [] # type: List[SceneNode]
nodes = []
not_fit_count = 0
for node in self._objects:
# If object is part of a group, multiply group
current_node = node
while current_node.getParent() and (current_node.getParent().callDecoration("isGroup") or current_node.getParent().callDecoration("isSliceable")):
current_node = current_node.getParent()
if current_node in processed_nodes:
continue
processed_nodes.append(current_node)
node_too_big = False
if node.getBoundingBox().width < machine_width or node.getBoundingBox().depth < machine_depth:
offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(current_node, min_offset = self._min_offset, scale = scale)
else:
node_too_big = True
found_solution_for_all = True
arranger.resetLastPriority()
for i in range(self._count):
# We do place the nodes one by one, as we want to yield in between.
new_node = copy.deepcopy(node)
solution_found = False
if not node_too_big:
if offset_shape_arr is not None and hull_shape_arr is not None:
solution_found = arranger.findNodePlacement(new_node, offset_shape_arr, hull_shape_arr)
else:
# The node has no shape, so no need to arrange it. The solution is simple: Do nothing.
solution_found = True
if node_too_big or not solution_found:
found_solution_for_all = False
new_location = new_node.getPosition()
new_location = new_location.set(z = - not_fit_count * 20)
new_node.setPosition(new_location)
not_fit_count += 1
# Same build plate
build_plate_number = current_node.callDecoration("getBuildPlateNumber")
new_node.callDecoration("setBuildPlateNumber", build_plate_number)
for child in new_node.getChildren():
child.callDecoration("setBuildPlateNumber", build_plate_number)
nodes.append(new_node)
current_progress += 1
status_message.setProgress((current_progress / total_progress) * 100)
Job.yieldThread()
Job.yieldThread()
# If type is moveo, move back to place
if self._type:
for node in self._objects:
op = GroupedOperation()
op.addOperation(SetTransformOperation(node, Vector(node.getPosition().x + self._save_x, node.getWorldPosition().y, node.getPosition().z + self._save_z)))
op.push()
if nodes:
op = GroupedOperation()
for new_node in nodes:
op.addOperation(AddSceneNodeOperation(new_node, current_node.getParent()))
if self._type:
for move_node in nodes:
op.addOperation(SetTransformOperation(move_node, Vector(move_node.getPosition().x + self._save_x, move_node.getWorldPosition().y, move_node.getPosition().z + self._save_z)))
op.push()
status_message.hide()
if not found_solution_for_all:
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status", "Unable to find a location within the build volume for all objects"), title = i18n_catalog.i18nc("@info:title", "Placing Object"))
no_full_solution_message.show() | Cura/Cura/cura/MultiplyObjectsJob.py |
import copy
from typing import List
from UM.Job import Job
from UM.Operations.GroupedOperation import GroupedOperation
from UM.Message import Message
from UM.Scene.SceneNode import SceneNode
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("cura")
from cura.Arranging.Arrange import Arrange
from cura.Arranging.ShapeArray import ShapeArray
from UM.Application import Application
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.SetTransformOperation import SetTransformOperation
from UM.Math.Vector import Vector
class MultiplyObjectsJob(Job):
def __init__(self, objects, count, min_offset = 8,shape_type = False):
super().__init__()
self._objects = objects
self._count = count
self._min_offset = min_offset
self._type = shape_type
self._moveo_move = None
self._save_x = 0
self._save_y = 0
self._save_z = 0
def run(self) -> None:
# If type is moveo, move to origin
if self._type:
for node in self._objects:
if self._moveo_move == None:
self._save_x = node.getPosition().x
self._save_y = node.getPosition().y
self._save_z = node.getPosition().z
op = GroupedOperation()
op.addOperation(SetTransformOperation(node, Vector(node.getPosition().x - self._save_x, node.getWorldPosition().y, node.getPosition().z - self._save_z)))
op.push()
status_message = Message(i18n_catalog.i18nc("@info:status", "Multiplying and placing objects"), lifetime=0,
dismissable=False, progress=0, title = i18n_catalog.i18nc("@info:title", "Placing Objects"))
status_message.show()
scene = Application.getInstance().getController().getScene()
total_progress = len(self._objects) * self._count
current_progress = 0
global_container_stack = Application.getInstance().getGlobalContainerStack()
if global_container_stack is None:
return # We can't do anything in this case.
machine_width = global_container_stack.getProperty("machine_width", "value")
machine_depth = global_container_stack.getProperty("machine_depth", "value")
root = scene.getRoot()
scale = 0.5
arranger = Arrange.create(x = machine_width, y = machine_depth, scene_root = root, scale = scale, min_offset = self._min_offset)
processed_nodes = [] # type: List[SceneNode]
nodes = []
not_fit_count = 0
for node in self._objects:
# If object is part of a group, multiply group
current_node = node
while current_node.getParent() and (current_node.getParent().callDecoration("isGroup") or current_node.getParent().callDecoration("isSliceable")):
current_node = current_node.getParent()
if current_node in processed_nodes:
continue
processed_nodes.append(current_node)
node_too_big = False
if node.getBoundingBox().width < machine_width or node.getBoundingBox().depth < machine_depth:
offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(current_node, min_offset = self._min_offset, scale = scale)
else:
node_too_big = True
found_solution_for_all = True
arranger.resetLastPriority()
for i in range(self._count):
# We do place the nodes one by one, as we want to yield in between.
new_node = copy.deepcopy(node)
solution_found = False
if not node_too_big:
if offset_shape_arr is not None and hull_shape_arr is not None:
solution_found = arranger.findNodePlacement(new_node, offset_shape_arr, hull_shape_arr)
else:
# The node has no shape, so no need to arrange it. The solution is simple: Do nothing.
solution_found = True
if node_too_big or not solution_found:
found_solution_for_all = False
new_location = new_node.getPosition()
new_location = new_location.set(z = - not_fit_count * 20)
new_node.setPosition(new_location)
not_fit_count += 1
# Same build plate
build_plate_number = current_node.callDecoration("getBuildPlateNumber")
new_node.callDecoration("setBuildPlateNumber", build_plate_number)
for child in new_node.getChildren():
child.callDecoration("setBuildPlateNumber", build_plate_number)
nodes.append(new_node)
current_progress += 1
status_message.setProgress((current_progress / total_progress) * 100)
Job.yieldThread()
Job.yieldThread()
# If type is moveo, move back to place
if self._type:
for node in self._objects:
op = GroupedOperation()
op.addOperation(SetTransformOperation(node, Vector(node.getPosition().x + self._save_x, node.getWorldPosition().y, node.getPosition().z + self._save_z)))
op.push()
if nodes:
op = GroupedOperation()
for new_node in nodes:
op.addOperation(AddSceneNodeOperation(new_node, current_node.getParent()))
if self._type:
for move_node in nodes:
op.addOperation(SetTransformOperation(move_node, Vector(move_node.getPosition().x + self._save_x, move_node.getWorldPosition().y, move_node.getPosition().z + self._save_z)))
op.push()
status_message.hide()
if not found_solution_for_all:
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status", "Unable to find a location within the build volume for all objects"), title = i18n_catalog.i18nc("@info:title", "Placing Object"))
no_full_solution_message.show() | 0.633637 | 0.222732 |
import torch.nn as nn
from .utils import standardize
class Conv_Block(nn.Module):
def __init__(self, input, filters, kernel_sizes, stride, padding, groups=1, name='', dilation=1,
bias=True, activation=nn.ReLU(), batch_norm=None, dropout=0, transpose=False):
super().__init__()
self.layers = conv_block(input, filters, kernel_sizes, stride, padding, groups, name, dilation,
bias, activation, batch_norm, dropout, transpose)
def forward(self, x):
return self.layers.forward(x)
def conv_block(input, filters, kernel_sizes, stride, padding, groups=1, name='', dilation=1,
bias=True, activation=nn.ReLU(), batch_norm=None, dropout=0, transpose=False):
"""
Create a convolutional block with several layers
:param input: input data channels
:param filters: int or list
:param kernel_sizes: int or list
:param stride: int or list
:param padding: int or list
:param groups: int or list, default 1
:param name:
:param activation:
:param batch_norm:
:return: nn.Sequential Object
"""
filters = [input] + [filters] if type(filters) is not list else [input] + filters
assert_length = len(filters) - 1
kernel_sizes = standardize(kernel_sizes, assert_length)
stride = standardize(stride, assert_length)
padding = standardize(padding, assert_length)
groups = standardize(groups, assert_length)
dilation = standardize(dilation, assert_length)
bias = standardize(bias, assert_length)
activation = standardize(activation, assert_length)
batch_norm = standardize(batch_norm, assert_length)
dropout = standardize(dropout, assert_length)
transpose = standardize(transpose, assert_length)
modules = nn.Sequential()
for i in range(len(filters) - 1):
if transpose[i]:
modules.add_module("convT_" + name + "_" + str(i),
nn.ConvTranspose2d(in_channels=filters[i], out_channels=filters[i + 1],
kernel_size=kernel_sizes[i], stride=stride[i], padding=padding[i],
dilation=dilation[i], groups=groups[i], bias=bias[i]))
else:
modules.add_module("conv_" + name + "_" + str(i),
nn.Conv2d(in_channels=filters[i], out_channels=filters[i + 1],
kernel_size=kernel_sizes[i], stride=stride[i], padding=padding[i],
dilation=dilation[i], groups=groups[i], bias=bias[i]))
if batch_norm[i]:
modules.add_module("bn_" + name + "_" + str(i), batch_norm[i](filters[i + 1]))
if activation[i]:
modules.add_module("act_" + name + "_" + str(i), activation[i])
if dropout[i] > 0:
modules.add_module("drop_" + name + "_" + str(i), nn.Dropout2d(dropout[i]))
return modules | networks/blocks/conv_block.py | import torch.nn as nn
from .utils import standardize
class Conv_Block(nn.Module):
def __init__(self, input, filters, kernel_sizes, stride, padding, groups=1, name='', dilation=1,
bias=True, activation=nn.ReLU(), batch_norm=None, dropout=0, transpose=False):
super().__init__()
self.layers = conv_block(input, filters, kernel_sizes, stride, padding, groups, name, dilation,
bias, activation, batch_norm, dropout, transpose)
def forward(self, x):
return self.layers.forward(x)
def conv_block(input, filters, kernel_sizes, stride, padding, groups=1, name='', dilation=1,
bias=True, activation=nn.ReLU(), batch_norm=None, dropout=0, transpose=False):
"""
Create a convolutional block with several layers
:param input: input data channels
:param filters: int or list
:param kernel_sizes: int or list
:param stride: int or list
:param padding: int or list
:param groups: int or list, default 1
:param name:
:param activation:
:param batch_norm:
:return: nn.Sequential Object
"""
filters = [input] + [filters] if type(filters) is not list else [input] + filters
assert_length = len(filters) - 1
kernel_sizes = standardize(kernel_sizes, assert_length)
stride = standardize(stride, assert_length)
padding = standardize(padding, assert_length)
groups = standardize(groups, assert_length)
dilation = standardize(dilation, assert_length)
bias = standardize(bias, assert_length)
activation = standardize(activation, assert_length)
batch_norm = standardize(batch_norm, assert_length)
dropout = standardize(dropout, assert_length)
transpose = standardize(transpose, assert_length)
modules = nn.Sequential()
for i in range(len(filters) - 1):
if transpose[i]:
modules.add_module("convT_" + name + "_" + str(i),
nn.ConvTranspose2d(in_channels=filters[i], out_channels=filters[i + 1],
kernel_size=kernel_sizes[i], stride=stride[i], padding=padding[i],
dilation=dilation[i], groups=groups[i], bias=bias[i]))
else:
modules.add_module("conv_" + name + "_" + str(i),
nn.Conv2d(in_channels=filters[i], out_channels=filters[i + 1],
kernel_size=kernel_sizes[i], stride=stride[i], padding=padding[i],
dilation=dilation[i], groups=groups[i], bias=bias[i]))
if batch_norm[i]:
modules.add_module("bn_" + name + "_" + str(i), batch_norm[i](filters[i + 1]))
if activation[i]:
modules.add_module("act_" + name + "_" + str(i), activation[i])
if dropout[i] > 0:
modules.add_module("drop_" + name + "_" + str(i), nn.Dropout2d(dropout[i]))
return modules | 0.955631 | 0.456652 |
import miRmedon_src
from miRmedon_src.alignment_to_emiRbase import alignment_to_emiRbase
from miRmedon_src.alignments_filter import main_alignments_filter
from miRmedon_src.count_filter import main_counts_filter
from miRmedon_src.consensus_generator import consensus_generator
from miRmedon_src.clusters_filter_bowtie import main_clusters_filter_bowtie
from miRmedon_src.clusters_filter_seqmap import main_clusters_filter_seqmap
from miRmedon_src.counter import counter
from miRmedon_src.MC_P_est import monte_catlo_p_estimation
from miRmedon_src.recount import recount
import argparse
import os
miRmedon_dir = miRmedon_src.__file__.replace('__init__.py', '')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-f', '-fastq', type=str,
help='Path to fastq file')
parser.add_argument('-star', '-star', type=str,
help='Path to Star')
parser.add_argument('-star_ref_dir', '-star_ref_dir', type=str,
help='Path to STAR e_miRbase ref directory')
parser.add_argument('-t', '-threads', type=str,
help='Number of threads for Star alignment')
parser.add_argument('-s', '-soft_clipping_threshold', type=int, default=2,
help='Soft-cliiped bases threshold')
parser.add_argument('-x', '-total_modifications_threshold', type=int, default=3,
help='Total number of modifications threshold (sofft-clipped+mismatches')
parser.add_argument('-c', '-counts_threshold', type=int, default=10,
help='Counts threshold')
parser.add_argument('-samtools', '-samtools', type=str,
help='Path to samtools.')
parser.add_argument('-mafft', '-mafft', type=str,
help='Path to Mafft.')
parser.add_argument('-seqmap', '-seqmap', type=str, required=False, default=None,
help='Path to Seqmap.')
parser.add_argument('-bowtie', '-bowtie', type=str, required=False, default=None,
help='Path to Bowtie.')
parser.add_argument('-G', '-genome_fasta', type=str,
help='Genome FASTA file or bowtie index.')
parser.add_argument('-T', '-transcriptome_fasta', type=str,
help='Transcriptome FASTA file or bowtie index.')
parser.add_argument('-r', '-resamples', type=int, default=10000,
help='Number of resamples for Monte-Carlo p-value estimation')
args = parser.parse_args()
vars_args = vars(args)
if (vars_args['seqmap'] != None and vars_args['bowtie'] != None):
raise Exception('You could only choose one of the following aligners:\n '
' - Bowtie\n '
' - Seqmap\n '
' Both were given to miRmedon')
fastq_file = args.f
path_to_star = args.star
threads = args.t
star_ref_dir = miRmedon_dir + 'star_ref/'
soft_clip_thresh = args.s
total_mod_thresh = args.x
counts_thresh = args.c
path_to_samtools = args.samtools
path_to_mafft = args.mafft
e_miRbase = miRmedon_dir + 'e_miRbase.pkl'
path_to_seqmap = args.seqmap
path_to_bowtie = args.bowtie
genome_index = args.G
transcriptome_index = args.T
resamples = args.r
bam = '_Aligned.out.bam'
st_filt_bam = '_Aligned.out.filt.st.bam'
bycount_filt_bam = '_Aligned.out.filt.bycount.bam'
final_filt_bam = '_Aligned.out.filt.final.bam'
alignment_to_emiRbase(fastq_file, path_to_star, threads, star_ref_dir, path_to_samtools)
main_alignments_filter(bam, e_miRbase, soft_clip_thresh, total_mod_thresh)
main_counts_filter(st_filt_bam, path_to_samtools, counts_thresh)
consensus_generator(bycount_filt_bam, path_to_mafft, path_to_samtools)
if vars_args['seqmap'] != None:
miRs_bed = miRmedon_dir + 'miRbase.seqmap.bed'
main_clusters_filter_seqmap(bycount_filt_bam, e_miRbase, path_to_seqmap, genome_index, transcriptome_index, miRs_bed, path_to_samtools)
elif vars_args['bowtie'] != None:
miRs_bed = miRmedon_dir + 'miRbase.bowtie.bed'
main_clusters_filter_bowtie(bycount_filt_bam, e_miRbase, path_to_bowtie, genome_index, transcriptome_index, miRs_bed, path_to_samtools)
counter(final_filt_bam)
monte_catlo_p_estimation(final_filt_bam, e_miRbase, resamples)
recount(e_miRbase)
# os.system('rm -rf _Log.final.out _Log.out _Log.progress.out _Unmapped.out.mate1 _SJ.out.tab')
# os.system('rm -rf _Aligned.out.*')
# os.system('rm -rf *.sam')
# os.system('rm -rf *.eland')
# os.system('rm -rf consensus.fasta reduced_consensus.fasta')
# os.system('rm -rf counts.txt')
# os.system('mv crt_counts.txt counts.txt') | miRmedon.py | import miRmedon_src
from miRmedon_src.alignment_to_emiRbase import alignment_to_emiRbase
from miRmedon_src.alignments_filter import main_alignments_filter
from miRmedon_src.count_filter import main_counts_filter
from miRmedon_src.consensus_generator import consensus_generator
from miRmedon_src.clusters_filter_bowtie import main_clusters_filter_bowtie
from miRmedon_src.clusters_filter_seqmap import main_clusters_filter_seqmap
from miRmedon_src.counter import counter
from miRmedon_src.MC_P_est import monte_catlo_p_estimation
from miRmedon_src.recount import recount
import argparse
import os
miRmedon_dir = miRmedon_src.__file__.replace('__init__.py', '')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-f', '-fastq', type=str,
help='Path to fastq file')
parser.add_argument('-star', '-star', type=str,
help='Path to Star')
parser.add_argument('-star_ref_dir', '-star_ref_dir', type=str,
help='Path to STAR e_miRbase ref directory')
parser.add_argument('-t', '-threads', type=str,
help='Number of threads for Star alignment')
parser.add_argument('-s', '-soft_clipping_threshold', type=int, default=2,
help='Soft-cliiped bases threshold')
parser.add_argument('-x', '-total_modifications_threshold', type=int, default=3,
help='Total number of modifications threshold (sofft-clipped+mismatches')
parser.add_argument('-c', '-counts_threshold', type=int, default=10,
help='Counts threshold')
parser.add_argument('-samtools', '-samtools', type=str,
help='Path to samtools.')
parser.add_argument('-mafft', '-mafft', type=str,
help='Path to Mafft.')
parser.add_argument('-seqmap', '-seqmap', type=str, required=False, default=None,
help='Path to Seqmap.')
parser.add_argument('-bowtie', '-bowtie', type=str, required=False, default=None,
help='Path to Bowtie.')
parser.add_argument('-G', '-genome_fasta', type=str,
help='Genome FASTA file or bowtie index.')
parser.add_argument('-T', '-transcriptome_fasta', type=str,
help='Transcriptome FASTA file or bowtie index.')
parser.add_argument('-r', '-resamples', type=int, default=10000,
help='Number of resamples for Monte-Carlo p-value estimation')
args = parser.parse_args()
vars_args = vars(args)
if (vars_args['seqmap'] != None and vars_args['bowtie'] != None):
raise Exception('You could only choose one of the following aligners:\n '
' - Bowtie\n '
' - Seqmap\n '
' Both were given to miRmedon')
fastq_file = args.f
path_to_star = args.star
threads = args.t
star_ref_dir = miRmedon_dir + 'star_ref/'
soft_clip_thresh = args.s
total_mod_thresh = args.x
counts_thresh = args.c
path_to_samtools = args.samtools
path_to_mafft = args.mafft
e_miRbase = miRmedon_dir + 'e_miRbase.pkl'
path_to_seqmap = args.seqmap
path_to_bowtie = args.bowtie
genome_index = args.G
transcriptome_index = args.T
resamples = args.r
bam = '_Aligned.out.bam'
st_filt_bam = '_Aligned.out.filt.st.bam'
bycount_filt_bam = '_Aligned.out.filt.bycount.bam'
final_filt_bam = '_Aligned.out.filt.final.bam'
alignment_to_emiRbase(fastq_file, path_to_star, threads, star_ref_dir, path_to_samtools)
main_alignments_filter(bam, e_miRbase, soft_clip_thresh, total_mod_thresh)
main_counts_filter(st_filt_bam, path_to_samtools, counts_thresh)
consensus_generator(bycount_filt_bam, path_to_mafft, path_to_samtools)
if vars_args['seqmap'] != None:
miRs_bed = miRmedon_dir + 'miRbase.seqmap.bed'
main_clusters_filter_seqmap(bycount_filt_bam, e_miRbase, path_to_seqmap, genome_index, transcriptome_index, miRs_bed, path_to_samtools)
elif vars_args['bowtie'] != None:
miRs_bed = miRmedon_dir + 'miRbase.bowtie.bed'
main_clusters_filter_bowtie(bycount_filt_bam, e_miRbase, path_to_bowtie, genome_index, transcriptome_index, miRs_bed, path_to_samtools)
counter(final_filt_bam)
monte_catlo_p_estimation(final_filt_bam, e_miRbase, resamples)
recount(e_miRbase)
# os.system('rm -rf _Log.final.out _Log.out _Log.progress.out _Unmapped.out.mate1 _SJ.out.tab')
# os.system('rm -rf _Aligned.out.*')
# os.system('rm -rf *.sam')
# os.system('rm -rf *.eland')
# os.system('rm -rf consensus.fasta reduced_consensus.fasta')
# os.system('rm -rf counts.txt')
# os.system('mv crt_counts.txt counts.txt') | 0.415136 | 0.102394 |
import unittest.mock as mock
import unittest
import pytest
import numpy as np
import tensorflow as tf
import yaml
from mlagents.trainers.ppo.models import PPOModel
from mlagents.trainers.ppo.trainer import PPOTrainer, discount_rewards
from mlagents.trainers.ppo.policy import PPOPolicy
from mlagents.trainers.rl_trainer import AllRewardsOutput
from mlagents.trainers.components.reward_signals import RewardSignalResult
from mlagents.envs.brain import BrainParameters
from mlagents.envs.environment import UnityEnvironment
from mlagents.envs.mock_communicator import MockCommunicator
from mlagents.trainers.tests import mock_brain as mb
from mlagents.trainers.tests.mock_brain import make_brain_parameters
from mlagents.trainers.custom_layer_specs import CustomConvLayerSpecs
@pytest.fixture
def dummy_config():
return yaml.safe_load(
"""
trainer: ppo
batch_size: 32
beta: 5.0e-3
buffer_size: 512
epsilon: 0.2
hidden_units: 128
lambd: 0.95
learning_rate: 3.0e-4
max_steps: 5.0e4
normalize: true
num_epoch: 5
num_layers: 2
time_horizon: 64
sequence_length: 64
summary_freq: 1000
use_recurrent: false
memory_size: 8
vis_encode_type: custom
curiosity_strength: 0.0
curiosity_enc_size: 1
summary_path: test
model_path: test
reward_signals:
extrinsic:
strength: 1.0
gamma: 0.99
"""
)
class TestStringMethods(unittest.TestCase):
def test_custom_layer_specs(self):
customConvLayerSpecs = CustomConvLayerSpecs(32,
kernel_shape=(3,3), strides=(1,1),
activation='elu',
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
use_bias=True, maxPool=False)
@mock.patch("mlagents.envs.environment.UnityEnvironment.executable_launcher")
@mock.patch("mlagents.envs.environment.UnityEnvironment.get_communicator")
def test_ppo_model_cc_visual(self, mock_communicator, mock_launcher):
tf.reset_default_graph()
mock_communicator.return_value = MockCommunicator(
discrete_action=False, visual_inputs=0
)
env = UnityEnvironment(" ")
brain_infos = env.reset()
brain_info = brain_infos[env.external_brain_names[0]]
trainer_parameters = dummy_config()
policy = PPOPolicy(
0, env.brains[env.external_brain_names[0]], trainer_parameters, False, False
)
run_out = policy.evaluate(brain_info)
assert run_out["action"].shape == (3, 2)
print("----")
print("boe")
env.close()
# model = PPOModel(
# make_brain_parameters(discrete_action=False, visual_inputs=2)
# )
# init = tf.global_variables_initializer()
# sess.run(init)
# run_list = [
# model.output,
# model.log_probs,
# model.value,
# model.entropy,
# model.learning_rate,
# ]
# feed_dict = {
# model.batch_size: 2,
# model.sequence_length: 1,
# model.vector_in: np.array([[1, 2, 3, 1, 2, 3], [3, 4, 5, 3, 4, 5]]),
# model.visual_in[0]: np.ones([2, 40, 30, 3]),
# model.visual_in[1]: np.ones([2, 40, 30, 3]),
# model.epsilon: np.array([[0, 1], [2, 3]]),
# }
# sess.run(run_list, feed_dict=feed_dict)
if __name__ == '__main__':
unittest.main() | ml-agents/mlagents/trainers/tests/test_custom_layers.py | import unittest.mock as mock
import unittest
import pytest
import numpy as np
import tensorflow as tf
import yaml
from mlagents.trainers.ppo.models import PPOModel
from mlagents.trainers.ppo.trainer import PPOTrainer, discount_rewards
from mlagents.trainers.ppo.policy import PPOPolicy
from mlagents.trainers.rl_trainer import AllRewardsOutput
from mlagents.trainers.components.reward_signals import RewardSignalResult
from mlagents.envs.brain import BrainParameters
from mlagents.envs.environment import UnityEnvironment
from mlagents.envs.mock_communicator import MockCommunicator
from mlagents.trainers.tests import mock_brain as mb
from mlagents.trainers.tests.mock_brain import make_brain_parameters
from mlagents.trainers.custom_layer_specs import CustomConvLayerSpecs
@pytest.fixture
def dummy_config():
return yaml.safe_load(
"""
trainer: ppo
batch_size: 32
beta: 5.0e-3
buffer_size: 512
epsilon: 0.2
hidden_units: 128
lambd: 0.95
learning_rate: 3.0e-4
max_steps: 5.0e4
normalize: true
num_epoch: 5
num_layers: 2
time_horizon: 64
sequence_length: 64
summary_freq: 1000
use_recurrent: false
memory_size: 8
vis_encode_type: custom
curiosity_strength: 0.0
curiosity_enc_size: 1
summary_path: test
model_path: test
reward_signals:
extrinsic:
strength: 1.0
gamma: 0.99
"""
)
class TestStringMethods(unittest.TestCase):
def test_custom_layer_specs(self):
customConvLayerSpecs = CustomConvLayerSpecs(32,
kernel_shape=(3,3), strides=(1,1),
activation='elu',
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
use_bias=True, maxPool=False)
@mock.patch("mlagents.envs.environment.UnityEnvironment.executable_launcher")
@mock.patch("mlagents.envs.environment.UnityEnvironment.get_communicator")
def test_ppo_model_cc_visual(self, mock_communicator, mock_launcher):
tf.reset_default_graph()
mock_communicator.return_value = MockCommunicator(
discrete_action=False, visual_inputs=0
)
env = UnityEnvironment(" ")
brain_infos = env.reset()
brain_info = brain_infos[env.external_brain_names[0]]
trainer_parameters = dummy_config()
policy = PPOPolicy(
0, env.brains[env.external_brain_names[0]], trainer_parameters, False, False
)
run_out = policy.evaluate(brain_info)
assert run_out["action"].shape == (3, 2)
print("----")
print("boe")
env.close()
# model = PPOModel(
# make_brain_parameters(discrete_action=False, visual_inputs=2)
# )
# init = tf.global_variables_initializer()
# sess.run(init)
# run_list = [
# model.output,
# model.log_probs,
# model.value,
# model.entropy,
# model.learning_rate,
# ]
# feed_dict = {
# model.batch_size: 2,
# model.sequence_length: 1,
# model.vector_in: np.array([[1, 2, 3, 1, 2, 3], [3, 4, 5, 3, 4, 5]]),
# model.visual_in[0]: np.ones([2, 40, 30, 3]),
# model.visual_in[1]: np.ones([2, 40, 30, 3]),
# model.epsilon: np.array([[0, 1], [2, 3]]),
# }
# sess.run(run_list, feed_dict=feed_dict)
if __name__ == '__main__':
unittest.main() | 0.636579 | 0.462837 |