repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringclasses
991 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
woozzu/pylearn2
pylearn2/sandbox/cuda_convnet/pool.py
47
28462
""" .. todo:: WRITEME """ import warnings from theano.gof import Apply from theano.sandbox.cuda import CudaNdarrayType from theano.sandbox.cuda.basic_ops import as_cuda_ndarray_variable from theano.sandbox.cuda.basic_ops import gpu_contiguous from theano.sandbox.cuda import GpuOp from theano.tensor import get_scalar_constant_value, NotScalarConstantError from pylearn2.sandbox.cuda_convnet.base_acts import UnimplementedError from pylearn2.sandbox.cuda_convnet.convnet_compile import convnet_available from pylearn2.sandbox.cuda_convnet.convnet_compile import cuda_convnet_loc from pylearn2.sandbox.cuda_convnet.shared_code import this_dir import pylearn2.sandbox.cuda_convnet.pthreads from theano import config def max_pool_c01b(c01b, pool_shape, pool_stride, image_shape = None, start=0): """ .. todo:: WRITEME """ assert pool_shape[0] == pool_shape[1] assert pool_shape[0] > 0 assert pool_stride[0] > 0 assert pool_stride[0] <= pool_shape[0] if pool_stride[0] != pool_stride[1]: raise ValueError("pool strides must match, but got "+str(pool_stride)) if image_shape is not None: warnings.warn("image_shape argument isn't needed anymore, quit passing it.") op = MaxPool(pool_shape[0], pool_stride[0], start) c01b = gpu_contiguous(c01b) return op(c01b) class MaxPool(GpuOp): """ This op wrap Alex's MaxPool code on the GPU. The input are in the order (channel, image rows, image cols, batch) Works only on square images and the grad works only when channel % 16 == 0. Parameters ---------- ds : int Defines the size of the pooling region in the x (equivalently, y) dimension. Squares of size (ds)2 get reduced to one value by this layer. There are no restrictions on the value of this parameter. It's fine for a pooling square to fall off the boundary of the image. Named SizeX in Alex's code. stride : int Defines the stride size between successive pooling squares. Setting this parameter smaller than sizeX produces overlapping pools. Setting it equal to sizeX gives the usual, non-overlapping pools. Values greater than sizeX are not allowed. start : int, optional Tells the net where in the input image to start the pooling (in x,y coordinates). In principle, you can start anywhere you want. Setting this to a positive number will cause the net to discard some pixels at the top and at the left of the image. Setting this to a negative number will cause it to include pixels that don't exist (which is fine). start=0 is the usual setting. outputs : int, optional Allows you to control how many output values in the x (equivalently, y) dimension this operation will produce. This parameter is analogous to the start parameter, in that it allows you to discard some portion of the image by setting it to a value small enough to leave part of the image uncovered. Setting it to zero instructs the net to produce as many outputs as is necessary to ensure that the whole image is covered. default 0 """ def __init__(self, ds, stride, start=0, outputs=0): self.ds = ds self.stride = stride self.start = start self.copy_non_contiguous = 0 assert stride > 0 and stride <= ds, (stride, ds) assert ds > 0, ds # We check in the code if ds <= imgSizeX def __eq__(self, other): """ .. todo:: WRITEME """ #Dont put copy_non_contigous as this doesn't change the output return (type(self) == type(other) and self.ds == other.ds and self.stride == other.stride and self.start == other.start) def __hash__(self): """ .. todo:: WRITEME """ #Dont put copy_non_contigous as this doesn't change the output return (hash(type(self)) ^ hash(self.ds) ^ hash(self.stride) ^ hash(self.start)) def c_header_dirs(self): """ .. todo:: WRITEME """ return [this_dir, config.pthreads.inc_dir] if config.pthreads.inc_dir else [this_dir] def c_headers(self): """ .. todo:: WRITEME """ return ['nvmatrix.cuh', 'conv_util.cuh'] def c_lib_dirs(self): """ .. todo:: WRITEME """ return [cuda_convnet_loc, config.pthreads.lib_dir] if config.pthreads.lib_dir else [cuda_convnet_loc] def c_libraries(self): """ .. todo:: WRITEME """ return ['cuda_convnet', config.pthreads.lib] if config.pthreads.lib else ['cuda_convnet'] def c_code_cache_version(self): """ .. todo:: WRITEME """ return (1,) def _argument_contiguity_check(self, arg_name): """ .. todo:: WRITEME """ return """ if (!CudaNdarray_is_c_contiguous(%%(%(arg_name)s)s)) { if (!(%(class_name_caps)s_COPY_NON_CONTIGUOUS)) { PyErr_SetString(PyExc_ValueError, "%(class)s: %(arg_name)s must be C contiguous"); %%(fail)s; } } """ % { 'class': self.__class__.__name__, 'arg_name': arg_name, 'class_name_caps': self.__class__.__name__.upper(), } def make_node(self, images): """ .. todo:: WRITEME """ images = as_cuda_ndarray_variable(images) assert images.ndim == 4 channels_broadcastable = images.type.broadcastable[0] batch_broadcastable = images.type.broadcastable[3] rows_broadcastable = False cols_broadcastable = False targets_broadcastable = (channels_broadcastable, rows_broadcastable, cols_broadcastable, batch_broadcastable) targets_type = CudaNdarrayType(broadcastable=targets_broadcastable) targets = targets_type() return Apply(self, [images], [targets]) def c_code(self, node, name, inputs, outputs, sub): """ .. todo:: WRITEME """ images, = inputs targets, = outputs fail = sub['fail'] # The amount of braces that must be closed at the end num_braces = 0 if self.copy_non_contiguous: raise UnimplementedError() else: basic_setup = "#define MAXPOOL_COPY_NON_CONTIGUOUS 0\n" # Convert images in nv_images, an NVMatrix, for compatibility # with the cuda-convnet functions setup_nv_images = self._argument_contiguity_check("images") + """ if (%(images)s->nd != 4) { PyErr_Format(PyExc_ValueError, "images must have nd=4, got nd=%%i", %(images)s->nd); %(fail)s; } { //setup_nv_images brace 1 const int * images_dims = CudaNdarray_HOST_DIMS(%(images)s); const int img_channels = images_dims[0]; const int imgSizeY = images_dims[1]; const int imgSizeX = images_dims[2]; const int batch_size = images_dims[3]; if(imgSizeY != imgSizeX){ PyErr_Format(PyExc_ValueError, "images must be square(dims[1] == dims[2]). Shape (%%i,%%i,%%i,%%i)", img_channels, imgSizeY, imgSizeX, batch_size); %(fail)s; } if(%(ds)s > imgSizeY){ PyErr_Format(PyExc_ValueError, "ds(%%d) must be <= imgSizeX(%%d) and imgSizeY(%%d).", %(ds)s, imgSizeX, imgSizeY); %(fail)s; } if(%(start)s >= imgSizeX){ PyErr_Format(PyExc_ValueError, "start is %%d but must be smaller then the images size of %%d x %%d.", %(start)s, imgSizeX, imgSizeY); %(fail)s; } NVMatrix nv_images(%(images)s, img_channels * imgSizeY * imgSizeX, batch_size, "MaxPool:nv_images"); """ num_braces += 1 setup_nv_targets = """ //int _outputsX = int(ceil((dic['imgSize'] - dic['start'] - dic['sizeX']) / float(dic['stride']))) + 1; int _outputsX = ((int)(ceil((imgSizeY - %(start)s - %(ds)s) / ((float)%(stride)s)))) + 1; int target_dims [] = { img_channels, _outputsX, _outputsX, batch_size }; if (CudaNdarray_prep_output(& %(targets)s, 4, target_dims)) { %(fail)s; } { // setup_nv_target brace # 1 NVMatrix nv_targets(%(targets)s, target_dims[0] * target_dims[1] * target_dims[2], target_dims[3], "MaxPool:nv_targets"); """ num_braces += 1 do_pool = """ convLocalPool(nv_images, nv_targets, img_channels, %(ds)s, %(start)s, %(stride)s, _outputsX, MaxPooler()); """ braces = '}' * num_braces rval = (basic_setup + setup_nv_images + setup_nv_targets + do_pool + braces) start = self.start stride = self.stride ds = self.ds rval = rval % locals() return rval def R_op(self, inp, evals): """ .. todo:: WRITEME """ x, = inp ev, = evals if ev is not None: ev = gpu_contiguous(ev) return [MaxPoolRop(self.ds, self.stride, self.start)(x, ev)] else: return [None] def grad(self, inp, grads): """ .. todo:: WRITEME """ x, = inp gz, = grads gz = gpu_contiguous(gz) maxout = self(x) return [MaxPoolGrad(self.ds, self.stride, self.start)(x, maxout, gz)] # Make sure the cuda_convnet library is compiled and up-to-date def make_thunk(self, node, storage_map, compute_map, no_recycling): """ .. todo:: WRITEME """ if not convnet_available(): raise RuntimeError('Could not compile cuda_convnet') return super(MaxPool, self).make_thunk( node, storage_map, compute_map, no_recycling) class MaxPoolRop(GpuOp): """ This op wrap Alex's MaxPool code on the GPU. The input are in the order (channel, image rows, image cols, batch) Works only on square images and the grad works only when channel % 16 == 0. Parameters ---------- ds : int Defines the size of the pooling region in the x (equivalently, y) dimension. Squares of size (ds)2 get reduced to one value by this layer. There are no restrictions on the value of this parameter. It's fine for a pooling square to fall off the boundary of the image. Named SizeX in Alex's code. stride : int Defines the stride size between successive pooling squares. Setting this parameter smaller than sizeX produces overlapping pools. Setting it equal to sizeX gives the usual, non-overlapping pools. Values greater than sizeX are not allowed. start : int, optional Tells the net where in the input image to start the pooling (in x,y coordinates). In principle, you can start anywhere you want. Setting this to a positive number will cause the net to discard some pixels at the top and at the left of the image. Setting this to a negative number will cause it to include pixels that don't exist (which is fine). start=0 is the usual setting. outputs : int, optional Allows you to control how many output values in the x (equivalently, y) dimension this operation will produce. This parameter is analogous to the start parameter, in that it allows you to discard some portion of the image by setting it to a value small enough to leave part of the image uncovered. Setting it to zero instructs the net to produce as many outputs as is necessary to ensure that the whole image is covered. default 0 """ def __init__(self, ds, stride, start=0, outputs=0): self.ds = ds self.stride = stride self.start = start self.copy_non_contiguous = 0 assert stride > 0 and stride <= ds, (stride, ds) assert ds > 0, ds # We check in the code if ds <= imgSizeX def __eq__(self, other): """ .. todo:: WRITEME """ #Dont put copy_non_contigous as this doesn't change the output return (type(self) == type(other) and self.ds == other.ds and self.stride == other.stride and self.start == other.start) def __hash__(self): """ .. todo:: WRITEME """ #Dont put copy_non_contigous as this doesn't change the output return (hash(type(self)) ^ hash(self.ds) ^ hash(self.stride) ^ hash(self.start)) def c_header_dirs(self): """ .. todo:: WRITEME """ return [this_dir] def c_headers(self): """ .. todo:: WRITEME """ return ['nvmatrix.cuh', 'conv_util.cuh', 'pool_rop.cuh'] def c_lib_dirs(self): """ .. todo:: WRITEME """ return [cuda_convnet_loc] def c_libraries(self): """ .. todo:: WRITEME """ return ['cuda_convnet'] def c_code_cache_version(self): """ .. todo:: WRITEME """ return (1,) def _argument_contiguity_check(self, arg_name): """ .. todo:: WRITEME """ return """ if (!CudaNdarray_is_c_contiguous(%%(%(arg_name)s)s)) { if (!(%(class_name_caps)s_COPY_NON_CONTIGUOUS)) { PyErr_SetString(PyExc_ValueError, "%(class)s: %(arg_name)s must be C contiguous"); %%(fail)s; } } """ % { 'class': self.__class__.__name__, 'arg_name': arg_name, 'class_name_caps': self.__class__.__name__.upper(), } def make_node(self, images, evals): """ .. todo:: WRITEME """ images = as_cuda_ndarray_variable(images) evals = as_cuda_ndarray_variable(evals) assert images.ndim == 4 assert evals.ndim == 4 channels_broadcastable = images.type.broadcastable[0] batch_broadcastable = images.type.broadcastable[3] rows_broadcastable = False cols_broadcastable = False targets_broadcastable = (channels_broadcastable, rows_broadcastable, cols_broadcastable, batch_broadcastable) targets_type = CudaNdarrayType(broadcastable=targets_broadcastable) targets = targets_type() return Apply(self, [images, evals], [targets]) def c_code(self, node, name, inputs, outputs, sub): """ .. todo:: WRITEME """ images,evals = inputs targets, = outputs fail = sub['fail'] # The amount of braces that must be closed at the end num_braces = 0 if self.copy_non_contiguous: raise UnimplementedError() else: basic_setup = "#define MAXPOOLROP_COPY_NON_CONTIGUOUS 0\n" # Convert images in nv_images, an NVMatrix, for compatibility # with the cuda-convnet functions setup_nv_images = self._argument_contiguity_check("images") + """ if (%(images)s->nd != 4) { PyErr_Format(PyExc_ValueError, "images must have nd=4, got nd=%%i", %(images)s->nd); %(fail)s; } { //setup_nv_images brace 1 const int * images_dims = CudaNdarray_HOST_DIMS(%(images)s); const int img_channels = images_dims[0]; const int imgSizeY = images_dims[1]; const int imgSizeX = images_dims[2]; const int batch_size = images_dims[3]; if(imgSizeY != imgSizeX){ PyErr_Format(PyExc_ValueError, "images must be square(dims[1] == dims[2]). Shape (%%i,%%i,%%i,%%i)", img_channels, imgSizeY, imgSizeX, batch_size); %(fail)s; } if(%(ds)s > imgSizeY){ PyErr_Format(PyExc_ValueError, "ds(%%d) must be <= imgSizeX(%%d) and imgSizeY(%%d).", %(ds)s, imgSizeX, imgSizeY); %(fail)s; } if(%(start)s >= imgSizeX){ PyErr_Format(PyExc_ValueError, "start is %%d but must be smaller then the images size of %%d x %%d.", %(start)s, imgSizeX, imgSizeY); %(fail)s; } NVMatrix nv_images(%(images)s, img_channels * imgSizeY * imgSizeX, batch_size, "MaxPoolRop:nv_images"); NVMatrix nv_evals(%(evals)s, img_channels * imgSizeY * imgSizeX, batch_size, "MaxPoolRop:nv_evals"); """ num_braces += 1 setup_nv_targets = """ //int _outputsX = int(ceil((dic['imgSize'] - dic['start'] - dic['sizeX']) / float(dic['stride']))) + 1; int _outputsX = ((int)(ceil((imgSizeY - %(start)s - %(ds)s) / ((float)%(stride)s)))) + 1; int target_dims [] = { img_channels, _outputsX, _outputsX, batch_size }; if (CudaNdarray_prep_output(& %(targets)s, 4, target_dims)) { %(fail)s; } { // setup_nv_target brace # 1 NVMatrix nv_targets(%(targets)s, target_dims[0] * target_dims[1] * target_dims[2], target_dims[3], "MaxPoolRop:nv_targets"); """ num_braces += 1 do_pool = """ convLocalPoolR(nv_images, nv_evals, nv_targets, img_channels, %(ds)s, %(start)s, %(stride)s, _outputsX, MaxPoolerR()); """ braces = '}' * num_braces rval = (basic_setup + setup_nv_images + setup_nv_targets + do_pool + braces) start = self.start stride = self.stride ds = self.ds rval = rval % locals() return rval # Make sure the cuda_convnet library is compiled and up-to-date def make_thunk(self, node, storage_map, compute_map, no_recycling): """ .. todo:: WRITEME """ if not convnet_available(): raise RuntimeError('Could not compile cuda_convnet') return super(MaxPoolRop, self).make_thunk( node, storage_map, storage_map, no_recycling) class MaxPoolGrad(GpuOp): """ .. todo:: WRITEME """ def __init__(self, ds, stride, start): self.ds = ds self.stride = stride self.start = start self.copy_non_contiguous = 0 assert stride > 0 and stride <= ds, (stride, ds) assert ds > 0, ds #We check in the code if ds <= imgSizeX def __eq__(self, other): """ .. todo:: WRITEME """ #Dont put copy_non_contigous as this doesn't change the output return (type(self) == type(other) and self.ds == other.ds and self.stride == other.stride and self.start == other.start) def __hash__(self): """ .. todo:: WRITEME """ #Dont put copy_non_contigous as this doesn't change the output return (hash(type(self)) ^ hash(self.ds) ^ hash(self.stride) ^ hash(self.start)) def c_header_dirs(self): """ .. todo:: WRITEME """ return [this_dir, config.pthreads.inc_dir] if config.pthreads.inc_dir else [this_dir] def c_headers(self): """ .. todo:: WRITEME """ return ['nvmatrix.cuh', 'conv_util.cuh'] def c_lib_dirs(self): """ .. todo:: WRITEME """ return [cuda_convnet_loc, config.pthreads.lib_dir] if config.pthreads.lib_dir else [cuda_convnet_loc] def c_libraries(self): """ .. todo:: WRITEME """ return ['cuda_convnet', config.pthreads.lib] if config.pthreads.lib else ['cuda_convnet'] def c_code_cache_version(self): """ .. todo:: WRITEME """ return (1,) def _argument_contiguity_check(self, arg_name): return """ if (!CudaNdarray_is_c_contiguous(%%(%(arg_name)s)s)) { if (!(%(class_name_caps)s_COPY_NON_CONTIGUOUS)) { PyErr_SetString(PyExc_ValueError, "%(class)s: %(arg_name)s must be C contiguous"); %%(fail)s; } } """ % { 'class': self.__class__.__name__, 'arg_name': arg_name, 'class_name_caps': self.__class__.__name__.upper(), } def make_node(self, images, maxout, gz): """ .. todo:: WRITEME """ images = as_cuda_ndarray_variable(images) maxout = as_cuda_ndarray_variable(maxout) gz = as_cuda_ndarray_variable(gz) assert images.ndim == 4 assert maxout.ndim == 4 assert gz.ndim == 4 try: # Note : `get_scalar_constant_value` returns a ndarray not a # int nb_channel = int(get_scalar_constant_value(images.shape[0])) assert nb_channel % 16 == 0 except NotScalarConstantError: pass return Apply(self, [images, maxout, gz], [images.type()]) def c_code(self, node, name, inputs, outputs, sub): """ .. todo:: WRITEME """ images, maxout, gz = inputs targets, = outputs fail = sub['fail'] # The amount of braces that must be closed at the end num_braces = 0 if self.copy_non_contiguous: raise UnimplementedError() else: basic_setup = "#define MAXPOOLGRAD_COPY_NON_CONTIGUOUS 0\n" # Convert images in nv_images, an NVMatrix, for compatibility # with the cuda-convnet functions setup_nv_images = self._argument_contiguity_check("images") + """ if (%(images)s->nd != 4) { PyErr_Format(PyExc_ValueError, "images must have nd=4, got nd=%%i", %(images)s->nd); %(fail)s; } { //setup_nv_images brace 1 const int * images_dims = CudaNdarray_HOST_DIMS(%(images)s); const int img_channels = images_dims[0]; const int imgSizeY = images_dims[1]; const int imgSizeX = images_dims[2]; const int batch_size = images_dims[3]; if(imgSizeY != imgSizeX){ PyErr_Format(PyExc_ValueError, "images must be square(dims[1] == dims[2]). Shape (%%i,%%i,%%i,%%i)", img_channels, imgSizeY, imgSizeX, batch_size); %(fail)s; } if(%(ds)s > imgSizeY){ PyErr_Format(PyExc_ValueError, "ds(%%d) must be <= imgSizeX(%%d) and imgSizeY(%%d).", %(ds)s, imgSizeX, imgSizeY); %(fail)s; } NVMatrix nv_images(%(images)s, img_channels * imgSizeY * imgSizeX, batch_size, "MaxPool:nv_images"); """ num_braces += 1 # Convert maxout in nv_maxout setup_nv_maxout = self._argument_contiguity_check("maxout") + """ if (%(maxout)s->nd != 4) { PyErr_Format(PyExc_ValueError, "maxout must have nd=4, got nd=%%i", %(maxout)s->nd); %(fail)s; } { //setup_nv_maxout brace 1 const int * maxout_dims = CudaNdarray_HOST_DIMS(%(maxout)s); const int maxout_channels = maxout_dims[0]; const int maxoutSizeY = maxout_dims[1]; const int maxoutSizeX = maxout_dims[2]; if(maxoutSizeY != maxoutSizeX){ PyErr_Format(PyExc_ValueError, "maxout must be square(dims[1] == dims[2])." " Shape (%%i,%%i,%%i,%%i)", maxout_channels, maxoutSizeY, maxoutSizeX, batch_size); %(fail)s; } if(img_channels != maxout_channels){ PyErr_Format(PyExc_ValueError, "img_channels(%%d) should be equal to maxout_channels(%%d).", img_channels, maxout_channels); %(fail)s; } if(maxout_dims[3] != batch_size){ PyErr_Format(PyExc_ValueError, "batch_size(%%d) should be equal to maxout_dims[3](%%d)", batch_size, maxout_dims[3]); %(fail)s; } NVMatrix nv_maxout(%(maxout)s, img_channels * maxoutSizeY * maxoutSizeX, batch_size, "MaxPool:nv_maxout"); """ num_braces += 1 # Convert gz in nv_gz setup_nv_gz = self._argument_contiguity_check("gz") + """ if (%(gz)s->nd != 4) { PyErr_Format(PyExc_ValueError, "gz must have nd=4, got nd=%%i", %(gz)s->nd); %(fail)s; } if (CudaNdarray_HOST_DIMS(%(gz)s)[0] %% 16 != 0) { PyErr_Format(PyExc_ValueError, "gz must have a number of channels that is a multiple of 16. Got %%d", CudaNdarray_HOST_DIMS(%(gz)s)[0]); %(fail)s; } { //setup_nv_gz brace 1 const int * gz_dims = CudaNdarray_HOST_DIMS(%(gz)s); const int gz_channels = gz_dims[0]; const int gzSizeY = gz_dims[1]; const int gzSizeX = gz_dims[2]; if(maxout_dims[0] != gz_dims[0] || maxout_dims[1] != gz_dims[1] || maxout_dims[2] != gz_dims[2] || maxout_dims[3] != gz_dims[3]){ PyErr_Format(PyExc_ValueError, "gz shape(%%d, %%d, %%d, %%d) must be the same" " as maxout(%%d, %%d, %%d, %%d)", maxout_dims[0], maxout_dims[1], maxout_dims[2], maxout_dims[3], gz_dims[0], gz_dims[1], gz_dims[2], gz_dims[3]); %(fail)s; } NVMatrix nv_gz(%(gz)s, img_channels * maxoutSizeY * maxoutSizeX, batch_size, "MaxPool:nv_gz"); """ num_braces += 1 setup_nv_targets = """ //int _outputsX = int(ceil((dic['imgSize'] - dic['start'] - dic['sizeX']) / float(dic['stride']))) + 1; int _outputsX = ((int)(ceil((imgSizeY - %(start)s - %(ds)s) / ((float)%(stride)s)))) + 1; int target_dims [] = { img_channels, imgSizeX, imgSizeY, batch_size }; if (CudaNdarray_prep_output(& %(targets)s, 4, target_dims)) { %(fail)s; } { // setup_nv_target brace # 1 NVMatrix nv_targets(%(targets)s, target_dims[0] * target_dims[1] * target_dims[2], target_dims[3], "MaxPool:nv_targets"); """ num_braces += 1 undo_pool = """ convLocalMaxUndo(nv_images, nv_gz, nv_maxout, nv_targets, %(ds)s, %(start)s, %(stride)s, _outputsX, 0, 1); """ braces = '}' * num_braces rval = (basic_setup + setup_nv_images + setup_nv_maxout + setup_nv_gz + setup_nv_targets + undo_pool + braces) start = self.start stride = self.stride ds = self.ds rval = rval % locals() return rval # Make sure the cuda_convnet library is compiled and up-to-date def make_thunk(self, node, storage_map, compute_map, no_recycling): """ .. todo:: WRITEME """ if not convnet_available(): raise RuntimeError('Could not compile cuda_convnet') return super(MaxPoolGrad, self).make_thunk( node, storage_map, compute_map, no_recycling)
bsd-3-clause
kiddinn/plaso
plaso/cli/helpers/output_modules.py
4
3181
# -*- coding: utf-8 -*- """The output modules CLI arguments helper.""" import sys from plaso.cli import tools from plaso.cli.helpers import interface from plaso.cli.helpers import manager from plaso.lib import errors from plaso.output import manager as output_manager class OutputModulesArgumentsHelper(interface.ArgumentsHelper): """Output modules CLI arguments helper.""" NAME = 'output_modules' DESCRIPTION = 'Output modules command line arguments.' @classmethod def AddArguments(cls, argument_group): """Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group. """ argument_group.add_argument( '-o', '--output_format', '--output-format', metavar='FORMAT', dest='output_format', default='dynamic', help=( 'The output format. Use "-o list" to see a list of available ' 'output formats.')) argument_group.add_argument( '-w', '--write', metavar='OUTPUT_FILE', dest='write', help='Output filename.') # TODO: determine if this is repeated elsewhere and refactor this into # a helper function. arguments = sys.argv[1:] argument_index = 0 if '-o' in arguments: argument_index = arguments.index('-o') + 1 elif '--output_format' in arguments: argument_index = arguments.index('--output_format') + 1 elif '--output-format' in arguments: argument_index = arguments.index('--output-format') + 1 if 0 < argument_index < len(arguments): names = [name.strip() for name in arguments[argument_index].split(',')] else: names = ['dynamic'] if names and names != ['list']: manager.ArgumentHelperManager.AddCommandLineArguments( argument_group, category='output', names=names) @classmethod def ParseOptions(cls, options, configuration_object): """Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type. BadConfigOption: when the output format is not supported or the output is not provided or already exists. """ if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') output_format = getattr(options, 'output_format', 'dynamic') output_filename = getattr(options, 'write', None) if output_format != 'list': if not output_manager.OutputManager.HasOutputClass(output_format): raise errors.BadConfigOption( 'Unsupported output format: {0:s}.'.format(output_format)) setattr(configuration_object, '_output_format', output_format) setattr(configuration_object, '_output_filename', output_filename) manager.ArgumentHelperManager.RegisterHelper(OutputModulesArgumentsHelper)
apache-2.0
Nolski/olympia
apps/amo/monitors.py
15
5198
import os import socket import StringIO import traceback from django.conf import settings import commonware.log from PIL import Image import amo.search from amo.helpers import user_media_path from applications.management.commands import dump_apps monitor_log = commonware.log.getLogger('z.monitor') def memcache(): memcache = getattr(settings, 'CACHES', {}).get('default') memcache_results = [] status = '' if memcache and 'memcache' in memcache['BACKEND']: hosts = memcache['LOCATION'] using_twemproxy = False if not isinstance(hosts, (tuple, list)): hosts = [hosts] for host in hosts: ip, port = host.split(':') if ip == '127.0.0.1': using_twemproxy = True try: s = socket.socket() s.connect((ip, int(port))) except Exception, e: result = False status = 'Failed to connect to memcached (%s): %s' % (host, e) monitor_log.critical(status) else: result = True finally: s.close() memcache_results.append((ip, port, result)) if not using_twemproxy and len(memcache_results) < 2: status = ('2+ memcache servers are required.' '%s available') % len(memcache_results) monitor_log.warning(status) if not memcache_results: status = 'Memcache is not configured' monitor_log.info(status) return status, memcache_results def libraries(): # Check Libraries and versions libraries_results = [] status = '' try: Image.new('RGB', (16, 16)).save(StringIO.StringIO(), 'JPEG') libraries_results.append(('PIL+JPEG', True, 'Got it!')) except Exception, e: msg = "Failed to create a jpeg image: %s" % e libraries_results.append(('PIL+JPEG', False, msg)) try: import M2Crypto # NOQA libraries_results.append(('M2Crypto', True, 'Got it!')) except ImportError: libraries_results.append(('M2Crypto', False, 'Failed to import')) if settings.SPIDERMONKEY: if os.access(settings.SPIDERMONKEY, os.R_OK): libraries_results.append(('Spidermonkey is ready!', True, None)) # TODO: see if it works? else: msg = "You said spidermonkey was at (%s)" % settings.SPIDERMONKEY libraries_results.append(('Spidermonkey', False, msg)) else: msg = "Please set SPIDERMONKEY in your settings file." libraries_results.append(('Spidermonkey', False, msg)) missing_libs = [l for l, s, m in libraries_results if not s] if missing_libs: status = 'missing libs: %s' % ",".join(missing_libs) return status, libraries_results def elastic(): elastic_results = None status = '' try: es = amo.search.get_es() health = es.cluster.health() if health['status'] == 'red': status = 'ES is red' elastic_results = health except Exception: elastic_results = {'exception': traceback.format_exc()} return status, elastic_results def path(): # Check file paths / permissions rw = (settings.TMP_PATH, settings.MEDIA_ROOT, user_media_path('addons'), user_media_path('guarded_addons'), user_media_path('addon_icons'), user_media_path('collection_icons'), user_media_path('previews'), user_media_path('userpics'), user_media_path('reviewer_attachments'), dump_apps.Command.JSON_PATH,) r = [os.path.join(settings.ROOT, 'locale'), # The deploy process will want write access to this. # We do not want Django to have write access though. settings.PROD_DETAILS_DIR] filepaths = [(path, os.R_OK | os.W_OK, "We want read + write") for path in rw] filepaths += [(path, os.R_OK, "We want read") for path in r] filepath_results = [] filepath_status = True for path, perms, notes in filepaths: path_exists = os.path.exists(path) path_perms = os.access(path, perms) filepath_status = filepath_status and path_exists and path_perms filepath_results.append((path, path_exists, path_perms, notes)) status = filepath_status status = '' if not filepath_status: status = 'check main status page for broken perms' return status, filepath_results def redis(): # Check Redis redis_results = [None, 'REDIS_BACKENDS is not set'] status = 'REDIS_BACKENDS is not set' if getattr(settings, 'REDIS_BACKENDS', False): import redisutils status = [] redis_results = {} for alias, redis in redisutils.connections.iteritems(): try: redis_results[alias] = redis.info() except Exception, e: redis_results[alias] = None status.append('Failed to chat with redis:%s' % alias) monitor_log.critical('Failed to chat with redis: (%s)' % e) status = ','.join(status) return status, redis_results
bsd-3-clause
muravjov/ansible-modules-core
windows/win_ping.py
68
1363
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>, and others # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # this is a windows documentation stub. actual code lives in the .ps1 # file of the same name DOCUMENTATION = ''' --- module: win_ping version_added: "1.7" short_description: A windows version of the classic ping module. description: - Checks management connectivity of a windows host options: data: description: - Alternate data to return instead of 'pong' required: false default: 'pong' aliases: [] author: Chris Church ''' EXAMPLES = ''' # Test connectivity to a windows host ansible winserver -m win_ping # Example from an Ansible Playbook - action: win_ping '''
gpl-3.0
Workday/OpenFrame
tools/telemetry/third_party/gsutilz/third_party/apitools/apitools/base/py/encoding_test.py
12
13894
import base64 import datetime import json from protorpc import message_types from protorpc import messages from protorpc import util import unittest2 from apitools.base.py import encoding from apitools.base.py import exceptions class SimpleMessage(messages.Message): field = messages.StringField(1) repfield = messages.StringField(2, repeated=True) class BytesMessage(messages.Message): field = messages.BytesField(1) repfield = messages.BytesField(2, repeated=True) class TimeMessage(messages.Message): timefield = message_types.DateTimeField(3) @encoding.MapUnrecognizedFields('additional_properties') class AdditionalPropertiesMessage(messages.Message): class AdditionalProperty(messages.Message): key = messages.StringField(1) value = messages.StringField(2) additional_properties = messages.MessageField( AdditionalProperty, 1, repeated=True) class CompoundPropertyType(messages.Message): index = messages.IntegerField(1) name = messages.StringField(2) class MessageWithEnum(messages.Message): class ThisEnum(messages.Enum): VALUE_ONE = 1 VALUE_TWO = 2 field_one = messages.EnumField(ThisEnum, 1) field_two = messages.EnumField(ThisEnum, 2, default=ThisEnum.VALUE_TWO) ignored_field = messages.EnumField(ThisEnum, 3) @encoding.MapUnrecognizedFields('additional_properties') class AdditionalMessagePropertiesMessage(messages.Message): class AdditionalProperty(messages.Message): key = messages.StringField(1) value = messages.MessageField(CompoundPropertyType, 2) additional_properties = messages.MessageField( 'AdditionalProperty', 1, repeated=True) class HasNestedMessage(messages.Message): nested = messages.MessageField(AdditionalPropertiesMessage, 1) nested_list = messages.StringField(2, repeated=True) class ExtraNestedMessage(messages.Message): nested = messages.MessageField(HasNestedMessage, 1) class MessageWithRemappings(messages.Message): class SomeEnum(messages.Enum): enum_value = 1 second_value = 2 enum_field = messages.EnumField(SomeEnum, 1) double_encoding = messages.EnumField(SomeEnum, 2) another_field = messages.StringField(3) repeated_enum = messages.EnumField(SomeEnum, 4, repeated=True) repeated_field = messages.StringField(5, repeated=True) encoding.AddCustomJsonEnumMapping(MessageWithRemappings.SomeEnum, 'enum_value', 'wire_name') encoding.AddCustomJsonFieldMapping(MessageWithRemappings, 'double_encoding', 'doubleEncoding') encoding.AddCustomJsonFieldMapping(MessageWithRemappings, 'another_field', 'anotherField') encoding.AddCustomJsonFieldMapping(MessageWithRemappings, 'repeated_field', 'repeatedField') class EncodingTest(unittest2.TestCase): def testCopyProtoMessage(self): msg = SimpleMessage(field='abc') new_msg = encoding.CopyProtoMessage(msg) self.assertEqual(msg.field, new_msg.field) msg.field = 'def' self.assertNotEqual(msg.field, new_msg.field) def testBytesEncoding(self): b64_str = 'AAc+' b64_msg = '{"field": "%s"}' % b64_str urlsafe_b64_str = 'AAc-' urlsafe_b64_msg = '{"field": "%s"}' % urlsafe_b64_str data = base64.b64decode(b64_str) msg = BytesMessage(field=data) self.assertEqual( msg, encoding.JsonToMessage(BytesMessage, urlsafe_b64_msg)) self.assertEqual(msg, encoding.JsonToMessage(BytesMessage, b64_msg)) self.assertEqual(urlsafe_b64_msg, encoding.MessageToJson(msg)) enc_rep_msg = '{"repfield": ["%(b)s", "%(b)s"]}' % { 'b': urlsafe_b64_str} rep_msg = BytesMessage(repfield=[data, data]) self.assertEqual( rep_msg, encoding.JsonToMessage(BytesMessage, enc_rep_msg)) self.assertEqual(enc_rep_msg, encoding.MessageToJson(rep_msg)) def testIncludeFields(self): msg = SimpleMessage() self.assertEqual('{}', encoding.MessageToJson(msg)) self.assertEqual( '{"field": null}', encoding.MessageToJson(msg, include_fields=['field'])) self.assertEqual( '{"repfield": []}', encoding.MessageToJson(msg, include_fields=['repfield'])) def testNestedIncludeFields(self): msg = HasNestedMessage( nested=AdditionalPropertiesMessage( additional_properties=[])) self.assertEqual( '{"nested": null}', encoding.MessageToJson(msg, include_fields=['nested'])) self.assertEqual( '{"nested": {"additional_properties": []}}', encoding.MessageToJson( msg, include_fields=['nested.additional_properties'])) msg = ExtraNestedMessage(nested=msg) self.assertEqual( '{"nested": {"nested": null}}', encoding.MessageToJson(msg, include_fields=['nested.nested'])) self.assertEqual( '{"nested": {"nested_list": []}}', encoding.MessageToJson(msg, include_fields=['nested.nested_list'])) self.assertEqual( '{"nested": {"nested": {"additional_properties": []}}}', encoding.MessageToJson( msg, include_fields=['nested.nested.additional_properties'])) def testAdditionalPropertyMapping(self): msg = AdditionalPropertiesMessage() msg.additional_properties = [ AdditionalPropertiesMessage.AdditionalProperty( key='key_one', value='value_one'), AdditionalPropertiesMessage.AdditionalProperty( key='key_two', value='value_two'), ] encoded_msg = encoding.MessageToJson(msg) self.assertEqual( {'key_one': 'value_one', 'key_two': 'value_two'}, json.loads(encoded_msg)) new_msg = encoding.JsonToMessage(type(msg), encoded_msg) self.assertEqual( set(('key_one', 'key_two')), set([x.key for x in new_msg.additional_properties])) self.assertIsNot(msg, new_msg) new_msg.additional_properties.pop() self.assertEqual(1, len(new_msg.additional_properties)) self.assertEqual(2, len(msg.additional_properties)) def testAdditionalMessageProperties(self): json_msg = '{"input": {"index": 0, "name": "output"}}' result = encoding.JsonToMessage( AdditionalMessagePropertiesMessage, json_msg) self.assertEqual(1, len(result.additional_properties)) self.assertEqual(0, result.additional_properties[0].value.index) def testNestedFieldMapping(self): nested_msg = AdditionalPropertiesMessage() nested_msg.additional_properties = [ AdditionalPropertiesMessage.AdditionalProperty( key='key_one', value='value_one'), AdditionalPropertiesMessage.AdditionalProperty( key='key_two', value='value_two'), ] msg = HasNestedMessage(nested=nested_msg) encoded_msg = encoding.MessageToJson(msg) self.assertEqual( {'nested': {'key_one': 'value_one', 'key_two': 'value_two'}}, json.loads(encoded_msg)) new_msg = encoding.JsonToMessage(type(msg), encoded_msg) self.assertEqual( set(('key_one', 'key_two')), set([x.key for x in new_msg.nested.additional_properties])) new_msg.nested.additional_properties.pop() self.assertEqual(1, len(new_msg.nested.additional_properties)) self.assertEqual(2, len(msg.nested.additional_properties)) def testValidEnums(self): message_json = '{"field_one": "VALUE_ONE"}' message = encoding.JsonToMessage(MessageWithEnum, message_json) self.assertEqual(MessageWithEnum.ThisEnum.VALUE_ONE, message.field_one) self.assertEqual(MessageWithEnum.ThisEnum.VALUE_TWO, message.field_two) self.assertEqual(json.loads(message_json), json.loads(encoding.MessageToJson(message))) def testIgnoredEnums(self): json_with_typo = '{"field_one": "VALUE_OEN"}' message = encoding.JsonToMessage(MessageWithEnum, json_with_typo) self.assertEqual(None, message.field_one) self.assertEqual(('VALUE_OEN', messages.Variant.ENUM), message.get_unrecognized_field_info('field_one')) self.assertEqual(json.loads(json_with_typo), json.loads(encoding.MessageToJson(message))) empty_json = '' message = encoding.JsonToMessage(MessageWithEnum, empty_json) self.assertEqual(None, message.field_one) def testIgnoredEnumsWithDefaults(self): json_with_typo = '{"field_two": "VALUE_OEN"}' message = encoding.JsonToMessage(MessageWithEnum, json_with_typo) self.assertEqual(MessageWithEnum.ThisEnum.VALUE_TWO, message.field_two) self.assertEqual(json.loads(json_with_typo), json.loads(encoding.MessageToJson(message))) def testUnknownNestedRoundtrip(self): json_message = '{"field": "abc", "submessage": {"a": 1, "b": "foo"}}' message = encoding.JsonToMessage(SimpleMessage, json_message) self.assertEqual(json.loads(json_message), json.loads(encoding.MessageToJson(message))) def testJsonDatetime(self): msg = TimeMessage(timefield=datetime.datetime( 2014, 7, 2, 23, 33, 25, 541000, tzinfo=util.TimeZoneOffset(datetime.timedelta(0)))) self.assertEqual( '{"timefield": "2014-07-02T23:33:25.541000+00:00"}', encoding.MessageToJson(msg)) def testEnumRemapping(self): msg = MessageWithRemappings( enum_field=MessageWithRemappings.SomeEnum.enum_value) json_message = encoding.MessageToJson(msg) self.assertEqual('{"enum_field": "wire_name"}', json_message) self.assertEqual( msg, encoding.JsonToMessage(MessageWithRemappings, json_message)) def testRepeatedEnumRemapping(self): msg = MessageWithRemappings( repeated_enum=[ MessageWithRemappings.SomeEnum.enum_value, MessageWithRemappings.SomeEnum.second_value, ]) json_message = encoding.MessageToJson(msg) self.assertEqual('{"repeated_enum": ["wire_name", "second_value"]}', json_message) self.assertEqual( msg, encoding.JsonToMessage(MessageWithRemappings, json_message)) def testFieldRemapping(self): msg = MessageWithRemappings(another_field='abc') json_message = encoding.MessageToJson(msg) self.assertEqual('{"anotherField": "abc"}', json_message) self.assertEqual( msg, encoding.JsonToMessage(MessageWithRemappings, json_message)) def testRepeatedFieldRemapping(self): msg = MessageWithRemappings(repeated_field=['abc', 'def']) json_message = encoding.MessageToJson(msg) self.assertEqual('{"repeatedField": ["abc", "def"]}', json_message) self.assertEqual( msg, encoding.JsonToMessage(MessageWithRemappings, json_message)) def testMultipleRemapping(self): msg = MessageWithRemappings( double_encoding=MessageWithRemappings.SomeEnum.enum_value) json_message = encoding.MessageToJson(msg) self.assertEqual('{"doubleEncoding": "wire_name"}', json_message) self.assertEqual( msg, encoding.JsonToMessage(MessageWithRemappings, json_message)) def testNoRepeatedRemapping(self): self.assertRaises( exceptions.InvalidDataError, encoding.AddCustomJsonFieldMapping, MessageWithRemappings, 'double_encoding', 'something_else') self.assertRaises( exceptions.InvalidDataError, encoding.AddCustomJsonFieldMapping, MessageWithRemappings, 'enum_field', 'anotherField') self.assertRaises( exceptions.InvalidDataError, encoding.AddCustomJsonEnumMapping, MessageWithRemappings.SomeEnum, 'enum_value', 'another_name') self.assertRaises( exceptions.InvalidDataError, encoding.AddCustomJsonEnumMapping, MessageWithRemappings.SomeEnum, 'second_value', 'wire_name') def testMessageToRepr(self): # Using the same string returned by MessageToRepr, with the # module names fixed. # pylint: disable=bad-whitespace msg = SimpleMessage(field='field', repfield=['field', 'field', ],) # pylint: enable=bad-whitespace self.assertEqual( encoding.MessageToRepr(msg), r"%s.SimpleMessage(field='field',repfield=['field','field',],)" % ( __name__,)) self.assertEqual( encoding.MessageToRepr(msg, no_modules=True), r"SimpleMessage(field='field',repfield=['field','field',],)") def testMessageToReprWithTime(self): msg = TimeMessage(timefield=datetime.datetime( 2014, 7, 2, 23, 33, 25, 541000, tzinfo=util.TimeZoneOffset(datetime.timedelta(0)))) self.assertEqual( encoding.MessageToRepr(msg, multiline=True), ('%s.TimeMessage(\n ' 'timefield=datetime.datetime(2014, 7, 2, 23, 33, 25, 541000, ' 'tzinfo=protorpc.util.TimeZoneOffset(' 'datetime.timedelta(0))),\n)') % __name__) self.assertEqual( encoding.MessageToRepr(msg, multiline=True, no_modules=True), 'TimeMessage(\n ' 'timefield=datetime.datetime(2014, 7, 2, 23, 33, 25, 541000, ' 'tzinfo=TimeZoneOffset(datetime.timedelta(0))),\n)')
bsd-3-clause
rahulunair/nova
nova/tests/unit/cmd/test_common.py
1
5356
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Unit tests for the common functions used by different CLI interfaces. """ import sys import fixtures import mock from six.moves import StringIO from nova.cmd import common as cmd_common from nova.db import api from nova import exception from nova import test class TestCmdCommon(test.NoDBTestCase): @mock.patch.object(cmd_common, 'LOG') @mock.patch.object(api, 'IMPL') def test_block_db_access(self, mock_db_IMPL, mock_LOG): cmd_common.block_db_access('unit-tests') self.assertEqual(api.IMPL, api.IMPL.foo) self.assertRaises(exception.DBNotAllowed, api.IMPL) self.assertEqual('unit-tests', mock_LOG.error.call_args[0][1]['service_name']) def test_args_decorator(self): @cmd_common.args(bar='<bar>') @cmd_common.args('foo') def f(): pass f_args = f.__dict__['args'] bar_args = ((), {'bar': '<bar>'}) foo_args = (('foo', ), {}) self.assertEqual(bar_args, f_args[0]) self.assertEqual(foo_args, f_args[1]) def test_methods_of(self): class foo(object): foo = 'bar' def public(self): pass def _private(self): pass methods = cmd_common.methods_of(foo()) method_names = [method_name for method_name, method in methods] self.assertIn('public', method_names) self.assertNotIn('_private', method_names) self.assertNotIn('foo', method_names) @mock.patch.object(cmd_common, 'CONF') def test_print_bash_completion_no_query_category(self, mock_CONF): self.useFixture(fixtures.MonkeyPatch('sys.stdout', StringIO())) mock_CONF.category.query_category = None categories = {'foo': mock.sentinel.foo, 'bar': mock.sentinel.bar} cmd_common.print_bash_completion(categories) self.assertEqual(' '.join(categories.keys()) + '\n', sys.stdout.getvalue()) @mock.patch.object(cmd_common, 'CONF') def test_print_bash_completion_mismatch(self, mock_CONF): self.useFixture(fixtures.MonkeyPatch('sys.stdout', StringIO())) mock_CONF.category.query_category = 'bar' categories = {'foo': mock.sentinel.foo} cmd_common.print_bash_completion(categories) self.assertEqual('', sys.stdout.getvalue()) @mock.patch.object(cmd_common, 'methods_of') @mock.patch.object(cmd_common, 'CONF') def test_print_bash_completion(self, mock_CONF, mock_method_of): self.useFixture(fixtures.MonkeyPatch('sys.stdout', StringIO())) mock_CONF.category.query_category = 'foo' actions = [('f1', mock.sentinel.f1), ('f2', mock.sentinel.f2)] mock_method_of.return_value = actions mock_fn = mock.Mock() categories = {'foo': mock_fn} cmd_common.print_bash_completion(categories) mock_fn.assert_called_once_with() mock_method_of.assert_called_once_with(mock_fn.return_value) self.assertEqual(' '.join([k for k, v in actions]) + '\n', sys.stdout.getvalue()) @mock.patch.object(cmd_common, 'validate_args') @mock.patch.object(cmd_common, 'CONF') def test_get_action_fn(self, mock_CONF, mock_validate_args): mock_validate_args.return_value = None action_args = [u'arg'] action_kwargs = ['missing', 'foo', 'bar'] mock_CONF.category.action_fn = mock.sentinel.action_fn mock_CONF.category.action_args = action_args mock_CONF.category.action_kwargs = action_kwargs mock_CONF.category.action_kwarg_foo = u'foo_val' mock_CONF.category.action_kwarg_bar = True mock_CONF.category.action_kwarg_missing = None actual_fn, actual_args, actual_kwargs = cmd_common.get_action_fn() self.assertEqual(mock.sentinel.action_fn, actual_fn) self.assertEqual(action_args, actual_args) self.assertEqual(u'foo_val', actual_kwargs['foo']) self.assertTrue(actual_kwargs['bar']) self.assertNotIn('missing', actual_kwargs) @mock.patch.object(cmd_common, 'validate_args') @mock.patch.object(cmd_common, 'CONF') def test_get_action_fn_missing_args(self, mock_CONF, mock_validate_args): # Don't leak the actual print call self.useFixture(fixtures.MonkeyPatch('sys.stdout', StringIO())) mock_validate_args.return_value = ['foo'] mock_CONF.category.action_fn = mock.sentinel.action_fn mock_CONF.category.action_args = [] mock_CONF.category.action_kwargs = [] self.assertRaises(exception.Invalid, cmd_common.get_action_fn) mock_CONF.print_help.assert_called_once_with()
apache-2.0
hasgeek/funnel
funnel/forms/notification.py
1
8978
from __future__ import annotations from collections import namedtuple from flask import url_for from baseframe import __ import baseframe.forms as forms from ..models import User, notification_type_registry from ..transports import platform_transports __all__ = [ 'transport_labels', 'UnsubscribeForm', 'SetNotificationPreferenceForm', ] TransportLabels = namedtuple( 'TransportLabels', [ 'title', 'requirement', 'requirement_action', 'unsubscribe_form', 'unsubscribe_description', 'switch', 'enabled_main', 'enabled', 'disabled_main', 'disabled', ], ) transport_labels = { 'email': TransportLabels( title=__("Email"), requirement=__("To enable, add a verified email address"), requirement_action=lambda: url_for('add_email'), unsubscribe_form=__("Notify me by email"), unsubscribe_description=__("Uncheck this to disable all email notifications"), switch=__("Email notifications"), enabled_main=__("Enabled selected email notifications"), enabled=__("Enabled this email notification"), disabled_main=__("Disabled all email notifications"), disabled=__("Disabled this email notification"), ), 'sms': TransportLabels( title=__("SMS"), requirement=__("To enable, add a verified phone number"), requirement_action=lambda: url_for('add_phone'), unsubscribe_form=__("Notify me by SMS"), unsubscribe_description=__("Uncheck this to disable all SMS notifications"), switch=__("SMS notifications"), enabled_main=__("Enabled selected SMS notifications"), enabled=__("Enabled this SMS notification"), disabled_main=__("Disabled all SMS notifications"), disabled=__("Disabled this SMS notification"), ), 'webpush': TransportLabels( title=__("Browser"), requirement=__("To enable, allow push notifications in the browser"), requirement_action=lambda: None, unsubscribe_form=__("Notify me with browser notifications"), unsubscribe_description=__("Uncheck this to disable all browser notifications"), switch=__("Push notifications"), enabled_main=__("Enabled selected push notifications"), enabled=__("Enabled this push notification"), disabled_main=__("Disabled all push notifications"), disabled=__("Disabled this push notification"), ), 'telegram': TransportLabels( title=__("Telegram"), requirement=__("To enable, link your Telegram account"), requirement_action=lambda: None, unsubscribe_form=__("Notify me on Telegram"), unsubscribe_description=__( "Uncheck this to disable all Telegram notifications" ), switch=__("Telegram notifications"), enabled_main=__("Enabled selected Telegram notifications"), enabled=__("Enabled this Telegram notification"), disabled_main=__("Disabled all Telegram notifications"), disabled=__("Disabled this Telegram notification"), ), 'whatsapp': TransportLabels( title=__("WhatsApp"), requirement=__("To enable, add your WhatsApp number"), requirement_action=lambda: url_for('add_phone'), unsubscribe_form=__("Notify me on WhatsApp"), unsubscribe_description=__( "Uncheck this to disable all WhatsApp notifications" ), switch=__("WhatsApp notifications"), enabled_main=__("Enabled selected WhatsApp notifications"), enabled=__("Enabled this WhatsApp notification"), disabled_main=__("Disabled all WhatsApp notifications"), disabled=__("Disabled this WhatsApp notification"), ), } @User.forms('unsubscribe') class UnsubscribeForm(forms.Form): __expects__ = ('transport', 'notification_type') # To consider: Replace the field's ListWidget with a GroupedListWidget, and show all # known notifications by category, not just the ones the user has received a # notification for. This will avoid a dark pattern wherein a user keeps getting # subscribed to new types of notifications, a problem Twitter had when they # attempted to engage dormant accounts by inventing new reasons to email them. # However, also consider that this will be a long and overwhelming list, and will # not help with new notification types added after the user visits this list. The # better option may be to set notification preferences based on previous # preferences. A crude form of this exists in the NotificationPreferences class, # but it should be smarter about defaults per category of notification. main = forms.BooleanField( __("Notify me"), description=__("Uncheck this to disable all notifications") ) types = forms.SelectMultipleField( __("Or disable only a specific notification"), widget=forms.ListWidget(), option_widget=forms.CheckboxInput(), ) # This token is validated in the view, not here, because it has to be valid in the # GET request itself, and the UI flow is very dependent on the validation error. token = forms.HiddenField( __("Unsubscribe token"), validators=[forms.validators.DataRequired()] ) token_type = forms.HiddenField( __("Unsubscribe token type"), validators=[forms.validators.DataRequired()] ) def set_queries(self): # Populate choices with all notification types that the user has a preference # row for. if self.transport in transport_labels: self.main.label.text = transport_labels[self.transport].unsubscribe_form self.main.description = transport_labels[ self.transport ].unsubscribe_description self.types.choices = [ ( ntype, notification_type_registry[ntype].title + (" 👈" if ntype == self.notification_type else ''), ) for ntype in notification_type_registry if ntype in self.edit_obj.notification_preferences and notification_type_registry[ntype].allow_transport(self.transport) ] # Sorted by definition order. Usable until we introduce grouping def get_main(self, obj): return obj.main_notification_preferences.by_transport(self.transport) def get_types(self, obj): # Populate data with all notification types for which the user has the # current transport enabled return [ ntype for ntype, user_prefs in obj.notification_preferences.items() if user_prefs.by_transport(self.transport) ] def set_main(self, obj): obj.main_notification_preferences.set_transport(self.transport, self.main.data) def set_types(self, obj): # self.types.data will only contain the enabled preferences. Therefore, iterate # through all choices and toggle true or false based on whether it's in the # enabled list. This uses dict access instead of .get because the rows are known # to exist (set_queries loaded from this source). for ntype, _title in self.types.choices: obj.notification_preferences[ntype].set_transport( self.transport, ntype in self.types.data ) @User.forms('set_notification_preference') class SetNotificationPreferenceForm(forms.Form): """Set one notification preference.""" notification_type = forms.SelectField(__("Notification type")) transport = forms.SelectField( __("Transport"), validators=[forms.validators.DataRequired()] ) enabled = forms.BooleanField(__("Enable this transport")) def set_queries(self): # The main switch is special-cased with an empty string for notification type self.notification_type.choices = [('', __("Main switch"))] + [ (ntype, cls.title) for ntype, cls in notification_type_registry.items() ] self.transport.choices = [ (transport, transport) for transport in platform_transports if platform_transports[transport] ] def status_message(self): """Render a success or error message.""" if self.errors: # Flatten errors into a single string because typically this will only # be a CSRF error. return ' '.join(' '.join(message) for message in self.errors.values()) if self.notification_type.data == '': return ( transport_labels[self.transport.data].enabled_main if self.enabled.data else transport_labels[self.transport.data].disabled_main ) return ( transport_labels[self.transport.data].enabled if self.enabled.data else transport_labels[self.transport.data].disabled )
agpl-3.0
timkrentz/SunTracker
IMU/VTK-6.2.0/IO/Geometry/Testing/Python/TestAVSucdReader.py
2
1247
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Read some AVS UCD data in ASCII form r = vtk.vtkAVSucdReader() r.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/cellsnd.ascii.inp") AVSMapper = vtk.vtkDataSetMapper() AVSMapper.SetInputConnection(r.GetOutputPort()) AVSActor = vtk.vtkActor() AVSActor.SetMapper(AVSMapper) # Read some AVS UCD data in binary form r2 = vtk.vtkAVSucdReader() r2.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/cellsnd.bin.inp") AVSMapper2 = vtk.vtkDataSetMapper() AVSMapper2.SetInputConnection(r2.GetOutputPort()) AVSActor2 = vtk.vtkActor() AVSActor2.SetMapper(AVSMapper2) AVSActor2.AddPosition(5,0,0) # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren1.AddActor(AVSActor) ren1.AddActor(AVSActor2) renWin.SetSize(300,150) iren.Initialize() renWin.Render() ren1.GetActiveCamera().Zoom(2) # prevent the tk window from showing up then start the event loop # --- end of script --
mit
hogarthj/ansible
test/units/module_utils/basic/test_selinux.py
41
11401
# -*- coding: utf-8 -*- # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type import errno import json from units.mock.procenv import ModuleTestCase, swap_stdin_and_argv from ansible.compat.tests.mock import patch, MagicMock, mock_open, Mock from ansible.module_utils.six.moves import builtins realimport = builtins.__import__ class TestSELinux(ModuleTestCase): def test_module_utils_basic_ansible_module_selinux_mls_enabled(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) basic.HAVE_SELINUX = False self.assertEqual(am.selinux_mls_enabled(), False) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.is_selinux_mls_enabled', return_value=0): self.assertEqual(am.selinux_mls_enabled(), False) with patch('selinux.is_selinux_mls_enabled', return_value=1): self.assertEqual(am.selinux_mls_enabled(), True) delattr(basic, 'selinux') def test_module_utils_basic_ansible_module_selinux_initial_context(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) am.selinux_mls_enabled = MagicMock() am.selinux_mls_enabled.return_value = False self.assertEqual(am.selinux_initial_context(), [None, None, None]) am.selinux_mls_enabled.return_value = True self.assertEqual(am.selinux_initial_context(), [None, None, None, None]) def test_module_utils_basic_ansible_module_selinux_enabled(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) # we first test the cases where the python selinux lib is # not installed, which has two paths: one in which the system # does have selinux installed (and the selinuxenabled command # is present and returns 0 when run), or selinux is not installed basic.HAVE_SELINUX = False am.get_bin_path = MagicMock() am.get_bin_path.return_value = '/path/to/selinuxenabled' am.run_command = MagicMock() am.run_command.return_value = (0, '', '') self.assertRaises(SystemExit, am.selinux_enabled) am.get_bin_path.return_value = None self.assertEqual(am.selinux_enabled(), False) # finally we test the case where the python selinux lib is installed, # and both possibilities there (enabled vs. disabled) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.is_selinux_enabled', return_value=0): self.assertEqual(am.selinux_enabled(), False) with patch('selinux.is_selinux_enabled', return_value=1): self.assertEqual(am.selinux_enabled(), True) delattr(basic, 'selinux') def test_module_utils_basic_ansible_module_selinux_default_context(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) am.selinux_initial_context = MagicMock(return_value=[None, None, None, None]) am.selinux_enabled = MagicMock(return_value=True) # we first test the cases where the python selinux lib is not installed basic.HAVE_SELINUX = False self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) # all following tests assume the python selinux bindings are installed basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): # next, we test with a mocked implementation of selinux.matchpathcon to simulate # an actual context being found with patch('selinux.matchpathcon', return_value=[0, 'unconfined_u:object_r:default_t:s0']): self.assertEqual(am.selinux_default_context(path='/foo/bar'), ['unconfined_u', 'object_r', 'default_t', 's0']) # we also test the case where matchpathcon returned a failure with patch('selinux.matchpathcon', return_value=[-1, '']): self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) # finally, we test where an OSError occurred during matchpathcon's call with patch('selinux.matchpathcon', side_effect=OSError): self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) delattr(basic, 'selinux') def test_module_utils_basic_ansible_module_selinux_context(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) am.selinux_initial_context = MagicMock(return_value=[None, None, None, None]) am.selinux_enabled = MagicMock(return_value=True) # we first test the cases where the python selinux lib is not installed basic.HAVE_SELINUX = False self.assertEqual(am.selinux_context(path='/foo/bar'), [None, None, None, None]) # all following tests assume the python selinux bindings are installed basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): # next, we test with a mocked implementation of selinux.lgetfilecon_raw to simulate # an actual context being found with patch('selinux.lgetfilecon_raw', return_value=[0, 'unconfined_u:object_r:default_t:s0']): self.assertEqual(am.selinux_context(path='/foo/bar'), ['unconfined_u', 'object_r', 'default_t', 's0']) # we also test the case where matchpathcon returned a failure with patch('selinux.lgetfilecon_raw', return_value=[-1, '']): self.assertEqual(am.selinux_context(path='/foo/bar'), [None, None, None, None]) # finally, we test where an OSError occurred during matchpathcon's call e = OSError() e.errno = errno.ENOENT with patch('selinux.lgetfilecon_raw', side_effect=e): self.assertRaises(SystemExit, am.selinux_context, path='/foo/bar') e = OSError() with patch('selinux.lgetfilecon_raw', side_effect=e): self.assertRaises(SystemExit, am.selinux_context, path='/foo/bar') delattr(basic, 'selinux') def test_module_utils_basic_ansible_module_is_special_selinux_path(self): from ansible.module_utils import basic args = json.dumps(dict(ANSIBLE_MODULE_ARGS={'_ansible_selinux_special_fs': "nfs,nfsd,foos"})) with swap_stdin_and_argv(stdin_data=args): basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) def _mock_find_mount_point(path): if path.startswith('/some/path'): return '/some/path' elif path.startswith('/weird/random/fstype'): return '/weird/random/fstype' return '/' am.find_mount_point = MagicMock(side_effect=_mock_find_mount_point) am.selinux_context = MagicMock(return_value=['foo_u', 'foo_r', 'foo_t', 's0']) m = mock_open() m.side_effect = OSError with patch.object(builtins, 'open', m, create=True): self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (False, None)) mount_data = [ '/dev/disk1 / ext4 rw,seclabel,relatime,data=ordered 0 0\n', '1.1.1.1:/path/to/nfs /some/path nfs ro 0 0\n', 'whatever /weird/random/fstype foos rw 0 0\n', ] # mock_open has a broken readlines() implementation apparently... # this should work by default but doesn't, so we fix it m = mock_open(read_data=''.join(mount_data)) m.return_value.readlines.return_value = mount_data with patch.object(builtins, 'open', m, create=True): self.assertEqual(am.is_special_selinux_path('/some/random/path'), (False, None)) self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (True, ['foo_u', 'foo_r', 'foo_t', 's0'])) self.assertEqual(am.is_special_selinux_path('/weird/random/fstype/path'), (True, ['foo_u', 'foo_r', 'foo_t', 's0'])) def test_module_utils_basic_ansible_module_set_context_if_different(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec=dict(), ) basic.HAVE_SELINUX = False am.selinux_enabled = MagicMock(return_value=False) self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True), True) self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), False) basic.HAVE_SELINUX = True am.selinux_enabled = MagicMock(return_value=True) am.selinux_context = MagicMock(return_value=['bar_u', 'bar_r', None, None]) am.is_special_selinux_path = MagicMock(return_value=(False, None)) basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.lsetfilecon', return_value=0) as m: self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) m.assert_called_with('/path/to/file', 'foo_u:foo_r:foo_t:s0') m.reset_mock() am.check_mode = True self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) self.assertEqual(m.called, False) am.check_mode = False with patch('selinux.lsetfilecon', return_value=1) as m: self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) with patch('selinux.lsetfilecon', side_effect=OSError) as m: self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) am.is_special_selinux_path = MagicMock(return_value=(True, ['sp_u', 'sp_r', 'sp_t', 's0'])) with patch('selinux.lsetfilecon', return_value=0) as m: self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) m.assert_called_with('/path/to/file', 'sp_u:sp_r:sp_t:s0') delattr(basic, 'selinux')
gpl-3.0
stormi/tsunami
src/primaires/perso/commandes/prompt/defaut.py
1
4813
# -*-coding:Utf-8 -* # Copyright (c) 2010 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Fichier contenant le paramètre dynamique de la commande 'prompt'.""" from primaires.format.fonctions import supprimer_accents from primaires.interpreteur.masque.parametre import Parametre # Constantes AIDE = """ Utilisez cette commande pour consulter ou modifier votre {courte}. {longue}. Utilisez %prompt% %prompt:{nom}% sans argument pour consulter votre {courte} actuel. Vous pouvez aussi : Masquer le prompt avec %prompt% %prompt:{nom}%|ent| caché|ff| Réinitialiser le prompt avec %prompt% %prompt:{nom}%|ent| init|ff| Ou encore %prompt% %prompt:{nom}% suivi du nouveau prompt pour le modifier. """.strip() class PrmDefaut(Parametre): """Commande dynamique de 'prompt'. Ce n'est pas un paramètre ordinaire car il est créé dynamiquement au moment de l'ajout de la commande. Voir la méthode 'ajouter_commandes'. """ def __init__(self, prompt): """Constructeur du paramètre""" Parametre.__init__(self, prompt.nom, prompt.nom_anglais) self.prompt = prompt self.schema = "(<prompt>)" self.aide_courte = prompt.aide_courte.capitalize() self.aide_longue = AIDE.format(nom=prompt.nom, courte=prompt.aide_courte, longue=prompt.aide_longue) if prompt.symboles_sup: self.aide_longue += "\n Symboles " \ "supplémentaires :\n" + prompt.symboles_sup.replace( "%", "|pc|") def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" prompt = dic_masques["prompt"] or None if prompt: prompt = prompt.prompt if supprimer_accents(prompt).lower() in ("cache", "cacher"): personnage.prompts[self.prompt.nom] = "" personnage << "Votre {} a bien été masqué.".format( self.prompt.aide_courte) return if supprimer_accents(prompt).lower() == "init": if self.prompt.nom in personnage.prompts: del personnage.prompts[self.prompt.nom] personnage << "Votre {} a bien été réinitialisé.".format( self.prompt.aide_courte) return prompt = prompt.replace("{", "{{") prompt = prompt.replace("}", "}}") for symbole, repl in sorted(tuple(self.prompt.symboles.items()), key=lambda c: len(c[0]), reverse=True): prompt = prompt.replace("%{}".format(symbole), "{" + \ repl + "}") personnage.prompts[self.prompt.nom] = prompt personnage << "Votre {} a bien été modifié.".format( self.prompt.aide_courte) prompt = personnage.prompts.get(self.prompt.nom, self.prompt.defaut) for symbole, repl in self.prompt.symboles.items(): prompt = prompt.replace("{" + repl + "}", "%" + symbole) prompt = prompt.replace("{", "{{").replace("}", "}}") personnage << self.prompt.aide_courte.capitalize() + " actuel : " + \ prompt
bsd-3-clause
marrow/mongo
marrow/mongo/core/field/reference.py
1
3191
# encoding: utf-8 from __future__ import unicode_literals from collections import Mapping from bson import ObjectId as OID from bson import DBRef from bson.errors import InvalidId from .. import Document, Field from ....package.canonical import name as canon from ....package.loader import traverse from ....schema import Attribute from ....schema.compat import odict, str, unicode from .base import _HasKind, Field class Reference(_HasKind, Field): concrete = Attribute(default=False) # If truthy, will store a DBRef instead of ObjectId. cache = Attribute(default=None) # Attributes to preserve from the referenced object at the reference level. @property def __foreign__(self): """Advertise that we store a simple reference, or deep reference, or object, depending on configuration.""" if self.cache: return 'object' if self.concrete: return 'dbPointer' return 'objectId' def _populate_cache(self, value): inst = odict() if isinstance(value, Document): try: inst['_id'] = value.__data__['_id'] if getattr(value, '__type_store__', None): inst[value.__type_store__] = canon(value.__class__) except KeyError: raise ValueError("Must reference a document with an _id.") elif isinstance(value, Mapping): try: inst['_id'] = value['_id'] except KeyError: raise ValueError("Must reference a document with an _id.") elif isinstance(value, OID): inst['_id'] = value elif isinstance(value, (str, unicode)) and len(value) == 24: try: inst['_id'] = OID(value) except InvalidId: raise ValueError("Not referenceable: " + repr(value)) else: raise ValueError("Not referenceable: " + repr(value)) for field in self.cache: if __debug__: # This verification is potentially expensive, so skip it in production. if any(chunk.isnumeric() for chunk in field.split('.')): raise ValueError("May not contain numeric array references.") try: nested = traverse(value, field) except LookupError: pass else: current = inst parts = field.split('.') for part in parts[:-1]: current = current.setdefault(part, odict()) current[parts[-1]] = nested return inst def to_foreign(self, obj, name, value): # pylint:disable=unused-argument """Transform to a MongoDB-safe value.""" if self.cache: return self._populate_cache(value) identifier = value # First, we handle the typcial Document object case. if isinstance(value, Document): identifier = value.__data__.get('_id', None) if identifier is None: raise ValueError("Can only store a reference to a saved Document instance with an `_id` stored.") elif isinstance(value, (str, unicode)) and len(value) == 24: try: identifier = OID(value) except InvalidId: pass kind = self._kind(obj.__class__) if self.concrete: if isinstance(value, Document) and value.__collection__: return DBRef(value.__collection__, identifier) if getattr(kind, '__collection__', None): return DBRef(kind.__collection__, identifier) raise ValueError("Could not infer collection name.") return identifier
mit
sprockets/sprockets.http
examples.py
1
1891
from tornado import web from sprockets.http import app, mixins import sprockets.http class StatusHandler(mixins.ErrorLogger, mixins.ErrorWriter, web.RequestHandler): """Example that exercises the mix-ins in this library.""" def get(self, status_code): """ Returns the requested status. :param int status_code: the status code to return :queryparam str reason: optional reason phrase """ status_code = int(status_code) if status_code >= 400: kwargs = {'status_code': status_code} if self.get_query_argument('reason', None): kwargs['reason'] = self.get_query_argument('reason') if self.get_query_argument('log_message', None): kwargs['log_message'] = self.get_query_argument('log_message') self.send_error(**kwargs) else: self.set_status(status_code) class Application(app.Application): def __init__(self, **kwargs): kwargs['debug'] = True super().__init__( [web.url(r'/status/(?P<status_code>\d+)', StatusHandler)], **kwargs) if __name__ == '__main__': sprockets.http.run( Application, settings={'port': 8888}, log_config={ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'readable': { 'format': '%(levelname)-13s %(name)s: %(message)s', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'readable', 'stream': 'ext://sys.stdout', } }, 'root': { 'level': 'DEBUG', 'handlers': ['console'], } }, )
bsd-3-clause
miyataken999/weblate
weblate/wsgi.py
2
1918
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ WSGI config for weblate project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "weblate.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
gpl-3.0
donspaulding/adspygoogle
tests/adspygoogle/dfa/v1_19/dfa_logger_unittest.py
3
2579
#!/usr/bin/python # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests to cover Logger.""" __author__ = 'api.jdilallo@gmail.com (Joseph DiLallo)' import logging import os import sys sys.path.insert(0, os.path.join('..', '..', '..', '..')) import unittest from adspygoogle.common import Utils from tests.adspygoogle.dfa.v1_19 import client from tests.adspygoogle.dfa.v1_19 import HTTP_PROXY from tests.adspygoogle.dfa.v1_19 import SERVER_V1_19 from tests.adspygoogle.dfa.v1_19 import VERSION_V1_19 class DfaLoggerTestV1_19(unittest.TestCase): """Unittest suite for Logger using v1_19.""" SERVER = SERVER_V1_19 VERSION = VERSION_V1_19 TMP_LOG = os.path.join('..', '..', '..', '..', 'logs', 'logger_unittest.log') DEBUG_MSG1 = 'Message before call to an API method.' DEBUG_MSG2 = 'Message after call to an API method.' client.debug = False def setUp(self): """Prepare unittest.""" print self.id() def testUpperStackLogging(self): """Tests whether we can define logger at client level and log before and after the API request is made. """ logger = logging.getLogger(self.__class__.__name__) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(self.__class__.TMP_LOG) fh.setLevel(logging.DEBUG) logger.addHandler(fh) # Clean up temporary log file. Utils.PurgeLog(self.__class__.TMP_LOG) logger.debug(self.__class__.DEBUG_MSG1) advertiser_service = client.GetAdvertiserService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) advertiser_service.GetAdvertisers({}) logger.debug(self.__class__.DEBUG_MSG2) data = Utils.ReadFile(self.__class__.TMP_LOG) self.assertEqual(data.find(self.__class__.DEBUG_MSG1), 0) self.assertEqual(data.find(self.__class__.DEBUG_MSG2), len(self.__class__.DEBUG_MSG1) + 1) # Clean up and remove temporary log file. Utils.PurgeLog(self.__class__.TMP_LOG) os.remove(self.__class__.TMP_LOG) if __name__ == '__main__': unittest.main()
apache-2.0
heikoheiko/pyethapp
pyethapp/db_service.py
1
1454
from devp2p.service import BaseService from ethereum.slogging import get_logger log = get_logger('db') # load available databases dbs = {} try: from leveldb_service import LevelDBService except ImportError: pass else: dbs['LevelDB'] = LevelDBService try: from codernitydb_service import CodernityDB except ImportError: pass else: dbs['CodernityDB'] = CodernityDB from ephemdb_service import EphemDB dbs['EphemDB'] = EphemDB class DBService(BaseService): name = 'db' default_config = dict(db=dict(implementation='LevelDB')) def __init__(self, app): super(DBService, self).__init__(app) impl = self.app.config['db']['implementation'] if len(dbs) == 0: log.warning('No db installed') self.db_service = dbs[impl](app) def start(self): return self.db_service.start() def _run(self): return self.db_service._run() def get(self, key): return self.db_service.get(key) def put(self, key, value): return self.db_service.put(key, value) def commit(self): return self.db_service.commit() def delete(self, key): return self.db_service.delete(key) def __contains__(self, key): return key in self.db_service def __eq__(self, other): return isinstance(other, self.__class__) and self.db_service == other.db_service def __repr__(self): return repr(self.db_service)
bsd-3-clause
SixTrack/SixDesk
boinc_software/monitor-boinc-server/general-activity/parseHTML.py
1
10987
""" A.Mereghetti, 2017-01-29 script for parsing the server_status.php and getting values from tables NB: html file is a table of tables! parsing of HTML table based on: http://codereview.stackexchange.com/questions/60769/scrape-an-html-table-with-python reminders on html tables: - <table>: start a new table; - <tr>: start a new table row; - <th>: start a table header (actually, a header cell); - <td>: start a table cell in a row; """ import sys from urllib2 import urlopen, URLError from argparse import ArgumentParser from bs4 import BeautifulSoup import time lDebug=False lPrintTables=False wantedApps=[ 'SixTrack', 'sixtracktest' ] wantedH4tags=[ 'Work', 'Users', 'Computers' ] wantedH3tags=[ 'Tasks by application' ] findEntries=['table','h4','h3'] class TABLE(): def __init__( self, name ): """creating a table""" self.columnNames=[] self.content=[] # array (rows) of dictionary (column header: value)! self.name=name def addColumnNames( self, table_columnNames ): self.columnNames=[ tmpColumnName.encode('ascii','ignore') for tmpColumnName in table_columnNames ] if ( lDebug ): print "HEAD:",self.columnNames def addField( self, columnName, value, iRow=-1 ): self.columnNames.append( columnName ) if ( len( self.content ) == 0 or iRow==len(self.content) ): self.content.append( {} ) elif ( iRow>len(self.content) ): print "error in building table!" sys.exit() self.content[iRow][ columnName ]=value if ( lDebug ): print "HEAD: %s - VAL: %s" % ( self.columnNames[-1], self.content[iRow][self.columnNames[-1]] ) def addContent( self, table_data ): self.content.append( dict( zip(self.columnNames,[data.encode('ascii','ignore') for data in table_data]) ) ) if ( lDebug ): print "DATA:",self.content[-1] def retColumn( self, columnName ): if ( columnName in self.columnNames ): return [ tmpLine[columnName] for tmpLine in self.content ] else: return None def retRowName( self, columnName=None, matchName=None, columnNames=None ): if ( columnName is None or matchName is None ): return None if ( columnNames is None ): columnNames=self.columnNames if ( columnName in self.columnNames ): for tmpLine in self.content: if ( tmpLine[columnName]==matchName ): return [ tmpLine[columnName] for columnName in columnNames ] else: return None def printAll( self ): print '' print 'TABLE:',self.name print 'HEADER:','\t'.join(self.columnNames) for tmpLine in self.content: print '\t'.join( [ tmpLine[tmpColumnName] for tmpColumnName in self.columnNames ] ) class TABLE_ComputingStatus( TABLE ): ''' Example of table to be parsed: <h3>Computing status</h3> <h4>Work</h4> <div class="table"> <table width="100%" class="table table-condensed table-striped" > <tr><td>Tasks ready to send</td><td>586</td></tr> <tr><td>Tasks in progress</td><td>207292</td></tr> <tr><td>Workunits waiting for validation</td><td>42644</td></tr> <tr><td>Workunits waiting for assimilation</td><td>10</td></tr> <tr><td>Workunits waiting for file deletion</td><td>53054</td></tr> <tr><td>Tasks waiting for file deletion</td><td>52639</td></tr> <tr><td>Transitioner backlog (hours)</td><td>0.00</td></tr> </table> </div> ''' @staticmethod def fromHTML( entries, TABLES ): ''' Final state of instance: self.columnNames=['entry','#'] self.content=[ {'entry':'Tasks in progress','#':207292}, {'entry':'Tasks ready to send','#':586}, ... ] ''' parseTab=None for entry in entries: if(lDebug): print "--> reading entry:",entry," -- end entry" if(entry.name=='h4'): if (lDebug): print '--> recognised h4 tag - value:',entry.text if (entry.text in wantedH4tags): parseTab=entry.text TABLES[parseTab]=TABLE(parseTab) TABLES[parseTab].addColumnNames(['entry','#']) elif(entry.name=='table' and parseTab is not None): if(lDebug): print '--> recognised table tag - acquring data' rows=entry.find_all('tr') for row in rows: data=row.find_all('td') if(len(data)==0): # skip empty line continue if(len(data)!=2): print 'error in reading table %s'%(parseTab) print 'at row:', row sys.exit() TABLES[parseTab].addContent( [ datum.get_text() for datum in data ] ) parseTab=None return TABLES class TABLE_TasksByApplication( TABLE ): @staticmethod def fromHTML( entries, TABLES ): ''' Final state of instance: self.columnNames=['Application','Unsent','In progress',...] self.content=[ {'Application':'SixTrack','Unsent':586, ...}, {'Application':'sixtracktest','Unsent':2867, ...}, ... ] ''' parseTab=None for entry in entries: if(lDebug): print "--> reading entry:",entry," -- end entry" if(entry.name=='h3'): if(lDebug): print '--> recognised h3 tag - value:',entry.text if(entry.text in wantedH3tags): parseTab=entry.text TABLES[parseTab]=TABLE(parseTab) elif (entry.name=='table' and parseTab is not None): if(lDebug): print 'recognised table tag - acquring data' rows=entry.find_all('tr') for row in rows: table_headers = row.find_all('th') if table_headers: TABLES[parseTab].addColumnNames([headers.get_text() for headers in table_headers]) continue data=row.find_all('td') if(len(data)==0): # skip empty line continue TABLES[parseTab].addContent([datum.get_text() for datum in data]) parseTab=None return TABLES def cleanIntegers( tmpArray ): return [ tmpNum.replace(',','' ) for tmpNum in tmpArray ] def parse_arguments(): """ Process command line arguments """ parser = ArgumentParser(description='Grabs tables from html') parser.add_argument('-u', '--url', help='url to grab from', required=False) parser.add_argument('-f', '--filN', help='local HTML file to grab from', required=False) parser.add_argument('-d', '--date', help='current date', required=False) parser.add_argument('-t', '--time', help='current time', required=False) args = parser.parse_args() return args def main(): outServerStatus="server_status_%s.dat" outAppStatus="%s_status_%s.dat" appDesiredColumns=['Unsent','In progress','Users in last 24 hours'] TABLES={} # get arguments args = parse_arguments() if args.url: # retrieve URL and parse HTML try: resp = urlopen(args.url) except URLError as e: print 'An error occured fetching %s \n %s' % (args.url, e.reason) return 10 try: soup = BeautifulSoup(resp.read(),'lxml') except: print 'Error while using BeautifulSoup' return 10 elif args.filN: # parse file with HTML try: iFile = open( args.filN, 'r' ) except: print 'No readable file %s' % (filN) return 10 try: soup = BeautifulSoup(open('server_status.php'), 'lxml') except: print 'Error while using BeautifulSoup' return 10 else: print ' please specify either a URL or a local file to parse' return 3 # output file names will embed timestamp if args.date: currDate=args.date else: currDate=time.strftime('%Y-%m-%d') if args.time: currTime=args.time else: currTime=time.strftime('%H-%M-%S') # get the main table try: entries=soup.find_all(findEntries) except AttributeError as e: raise ValueError("No valid entries found") return 1 if(lDebug): print '--> acquired',len(entries),'entries, searching for:',findEntries # extract tables of Work, Users, Computers TABLES = TABLE_ComputingStatus.fromHTML( entries[1:], TABLES ) # extract table of tasks by apps TABLES = TABLE_TasksByApplication.fromHTML( entries[1:], TABLES ) if ( lPrintTables ): for table in TABLES.values(): table.printAll() # strem in output files: # - serverStatus # NB: format depends directly on tables and their order of parsing: # $1, $2: date (YYYY-MM-DD), time (HH-MM-SS); # - Work table: # $3: ready to send (plotted); # $4: in progress (plotted); # $5: workunits waiting for validation (plotted); # $6: workunits waiting for assimilation (plotted); # $7: workunits waiting for file deletion; # $8: tasks waiting for file deletion; # $9: transitioner backlog; # - Users table: # $10: credit (plotted - no longer $11); # $11: recent credit (plotted - no longer $10); # $12: registered in past 24h; # - Computers table: # $13: credit (plotted - no longer $14); # $14: recent credit (plotted - no longer $13); # $15: registered in past 24h; # $16: current gigaflops (plotted); oFile=open(outServerStatus%(currDate),'a') oFile.write( '%s %s ' % ( currDate, currTime ) ) for tmpTag in wantedH4tags: oFile.write( '%s ' % ( ' '.join(cleanIntegers(TABLES[tmpTag].retColumn('#') ) ) ) ) oFile.write('\n') oFile.close() # - apps status: # NB: format depends on appDesiredColumns for wantedApp in wantedApps: oFile=open(outAppStatus%(wantedApp,currDate),'a') oFile.write( '%s %s %s \n' % ( currDate, currTime, ' '.join(cleanIntegers(TABLES[wantedH3tags[0]].retRowName( columnName='Application', matchName=wantedApp, columnNames=appDesiredColumns ) ) ) ) ) oFile.close() return 0 if __name__ == '__main__': status = main() sys.exit(status)
lgpl-2.1
dagwieers/ansible
lib/ansible/plugins/action/edgeos_config.py
42
1305
# # Copyright 2018 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action.network import ActionModule as ActionNetworkModule class ActionModule(ActionNetworkModule): def run(self, tmp=None, task_vars=None): del tmp # tmp no longer has any effect self._config_module = True if self._play_context.connection != 'network_cli': return {'failed': True, 'msg': 'Connection type %s is not valid for this module. Must use network_cli.' % self._play_context.connection} return super(ActionModule, self).run(task_vars=task_vars)
gpl-3.0
dkm/RIOT
dist/tools/pyterm/testbeds/testbeds.py
100
7138
#!/usr/bin/python2 # -*- coding: utf-8 -*- # Copyright (C) 2014 Philipp Rosenkranz <philipp.rosenkranz@fu-berlin.de> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA import os, re, datetime from subprocess import call, Popen, PIPE class Testbed(): log_dir_name = 'log' def __init__(self): pass def initCleanWithFlash(self): self.stop() self.cleanLogs() self.flashNodes() self.start() def initClean(self): self.cleanLogs() self.start() def flashNodes(self): raise NotImplementedError("Inherit from Testbed and implement flashNodes") def cleanLogs(self): raise NotImplementedError("Inherit from Testbed and implement flashNodes") def archiveLogs(self, experiment = None): raise NotImplementedError("Inherit from Testbed and implement flashNodes") def start(self): raise NotImplementedError("Inherit from Testbed and implement flashNodes") def stop(self): raise NotImplementedError("Inherit from Testbed and implement flashNodes") def defaultArchivePostfix(self, experimentName = None): if not experimentName: experimentName = "unknown" time = datetime.datetime.now().strftime("%Y-%m-%d_%H_%M_%S") postfix = "-" + experimentName +"_" + time return postfix def printAndCall(self, cmdString): print(cmdString) call(cmdString, shell=True) class DESTestbed(Testbed): def __init__(self, serverHost = None, serverPort=None, userName = None, flasher = None, hexfilePath = None, pyterm = None, logFilePath = None, hostFile = None): self.serverHost = serverHost self.serverPort = str(serverPort) self.userName = userName self.flasher = flasher self.hexFilePath = hexfilePath self.pyterm = pyterm self.logFilePath = logFilePath self.hostFile = hostFile def flashNodes(self): self.printAndCall("parallel-ssh -h %s -l %s 'python %s'" % (self.hostFile, self.userName, self.flasher)) def cleanLogs(self): self.printAndCall("rm -rf %s/*.log" % (self.logFilePath)) def archiveLogs(self, postfix = None): postfix = self.defaultArchivePostfix(postfix) logDir = self.logFilePath.split("/")[-1] self.printAndCall("cd %s/..; tar -cjf archived_logs%s.tar.bz2 %s/*.log" % (self.logFilePath, postfix, logDir)) def start(self): self.printAndCall("parallel-ssh -h %s -l %s 'screen -S pyterm -d -m python %s -ln %s'" % (self.hostFile, self.userName, self.pyterm, self.log_dir_name)) def stop(self): self.printAndCall("parallel-ssh -h %s -l %s 'screen -X -S pyterm quit'" % (self.hostFile, self.userName)) class LocalTestbed(Testbed): def __init__(self, serverHost = None, serverPort=None, flasher = None, hexfilePath = None, pyterm = None, logFilePath = None): self.serverHost = serverHost self.serverPort = str(serverPort) self.flasher = flasher self.hexFilePath = hexfilePath self.pyterm = pyterm self.logFilePath = logFilePath def findPorts(self): devlist = os.listdir("/dev/") regex = re.compile('^ttyUSB') return sorted([port for port in devlist if regex.match(port)]) def flashNodes(self): self.printAndCall("python %s %s" % (self.flasher, self.hexFilePath)) def cleanLogs(self): self.printAndCall("rm -rf %s/*.log" % (self.logFilePath)) def archiveLogs(self, postfix = None): postfix = self.defaultArchivePostfix(postfix) logDir = self.logFilePath.split("/")[-1] self.printAndCall("cd %s/..; tar -cjf archived_logs%s.tar.bz2 %s/*.log" % (self.logFilePath, postfix, logDir)) def start(self): portList = self.findPorts() for port in portList: self.printAndCall("screen -S pyterm-%s -d -m python %s -H %s -rn %s -p /dev/%s -ln %s" % (port, self.pyterm, port, port, port, self.log_dir_name)) def stop(self): portList = self.findPorts() for port in portList: self.printAndCall("screen -X -S pyterm-%s quit" % (port)) class DesVirtTestbed(Testbed): def __init__(self, serverHost = None, serverPort=None, desvirtPath = None, topologyName = None, pyterm = None, logFilePath = None): self.serverHost = serverHost self.serverPort = str(serverPort) self.desvirtPath = desvirtPath self.topologyName = topologyName self.pyterm = pyterm self.logFilePath = logFilePath self.namePortList = [] def findPorts(self): return self.namePortList def startDesVirtNetwork(self): print "executing: " + "./vnet --start --name " + self.topologyName + " in: " + self.desvirtPath call("sh -c \"./vnet --define --name " + self.topologyName + "\"", cwd=self.desvirtPath, shell=True) stream = Popen("sh -c \"./vnet --start --name " + self.topologyName + "\"", cwd=self.desvirtPath, shell=True, stderr=PIPE).stderr pats = r'.*riotnative.*\.elf (\S+) -t (\S+)' pattern = re.compile(pats) for line in stream: match = pattern.match(line) if(match): tuple = match.groups() self.namePortList.append((tuple[0], int(tuple[1]))) self.namePortList = sorted(self.namePortList) for tuple in self.namePortList: print "name: " + tuple[0] + " port: " + str(tuple[1]) def stopDesVirtNetwork(self): call("sh -c \"./vnet --stop --name " + self.topologyName + "\"", cwd=self.desvirtPath, shell=True) def flashNodes(self): pass def cleanLogs(self): self.printAndCall("rm -rf %s/*.log" % (self.logFilePath)) def archiveLogs(self, postfix = None): postfix = self.defaultArchivePostfix(postfix) logDir = self.logFilePath.split("/")[-1] self.printAndCall("cd %s/..; tar -cjf archived_logs%s.tar.bz2 %s/*.log" % (self.logFilePath, postfix, logDir)) def start(self): for node in self.namePortList: self.printAndCall("screen -S pyterm-%s -d -m python %s -H %s -rn %s -ts %s -ln %s" % (node[0], self.pyterm, node[0], node[0], node[1], self.log_dir_name)) def stop(self): print "stop called" for node in self.namePortList: self.printAndCall("screen -X -S pyterm-%s quit" % (node[0])) self.stopDesVirtNetwork()
lgpl-2.1
albfan/terminator
terminatorlib/keybindings.py
3
4960
#!/usr/bin/env python2 # Terminator - multiple gnome terminals in one window # Copyright (C) 2006-2010 cmsj@tenshu.net # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 only. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """Terminator by Chris Jones <cmsj@tenshu.net> Validator and functions for dealing with Terminator's customisable keyboard shortcuts. """ import re from gi.repository import Gtk, Gdk from util import err class KeymapError(Exception): """Custom exception for errors in keybinding configurations""" MODIFIER = re.compile('<([^<]+)>') class Keybindings: """Class to handle loading and lookup of Terminator keybindings""" modifiers = { 'ctrl': Gdk.ModifierType.CONTROL_MASK, 'control': Gdk.ModifierType.CONTROL_MASK, 'primary': Gdk.ModifierType.CONTROL_MASK, 'shift': Gdk.ModifierType.SHIFT_MASK, 'alt': Gdk.ModifierType.MOD1_MASK, 'super': Gdk.ModifierType.SUPER_MASK, 'hyper': Gdk.ModifierType.HYPER_MASK, } empty = {} keys = None _masks = None _lookup = None def __init__(self): self.keymap = Gdk.Keymap.get_default() self.configure({}) def configure(self, bindings): """Accept new bindings and reconfigure with them""" self.keys = bindings self.reload() def reload(self): """Parse bindings and mangle into an appropriate form""" self._lookup = {} self._masks = 0 for action, bindings in self.keys.items(): if not isinstance(bindings, tuple): bindings = (bindings,) for binding in bindings: if not binding or binding == "None": continue try: keyval, mask = self._parsebinding(binding) # Does much the same, but with poorer error handling. #keyval, mask = Gtk.accelerator_parse(binding) except KeymapError as e: err ("keybindings.reload failed to parse binding '%s': %s" % (binding, e)) else: if mask & Gdk.ModifierType.SHIFT_MASK: if keyval == Gdk.KEY_Tab: keyval = Gdk.KEY_ISO_Left_Tab mask &= ~Gdk.ModifierType.SHIFT_MASK else: keyvals = Gdk.keyval_convert_case(keyval) if keyvals[0] != keyvals[1]: keyval = keyvals[1] mask &= ~Gdk.ModifierType.SHIFT_MASK else: keyval = Gdk.keyval_to_lower(keyval) self._lookup.setdefault(mask, {}) self._lookup[mask][keyval] = action self._masks |= mask def _parsebinding(self, binding): """Parse an individual binding using gtk's binding function""" mask = 0 modifiers = re.findall(MODIFIER, binding) if modifiers: for modifier in modifiers: mask |= self._lookup_modifier(modifier) key = re.sub(MODIFIER, '', binding) if key == '': raise KeymapError('No key found') keyval = Gdk.keyval_from_name(key) if keyval == 0: raise KeymapError("Key '%s' is unrecognised" % key) return (keyval, mask) def _lookup_modifier(self, modifier): """Map modifier names to gtk values""" try: return self.modifiers[modifier.lower()] except KeyError: raise KeymapError("Unhandled modifier '<%s>'" % modifier) def lookup(self, event): """Translate a keyboard event into a mapped key""" try: _found, keyval, _egp, _lvl, consumed = self.keymap.translate_keyboard_state( event.hardware_keycode, Gdk.ModifierType(event.get_state() & ~Gdk.ModifierType.LOCK_MASK), event.group) except TypeError: err ("keybindings.lookup failed to translate keyboard event: %s" % dir(event)) return None mask = (event.get_state() & ~consumed) & self._masks return self._lookup.get(mask, self.empty).get(keyval, None)
gpl-2.0
robbiet480/home-assistant
homeassistant/components/ambiclimate/__init__.py
7
1057
"""Support for Ambiclimate devices.""" import logging import voluptuous as vol from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET from homeassistant.helpers import config_validation as cv from . import config_flow from .const import DOMAIN _LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_CLIENT_ID): cv.string, vol.Required(CONF_CLIENT_SECRET): cv.string, } ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up Ambiclimate components.""" if DOMAIN not in config: return True conf = config[DOMAIN] config_flow.register_flow_implementation( hass, conf[CONF_CLIENT_ID], conf[CONF_CLIENT_SECRET] ) return True async def async_setup_entry(hass, entry): """Set up Ambiclimate from a config entry.""" hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "climate") ) return True
apache-2.0
appsembler/edx-platform
lms/djangoapps/grades/tests/integration/test_events.py
1
9599
""" Test grading events across apps. """ # pylint: disable=protected-access from mock import call as mock_call, patch from unittest import skip from capa.tests.response_xml_factory import MultipleChoiceResponseXMLFactory from courseware.tests.test_submitting_problems import ProblemSubmissionTestMixin from lms.djangoapps.instructor.enrollment import reset_student_attempts from lms.djangoapps.instructor_task.api import submit_rescore_problem_for_student from openedx.core.djangolib.testing.utils import get_mock_request from student.models import CourseEnrollment from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory from ... import events class GradesEventIntegrationTest(ProblemSubmissionTestMixin, SharedModuleStoreTestCase): """ Tests integration between the eventing in various layers of the grading infrastructure. """ shard = 4 ENABLED_SIGNALS = ['course_published'] @classmethod def reset_course(cls): """ Sets up the course anew. """ with cls.store.default_store(ModuleStoreEnum.Type.split): cls.course = CourseFactory.create() cls.chapter = ItemFactory.create( parent=cls.course, category="chapter", display_name="Test Chapter" ) cls.sequence = ItemFactory.create( parent=cls.chapter, category='sequential', display_name="Test Sequential 1", graded=True, format="Homework" ) cls.vertical = ItemFactory.create( parent=cls.sequence, category='vertical', display_name='Test Vertical 1' ) problem_xml = MultipleChoiceResponseXMLFactory().build_xml( question_text='The correct answer is Choice 2', choices=[False, False, True, False], choice_names=['choice_0', 'choice_1', 'choice_2', 'choice_3'] ) cls.problem = ItemFactory.create( parent=cls.vertical, category="problem", display_name="p1", data=problem_xml, metadata={'weight': 2} ) def setUp(self): self.reset_course() super(GradesEventIntegrationTest, self).setUp() self.request = get_mock_request(UserFactory()) self.student = self.request.user self.client.login(username=self.student.username, password="test") CourseEnrollment.enroll(self.student, self.course.id) self.instructor = UserFactory.create(is_staff=True, username=u'test_instructor', password=u'test') self.refresh_course() @skip("Occasionally fails and adding the flaky decorator doesn't help") @patch('lms.djangoapps.grades.events.tracker') def test_submit_answer(self, events_tracker): self.submit_question_answer('p1', {'2_1': 'choice_choice_2'}) course = self.store.get_course(self.course.id, depth=0) event_transaction_id = events_tracker.emit.mock_calls[0][1][1]['event_transaction_id'] events_tracker.emit.assert_has_calls( [ mock_call( events.PROBLEM_SUBMITTED_EVENT_TYPE, { 'user_id': unicode(self.student.id), 'event_transaction_id': event_transaction_id, 'event_transaction_type': events.PROBLEM_SUBMITTED_EVENT_TYPE, 'course_id': unicode(self.course.id), 'problem_id': unicode(self.problem.location), 'weighted_earned': 2.0, 'weighted_possible': 2.0, }, ), mock_call( events.COURSE_GRADE_CALCULATED, { 'course_version': unicode(course.course_version), 'percent_grade': 0.02, 'grading_policy_hash': u'ChVp0lHGQGCevD0t4njna/C44zQ=', 'user_id': unicode(self.student.id), 'letter_grade': u'', 'event_transaction_id': event_transaction_id, 'event_transaction_type': events.PROBLEM_SUBMITTED_EVENT_TYPE, 'course_id': unicode(self.course.id), 'course_edited_timestamp': unicode(course.subtree_edited_on), } ), ], any_order=True, ) def test_delete_student_state(self): self.submit_question_answer('p1', {'2_1': 'choice_choice_2'}) with patch('lms.djangoapps.instructor.enrollment.tracker') as enrollment_tracker: with patch('lms.djangoapps.grades.events.tracker') as events_tracker: reset_student_attempts( self.course.id, self.student, self.problem.location, self.instructor, delete_module=True, ) course = self.store.get_course(self.course.id, depth=0) event_transaction_id = enrollment_tracker.method_calls[0][1][1]['event_transaction_id'] enrollment_tracker.emit.assert_called_with( events.STATE_DELETED_EVENT_TYPE, { 'user_id': unicode(self.student.id), 'course_id': unicode(self.course.id), 'problem_id': unicode(self.problem.location), 'instructor_id': unicode(self.instructor.id), 'event_transaction_id': event_transaction_id, 'event_transaction_type': events.STATE_DELETED_EVENT_TYPE, } ) events_tracker.emit.assert_called_with( events.COURSE_GRADE_CALCULATED, { 'percent_grade': 0.0, 'grading_policy_hash': u'ChVp0lHGQGCevD0t4njna/C44zQ=', 'user_id': unicode(self.student.id), 'letter_grade': u'', 'event_transaction_id': event_transaction_id, 'event_transaction_type': events.STATE_DELETED_EVENT_TYPE, 'course_id': unicode(self.course.id), 'course_edited_timestamp': unicode(course.subtree_edited_on), 'course_version': unicode(course.course_version), } ) def test_rescoring_events(self): self.submit_question_answer('p1', {'2_1': 'choice_choice_3'}) new_problem_xml = MultipleChoiceResponseXMLFactory().build_xml( question_text='The correct answer is Choice 3', choices=[False, False, False, True], choice_names=['choice_0', 'choice_1', 'choice_2', 'choice_3'] ) with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, self.course.id): self.problem.data = new_problem_xml self.store.update_item(self.problem, self.instructor.id) self.store.publish(self.problem.location, self.instructor.id) with patch('lms.djangoapps.grades.events.tracker') as events_tracker: submit_rescore_problem_for_student( request=get_mock_request(self.instructor), usage_key=self.problem.location, student=self.student, only_if_higher=False ) course = self.store.get_course(self.course.id, depth=0) # make sure the tracker's context is updated with course info for args in events_tracker.get_tracker().context.call_args_list: self.assertEqual( args[0][1], {'course_id': unicode(self.course.id), 'org_id': unicode(self.course.org)} ) event_transaction_id = events_tracker.emit.mock_calls[0][1][1]['event_transaction_id'] events_tracker.emit.assert_has_calls( [ mock_call( events.GRADES_RESCORE_EVENT_TYPE, { 'course_id': unicode(self.course.id), 'user_id': unicode(self.student.id), 'problem_id': unicode(self.problem.location), 'new_weighted_earned': 2, 'new_weighted_possible': 2, 'only_if_higher': False, 'instructor_id': unicode(self.instructor.id), 'event_transaction_id': event_transaction_id, 'event_transaction_type': events.GRADES_RESCORE_EVENT_TYPE, }, ), mock_call( events.COURSE_GRADE_CALCULATED, { 'course_version': unicode(course.course_version), 'percent_grade': 0.02, 'grading_policy_hash': u'ChVp0lHGQGCevD0t4njna/C44zQ=', 'user_id': unicode(self.student.id), 'letter_grade': u'', 'event_transaction_id': event_transaction_id, 'event_transaction_type': events.GRADES_RESCORE_EVENT_TYPE, 'course_id': unicode(self.course.id), 'course_edited_timestamp': unicode(course.subtree_edited_on), }, ), ], any_order=True, )
agpl-3.0
xtao/code
tests/test_user_fav.py
3
1359
# -*- coding: utf-8 -*- from tests.base import TestCase from vilya.models.user_fav import UserFavItem from vilya.models.consts import K_PULL, K_ISSUE class TestUser(TestCase): def test_add_fav(self): user_id = "testuser" pull_id = 1 kind = K_PULL UserFavItem.add(user_id, pull_id, kind) favs = UserFavItem.gets_by_user_kind(user_id) assert len(favs) == 1 fav = favs[0] assert fav.target_id == pull_id target_ids = UserFavItem.get_target_ids_by_user_kind(user_id, K_PULL) assert len(target_ids) == 1 assert target_ids[0] == str(pull_id) assert UserFavItem.is_liked_by_user(user_id, K_PULL, pull_id), True def test_delete_fav(self): user_id = "testuser" pull_id = 1 kind = K_PULL UserFavItem.add(user_id, pull_id, kind) issue_id = 3 kind = K_ISSUE UserFavItem.add(user_id, issue_id, kind) favs = UserFavItem.gets_by_user_kind(user_id) assert len(favs) == 2 UserFavItem.delete_by_user_target_kind(user_id, pull_id, K_PULL) favs = UserFavItem.gets_by_user_kind(user_id) assert len(favs) == 1 UserFavItem.delete_by_user_target_kind(user_id, issue_id, K_ISSUE) favs = UserFavItem.gets_by_user_kind(user_id) assert len(favs) == 0
bsd-3-clause
axinging/chromium-crosswalk
third_party/logilab/logilab/astroid/builder.py
66
9425
# copyright 2003-2014 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of astroid. # # astroid is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # astroid is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with astroid. If not, see <http://www.gnu.org/licenses/>. """The AstroidBuilder makes astroid from living object and / or from _ast The builder is not thread safe and can't be used to parse different sources at the same time. """ from __future__ import with_statement __docformat__ = "restructuredtext en" import sys from os.path import splitext, basename, exists, abspath from astroid.exceptions import AstroidBuildingException, InferenceError from astroid.raw_building import InspectBuilder from astroid.rebuilder import TreeRebuilder from astroid.manager import AstroidManager from astroid.bases import YES, Instance from astroid.modutils import modpath_from_file from _ast import PyCF_ONLY_AST def parse(string): return compile(string, "<string>", 'exec', PyCF_ONLY_AST) if sys.version_info >= (3, 0): from tokenize import detect_encoding def open_source_file(filename): with open(filename, 'rb') as byte_stream: encoding = detect_encoding(byte_stream.readline)[0] stream = open(filename, 'r', newline=None, encoding=encoding) try: data = stream.read() except UnicodeError: # wrong encodingg # detect_encoding returns utf-8 if no encoding specified msg = 'Wrong (%s) or no encoding specified' % encoding raise AstroidBuildingException(msg) return stream, encoding, data else: import re _ENCODING_RGX = re.compile(r"\s*#+.*coding[:=]\s*([-\w.]+)") def _guess_encoding(string): """get encoding from a python file as string or return None if not found """ # check for UTF-8 byte-order mark if string.startswith('\xef\xbb\xbf'): return 'UTF-8' for line in string.split('\n', 2)[:2]: # check for encoding declaration match = _ENCODING_RGX.match(line) if match is not None: return match.group(1) def open_source_file(filename): """get data for parsing a file""" stream = open(filename, 'U') data = stream.read() encoding = _guess_encoding(data) return stream, encoding, data # ast NG builder ############################################################## MANAGER = AstroidManager() class AstroidBuilder(InspectBuilder): """provide astroid building methods""" def __init__(self, manager=None): InspectBuilder.__init__(self) self._manager = manager or MANAGER def module_build(self, module, modname=None): """build an astroid from a living module instance """ node = None path = getattr(module, '__file__', None) if path is not None: path_, ext = splitext(module.__file__) if ext in ('.py', '.pyc', '.pyo') and exists(path_ + '.py'): node = self.file_build(path_ + '.py', modname) if node is None: # this is a built-in module # get a partial representation by introspection node = self.inspect_build(module, modname=modname, path=path) # we have to handle transformation by ourselves since the rebuilder # isn't called for builtin nodes # # XXX it's then only called for Module nodes, not for underlying # nodes node = self._manager.transform(node) return node def file_build(self, path, modname=None): """build astroid from a source code file (i.e. from an ast) path is expected to be a python source file """ try: stream, encoding, data = open_source_file(path) except IOError as exc: msg = 'Unable to load file %r (%s)' % (path, exc) raise AstroidBuildingException(msg) except SyntaxError as exc: # py3k encoding specification error raise AstroidBuildingException(exc) except LookupError as exc: # unknown encoding raise AstroidBuildingException(exc) with stream: # get module name if necessary if modname is None: try: modname = '.'.join(modpath_from_file(path)) except ImportError: modname = splitext(basename(path))[0] # build astroid representation module = self._data_build(data, modname, path) return self._post_build(module, encoding) def string_build(self, data, modname='', path=None): """build astroid from source code string and return rebuilded astroid""" module = self._data_build(data, modname, path) module.file_bytes = data.encode('utf-8') return self._post_build(module, 'utf-8') def _post_build(self, module, encoding): """handles encoding and delayed nodes after a module has been built """ module.file_encoding = encoding self._manager.cache_module(module) # post tree building steps after we stored the module in the cache: for from_node in module._from_nodes: if from_node.modname == '__future__': for symbol, _ in from_node.names: module.future_imports.add(symbol) self.add_from_names_to_locals(from_node) # handle delayed assattr nodes for delayed in module._delayed_assattr: self.delayed_assattr(delayed) return module def _data_build(self, data, modname, path): """build tree node from data and add some informations""" # this method could be wrapped with a pickle/cache function try: node = parse(data + '\n') except TypeError as exc: raise AstroidBuildingException(exc) if path is not None: node_file = abspath(path) else: node_file = '<?>' if modname.endswith('.__init__'): modname = modname[:-9] package = True else: package = path and path.find('__init__.py') > -1 or False rebuilder = TreeRebuilder(self._manager) module = rebuilder.visit_module(node, modname, node_file, package) module._from_nodes = rebuilder._from_nodes module._delayed_assattr = rebuilder._delayed_assattr return module def add_from_names_to_locals(self, node): """store imported names to the locals; resort the locals if coming from a delayed node """ _key_func = lambda node: node.fromlineno def sort_locals(my_list): my_list.sort(key=_key_func) for (name, asname) in node.names: if name == '*': try: imported = node.do_import_module() except InferenceError: continue for name in imported.wildcard_import_names(): node.parent.set_local(name, node) sort_locals(node.parent.scope().locals[name]) else: node.parent.set_local(asname or name, node) sort_locals(node.parent.scope().locals[asname or name]) def delayed_assattr(self, node): """visit a AssAttr node -> add name to locals, handle members definition """ try: frame = node.frame() for infered in node.expr.infer(): if infered is YES: continue try: if infered.__class__ is Instance: infered = infered._proxied iattrs = infered.instance_attrs elif isinstance(infered, Instance): # Const, Tuple, ... we may be wrong, may be not, but # anyway we don't want to pollute builtin's namespace continue elif infered.is_function: iattrs = infered.instance_attrs else: iattrs = infered.locals except AttributeError: # XXX log error #import traceback #traceback.print_exc() continue values = iattrs.setdefault(node.attrname, []) if node in values: continue # get assign in __init__ first XXX useful ? if frame.name == '__init__' and values and not \ values[0].frame().name == '__init__': values.insert(0, node) else: values.append(node) except InferenceError: pass
bsd-3-clause
BBN-Q/PySimulator
tests/SimSpeedTest.py
1
5046
# -*- coding: utf-8 -*- """ Created on Wed Dec 5 21:44:22 2012 @author: cryan """ import numpy as np from numpy import sin, cos from scipy.constants import pi from scipy.linalg import expm, eigh from PySim.SystemParams import SystemParams from PySim.PulseSequence import PulseSequence from PySim.Simulation import simulate_sequence_stack, simulate_sequence from PySim.QuantumSystems import SCQubit, Hamiltonian, Dissipator from numba import * #import matplotlib.pyplot as plt #from timeit import timeit #Try to load the CPPBackEnd try: import PySim.CySim CPPBackEnd = True except ImportError: CPPBackEnd = False #@jit(c16[:,:](c16[:,:], c16)) def expm_eigen(matIn, mult): ''' Helper function to compute matrix exponential of Hermitian matrix ''' dim = matIn.shape[0] D, V = eigh(matIn) return V.dot(np.diag(np.exp(mult*D))).dot(V.conj().T) @autojit() def mult_a_X(alpha, X): outArray = np.zeros_like(X) for rowct in range(X.shape[0]): for colct in range(X.shape[1]): outArray[rowct,colct] = alpha*X[rowct, colct] return outArray @jit(c16[:,:](c16[:,:], c16[:,:,:], f8[:,:], f8[:])) #@autojit def evolution_numba(Hnat, controlHams, controlFields, controlFreqs): timeStep = 0.01 curTime = 0.0 Uprop = np.eye(Hnat.shape[0]) for timect in range(controlFields.shape[1]): tmpH = np.copy(Hnat) for controlct in range(controlFields.shape[0]): tmpMult = controlFields[controlct, timect]*cos(2*pi*curTime*controlFreqs[controlct]) for rowct in range(tmpH.shape[0]): for colct in range(tmpH.shape[1]): tmpH[rowct,colct] += tmpMult*controlHams[controlct, rowct, colct] Uprop = np.dot(expm_eigen(tmpH,-1j*2*pi*timeStep)[0],Uprop) curTime += timeStep return Uprop def evolution_numpy(Hnat, controlHams, controlFields, controlFreqs): timeStep = 0.01 curTime = 0.0 Uprop = np.eye(Hnat.shape[0]) for timect in range(controlFields.shape[1]): tmpH = np.copy(Hnat) for controlct in range(controlFields.shape[0]): tmpH += controlFields[controlct, timect]*cos(2*pi*curTime*controlFreqs[controlct])*controlHams[controlct] Uprop = np.dot(expm_eigen(tmpH,-1j*2*pi*timeStep)[0],Uprop) curTime += timeStep return Uprop def sim_setup(dimension, numTimeSteps, numControls): #Create a random natural hamiltonian tmpMat = np.random.randn(dimension, dimension) + 1j*np.random.randn(dimension, dimension) Hnat = tmpMat+tmpMat.conj().T #Create random control Hamiltonians controlHams = np.zeros((numControls,dimension, dimension), dtype=np.complex128) for ct in range(numControls): tmpMat = np.random.randn(dimension, dimension) + 1j*np.random.randn(dimension, dimension) controlHams[ct] = tmpMat+tmpMat.conj().T #Create random controlfields controlFields = np.random.randn(numControls, numTimeSteps) #Control frequencies controlFreqs = np.random.randn(numControls) return Hnat, controlHams, controlFields, controlFreqs def sim_setup_cython(Hnat, controlHams, controlFields, controlFreqs): systemParams = SystemParams() systemParams.Hnat = Hamiltonian(Hnat) pulseSeq = PulseSequence() pulseSeq.controlAmps = controlFields for ct in range(len(controlHams)): systemParams.add_control_ham(inphase=Hamiltonian(controlHams[ct])) pulseSeq.add_control_line(freq = controlFreqs[ct], phase=0, controlType='sinusoidal') for ct in range(np.int(np.log2(Hnat.shape[0]))): systemParams.add_sub_system(SCQubit(2,0e9, name='Q1', T1=1e-6)) pulseSeq.timeSteps = 0.01*np.ones(controlFields.shape[1]) pulseSeq.maxTimeStep = 1e6 return systemParams, pulseSeq if __name__ == '__main__': dims = 2**np.arange(1,6) dim = 16 Hnat, controlHams, controlFields, controlFreqs = sim_setup(dim, 1000, 4) print(evolution_numba(Hnat, controlHams, controlFields, controlFreqs)) # systemParams, pulseSeq = sim_setup_cython(Hnat, controlHams, controlFields, controlFreqs) # cythonTimes = [] # numpyTimes = [] # for dim in dims: # print(dim) # Hnat, controlHams, controlFields, controlFreqs = sim_setup(dim, 2000, 4) # systemParams, pulseSeq = sim_setup_cython(Hnat, controlHams, controlFields, controlFreqs) # numpyTimes.append(timeit('evolution_numpy(Hnat, controlHams, controlFields, controlFreqs)', # setup='from __main__ import evolution_numpy, Hnat, controlHams, controlFields, controlFreqs', number=3)/3) # cythonTimes.append(timeit('simulate_sequence(pulseSeq, systemParams)', setup='from __main__ import simulate_sequence, pulseSeq, systemParams', number=3)/3) # # plt.plot(dims, numpyTimes) # plt.plot(dims, cythonTimes) # plt.legend(('Numpy', 'Cython')) # plt.xlabel('System Dimension') # plt.show()
apache-2.0
jvanasco/beaker
beaker/ext/sqla.py
7
4721
from beaker._compat import pickle import logging import pickle from datetime import datetime from beaker.container import OpenResourceNamespaceManager, Container from beaker.exceptions import InvalidCacheBackendError, MissingCacheParameter from beaker.synchronization import file_synchronizer, null_synchronizer from beaker.util import verify_directory, SyncDict log = logging.getLogger(__name__) sa = None class SqlaNamespaceManager(OpenResourceNamespaceManager): binds = SyncDict() tables = SyncDict() @classmethod def _init_dependencies(cls): global sa if sa is not None: return try: import sqlalchemy as sa except ImportError: raise InvalidCacheBackendError("SQLAlchemy, which is required by " "this backend, is not installed") def __init__(self, namespace, bind, table, data_dir=None, lock_dir=None, **kwargs): """Create a namespace manager for use with a database table via SQLAlchemy. ``bind`` SQLAlchemy ``Engine`` or ``Connection`` object ``table`` SQLAlchemy ``Table`` object in which to store namespace data. This should usually be something created by ``make_cache_table``. """ OpenResourceNamespaceManager.__init__(self, namespace) if lock_dir: self.lock_dir = lock_dir elif data_dir: self.lock_dir = data_dir + "/container_db_lock" if self.lock_dir: verify_directory(self.lock_dir) self.bind = self.__class__.binds.get(str(bind.url), lambda: bind) self.table = self.__class__.tables.get('%s:%s' % (bind.url, table.name), lambda: table) self.hash = {} self._is_new = False self.loaded = False def get_access_lock(self): return null_synchronizer() def get_creation_lock(self, key): return file_synchronizer( identifier="databasecontainer/funclock/%s" % self.namespace, lock_dir=self.lock_dir) def do_open(self, flags, replace): if self.loaded: self.flags = flags return select = sa.select([self.table.c.data], (self.table.c.namespace == self.namespace)) result = self.bind.execute(select).fetchone() if not result: self._is_new = True self.hash = {} else: self._is_new = False try: self.hash = result['data'] except (IOError, OSError, EOFError, pickle.PickleError, pickle.PickleError): log.debug("Couln't load pickle data, creating new storage") self.hash = {} self._is_new = True self.flags = flags self.loaded = True def do_close(self): if self.flags is not None and (self.flags == 'c' or self.flags == 'w'): if self._is_new: insert = self.table.insert() self.bind.execute(insert, namespace=self.namespace, data=self.hash, accessed=datetime.now(), created=datetime.now()) self._is_new = False else: update = self.table.update(self.table.c.namespace == self.namespace) self.bind.execute(update, data=self.hash, accessed=datetime.now()) self.flags = None def do_remove(self): delete = self.table.delete(self.table.c.namespace == self.namespace) self.bind.execute(delete) self.hash = {} self._is_new = True def __getitem__(self, key): return self.hash[key] def __contains__(self, key): return key in self.hash def __setitem__(self, key, value): self.hash[key] = value def __delitem__(self, key): del self.hash[key] def keys(self): return self.hash.keys() class SqlaContainer(Container): namespace_manager = SqlaNamespaceManager def make_cache_table(metadata, table_name='beaker_cache', schema_name=None): """Return a ``Table`` object suitable for storing cached values for the namespace manager. Do not create the table.""" return sa.Table(table_name, metadata, sa.Column('namespace', sa.String(255), primary_key=True), sa.Column('accessed', sa.DateTime, nullable=False), sa.Column('created', sa.DateTime, nullable=False), sa.Column('data', sa.PickleType, nullable=False), schema=schema_name if schema_name else metadata.schema)
bsd-3-clause
fHachenberg/pyecstaticalib
Ecstatica/XmlLoad.py
1
29497
# coding: utf-8 #Created on 12.02.2012 #Copyright (C) 2013 Fabian Hachenberg #This file is part of EcstaticaLib. #EcstaticaLib is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. #More information about the license is provided in the LICENSE file. import re import struct import functools import xml.parsers.expat from . import Sound from . import Code from . import Camera from . import Event from . import SectorSection from .Event import createEventFromTextData, ev_NO_EVENT from .Code import createCodeFromText from .FantFile import FANTFile from . import MapArea from . import XmlSave from . import FANTSave class XmlLoadError(Exception): def __init__(self, str): Exception.__init__(self, str) class XmlHandler(object): def __init__(self, context): self.context = context def handleEnterElement(self, tag, atts): raise StandardError("not implemented") def handleLeaveElement(self, tag): raise StandardError("not implemented") def handleText(self, text): raise StandardError("not implemented") def CDataStart(self): pass def CDataStop(self): pass class GenericXmlSingularTagHandler(XmlHandler): ''' Used to parse an empty-tag value like <foo attrib="haha" /> ''' def __init__(self, context, tag, attrs, resultobj): XmlHandler.__init__(self, context) self.tag = tag self.attrs = attrs self.propname = tag self.resultobj = resultobj def handleEnterElement(self, tag, atts): raise StandardError("No subtags allowed within empty-tag value") def handleLeaveElement(self, tag): assert tag == self.tag self._createValue() self.context.popHandler(self) def handleText(self, text): raise StandardError("No data allowed within empty-tag value") class GenericXmlValueHandler(XmlHandler): ''' Used to parse a single value <bla> ewrfgaswfef </bla> Subtags are NOT allowed! Does NOT implement the evaluation of text data, which has to be implemented by derived classes! ''' def __init__(self, context, tag, attrs, resultobj, only_cdata=False): XmlHandler.__init__(self, context) self.tag = tag self.propname = tag self.resultobj = resultobj self.text = "" self.only_cdata = only_cdata #if set, only text within CDATA-section is collected self.incdata = False def handleEnterElement(self, tag, atts): raise StandardError("No subtags allowed in simple value definition") def handleLeaveElement(self, tag): assert tag == self.tag self._createValue() self.context.popHandler(self) def handleText(self, text): if self.only_cdata: if self.incdata: self.text += text else: self.text += text def CDataStart(self): self.incdata = True def CDataStop(self): self.incdata = False ''' The reason for these classes is: There are cases where we want to get just a simple string from xml. In those cases, we could just write the read string into the python object. But in other cases, we want to create a python list from a sequence a,b,c,d,e,... or something like that. ''' class _addInteger(GenericXmlValueHandler): def __init__(self, context, tag, attrs, resultobj): GenericXmlValueHandler.__init__(self, context, tag, attrs, resultobj) def _createValue(self): try: int(self.text) except: print("**********************************", self.tag) self.resultobj.__setattr__(self.propname, int(self.text)) class _addFloat(GenericXmlValueHandler): def __init__(self, context, tag, attrs, resultobj): GenericXmlValueHandler.__init__(self, context, tag, attrs, resultobj) def _createValue(self): self.resultobj.__setattr__(self.propname, float(self.text)) class _addString(GenericXmlValueHandler): def __init__(self, context, tag, attrs, resultobj): GenericXmlValueHandler.__init__(self, context, tag, attrs, resultobj) def _createValue(self): self.resultobj.__setattr__(self.propname, self.text.strip()) class _addCDATA(GenericXmlValueHandler): def __init__(self, context, tag, attrs, resultobj): GenericXmlValueHandler.__init__(self, context, tag, attrs, resultobj, True) def _createValue(self): self.resultobj.__setattr__(self.propname, self.text) class _addStringList(GenericXmlValueHandler): def __init__(self, context, tag, attrs, resultobj): GenericXmlValueHandler.__init__(self, context, tag, attrs, resultobj) def _createValue(self): self.resultobj.__setattr__(self.propname, self.text.split(",")) class _addDataFileRef(GenericXmlSingularTagHandler): def __init__(self, context, tag, attrs, resultobj): GenericXmlSingularTagHandler.__init__(self, context, tag, attrs, resultobj) def _createValue(self): f = open(self.attrs['Filename'], "rb") data = f.read() self.resultobj.__setattr__(self.propname, data) class _addIntegerList(GenericXmlValueHandler): ''' @param fixedsize: If given >0, an exception is thrown if the list size does not match! ''' def __init__(self, context, tag, attrs, resultobj, fixedsize=None): self.fixedsize = fixedsize GenericXmlValueHandler.__init__(self, context, tag, attrs, resultobj) def _createValue(self): intlist = [ int(a) for a in self.text.split(',') if a.strip() != ""] if self.fixedsize != None: if len(intlist) != self.fixedsize: raise XmlLoadError("invalid integer list size: " + str(len(intlist)) + " < " + str(self.fixedsize)) self.resultobj.__setattr__(self.propname, intlist) class _addVector3(XmlHandler): def __init__(self, context, tag, attrs, resultobj): XmlHandler.__init__(self, context) self.tag = tag self.propname = tag self.resultobj = resultobj self.text = "" def handleEnterElement(self, tag, atts): assert tag == "Vector3" or tag == self.tag def handleLeaveElement(self, tag): if tag == self.tag: self.context.popHandler(self) self.resultobj.__setattr__(self.propname, tuple( float(a) for a in self.text.split(','))) #TODO:read in Fixed-Point-Value def handleText(self, text): self.text += text class GenericXmlDataHandler(XmlHandler): ''' Used to parse a tag containing a finite number of special sub-tags, not a list or something like that <bla> <a> fsfesf </a> <b> sfsf </b> </bla> ''' def __init__(self, context, tag, attrs, property_mapping, allow_top_value=False): XmlHandler.__init__(self, context) self.tag = tag self.property_mapping = property_mapping def handleEnterElement(self, tag, atts): assert tag in self.property_mapping.keys() self.context.pushHandler(self.property_mapping[tag](self.context, tag, atts, self)) def handleLeaveElement(self, tag): assert tag == self.tag self.context.popHandler(self) def handleText(self, text): assert text.strip() == "" class GenericXmlClassHandler(XmlHandler): ''' Used to parse the XML representation of a specific object, like an Event or a Code Is used together with GenericXmlClassListHandler @param classtag: The tag for which this handler was entered. This is normally one specific tag but we provide means to communicate the explizit tag name @param attrs: The attributes of the opening tag which caused entering this handler ''' def __init__(self, context, classtag, attrs, property_mapping, object_list): XmlHandler.__init__(self, context) self.property_mapping = property_mapping self.classtag = classtag self.object_list = object_list def _createInstance(self): ''' Has to be overloaded by all derived types ''' raise StandardError("No creation routine implemented") def handleEnterElement(self, tag, atts): if not tag in self.property_mapping.keys(): print("unexptected tag", tag, "in handler", type(self)) assert tag in self.property_mapping.keys() self.context.pushHandler(self.property_mapping[tag](self.context, tag, atts, self)) def handleLeaveElement(self, tag): assert tag == self.classtag self.object_list.append(self._createInstance()) self.context.popHandler(self) def handleText(self, text): assert text.strip() == '' class GenericXmlClassListHandler(XmlHandler): ''' Used to parse lists of objects <blubs> <blub> ... </blub> <blub> ... </blub> <blub> ... </blub> <blub> ... </blub> <blub> ... </blub> <blub> ... </blub> </blubs> ''' def __init__(self, context, listtag, typeattribs, ListElementClass): XmlHandler.__init__(self, context) self.listtag = listtag self.typeattribs = typeattribs self.ListElementClass = ListElementClass self.classtag = self.ListElementClass.tagname self.object_list = [] def handleEnterElement(self, tag, atts): if tag != self.listtag and tag != self.classtag: print("Unerwartetes tag", tag, "for handler", type(self)) assert (tag == self.listtag or tag == self.classtag) if tag == self.classtag: handler = self.ListElementClass(self.context, self.classtag, atts, self.object_list) self.context.pushHandler(handler) def handleLeaveElement(self, tag): assert tag == self.listtag or tag == self.classtag if tag == self.listtag: self._setList() self.context.popHandler(self) def handleText(self, text): if text.strip() == '': return raise StandardError("No text expected in list tag. Found:" + text) class StackHandler(XmlHandler): def __init__(self, context): XmlHandler.__init__(self, context) def handleEnterElement(self, tag, attrs): assert tag == "FANT" or tag == "FANT_stack" if tag == "FANT": self.context.pushHandler(TopHandler(self.context)) def handleLeaveElement(self, tag): pass def handleText(self, text): if text.strip() == "": return raise StandardError("Unexpected text \"" + text + "\"" ) class TopHandler(XmlHandler): def __init__(self, context): XmlHandler.__init__(self, context) self.nametypes = ["Part", "Actor", "Action", "Scene", "Point", "Triangle", "Repertoire", "Code", "MapArea", "Sound"] self.eventlisttypes = ["Action", "Actor", "Scene", "Repertoire"] self.eventtypes = { 'Actor' : map(lambda evtidx: Event.event_names[evtidx], Event.ActorEvents), 'Action' : map(lambda evtidx: Event.event_names[evtidx], Event.ActionEvents), 'Scene' : map(lambda evtidx: Event.event_names[evtidx], Event.SceneEvents), 'Repertoire': map(lambda evtidx: Event.event_names[evtidx], Event.RepertoireEvents) } self.context.newFANTFile() def handleEnterElement(self, tag, attrs):# #print tag if tag == 'Header': self.context.pushHandler(HeaderHandler(self.context)) return elif tag == "Names": assert 'Type' in attrs.keys() #print attrs['Type'] assert attrs['Type'] in self.nametypes self.context.pushHandler(NameHandler(attrs['Type'], self.context)) return elif tag == "Events": assert 'Type' in attrs.keys() assert attrs['Type'] in self.eventlisttypes self.context.pushHandler(EventListHandler(self.context, attrs['Type'], self.eventtypes[attrs['Type']])) return elif tag == "Codes": self.context.pushHandler(CodeListHandler(self.context)) return elif tag == "Sounds": self.context.pushHandler(SoundListHandler(self.context)) return elif tag == "Sectormap": self.context.pushHandler(SectormapHandler(self.context)) return elif tag == "SectorSections": self.context.pushHandler(SectorSectionListHandler(self.context)) return elif tag == "Cameras": self.context.pushHandler(CameraListHandler(self.context)) return elif tag == "MapAreas": self.context.pushHandler(MapAreaListHandler(self.context)) return assert False def handleLeaveElement(self, tag): assert tag == "FANT" self.context.popHandler(self) def handleText(self, text): if text.strip() == "": return raise StandardError("Unexpected text \"" + text + "\"" ) # --------------------------------------------------------------------------------------------- class CodeHandler(GenericXmlClassHandler): tagname = 'Code' def _createInstance(self): #print self.Sourcecode #we have to pass a list of lines to the Code return Code.Code(self.Index, self.Sourcecode.split("\n"), self.Tokenlist) def __init__(self, context, tag, attrs, codelist): ''' ''' assert tag == CodeHandler.tagname #just make sure we were called for the correct tag propmap = {"Index":_addInteger, "Sourcecode":_addCDATA, "Tokenlist": _addIntegerList} GenericXmlClassHandler.__init__(self, context, "Code", attrs, propmap, codelist) class CodeListHandler(GenericXmlClassListHandler): def _setList(self): self.context.fantfile.codes = self.object_list def __init__(self, context): GenericXmlClassListHandler.__init__(self, context, 'Codes', None, CodeHandler) # --------------------------------------------------------------------------------------------- class SoundHandler(GenericXmlClassHandler): tagname = 'Sound' def _createInstance(self): return Sound.Sound(self.Index, self.Length, self.Unknown, self.Unknown1, self.Data, self.Flags) def __init__(self, context, tag, attrs, codelist): ''' ''' assert tag == SoundHandler.tagname #just make sure we were called for the correct tag propmap = {"Index":_addInteger, "Flags":_addInteger, "Length":_addInteger, "Unknown": _addInteger, "Unknown1": _addInteger, "Data": _addDataFileRef} GenericXmlClassHandler.__init__(self, context, SoundHandler.tagname, attrs, propmap, codelist) class SoundListHandler(GenericXmlClassListHandler): def _setList(self): self.context.fantfile.sounds = self.object_list def __init__(self, context): GenericXmlClassListHandler.__init__(self, context, 'Sounds', None, SoundHandler) # --------------------------------------------------------------------------------------------- class SectorSectionHandler(GenericXmlClassHandler): tagname = 'SectorSection' def _createInstance(self): return SectorSection.SectorSection(self.Priority, self.Section, self.Unknown1, self.CameraIndex, self.Y_Unknown, self.YMax, self.Index, self.Flags) def __init__(self, context, tag, attrs, seclist): ''' ''' assert tag == SectorSectionHandler.tagname #just make sure we were called for the correct tag propmap = {"Priority": _addInteger, "Section": _addInteger, "Unknown1": _addInteger, "CameraIndex": _addInteger, "Y_Unknown": _addInteger, "YMax": _addInteger, "Index": _addInteger, "Flags": _addInteger} GenericXmlClassHandler.__init__(self, context, SectorSectionHandler.tagname, attrs, propmap, seclist) class SectorSectionListHandler(GenericXmlClassListHandler): def _setList(self): print("number of sectorsections in XML data:", len(self.object_list)) self.context.fantfile.sectorsections = self.object_list def __init__(self, context): GenericXmlClassListHandler.__init__(self, context, 'SectorSections', None, SectorSectionHandler) # --------------------------------------------------------------------------------------------- class CameraHandler(GenericXmlClassHandler): tagname = 'Camera' def _createInstance(self): return Camera.Camera(self.Position, self.Angles, self.F) def __init__(self, context, tag, attrs, camlist): ''' ''' assert tag == CameraHandler.tagname #just make sure we were called for the correct tag propmap = {"Position":_addVector3, "Angles":_addVector3, "F":_addInteger} #TODO:read in Fixed-Point-Value GenericXmlClassHandler.__init__(self, context, CameraHandler.tagname, attrs, propmap, camlist) self.F = 1.0 class CameraListHandler(GenericXmlClassListHandler): def _setList(self): self.context.fantfile.cameras = self.object_list def __init__(self, context): GenericXmlClassListHandler.__init__(self, context, 'Cameras', None, CameraHandler) # --------------------------------------------------------------------------------------------- class MapAreaHandler(GenericXmlClassHandler): tagname = 'MapArea' def _createInstance(self): return MapArea.MapArea(self.Index, self.Values) def __init__(self, context, tag, attrs, maparealist): ''' ''' assert tag == MapAreaHandler.tagname #just make sure we were called for the correct tag propmap = {"Index":_addInteger, "Values":_addIntegerList} GenericXmlClassHandler.__init__(self, context, MapAreaHandler.tagname, attrs, propmap, maparealist) self.F = 1.0 class MapAreaListHandler(GenericXmlClassListHandler): def _setList(self): self.context.fantfile.mapareas = self.object_list def __init__(self, context): GenericXmlClassListHandler.__init__(self, context, 'MapAreas', None, MapAreaHandler) # --------------------------------------------------------------------------------------------- class SectormapHandler(_addIntegerList): def __init__(self, context): _addIntegerList.__init__(self, context, "Sectormap", {}, context.fantfile, 16384) self.propname = "sectormap" # --------------------------------------------------------------------------------------------- class HeaderHandler(GenericXmlDataHandler): def __init__(self, context): propmap = {"Version":_addInteger} GenericXmlDataHandler.__init__(self, context, 'Header', {}, propmap) # --------------------------------------------------------------------------------------------- class EventHandler(GenericXmlClassHandler): tagname = 'Event' def _createInstance(self): if self.event_type == Event.ev_NEXT_SCENE: #in this case we create a special event class return Event.NextSceneEvent(self.Index, self.Value1, self.Value2, self.Value3, self.ExtraData) else: return Event.Event(self.Index, self.event_type, self.Value1, self.Value2, self.Value3) def __init__(self, context, tag, attrs, objlist): assert tag == EventHandler.tagname #just make sure we were called for the correct tag assert "Type" in attrs.keys() self.event_type = Event.EventTypeName[attrs['Type']].typeid mapping = { "Index":_addInteger, "Value1":_addInteger, "Value2":_addInteger, "Value3":_addInteger, "ExtraData":_addCDATA } GenericXmlClassHandler.__init__(self, context, EventHandler.tagname, attrs, mapping, objlist) class EventListHandler(GenericXmlClassListHandler): def _setList(self): ''' This routine grabs the generic "object list" and puts it - depending on the eventlist type - into the right spot in the context! ''' if self.eventlisttype == "Scene": self.context.fantfile.sceneevents = self.object_list elif self.eventlisttype == "Actor": self.context.fantfile.actorevents = self.object_list elif self.eventlisttype == "Action": self.context.fantfile.actionevents = self.object_list elif self.eventlisttype == "Repertoire": self.context.fantfile.repertoireevents = self.object_list else: raise StandardError("Unknown Event list type") def __init__(self, context, eventlisttype, eventtypes): GenericXmlClassListHandler.__init__(self, context, 'Events', eventtypes, EventHandler) self.eventlisttype = eventlisttype # --------------------------------------------------------------------------------------------- class NameHandler(XmlHandler): ''' Handles a list of Names AS WELL AS THE SURROUNDING TAG ''' def setList(self): if self.nametype == "Actor": self.context.fantfile.actornameidxs = self.context.fantfile.actornames.addNames(self.namelist) elif self.nametype == "Action": #print self.namelist self.context.fantfile.actionameidxs = self.context.fantfile.actionnames.addNames(self.namelist) elif self.nametype == "Part": self.context.fantfile.partnameidxs = self.context.fantfile.partnames.addNames(self.namelist) elif self.nametype == "Scene": self.context.fantfile.scenenameidxs = self.context.fantfile.scenenames.addNames(self.namelist) elif self.nametype == "Repertoire": self.context.fantfile.repertnameidxs = self.context.fantfile.repertoirenames.addNames(self.namelist) elif self.nametype == "MapArea": self.context.fantfile.mapareanameidxs = self.context.fantfile.mapareanames.addNames(self.namelist) elif self.nametype == "Point": self.context.fantfile.pointnameidxs = self.context.fantfile.pointnames.addNames(self.namelist) elif self.nametype == "Triangle": self.context.fantfile.trinameidxs = self.context.fantfile.trianglenames.addNames(self.namelist) elif self.nametype == "Code": self.context.fantfile.codenameidxs = self.context.fantfile.codenames.addNames(self.namelist) elif self.nametype == "Sound": self.context.fantfile.soundnameidxs = self.context.fantfile.soundnames.addNames(self.namelist) else: raise StandardError("Unknown name type " + self.nametype) def __init__(self, nametype, context): XmlHandler.__init__(self, context) self.nametype = nametype self.inlist = False #whether we are in the names list or not self.inname = False #whether we are in a name tag or not self.namelist = [] def handleEnterElement(self, tag, attrs): #print attrs assert tag == "Names" or tag == "Name" assert attrs["Type"] == self.nametype if tag == "Names": self.inlist = True elif tag == "Name": self.inname = True def handleLeaveElement(self, tag): assert tag == "Names" or tag == "Name" if tag == "Names": self.setList() self.context.popHandler(self) self.context = None elif tag == "Name": self.inname = False def handleText(self, text): if text.strip() == "": if self.inname == False: return assert self.inname == True #see XmlExport.encodeName #XML forbids most characters in range 0-32 #unfortunately Python does not escape them nor unescape them, so I do this manually here #(actually the ampersand in the escape sequence is escaped by python) #print text self.namelist.append(re.sub('&#([0-9]+);', lambda x: struct.pack('b', int(x.group(1))).decode("utf-8"), text.strip())) #print re.sub('&#([0-9]+);', lambda x: struct.pack('b', int(x)), text) # --------------------------------------------------------------------------------------------- class LoadXMLFile(object): ''' This class creates a FANT file from a XML document ''' def pushHandler(self, handler): self.handlerstack.append(handler) self.parser.StartElementHandler = handler.handleEnterElement self.parser.EndElementHandler = handler.handleLeaveElement self.parser.CharacterDataHandler = handler.handleText self.parser.StartCdataSectionHandler = handler.CDataStart self.parser.EndCdataSectionHandler = handler.CDataStop def popHandler(self, handler): assert len(self.handlerstack) > 1 assert handler == self.handlerstack[-1] self.handlerstack = self.handlerstack[:-1] self.parser.StartElementHandler = self.handlerstack[-1].handleEnterElement self.parser.EndElementHandler = self.handlerstack[-1].handleLeaveElement self.parser.CharacterDataHandler = self.handlerstack[-1].handleText self.parser.StartCdataSectionHandler = self.handlerstack[-1].CDataStart self.parser.EndCdataSectionHandler = self.handlerstack[-1].CDataStop def newFANTFile(self): ''' moves on to a new FANT file. Is called by the FANT-tag handler ''' if self.fantfile != None: #now we check if there were any names given in the file. If not, we set skip_transtables to True #how do we decide that? We get all name lists and check if they all are empty if len(list(filter(lambda x: len(x)!=0, self.fantfile.getAllNameLists().values()))) == 0: self.fantfile._initIndexArrays() self.fantfile.skip_transtables = True self.fantfiles.append(self.fantfile) self.fantfile = FANTFile() def __init__(self, input_filename): ''' Constructor ''' self.input_filename = input_filename #the XML interface can handle a stack of FANT files, which are sequentially loaded self.fantfile = None #points always on the current FANT file self.fantfiles = [] #in the end this list contains all loaded FANT files self.parser = xml.parsers.expat.ParserCreate() self.parser.buffer_text = True self.handlerstack = [] stackhandler = StackHandler(self) self.pushHandler(stackhandler) def run(self): infile = open(self.input_filename, "rb") self.parser.Parse(infile.read()) infile.close() #the following procedure has to be done for the last FANT file as well! if self.fantfile != None: self.fantfiles.append(self.fantfile) #now we check if there were any names given in the file. If not, we set skip_transtables to True #how do we decide that? We get all name lists and check if they all are empty if len(list(filter(lambda x: len(x)!=0, self.fantfile.getAllNameLists().values()))) == 0: self.fantfile._initIndexArrays() self.fantfile.skip_transtables = True def loadStack(filename): loader = LoadXMLFile(filename) loader.run() return loader.fantfiles import unittest class TestLoadXML(unittest.TestCase): def test_load_save_xml(self): loader = LoadXMLFile('/tmp/fant.xml') loader.run() f = open("/tmp/fant_rewritten.xml", "wb") f.write(XmlSave.exportXml(loader.fantfile).encode("utf-8")) f.close() def test_load_xml_save_fant(self): loader = LoadXMLFile('/tmp/fant.xml') loader.run() print(loader.fantfile) FANTSave.exportFANT(open("/tmp/rewritten.fant", "wb"), loader.fantfile, False)
gpl-3.0
kartikgupta0909/mozilla-mozharness
configs/single_locale/staging_release_mozilla-beta_android.py
4
4884
BRANCH = "mozilla-beta" MOZ_UPDATE_CHANNEL = "beta" MOZILLA_DIR = BRANCH OBJDIR = "obj-l10n" STAGE_SERVER = "dev-stage01.srv.releng.scl3.mozilla.com" #STAGE_SERVER = "stage.mozilla.org" EN_US_BINARY_URL = "http://" + STAGE_SERVER + "/pub/mozilla.org/mobile/candidates/%(version)s-candidates/build%(buildnum)d/android/en-US" STAGE_USER = "ffxbld" STAGE_SSH_KEY = "~/.ssh/ffxbld_dsa" HG_SHARE_BASE_DIR = "/builds/hg-shared" config = { "log_name": "single_locale", "objdir": OBJDIR, "is_automation": True, "buildbot_json_path": "buildprops.json", "purge_minsize": 10, "force_clobber": True, "clobberer_url": "http://clobberer-stage.pvt.build.mozilla.org/index.php", "locales_file": "buildbot-configs/mozilla/l10n-changesets_mobile-beta.json", "locales_dir": "mobile/android/locales", "locales_platform": "android", "ignore_locales": ["en-US"], "tooltool_config": { "manifest": "mobile/android/config/tooltool-manifests/android/releng.manifest", "output_dir": "%(abs_work_dir)s/" + MOZILLA_DIR, "bootstrap_cmd": ["bash", "-xe", "setup.sh"], }, "exes": { 'tooltool.py': '/tools/tooltool.py', }, "tooltool_servers": ["http://runtime-binaries.pvt.build.mozilla.org/tooltool/"], "repos": [{ "repo": "https://hg.mozilla.org/%(user_repo_override)s/mozilla-beta", "revision": "default", "dest": MOZILLA_DIR, }, { "repo": "https://hg.mozilla.org/%(user_repo_override)s/buildbot-configs", "revision": "default", "dest": "buildbot-configs" }, { "repo": "https://hg.mozilla.org/%(user_repo_override)s/tools", "revision": "default", "dest": "tools" }, { "repo": "https://hg.mozilla.org/%(user_repo_override)s/compare-locales", "revision": "RELEASE_AUTOMATION" }], "hg_l10n_base": "https://hg.mozilla.org/%(user_repo_override)s/", "hg_l10n_tag": "default", 'vcs_share_base': HG_SHARE_BASE_DIR, "l10n_dir": MOZILLA_DIR, "release_config_file": "buildbot-configs/mozilla/staging_release-fennec-mozilla-beta.py", "repack_env": { # so ugly, bug 951238 "LD_LIBRARY_PATH": "/lib:/tools/gcc-4.7.2-0moz1/lib:/tools/gcc-4.7.2-0moz1/lib64", "MOZ_PKG_VERSION": "%(version)s", "MOZ_OBJDIR": OBJDIR, "LOCALE_MERGEDIR": "%(abs_merge_dir)s/", "MOZ_UPDATE_CHANNEL": MOZ_UPDATE_CHANNEL, }, "base_en_us_binary_url": EN_US_BINARY_URL, # TODO ideally we could get this info from a central location. # However, the agility of these individual config files might trump that. "upload_env": { "UPLOAD_USER": STAGE_USER, "UPLOAD_SSH_KEY": STAGE_SSH_KEY, "UPLOAD_HOST": STAGE_SERVER, "UPLOAD_TO_TEMP": "1", "MOZ_PKG_VERSION": "%(version)s", }, "base_post_upload_cmd": "post_upload.py -p mobile -n %(buildnum)s -v %(version)s --builddir android/%(locale)s --release-to-mobile-candidates-dir --nightly-dir=candidates", "merge_locales": True, "make_dirs": ['config'], "mozilla_dir": MOZILLA_DIR, "mozconfig": "%s/mobile/android/config/mozconfigs/android/l10n-release" % MOZILLA_DIR, "signature_verification_script": "tools/release/signing/verify-android-signature.sh", "default_actions": [ "clobber", "pull", "list-locales", "setup", "repack", "upload-repacks", "summary", ], # Mock "mock_target": "mozilla-centos6-x86_64", "mock_packages": ['autoconf213', 'python', 'zip', 'mozilla-python27-mercurial', 'git', 'ccache', 'glibc-static', 'libstdc++-static', 'perl-Test-Simple', 'perl-Config-General', 'gtk2-devel', 'libnotify-devel', 'yasm', 'alsa-lib-devel', 'libcurl-devel', 'wireless-tools-devel', 'libX11-devel', 'libXt-devel', 'mesa-libGL-devel', 'gnome-vfs2-devel', 'GConf2-devel', 'wget', 'mpfr', # required for system compiler 'xorg-x11-font*', # fonts required for PGO 'imake', # required for makedepend!?! 'gcc45_0moz3', 'gcc454_0moz1', 'gcc472_0moz1', 'gcc473_0moz1', 'yasm', 'ccache', # <-- from releng repo 'valgrind', 'dbus-x11', 'pulseaudio-libs-devel', 'gstreamer-devel', 'gstreamer-plugins-base-devel', 'freetype-2.3.11-6.el6_1.8.x86_64', 'freetype-devel-2.3.11-6.el6_1.8.x86_64', 'java-1.6.0-openjdk-devel', 'openssh-clients', 'zlib-devel-1.2.3-27.el6.i686', ], "mock_files": [ ("/home/cltbld/.ssh", "/home/mock_mozilla/.ssh"), ], }
mpl-2.0
regular/pyglet-avbin-optimizations
experimental/buffer/sprites.py
28
2875
#!/usr/bin/python # $Id:$ import random import sys from pyglet.gl import * from pyglet import clock from pyglet import image from pyglet import window from pyglet.graphics import vertexdomain if len(sys.argv) > 1: SPRITES = int(sys.argv[1]) else: SPRITES = 2000 SPRITE_IMAGE = 'examples/noisy/ball.png' # How many sprites to move each frame. e.g. # 0 -- all sprites are static # 1 -- all sprites move every frame (all are dynamic) # 2 -- only 2 sprites move every frame # 50 -- 50 sprites move every frame SPRITE_UPDATE_N = 1 win = window.Window(vsync=False) class Sprite(object): width = 32 height = 32 def __init__(self, domain): self.primitive = domain.create(4) self.x = win.width * random.random() self.y = win.height * random.random() self.dx = (random.random() - .5) * 200 self.dy = (random.random() - .5) * 200 self.primitive.tex_coords = [ 0, 0, 1, 0, 1, 1, 0, 1 ] self.update(0) def update(self, dt): self.x += self.dx * dt self.y += self.dy * dt if not 0 < self.x < win.width: self.dx = -self.dx self.x += self.dx * dt * 2 if not 0 < self.y < win.height: self.dy = -self.dy self.y += self.dy * dt * 2 x = self.x y = self.y rx = self.width // 2 ry = self.height // 2 self.primitive.vertices = [ x - rx, y - ry, x + rx, y - ry, x + rx, y + rx, x - rx, y + rx ] def draw_sprites(domain, texture): glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT) glEnable(GL_BLEND) glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) glColor4f(.2, .2, .2, .2) glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, texture.id) domain.draw(GL_QUADS) glPopAttrib() if __name__ == '__main__': domain = vertexdomain.create_domain('v2f/static', 't2f/static') sprites = [Sprite(domain) for i in range(SPRITES)] fps = clock.ClockDisplay(color=(1, 1, 1, 1)) texture = image.load(SPRITE_IMAGE).texture if SPRITE_UPDATE_N: update_n = 0 while not win.has_exit: dt = clock.tick() if dt == 0: dt = 0.01 win.dispatch_events() if SPRITE_UPDATE_N > 1: # Update small number of sprites for sprite in sprites[update_n:update_n+SPRITE_UPDATE_N]: sprite.update(dt) update_n = (update_n + SPRITE_UPDATE_N) % len(sprites) elif SPRITE_UPDATE_N: # Update all sprites for sprite in sprites: sprite.update(dt) # Otherwise, update no sprites (static) win.clear() draw_sprites(domain, texture) fps.draw() win.flip()
bsd-3-clause
cryptickp/heat
heat/engine/resources/stack_resource.py
1
21691
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import hashlib import json from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import excutils import six from heat.common import exception from heat.common.i18n import _ from heat.common.i18n import _LE from heat.common.i18n import _LW from heat.common import identifier from heat.common import template_format from heat.engine import attributes from heat.engine import environment from heat.engine import resource from heat.engine import scheduler from heat.engine import stack as parser from heat.engine import template from heat.rpc import api as rpc_api LOG = logging.getLogger(__name__) class StackResource(resource.Resource): ''' An abstract Resource subclass that allows the management of an entire Stack as a resource in a parent stack. ''' # Assume True as this is evaluated before the stack is created # so there is no way to know for sure without subclass-specific # template parsing. requires_deferred_auth = True def __init__(self, name, json_snippet, stack): super(StackResource, self).__init__(name, json_snippet, stack) self._nested = None self.resource_info = None def validate(self): super(StackResource, self).validate() self.validate_nested_stack() def validate_nested_stack(self): try: name = "%s-%s" % (self.stack.name, self.name) nested_stack = self._parse_nested_stack( name, self.child_template(), self.child_params()) nested_stack.strict_validate = False nested_stack.validate() except AssertionError: raise except Exception as ex: raise exception.StackValidationFailed( error=_("Failed to validate"), path=[self.stack.t.get_section_name('resources'), self.name], message=six.text_type(ex)) def _outputs_to_attribs(self, json_snippet): outputs = json_snippet.get('Outputs') if not self.attributes and outputs: self.attributes_schema = ( attributes.Attributes.schema_from_outputs(outputs)) # Note: it can be updated too and for show return dictionary # with all available outputs self.attributes = attributes.Attributes( self.name, self.attributes_schema, self._resolve_all_attributes) def _needs_update(self, after, before, after_props, before_props, prev_resource, check_init_complete=True): # Issue an update to the nested stack if the stack resource # is able to update. If return true, let the individual # resources in it decide if they need updating. # FIXME (ricolin): seems currently can not call super here if self.nested() is None and self.status == self.FAILED: raise resource.UpdateReplace(self) if (check_init_complete and self.nested() is None and self.action == self.INIT and self.status == self.COMPLETE): raise resource.UpdateReplace(self) return True @scheduler.wrappertask def update(self, after, before=None, prev_resource=None): try: yield super(StackResource, self).update(after, before, prev_resource) except StopIteration: with excutils.save_and_reraise_exception(): stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) self.rpc_client().stack_cancel_update( self.context, stack_identity, cancel_with_rollback=False) def has_nested(self): if self.nested() is not None: return True return False def nested(self, force_reload=False, show_deleted=False): '''Return a Stack object representing the nested (child) stack. if we catch NotFound exception when loading, return None. :param force_reload: Forces reloading from the DB instead of returning the locally cached Stack object :param show_deleted: Returns the stack even if it's been deleted ''' if force_reload: self._nested = None if self._nested is None and self.resource_id is not None: try: self._nested = parser.Stack.load(self.context, self.resource_id, show_deleted=show_deleted, force_reload=force_reload) except exception.NotFound: return None return self._nested def child_template(self): ''' Default implementation to get the child template. Resources that inherit from StackResource should override this method with specific details about the template used by them. ''' raise NotImplementedError() def child_params(self): ''' Default implementation to get the child params. Resources that inherit from StackResource should override this method with specific details about the parameters used by them. ''' raise NotImplementedError() def preview(self): ''' Preview a StackResource as resources within a Stack. This method overrides the original Resource.preview to return a preview of all the resources contained in this Stack. For this to be possible, the specific resources need to override both ``child_template`` and ``child_params`` with specific information to allow the stack to be parsed correctly. If any of these methods is missing, the entire StackResource will be returned as if it were a regular Resource. ''' try: child_template = self.child_template() params = self.child_params() except NotImplementedError: LOG.warn(_LW("Preview of '%s' not yet implemented"), self.__class__.__name__) return self name = "%s-%s" % (self.stack.name, self.name) self._nested = self._parse_nested_stack(name, child_template, params) return self.nested().preview_resources() def _parse_child_template(self, child_template, child_env): parsed_child_template = child_template if isinstance(parsed_child_template, template.Template): parsed_child_template = parsed_child_template.t return template.Template(parsed_child_template, files=self.stack.t.files, env=child_env) def _parse_nested_stack(self, stack_name, child_template, child_params, timeout_mins=None, adopt_data=None): if timeout_mins is None: timeout_mins = self.stack.timeout_mins stack_user_project_id = self.stack.stack_user_project_id new_nested_depth = self._child_nested_depth() child_env = environment.get_child_environment( self.stack.env, child_params, child_resource_name=self.name, item_to_remove=self.resource_info) parsed_template = self._child_parsed_template(child_template, child_env) # Note we disable rollback for nested stacks, since they # should be rolled back by the parent stack on failure nested = parser.Stack(self.context, stack_name, parsed_template, timeout_mins=timeout_mins, disable_rollback=True, parent_resource=self.name, owner_id=self.stack.id, user_creds_id=self.stack.user_creds_id, stack_user_project_id=stack_user_project_id, adopt_stack_data=adopt_data, nested_depth=new_nested_depth) return nested def _child_nested_depth(self): if self.stack.nested_depth >= cfg.CONF.max_nested_stack_depth: msg = _("Recursion depth exceeds %d." ) % cfg.CONF.max_nested_stack_depth raise exception.RequestLimitExceeded(message=msg) return self.stack.nested_depth + 1 def _child_parsed_template(self, child_template, child_env): parsed_template = self._parse_child_template(child_template, child_env) self._validate_nested_resources(parsed_template) # Don't overwrite the attributes_schema for subclasses that # define their own attributes_schema. if not hasattr(type(self), 'attributes_schema'): self.attributes = None self._outputs_to_attribs(parsed_template) return parsed_template def _validate_nested_resources(self, templ): if cfg.CONF.max_resources_per_stack == -1: return root_stack_id = self.stack.root_stack_id() total_resources = (len(templ[templ.RESOURCES]) + self.stack.total_resources(root_stack_id)) if self.nested(): # It's an update and these resources will be deleted total_resources -= len(self.nested().resources) if (total_resources > cfg.CONF.max_resources_per_stack): message = exception.StackResourceLimitExceeded.msg_fmt raise exception.RequestLimitExceeded(message=message) def create_with_template(self, child_template, user_params=None, timeout_mins=None, adopt_data=None): """Create the nested stack with the given template.""" name = self.physical_resource_name() if timeout_mins is None: timeout_mins = self.stack.timeout_mins stack_user_project_id = self.stack.stack_user_project_id if user_params is None: user_params = self.child_params() child_env = environment.get_child_environment( self.stack.env, user_params, child_resource_name=self.name, item_to_remove=self.resource_info) new_nested_depth = self._child_nested_depth() parsed_template = self._child_parsed_template(child_template, child_env) adopt_data_str = None if adopt_data is not None: if 'environment' not in adopt_data: adopt_data['environment'] = child_env.user_env_as_dict() if 'template' not in adopt_data: adopt_data['template'] = child_template adopt_data_str = json.dumps(adopt_data) args = {rpc_api.PARAM_TIMEOUT: timeout_mins, rpc_api.PARAM_DISABLE_ROLLBACK: True, rpc_api.PARAM_ADOPT_STACK_DATA: adopt_data_str} try: result = self.rpc_client()._create_stack( self.context, name, parsed_template.t, child_env.user_env_as_dict(), parsed_template.files, args, owner_id=self.stack.id, user_creds_id=self.stack.user_creds_id, stack_user_project_id=stack_user_project_id, nested_depth=new_nested_depth, parent_resource_name=self.name) except Exception as ex: self.raise_local_exception(ex) self.resource_id_set(result['stack_id']) def raise_local_exception(self, ex): if (isinstance(ex, exception.ActionInProgress) and self.stack.action == self.stack.ROLLBACK): # The update was interrupted and the rollback is already in # progress, so just ignore the error and wait for the rollback to # finish return if not ex.__class__.__name__.endswith('_Remote'): raise ex full_message = six.text_type(ex) if full_message.find('\n') > -1: message, msg_trace = full_message.split('\n', 1) else: message = full_message raise exception.ResourceFailure(message, self, action=self.action) def check_create_complete(self, cookie=None): return self._check_status_complete(resource.Resource.CREATE) def _check_status_complete(self, action, show_deleted=False, cookie=None): nested = self.nested(force_reload=True, show_deleted=show_deleted) if nested is None: if action == resource.Resource.DELETE: return True # It's possible the engine handling the create hasn't persisted # the stack to the DB when we first start polling for state return False if nested.action != action: return False # Has the action really started? # # The rpc call to update does not guarantee that the stack will be # placed into IN_PROGRESS by the time it returns (it runs stack.update # in a thread) so you could also have a situation where we get into # this method and the update hasn't even started. # # So we are using a mixture of state (action+status) and updated_at # to see if the action has actually progressed. # - very fast updates (like something with one RandomString) we will # probably miss the state change, but we should catch the updated_at. # - very slow updates we won't see the updated_at for quite a while, # but should see the state change. if cookie is not None: prev_state = cookie['previous']['state'] prev_updated_at = cookie['previous']['updated_at'] if (prev_updated_at == nested.updated_time and prev_state == nested.state): return False if nested.status == resource.Resource.IN_PROGRESS: return False elif nested.status == resource.Resource.COMPLETE: return True elif nested.status == resource.Resource.FAILED: raise exception.ResourceFailure(nested.status_reason, self, action=action) else: raise resource.ResourceUnknownStatus( resource_status=nested.status, status_reason=nested.status_reason, result=_('Stack unknown status')) def check_adopt_complete(self, cookie=None): return self._check_status_complete(resource.Resource.ADOPT) def update_with_template(self, child_template, user_params=None, timeout_mins=None): """Update the nested stack with the new template.""" if self.id is None: self._store() nested_stack = self.nested() if nested_stack is None: # if the create failed for some reason and the nested # stack was not created, we need to create an empty stack # here so that the update will work. def _check_for_completion(creator_fn): while not self.check_create_complete(creator_fn): yield empty_temp = template_format.parse( "heat_template_version: '2013-05-23'") stack_creator = self.create_with_template(empty_temp, {}) checker = scheduler.TaskRunner(_check_for_completion, stack_creator) checker(timeout=self.stack.timeout_secs()) if stack_creator is not None: stack_creator.run_to_completion() nested_stack = self.nested() if timeout_mins is None: timeout_mins = self.stack.timeout_mins if user_params is None: user_params = self.child_params() child_env = environment.get_child_environment( self.stack.env, user_params, child_resource_name=self.name, item_to_remove=self.resource_info) parsed_template = self._child_parsed_template(child_template, child_env) cookie = {'previous': { 'updated_at': nested_stack.updated_time, 'state': nested_stack.state}} args = {rpc_api.PARAM_TIMEOUT: timeout_mins} try: self.rpc_client().update_stack( self.context, nested_stack.identifier(), parsed_template.t, child_env.user_env_as_dict(), parsed_template.files, args) except Exception as ex: LOG.exception(_LE('update_stack')) self.raise_local_exception(ex) return cookie def check_update_complete(self, cookie=None): return self._check_status_complete(resource.Resource.UPDATE, cookie=cookie) def delete_nested(self): ''' Delete the nested stack. ''' stack = self.nested() if stack is None: return stack_identity = stack.identifier() try: self.rpc_client().delete_stack(self.context, stack_identity) except Exception as ex: self.rpc_client().ignore_error_named(ex, 'NotFound') def handle_delete(self): return self.delete_nested() def check_delete_complete(self, cookie=None): return self._check_status_complete(resource.Resource.DELETE, show_deleted=True) def handle_suspend(self): stack = self.nested() if stack is None: raise exception.Error(_('Cannot suspend %s, stack not created') % self.name) stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) self.rpc_client().stack_suspend(self.context, stack_identity) def check_suspend_complete(self, cookie=None): return self._check_status_complete(resource.Resource.SUSPEND) def handle_resume(self): stack = self.nested() if stack is None: raise exception.Error(_('Cannot resume %s, stack not created') % self.name) stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) self.rpc_client().stack_resume(self.context, stack_identity) def check_resume_complete(self, cookie=None): return self._check_status_complete(resource.Resource.RESUME) def handle_check(self): stack = self.nested() if stack is None: raise exception.Error(_('Cannot check %s, stack not created') % self.name) stack_identity = identifier.HeatIdentifier( self.context.tenant_id, self.physical_resource_name(), self.resource_id) self.rpc_client().stack_check(self.context, stack_identity) def check_check_complete(self, cookie=None): return self._check_status_complete(resource.Resource.CHECK) def prepare_abandon(self): nested_stack = self.nested() if nested_stack: return self.nested().prepare_abandon() return {} def get_output(self, op): ''' Return the specified Output value from the nested stack. If the output key does not exist, raise an InvalidTemplateAttribute exception. ''' stack = self.nested() if stack is None: return None if op not in stack.outputs: raise exception.InvalidTemplateAttribute(resource=self.name, key=op) result = stack.output(op) if result is None and stack.outputs[op].get('error_msg') is not None: raise exception.InvalidTemplateAttribute(resource=self.name, key=op) return result def _resolve_attribute(self, name): return self.get_output(name) def implementation_signature(self): schema_names = ([prop for prop in self.properties_schema] + [at for at in self.attributes_schema]) schema_hash = hashlib.sha256(';'.join(schema_names)) definition = {'template': self.child_template(), 'files': self.stack.t.files} definition_hash = hashlib.sha256(jsonutils.dumps(definition)) return (schema_hash.hexdigest(), definition_hash.hexdigest())
apache-2.0
JVenberg/PokemonGo-Bot-Desktop
pywin/Lib/UserDict.py
62
7060
"""A more or less complete user-defined wrapper around dictionary objects.""" class UserDict: def __init__(*args, **kwargs): if not args: raise TypeError("descriptor '__init__' of 'UserDict' object " "needs an argument") self = args[0] args = args[1:] if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) if args: dict = args[0] elif 'dict' in kwargs: dict = kwargs.pop('dict') import warnings warnings.warn("Passing 'dict' as keyword argument is " "deprecated", PendingDeprecationWarning, stacklevel=2) else: dict = None self.data = {} if dict is not None: self.update(dict) if len(kwargs): self.update(kwargs) def __repr__(self): return repr(self.data) def __cmp__(self, dict): if isinstance(dict, UserDict): return cmp(self.data, dict.data) else: return cmp(self.data, dict) __hash__ = None # Avoid Py3k warning def __len__(self): return len(self.data) def __getitem__(self, key): if key in self.data: return self.data[key] if hasattr(self.__class__, "__missing__"): return self.__class__.__missing__(self, key) raise KeyError(key) def __setitem__(self, key, item): self.data[key] = item def __delitem__(self, key): del self.data[key] def clear(self): self.data.clear() def copy(self): if self.__class__ is UserDict: return UserDict(self.data.copy()) import copy data = self.data try: self.data = {} c = copy.copy(self) finally: self.data = data c.update(self) return c def keys(self): return self.data.keys() def items(self): return self.data.items() def iteritems(self): return self.data.iteritems() def iterkeys(self): return self.data.iterkeys() def itervalues(self): return self.data.itervalues() def values(self): return self.data.values() def has_key(self, key): return key in self.data def update(*args, **kwargs): if not args: raise TypeError("descriptor 'update' of 'UserDict' object " "needs an argument") self = args[0] args = args[1:] if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) if args: dict = args[0] elif 'dict' in kwargs: dict = kwargs.pop('dict') import warnings warnings.warn("Passing 'dict' as keyword argument is deprecated", PendingDeprecationWarning, stacklevel=2) else: dict = None if dict is None: pass elif isinstance(dict, UserDict): self.data.update(dict.data) elif isinstance(dict, type({})) or not hasattr(dict, 'items'): self.data.update(dict) else: for k, v in dict.items(): self[k] = v if len(kwargs): self.data.update(kwargs) def get(self, key, failobj=None): if key not in self: return failobj return self[key] def setdefault(self, key, failobj=None): if key not in self: self[key] = failobj return self[key] def pop(self, key, *args): return self.data.pop(key, *args) def popitem(self): return self.data.popitem() def __contains__(self, key): return key in self.data @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d class IterableUserDict(UserDict): def __iter__(self): return iter(self.data) import _abcoll _abcoll.MutableMapping.register(IterableUserDict) class DictMixin: # Mixin defining all dictionary methods for classes that already have # a minimum dictionary interface including getitem, setitem, delitem, # and keys. Without knowledge of the subclass constructor, the mixin # does not define __init__() or copy(). In addition to the four base # methods, progressively more efficiency comes with defining # __contains__(), __iter__(), and iteritems(). # second level definitions support higher levels def __iter__(self): for k in self.keys(): yield k def has_key(self, key): try: self[key] except KeyError: return False return True def __contains__(self, key): return self.has_key(key) # third level takes advantage of second level definitions def iteritems(self): for k in self: yield (k, self[k]) def iterkeys(self): return self.__iter__() # fourth level uses definitions from lower levels def itervalues(self): for _, v in self.iteritems(): yield v def values(self): return [v for _, v in self.iteritems()] def items(self): return list(self.iteritems()) def clear(self): for key in self.keys(): del self[key] def setdefault(self, key, default=None): try: return self[key] except KeyError: self[key] = default return default def pop(self, key, *args): if len(args) > 1: raise TypeError, "pop expected at most 2 arguments, got "\ + repr(1 + len(args)) try: value = self[key] except KeyError: if args: return args[0] raise del self[key] return value def popitem(self): try: k, v = self.iteritems().next() except StopIteration: raise KeyError, 'container is empty' del self[k] return (k, v) def update(self, other=None, **kwargs): # Make progressively weaker assumptions about "other" if other is None: pass elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups for k, v in other.iteritems(): self[k] = v elif hasattr(other, 'keys'): for k in other.keys(): self[k] = other[k] else: for k, v in other: self[k] = v if kwargs: self.update(kwargs) def get(self, key, default=None): try: return self[key] except KeyError: return default def __repr__(self): return repr(dict(self.iteritems())) def __cmp__(self, other): if other is None: return 1 if isinstance(other, DictMixin): other = dict(other.iteritems()) return cmp(dict(self.iteritems()), other) def __len__(self): return len(self.keys())
mit
funkring/fdoo
addons/sale/wizard/sale_make_invoice_advance.py
163
10872
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp class sale_advance_payment_inv(osv.osv_memory): _name = "sale.advance.payment.inv" _description = "Sales Advance Payment Invoice" _columns = { 'advance_payment_method':fields.selection( [('all', 'Invoice the whole sales order'), ('percentage','Percentage'), ('fixed','Fixed price (deposit)'), ('lines', 'Some order lines')], 'What do you want to invoice?', required=True, help="""Use Invoice the whole sale order to create the final invoice. Use Percentage to invoice a percentage of the total amount. Use Fixed Price to invoice a specific amound in advance. Use Some Order Lines to invoice a selection of the sales order lines."""), 'qtty': fields.float('Quantity', digits=(16, 2), required=True), 'product_id': fields.many2one('product.product', 'Advance Product', domain=[('type', '=', 'service')], help="""Select a product of type service which is called 'Advance Product'. You may have to create it and set it as a default value on this field."""), 'amount': fields.float('Advance Amount', digits_compute= dp.get_precision('Account'), help="The amount to be invoiced in advance."), } def _get_advance_product(self, cr, uid, context=None): try: product = self.pool.get('ir.model.data').get_object(cr, uid, 'sale', 'advance_product_0') except ValueError: # a ValueError is returned if the xml id given is not found in the table ir_model_data return False return product.id _defaults = { 'advance_payment_method': 'all', 'qtty': 1.0, 'product_id': _get_advance_product, } def _translate_advance(self, cr, uid, percentage=False, context=None): return _("Advance of %s %%") if percentage else _("Advance of %s %s") def onchange_method(self, cr, uid, ids, advance_payment_method, product_id, context=None): if advance_payment_method == 'percentage': return {'value': {'amount':0, 'product_id':False }} if product_id: product = self.pool.get('product.product').browse(cr, uid, product_id, context=context) return {'value': {'amount': product.list_price}} return {'value': {'amount': 0}} def _prepare_advance_invoice_vals(self, cr, uid, ids, context=None): if context is None: context = {} sale_obj = self.pool.get('sale.order') ir_property_obj = self.pool.get('ir.property') fiscal_obj = self.pool.get('account.fiscal.position') inv_line_obj = self.pool.get('account.invoice.line') wizard = self.browse(cr, uid, ids[0], context) sale_ids = context.get('active_ids', []) result = [] for sale in sale_obj.browse(cr, uid, sale_ids, context=context): val = inv_line_obj.product_id_change(cr, uid, [], wizard.product_id.id, False, partner_id=sale.partner_id.id, fposition_id=sale.fiscal_position.id, company_id=sale.company_id.id) res = val['value'] # determine and check income account if not wizard.product_id.id : prop = ir_property_obj.get(cr, uid, 'property_account_income_categ', 'product.category', context=context) prop_id = prop and prop.id or False account_id = fiscal_obj.map_account(cr, uid, sale.fiscal_position or False, prop_id) if not account_id: raise osv.except_osv(_('Configuration Error!'), _('There is no income account defined as global property.')) res['account_id'] = account_id if not res.get('account_id'): raise osv.except_osv(_('Configuration Error!'), _('There is no income account defined for this product: "%s" (id:%d).') % \ (wizard.product_id.name, wizard.product_id.id,)) # determine invoice amount if wizard.amount <= 0.00: raise osv.except_osv(_('Incorrect Data'), _('The value of Advance Amount must be positive.')) if wizard.advance_payment_method == 'percentage': inv_amount = sale.amount_untaxed * wizard.amount / 100 if not res.get('name'): res['name'] = self._translate_advance(cr, uid, percentage=True, context=dict(context, lang=sale.partner_id.lang)) % (wizard.amount) else: inv_amount = wizard.amount if not res.get('name'): #TODO: should find a way to call formatLang() from rml_parse symbol = sale.pricelist_id.currency_id.symbol if sale.pricelist_id.currency_id.position == 'after': symbol_order = (inv_amount, symbol) else: symbol_order = (symbol, inv_amount) res['name'] = self._translate_advance(cr, uid, context=dict(context, lang=sale.partner_id.lang)) % symbol_order # determine taxes if res.get('invoice_line_tax_id'): res['invoice_line_tax_id'] = [(6, 0, res.get('invoice_line_tax_id'))] else: res['invoice_line_tax_id'] = False # create the invoice inv_line_values = { 'name': res.get('name'), 'origin': sale.name, 'account_id': res['account_id'], 'price_unit': inv_amount, 'quantity': wizard.qtty or 1.0, 'discount': False, 'uos_id': res.get('uos_id', False), 'product_id': wizard.product_id.id, 'invoice_line_tax_id': res.get('invoice_line_tax_id'), 'account_analytic_id': sale.project_id.id or False, } inv_values = { 'name': sale.client_order_ref or sale.name, 'origin': sale.name, 'type': 'out_invoice', 'reference': False, 'account_id': sale.partner_id.property_account_receivable.id, 'partner_id': sale.partner_invoice_id.id, 'invoice_line': [(0, 0, inv_line_values)], 'currency_id': sale.pricelist_id.currency_id.id, 'comment': sale.note, 'payment_term': sale.payment_term.id, 'fiscal_position': sale.fiscal_position.id or sale.partner_id.property_account_position.id, 'section_id': sale.section_id.id, } result.append((sale.id, inv_values)) return result def _create_invoices(self, cr, uid, inv_values, sale_id, context=None): inv_obj = self.pool.get('account.invoice') sale_obj = self.pool.get('sale.order') inv_id = inv_obj.create(cr, uid, inv_values, context=context) inv_obj.button_reset_taxes(cr, uid, [inv_id], context=context) # add the invoice to the sales order's invoices sale_obj.write(cr, uid, sale_id, {'invoice_ids': [(4, inv_id)]}, context=context) return inv_id def create_invoices(self, cr, uid, ids, context=None): """ create invoices for the active sales orders """ sale_obj = self.pool.get('sale.order') act_window = self.pool.get('ir.actions.act_window') wizard = self.browse(cr, uid, ids[0], context) sale_ids = context.get('active_ids', []) if wizard.advance_payment_method == 'all': # create the final invoices of the active sales orders res = sale_obj.manual_invoice(cr, uid, sale_ids, context) if context.get('open_invoices', False): return res return {'type': 'ir.actions.act_window_close'} if wizard.advance_payment_method == 'lines': # open the list view of sales order lines to invoice res = act_window.for_xml_id(cr, uid, 'sale', 'action_order_line_tree2', context) res['context'] = { 'search_default_uninvoiced': 1, 'search_default_order_id': sale_ids and sale_ids[0] or False, } return res assert wizard.advance_payment_method in ('fixed', 'percentage') inv_ids = [] for sale_id, inv_values in self._prepare_advance_invoice_vals(cr, uid, ids, context=context): inv_ids.append(self._create_invoices(cr, uid, inv_values, sale_id, context=context)) if context.get('open_invoices', False): return self.open_invoices( cr, uid, ids, inv_ids, context=context) return {'type': 'ir.actions.act_window_close'} def open_invoices(self, cr, uid, ids, invoice_ids, context=None): """ open a view on one of the given invoice_ids """ ir_model_data = self.pool.get('ir.model.data') form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_form') form_id = form_res and form_res[1] or False tree_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_tree') tree_id = tree_res and tree_res[1] or False return { 'name': _('Advance Invoice'), 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'account.invoice', 'res_id': invoice_ids[0], 'view_id': False, 'views': [(form_id, 'form'), (tree_id, 'tree')], 'context': "{'type': 'out_invoice'}", 'type': 'ir.actions.act_window', } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
beckastar/django
tests/many_to_one_regress/tests.py
26
5397
from __future__ import unicode_literals from django.db import models from django.test import TestCase from .models import ( First, Third, Parent, Child, Category, Record, Relation, Car, Driver) class ManyToOneRegressionTests(TestCase): def test_object_creation(self): Third.objects.create(id='3', name='An example') parent = Parent(name='fred') parent.save() Child.objects.create(name='bam-bam', parent=parent) def test_fk_assignment_and_related_object_cache(self): # Tests of ForeignKey assignment and the related-object cache (see #6886). p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) # Look up the object again so that we get a "fresh" object. c = Child.objects.get(name="Child") p = c.parent # Accessing the related object again returns the exactly same object. self.assertTrue(c.parent is p) # But if we kill the cache, we get a new object. del c._parent_cache self.assertFalse(c.parent is p) # Assigning a new object results in that object getting cached immediately. p2 = Parent.objects.create(name="Parent 2") c.parent = p2 self.assertTrue(c.parent is p2) # Assigning None succeeds if field is null=True. p.bestchild = None self.assertTrue(p.bestchild is None) # bestchild should still be None after saving. p.save() self.assertTrue(p.bestchild is None) # bestchild should still be None after fetching the object again. p = Parent.objects.get(name="Parent") self.assertTrue(p.bestchild is None) # Assigning None fails: Child.parent is null=False. self.assertRaises(ValueError, setattr, c, "parent", None) # You also can't assign an object of the wrong type here self.assertRaises(ValueError, setattr, c, "parent", First(id=1, second=1)) # Nor can you explicitly assign None to Child.parent during object # creation (regression for #9649). self.assertRaises(ValueError, Child, name='xyzzy', parent=None) self.assertRaises(ValueError, Child.objects.create, name='xyzzy', parent=None) # Creation using keyword argument should cache the related object. p = Parent.objects.get(name="Parent") c = Child(parent=p) self.assertTrue(c.parent is p) # Creation using keyword argument and unsaved related instance (#8070). p = Parent() c = Child(parent=p) self.assertTrue(c.parent is p) # Creation using attname keyword argument and an id will cause the # related object to be fetched. p = Parent.objects.get(name="Parent") c = Child(parent_id=p.id) self.assertFalse(c.parent is p) self.assertEqual(c.parent, p) def test_multiple_foreignkeys(self): # Test of multiple ForeignKeys to the same model (bug #7125). c1 = Category.objects.create(name='First') c2 = Category.objects.create(name='Second') c3 = Category.objects.create(name='Third') r1 = Record.objects.create(category=c1) r2 = Record.objects.create(category=c1) r3 = Record.objects.create(category=c2) r4 = Record.objects.create(category=c2) r5 = Record.objects.create(category=c3) Relation.objects.create(left=r1, right=r2) Relation.objects.create(left=r3, right=r4) Relation.objects.create(left=r1, right=r3) Relation.objects.create(left=r5, right=r2) Relation.objects.create(left=r3, right=r2) q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second']) self.assertQuerysetEqual(q1, ["<Relation: First - Second>"]) q2 = Category.objects.filter(record__left_set__right__category__name='Second').order_by('name') self.assertQuerysetEqual(q2, ["<Category: First>", "<Category: Second>"]) p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) self.assertRaises(ValueError, Child.objects.create, name="Grandchild", parent=c) def test_fk_instantiation_outside_model(self): # Regression for #12190 -- Should be able to instantiate a FK outside # of a model, and interrogate its related field. cat = models.ForeignKey(Category) self.assertEqual('id', cat.rel.get_related_field().name) def test_relation_unsaved(self): # Test that the <field>_set manager does not join on Null value fields (#17541) Third.objects.create(name='Third 1') Third.objects.create(name='Third 2') th = Third(name="testing") # The object isn't saved an thus the relation field is null - we won't even # execute a query in this case. with self.assertNumQueries(0): self.assertEqual(th.child_set.count(), 0) th.save() # Now the model is saved, so we will need to execute an query. with self.assertNumQueries(1): self.assertEqual(th.child_set.count(), 0) def test_related_null_to_field(self): c1 = Car.objects.create() d1 = Driver.objects.create() self.assertIs(d1.car, None) with self.assertNumQueries(0): self.assertEqual(list(c1.drivers.all()), [])
bsd-3-clause
bnbowman/HlaTools
src/pbhla/amplicons/__init__.py
10
1848
################################################################################# # Copyright (c) 2013, Pacific Biosciences of California, Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of Pacific Biosciences nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY # THIS LICENSE. THIS SOFTWARE IS PROVIDED BY PACIFIC BIOSCIENCES AND ITS # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PACIFIC BIOSCIENCES OR # ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ################################################################################# # Author: Brett Bowman
bsd-3-clause
bitcity/django
django/contrib/gis/gdal/driver.py
526
3260
from ctypes import c_void_p from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi from django.utils import six from django.utils.encoding import force_bytes, force_text class Driver(GDALBase): """ Wraps a GDAL/OGR Data Source Driver. For more information, see the C API source code: http://www.gdal.org/gdal_8h.html - http://www.gdal.org/ogr__api_8h.html """ # Case-insensitive aliases for some GDAL/OGR Drivers. # For a complete list of original driver names see # http://www.gdal.org/ogr_formats.html (vector) # http://www.gdal.org/formats_list.html (raster) _alias = { # vector 'esri': 'ESRI Shapefile', 'shp': 'ESRI Shapefile', 'shape': 'ESRI Shapefile', 'tiger': 'TIGER', 'tiger/line': 'TIGER', # raster 'tiff': 'GTiff', 'tif': 'GTiff', 'jpeg': 'JPEG', 'jpg': 'JPEG', } def __init__(self, dr_input): """ Initializes an GDAL/OGR driver on either a string or integer input. """ if isinstance(dr_input, six.string_types): # If a string name of the driver was passed in self.ensure_registered() # Checking the alias dictionary (case-insensitive) to see if an # alias exists for the given driver. if dr_input.lower() in self._alias: name = self._alias[dr_input.lower()] else: name = dr_input # Attempting to get the GDAL/OGR driver by the string name. for iface in (vcapi, rcapi): driver = iface.get_driver_by_name(force_bytes(name)) if driver: break elif isinstance(dr_input, int): self.ensure_registered() for iface in (vcapi, rcapi): driver = iface.get_driver(dr_input) if driver: break elif isinstance(dr_input, c_void_p): driver = dr_input else: raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % str(type(dr_input))) # Making sure we get a valid pointer to the OGR Driver if not driver: raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % str(dr_input)) self.ptr = driver def __str__(self): return self.name @classmethod def ensure_registered(cls): """ Attempts to register all the data source drivers. """ # Only register all if the driver count is 0 (or else all drivers # will be registered over and over again) if not cls.driver_count(): vcapi.register_all() rcapi.register_all() @classmethod def driver_count(cls): """ Returns the number of GDAL/OGR data source drivers registered. """ return vcapi.get_driver_count() + rcapi.get_driver_count() @property def name(self): """ Returns description/name string for this driver. """ return force_text(rcapi.get_driver_description(self.ptr))
bsd-3-clause
jmiserez/pox
tools/pox-gui.py
2
9886
#!/usr/bin/env python ''' POX GUI This file creates the main application window, sets up the layout and invokes the GUI's widgets. The left panel (log) is used for displaying context-specific information. The right panel (topology) is an interactive display of the topology. @author Kyriakos Zarifis (kyr.zarifis@gmail.com) ''' import struct import sys import getopt from PyQt4 import QtGui, QtCore import gui.log as log import gui.info as info import gui.topology as topology import gui.Popup as Popup import gui.settings as settings from gui.communication import Communication import signal class MainWindow(QtGui.QMainWindow): def usage(self): """Print usage information """ print "Usage: "+sys.argv[0]+" <options> [IP address | default to localhost]" print "Options:" print "-h / --help \tPrint this usage guide" print "-p / --port \tPort to connect to" print "-m / --mininet \tMininet IP address" def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) #Parse options and commandline arguments try: opts, args = getopt.getopt(sys.argv[1:], "hp:m:", ["help","port=","mininet="]) except getopt.GetoptError: print "Option error!" self.usage() sys.exit(2) self.mininet_address = None #Get options self.backend_port = 7790 #GuiMessenger port for opt,arg in opts: if (opt in ("-h","--help")): self.usage() sys.exit(0) elif (opt in ("-p","--port")): self.backend_port = int(arg) elif (opt in ("-m","--mininet")): self.mininet_address = arg else: print "Unhandled option :"+opt sys.exit(2) # Messenger socket: if len(args) >= 1: self.backend_ip = args[0] else: self.backend_ip = "127.0.0.1" # Global Settings self.settings = settings.Settings(self) # Configure layout self.setWindowTitle('POX Graphical User Interface') self.resize(1280, 800) self.statusBar().showMessage('Ready') self.center() self.communication = Communication(self) self.communication.start() self.logWidget = log.LogWidget(self) self.infoWidget = info.InfoWidget(self) self.topoWidget = topology.TopoWidget(self) # Initialize communication with backend messengers #self.topoWidget.topologyView.helloMessenger() self.logWidget.helloMessenger() self.leftvbox = QtGui.QVBoxLayout() self.vSplitter = QtGui.QSplitter(QtCore.Qt.Vertical) self.vSplitter.addWidget(self.infoWidget) # Hide info pane initially, show when needed (e.q. switch query) self.infoWidget.hide() self.vSplitter.addWidget(self.logWidget) self.leftvbox.addWidget(self.vSplitter) self.left = QtGui.QWidget() self.left.setLayout(self.leftvbox) self.rightvbox = QtGui.QVBoxLayout() self.rightvbox.addWidget(self.topoWidget) self.right = QtGui.QWidget() self.right.setLayout(self.rightvbox) self.hSplitter = QtGui.QSplitter(QtCore.Qt.Horizontal) self.hSplitter.addWidget(self.left) self.hSplitter.addWidget(self.right) self.setCentralWidget(self.hSplitter) signal.signal(signal.SIGINT, self.sigint_handler) # Actions start = QtGui.QAction(QtGui.QIcon('gui/icons/logo.png'), 'Start', self) start.setShortcut('Ctrl+S') start.setStatusTip('Start POX') self.connect(start, QtCore.SIGNAL('triggered()'), self.start_nox) switch_to_log = QtGui.QAction(QtGui.QIcon('gui/icons/log.png'),'Log View',self) switch_to_log.setShortcut('Ctrl+1') switch_to_log.setStatusTip('Switch to system log view') self.connect(switch_to_log, QtCore.SIGNAL('triggered()'), self.show_log) switch_to_topo = QtGui.QAction(QtGui.QIcon('gui/icons/topo.png'),'Topology View',self) switch_to_topo.setShortcut('Ctrl+2') switch_to_topo.setStatusTip('Switch to topology view') self.connect(switch_to_topo, QtCore.SIGNAL('triggered()'), self.show_topo) switch_to_split = QtGui.QAction(QtGui.QIcon('gui/icons/split.png'),'Split View',self) switch_to_split.setShortcut('Ctrl+3') switch_to_split.setStatusTip('Switch to split view') self.connect(switch_to_split, QtCore.SIGNAL('triggered()'), self.show_split) exit = QtGui.QAction(QtGui.QIcon('gui/icons/exit.png'), 'Exit', self) exit.setShortcut('Ctrl+Q') exit.setStatusTip('Exit application') self.connect(exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()')) switch_to_dark = QtGui.QAction('Dark',self) switch_to_dark.setStatusTip('Switch to dark color theme') self.connect(switch_to_dark, QtCore.SIGNAL('triggered()'), self.dark) switch_to_bright = QtGui.QAction('Bright',self) switch_to_bright.setStatusTip('Switch to bright color theme') self.connect(switch_to_bright, QtCore.SIGNAL('triggered()'), self.bright) set_node_id_size_small = QtGui.QAction('Small',self) set_node_id_size_small.setStatusTip('Set node ID fonts to small') self.connect(set_node_id_size_small, QtCore.SIGNAL('triggered()'), \ self.settings.set_node_id_size_small) set_node_id_size_normal = QtGui.QAction('Normal',self) set_node_id_size_normal.setStatusTip('Set node ID fonts to small') self.connect(set_node_id_size_normal, QtCore.SIGNAL('triggered()'), \ self.settings.set_node_id_size_normal) set_node_id_size_large = QtGui.QAction('Large',self) set_node_id_size_large.setStatusTip('Set node ID fonts to small') self.connect(set_node_id_size_large, QtCore.SIGNAL('triggered()'), \ self.settings.set_node_id_size_large) self.statusBar() # Configure Menubar menubar = self.menuBar() file_menu = menubar.addMenu('&File') file_menu.addAction(start) file_menu.addAction(exit) view_menu = menubar.addMenu('&View') view_menu.addAction(switch_to_log) view_menu.addAction(switch_to_topo) view_menu.addAction(switch_to_split) id_size_menu = view_menu.addMenu('ID size') id_size_menu.addAction(set_node_id_size_small) id_size_menu.addAction(set_node_id_size_normal) id_size_menu.addAction(set_node_id_size_large) components_menu = menubar.addMenu('&Components') components_menu.addAction('Installed Components') components_menu.addAction('Active Components') #''' theme_menu = menubar.addMenu('&Colors') theme_menu.addAction(switch_to_dark) theme_menu.addAction(switch_to_bright) #''' help_menu = menubar.addMenu('&Help') help_menu.addAction('Help') help_menu.addAction('About') # Configure Toolbar toolbar = self.addToolBar('Exit') toolbar.addAction(start) toolbar.addAction(switch_to_log) toolbar.addAction(switch_to_topo) toolbar.addAction(switch_to_split) toolbar.addAction(exit) def center(self): screen = QtGui.QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) def sigint_handler(self, signal, frame): sys.exit(0) def closeEvent(self, event): ''' reply = QtGui.QMessageBox.question(self, 'Exit NOX', "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: # Close log DB self.logWidget.dbWrapper.closeDb() # Close log message communication interface # Close topology communication interface self.topoWidget.topologyView.topologyInterface.shutdown() event.accept() else: event.ignore() ''' """ self.logWidget.logInterface.stop_serving() self.logWidget.logInterface.shutdown() self.logWidget.logInterface.quit() self.logWidget.logInterface.exit() """ self.topoWidget.topologyView.topologyInterface.shutdown() self.logWidget.dbWrapper.closeDb() def start_nox(self): popup = Popup.StartComboBox(self) popup.exec_() def show_log(self): self.right.hide() self.left.show() def show_topo(self): self.right.show() self.left.hide() def show_split(self): self.right.show() self.left.show() def dark(self): # Change Log colors self.logWidget.logDisplay.setStyleSheet("background-color: \ black; color: green") # Change Topology colors self.topoWidget.topologyView.setStyleSheet("background: black") #self.topoWidget.topologyView.update() # stupid way to refresh background color: self.topoWidget.topologyView.scaleView(0.5) self.topoWidget.topologyView.scaleView(2) def bright(self): # Change Topology colors self.logWidget.logDisplay.setStyleSheet("background-color: white; \ color: black") # Change Topology colors self.topoWidget.topologyView.setStyleSheet("background: white") #self.topoWidget.topologyView.update() self.topoWidget.topologyView.scaleView(0.5) self.topoWidget.topologyView.scaleView(2) app = QtGui.QApplication(sys.argv) app.setWindowIcon(QtGui.QIcon('gui/icons/logo.ico')) noxgui = MainWindow() noxgui.show() sys.exit(app.exec_())
gpl-3.0
porcobosso/spark-ec2
lib/boto-2.34.0/tests/unit/s3/test_website.py
114
9219
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # from tests.unit import unittest import xml.dom.minidom import xml.sax from boto.s3.website import WebsiteConfiguration from boto.s3.website import RedirectLocation from boto.s3.website import RoutingRules from boto.s3.website import Condition from boto.s3.website import RoutingRules from boto.s3.website import RoutingRule from boto.s3.website import Redirect from boto import handler def pretty_print_xml(text): text = ''.join(t.strip() for t in text.splitlines()) x = xml.dom.minidom.parseString(text) return x.toprettyxml() class TestS3WebsiteConfiguration(unittest.TestCase): maxDiff = None def setUp(self): pass def tearDown(self): pass def test_suffix_only(self): config = WebsiteConfiguration(suffix='index.html') xml = config.to_xml() self.assertIn( '<IndexDocument><Suffix>index.html</Suffix></IndexDocument>', xml) def test_suffix_and_error(self): config = WebsiteConfiguration(suffix='index.html', error_key='error.html') xml = config.to_xml() self.assertIn( '<ErrorDocument><Key>error.html</Key></ErrorDocument>', xml) def test_redirect_all_request_to_with_just_host(self): location = RedirectLocation(hostname='example.com') config = WebsiteConfiguration(redirect_all_requests_to=location) xml = config.to_xml() self.assertIn( ('<RedirectAllRequestsTo><HostName>' 'example.com</HostName></RedirectAllRequestsTo>'), xml) def test_redirect_all_requests_with_protocol(self): location = RedirectLocation(hostname='example.com', protocol='https') config = WebsiteConfiguration(redirect_all_requests_to=location) xml = config.to_xml() self.assertIn( ('<RedirectAllRequestsTo><HostName>' 'example.com</HostName><Protocol>https</Protocol>' '</RedirectAllRequestsTo>'), xml) def test_routing_rules_key_prefix(self): x = pretty_print_xml # This rule redirects requests for docs/* to documentation/* rules = RoutingRules() condition = Condition(key_prefix='docs/') redirect = Redirect(replace_key_prefix='documents/') rules.add_rule(RoutingRule(condition, redirect)) config = WebsiteConfiguration(suffix='index.html', routing_rules=rules) xml = config.to_xml() expected_xml = """<?xml version="1.0" encoding="UTF-8"?> <WebsiteConfiguration xmlns='http://s3.amazonaws.com/doc/2006-03-01/'> <IndexDocument> <Suffix>index.html</Suffix> </IndexDocument> <RoutingRules> <RoutingRule> <Condition> <KeyPrefixEquals>docs/</KeyPrefixEquals> </Condition> <Redirect> <ReplaceKeyPrefixWith>documents/</ReplaceKeyPrefixWith> </Redirect> </RoutingRule> </RoutingRules> </WebsiteConfiguration> """ self.assertEqual(x(expected_xml), x(xml)) def test_routing_rules_to_host_on_404(self): x = pretty_print_xml # Another example from the docs: # Redirect requests to a specific host in the event of a 404. # Also, the redirect inserts a report-404/. For example, # if you request a page ExamplePage.html and it results # in a 404, the request is routed to a page report-404/ExamplePage.html rules = RoutingRules() condition = Condition(http_error_code=404) redirect = Redirect(hostname='example.com', replace_key_prefix='report-404/') rules.add_rule(RoutingRule(condition, redirect)) config = WebsiteConfiguration(suffix='index.html', routing_rules=rules) xml = config.to_xml() expected_xml = """<?xml version="1.0" encoding="UTF-8"?> <WebsiteConfiguration xmlns='http://s3.amazonaws.com/doc/2006-03-01/'> <IndexDocument> <Suffix>index.html</Suffix> </IndexDocument> <RoutingRules> <RoutingRule> <Condition> <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals> </Condition> <Redirect> <HostName>example.com</HostName> <ReplaceKeyPrefixWith>report-404/</ReplaceKeyPrefixWith> </Redirect> </RoutingRule> </RoutingRules> </WebsiteConfiguration> """ self.assertEqual(x(expected_xml), x(xml)) def test_key_prefix(self): x = pretty_print_xml rules = RoutingRules() condition = Condition(key_prefix="images/") redirect = Redirect(replace_key='folderdeleted.html') rules.add_rule(RoutingRule(condition, redirect)) config = WebsiteConfiguration(suffix='index.html', routing_rules=rules) xml = config.to_xml() expected_xml = """<?xml version="1.0" encoding="UTF-8"?> <WebsiteConfiguration xmlns='http://s3.amazonaws.com/doc/2006-03-01/'> <IndexDocument> <Suffix>index.html</Suffix> </IndexDocument> <RoutingRules> <RoutingRule> <Condition> <KeyPrefixEquals>images/</KeyPrefixEquals> </Condition> <Redirect> <ReplaceKeyWith>folderdeleted.html</ReplaceKeyWith> </Redirect> </RoutingRule> </RoutingRules> </WebsiteConfiguration> """ self.assertEqual(x(expected_xml), x(xml)) def test_builders(self): x = pretty_print_xml # This is a more declarative way to create rules. # First the long way. rules = RoutingRules() condition = Condition(http_error_code=404) redirect = Redirect(hostname='example.com', replace_key_prefix='report-404/') rules.add_rule(RoutingRule(condition, redirect)) xml = rules.to_xml() # Then the more concise way. rules2 = RoutingRules().add_rule( RoutingRule.when(http_error_code=404).then_redirect( hostname='example.com', replace_key_prefix='report-404/')) xml2 = rules2.to_xml() self.assertEqual(x(xml), x(xml2)) def test_parse_xml(self): x = pretty_print_xml xml_in = """<?xml version="1.0" encoding="UTF-8"?> <WebsiteConfiguration xmlns='http://s3.amazonaws.com/doc/2006-03-01/'> <IndexDocument> <Suffix>index.html</Suffix> </IndexDocument> <ErrorDocument> <Key>error.html</Key> </ErrorDocument> <RoutingRules> <RoutingRule> <Condition> <KeyPrefixEquals>docs/</KeyPrefixEquals> </Condition> <Redirect> <Protocol>https</Protocol> <HostName>www.example.com</HostName> <ReplaceKeyWith>documents/</ReplaceKeyWith> <HttpRedirectCode>302</HttpRedirectCode> </Redirect> </RoutingRule> <RoutingRule> <Condition> <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals> </Condition> <Redirect> <HostName>example.com</HostName> <ReplaceKeyPrefixWith>report-404/</ReplaceKeyPrefixWith> </Redirect> </RoutingRule> </RoutingRules> </WebsiteConfiguration> """ webconfig = WebsiteConfiguration() h = handler.XmlHandler(webconfig, None) xml.sax.parseString(xml_in.encode('utf-8'), h) xml_out = webconfig.to_xml() self.assertEqual(x(xml_in), x(xml_out))
apache-2.0
NicCOConnor/ansible-modules-extras
cloud/cloudstack/cs_portforward.py
31
13774
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2015, René Moser <mail@renemoser.net> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: cs_portforward short_description: Manages port forwarding rules on Apache CloudStack based clouds. description: - Create, update and remove port forwarding rules. version_added: '2.0' author: "René Moser (@resmo)" options: ip_address: description: - Public IP address the rule is assigned to. required: true vm: description: - Name of virtual machine which we make the port forwarding rule for. - Required if C(state=present). required: false default: null state: description: - State of the port forwarding rule. required: false default: 'present' choices: [ 'present', 'absent' ] protocol: description: - Protocol of the port forwarding rule. required: false default: 'tcp' choices: [ 'tcp', 'udp' ] public_port: description: - Start public port for this rule. required: true public_end_port: description: - End public port for this rule. - If not specified equal C(public_port). required: false default: null private_port: description: - Start private port for this rule. required: true private_end_port: description: - End private port for this rule. - If not specified equal C(private_port). required: false default: null open_firewall: description: - Whether the firewall rule for public port should be created, while creating the new rule. - Use M(cs_firewall) for managing firewall rules. required: false default: false vm_guest_ip: description: - VM guest NIC secondary IP address for the port forwarding rule. required: false default: false domain: description: - Domain the C(vm) is related to. required: false default: null account: description: - Account the C(vm) is related to. required: false default: null project: description: - Name of the project the C(vm) is located in. required: false default: null zone: description: - Name of the zone in which the virtual machine is in. - If not set, default zone is used. required: false default: null poll_async: description: - Poll async jobs until job has finished. required: false default: true extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' # 1.2.3.4:80 -> web01:8080 - local_action: module: cs_portforward ip_address: 1.2.3.4 vm: web01 public_port: 80 private_port: 8080 # forward SSH and open firewall - local_action: module: cs_portforward ip_address: '{{ public_ip }}' vm: '{{ inventory_hostname }}' public_port: '{{ ansible_ssh_port }}' private_port: 22 open_firewall: true # forward DNS traffic, but do not open firewall - local_action: module: cs_portforward ip_address: 1.2.3.4 vm: '{{ inventory_hostname }}' public_port: 53 private_port: 53 protocol: udp # remove ssh port forwarding - local_action: module: cs_portforward ip_address: 1.2.3.4 public_port: 22 private_port: 22 state: absent ''' RETURN = ''' --- id: description: UUID of the public IP address. returned: success type: string sample: a6f7a5fc-43f8-11e5-a151-feff819cdc9f ip_address: description: Public IP address. returned: success type: string sample: 1.2.3.4 protocol: description: Protocol. returned: success type: string sample: tcp private_port: description: Start port on the virtual machine's IP address. returned: success type: int sample: 80 private_end_port: description: End port on the virtual machine's IP address. returned: success type: int public_port: description: Start port on the public IP address. returned: success type: int sample: 80 public_end_port: description: End port on the public IP address. returned: success type: int sample: 80 tags: description: Tags related to the port forwarding. returned: success type: list sample: [] vm_name: description: Name of the virtual machine. returned: success type: string sample: web-01 vm_display_name: description: Display name of the virtual machine. returned: success type: string sample: web-01 vm_guest_ip: description: IP of the virtual machine. returned: success type: string sample: 10.101.65.152 ''' try: from cs import CloudStack, CloudStackException, read_config has_lib_cs = True except ImportError: has_lib_cs = False # import cloudstack common from ansible.module_utils.cloudstack import * class AnsibleCloudStackPortforwarding(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackPortforwarding, self).__init__(module) self.returns = { 'virtualmachinedisplayname': 'vm_display_name', 'virtualmachinename': 'vm_name', 'ipaddress': 'ip_address', 'vmguestip': 'vm_guest_ip', 'publicip': 'public_ip', 'protocol': 'protocol', } # these values will be casted to int self.returns_to_int = { 'publicport': 'public_port', 'publicendport': 'public_end_port', 'privateport': 'private_port', 'privateendport': 'private_end_port', } self.portforwarding_rule = None self.vm_default_nic = None def get_vm_guest_ip(self): vm_guest_ip = self.module.params.get('vm_guest_ip') default_nic = self.get_vm_default_nic() if not vm_guest_ip: return default_nic['ipaddress'] for secondary_ip in default_nic['secondaryip']: if vm_guest_ip == secondary_ip['ipaddress']: return vm_guest_ip self.module.fail_json(msg="Secondary IP '%s' not assigned to VM" % vm_guest_ip) def get_vm_default_nic(self): if self.vm_default_nic: return self.vm_default_nic nics = self.cs.listNics(virtualmachineid=self.get_vm(key='id')) if nics: for n in nics['nic']: if n['isdefault']: self.vm_default_nic = n return self.vm_default_nic self.module.fail_json(msg="No default IP address of VM '%s' found" % self.module.params.get('vm')) def get_portforwarding_rule(self): if not self.portforwarding_rule: protocol = self.module.params.get('protocol') public_port = self.module.params.get('public_port') public_end_port = self.get_or_fallback('public_end_port', 'public_port') private_port = self.module.params.get('private_port') private_end_port = self.get_or_fallback('private_end_port', 'private_port') args = {} args['ipaddressid'] = self.get_ip_address(key='id') args['projectid'] = self.get_project(key='id') portforwarding_rules = self.cs.listPortForwardingRules(**args) if portforwarding_rules and 'portforwardingrule' in portforwarding_rules: for rule in portforwarding_rules['portforwardingrule']: if protocol == rule['protocol'] \ and public_port == int(rule['publicport']): self.portforwarding_rule = rule break return self.portforwarding_rule def present_portforwarding_rule(self): portforwarding_rule = self.get_portforwarding_rule() if portforwarding_rule: portforwarding_rule = self.update_portforwarding_rule(portforwarding_rule) else: portforwarding_rule = self.create_portforwarding_rule() return portforwarding_rule def create_portforwarding_rule(self): args = {} args['protocol'] = self.module.params.get('protocol') args['publicport'] = self.module.params.get('public_port') args['publicendport'] = self.get_or_fallback('public_end_port', 'public_port') args['privateport'] = self.module.params.get('private_port') args['privateendport'] = self.get_or_fallback('private_end_port', 'private_port') args['openfirewall'] = self.module.params.get('open_firewall') args['vmguestip'] = self.get_vm_guest_ip() args['ipaddressid'] = self.get_ip_address(key='id') args['virtualmachineid'] = self.get_vm(key='id') portforwarding_rule = None self.result['changed'] = True if not self.module.check_mode: portforwarding_rule = self.cs.createPortForwardingRule(**args) poll_async = self.module.params.get('poll_async') if poll_async: portforwarding_rule = self._poll_job(portforwarding_rule, 'portforwardingrule') return portforwarding_rule def update_portforwarding_rule(self, portforwarding_rule): args = {} args['protocol'] = self.module.params.get('protocol') args['publicport'] = self.module.params.get('public_port') args['publicendport'] = self.get_or_fallback('public_end_port', 'public_port') args['privateport'] = self.module.params.get('private_port') args['privateendport'] = self.get_or_fallback('private_end_port', 'private_port') args['vmguestip'] = self.get_vm_guest_ip() args['ipaddressid'] = self.get_ip_address(key='id') args['virtualmachineid'] = self.get_vm(key='id') if self._has_changed(args, portforwarding_rule): self.result['changed'] = True if not self.module.check_mode: # API broken in 4.2.1?, workaround using remove/create instead of update # portforwarding_rule = self.cs.updatePortForwardingRule(**args) self.absent_portforwarding_rule() portforwarding_rule = self.cs.createPortForwardingRule(**args) poll_async = self.module.params.get('poll_async') if poll_async: portforwarding_rule = self._poll_job(portforwarding_rule, 'portforwardingrule') return portforwarding_rule def absent_portforwarding_rule(self): portforwarding_rule = self.get_portforwarding_rule() if portforwarding_rule: self.result['changed'] = True args = {} args['id'] = portforwarding_rule['id'] if not self.module.check_mode: res = self.cs.deletePortForwardingRule(**args) poll_async = self.module.params.get('poll_async') if poll_async: self._poll_job(res, 'portforwardingrule') return portforwarding_rule def get_result(self, portforwarding_rule): super(AnsibleCloudStackPortforwarding, self).get_result(portforwarding_rule) if portforwarding_rule: # Bad bad API does not always return int when it should. for search_key, return_key in self.returns_to_int.iteritems(): if search_key in portforwarding_rule: self.result[return_key] = int(portforwarding_rule[search_key]) return self.result def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( ip_address = dict(required=True), protocol= dict(choices=['tcp', 'udp'], default='tcp'), public_port = dict(type='int', required=True), public_end_port = dict(type='int', default=None), private_port = dict(type='int', required=True), private_end_port = dict(type='int', default=None), state = dict(choices=['present', 'absent'], default='present'), open_firewall = dict(type='bool', default=False), vm_guest_ip = dict(default=None), vm = dict(default=None), zone = dict(default=None), domain = dict(default=None), account = dict(default=None), project = dict(default=None), poll_async = dict(type='bool', default=True), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True ) if not has_lib_cs: module.fail_json(msg="python library cs required: pip install cs") try: acs_pf = AnsibleCloudStackPortforwarding(module) state = module.params.get('state') if state in ['absent']: pf_rule = acs_pf.absent_portforwarding_rule() else: pf_rule = acs_pf.present_portforwarding_rule() result = acs_pf.get_result(pf_rule) except CloudStackException as e: module.fail_json(msg='CloudStackException: %s' % str(e)) module.exit_json(**result) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
yoghadj/or-tools
examples/python/nonogram_table2.py
34
6833
# Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Nonogram (Painting by numbers) in Google CP Solver. http://en.wikipedia.org/wiki/Nonogram ''' Nonograms or Paint by Numbers are picture logic puzzles in which cells in a grid have to be colored or left blank according to numbers given at the side of the grid to reveal a hidden picture. In this puzzle type, the numbers measure how many unbroken lines of filled-in squares there are in any given row or column. For example, a clue of '4 8 3' would mean there are sets of four, eight, and three filled squares, in that order, with at least one blank square between successive groups. ''' See problem 12 at http://www.csplib.org/. http://www.puzzlemuseum.com/nonogram.htm Haskell solution: http://twan.home.fmf.nl/blog/haskell/Nonograms.details Brunetti, Sara & Daurat, Alain (2003) 'An algorithm reconstructing convex lattice sets' http://geodisi.u-strasbg.fr/~daurat/papiers/tomoqconv.pdf The Comet model (http://www.hakank.org/comet/nonogram_regular.co) was a major influence when writing this Google CP solver model. I have also blogged about the development of a Nonogram solver in Comet using the regular constraint. * 'Comet: Nonogram improved: solving problem P200 from 1:30 minutes to about 1 second' http://www.hakank.org/constraint_programming_blog/2009/03/comet_nonogram_improved_solvin_1.html * 'Comet: regular constraint, a much faster Nonogram with the regular constraint, some OPL models, and more' http://www.hakank.org/constraint_programming_blog/2009/02/comet_regular_constraint_a_muc_1.html Compare with the other models: * Gecode/R: http://www.hakank.org/gecode_r/nonogram.rb (using 'regexps') * MiniZinc: http://www.hakank.org/minizinc/nonogram_regular.mzn * MiniZinc: http://www.hakank.org/minizinc/nonogram_create_automaton.mzn * MiniZinc: http://www.hakank.org/minizinc/nonogram_create_automaton2.mzn Note: nonogram_create_automaton2.mzn is the preferred model This model was created by Hakan Kjellerstrand (hakank@bonetmail.com) Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/ """ import sys from ortools.constraint_solver import pywrapcp # # Make a transition (automaton) list of tuples from a # single pattern, e.g. [3,2,1] # def make_transition_tuples(pattern): p_len = len(pattern) num_states = p_len + sum(pattern) tuples = [] # this is for handling 0-clues. It generates # just the minimal state if num_states == 0: tuples.append((1, 0, 1)) return (tuples, 1) # convert pattern to a 0/1 pattern for easy handling of # the states tmp = [0] c = 0 for pattern_index in range(p_len): tmp.extend([1] * pattern[pattern_index]) tmp.append(0) for i in range(num_states): state = i + 1 if tmp[i] == 0: tuples.append((state, 0, state)) tuples.append((state, 1, state + 1)) else: if i < num_states - 1: if tmp[i + 1] == 1: tuples.append((state, 1, state + 1)) else: tuples.append((state, 0, state + 1)) tuples.append((num_states, 0, num_states)) return (tuples, num_states) # # check each rule by creating an automaton and transition constraint. # def check_rule(rules, y): cleaned_rule = [rules[i] for i in range(len(rules)) if rules[i] > 0] (transition_tuples, last_state) = make_transition_tuples(cleaned_rule) initial_state = 1 accepting_states = [last_state] solver = y[0].solver() solver.Add(solver.TransitionConstraint(y, transition_tuples, initial_state, accepting_states)) def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules): # Create the solver. solver = pywrapcp.Solver('Regular test') # # variables # board = {} for i in range(rows): for j in range(cols): board[i, j] = solver.IntVar(0, 1, 'board[%i, %i]' % (i, j)) board_flat = [board[i, j] for i in range(rows) for j in range(cols)] # Flattened board for labeling. # This labeling was inspired by a suggestion from # Pascal Van Hentenryck about my Comet nonogram model. board_label = [] if rows * row_rule_len < cols * col_rule_len: for i in range(rows): for j in range(cols): board_label.append(board[i, j]) else: for j in range(cols): for i in range(rows): board_label.append(board[i, j]) # # constraints # for i in range(rows): check_rule(row_rules[i], [board[i, j] for j in range(cols)]) for j in range(cols): check_rule(col_rules[j], [board[i, j] for i in range(rows)]) # # solution and search # db = solver.Phase(board_label, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE) print 'before solver, wall time = ', solver.WallTime(), 'ms' solver.NewSearch(db) num_solutions = 0 while solver.NextSolution(): print num_solutions += 1 for i in range(rows): row = [board[i, j].Value() for j in range(cols)] row_pres = [] for j in row: if j == 1: row_pres.append('#') else: row_pres.append(' ') print ' ', ''.join(row_pres) print print ' ', '-' * cols if num_solutions >= 2: print '2 solutions is enough...' break solver.EndSearch() print print 'num_solutions:', num_solutions print 'failures:', solver.Failures() print 'branches:', solver.Branches() print 'WallTime:', solver.WallTime(), 'ms' # # Default problem # # From http://twan.home.fmf.nl/blog/haskell/Nonograms.details # The lambda picture # rows = 12 row_rule_len = 3 row_rules = [ [0, 0, 2], [0, 1, 2], [0, 1, 1], [0, 0, 2], [0, 0, 1], [0, 0, 3], [0, 0, 3], [0, 2, 2], [0, 2, 1], [2, 2, 1], [0, 2, 3], [0, 2, 2] ] cols = 10 col_rule_len = 2 col_rules = [ [2, 1], [1, 3], [2, 4], [3, 4], [0, 4], [0, 3], [0, 3], [0, 3], [0, 2], [0, 2] ] if __name__ == '__main__': if len(sys.argv) > 1: file = sys.argv[1] execfile(file) main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules)
apache-2.0
dongjoon-hyun/spark
python/pyspark/mllib/linalg/__init__.py
15
46746
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ MLlib utilities for linear algebra. For dense vectors, MLlib uses the NumPy `array` type, so you can simply pass NumPy arrays around. For sparse vectors, users can construct a :class:`SparseVector` object from MLlib or pass SciPy `scipy.sparse` column vectors if SciPy is available in their environment. """ import sys import array import struct import numpy as np from pyspark import since from pyspark.ml import linalg as newlinalg from pyspark.sql.types import UserDefinedType, StructField, StructType, ArrayType, DoubleType, \ IntegerType, ByteType, BooleanType __all__ = ['Vector', 'DenseVector', 'SparseVector', 'Vectors', 'Matrix', 'DenseMatrix', 'SparseMatrix', 'Matrices', 'QRDecomposition'] # Check whether we have SciPy. MLlib works without it too, but if we have it, some methods, # such as _dot and _serialize_double_vector, start to support scipy.sparse matrices. try: import scipy.sparse _have_scipy = True except: # No SciPy in environment, but that's okay _have_scipy = False def _convert_to_vector(l): if isinstance(l, Vector): return l elif type(l) in (array.array, np.array, np.ndarray, list, tuple, range): return DenseVector(l) elif _have_scipy and scipy.sparse.issparse(l): assert l.shape[1] == 1, "Expected column vector" # Make sure the converted csc_matrix has sorted indices. csc = l.tocsc() if not csc.has_sorted_indices: csc.sort_indices() return SparseVector(l.shape[0], csc.indices, csc.data) else: raise TypeError("Cannot convert type %s into Vector" % type(l)) def _vector_size(v): """ Returns the size of the vector. Examples -------- >>> _vector_size([1., 2., 3.]) 3 >>> _vector_size((1., 2., 3.)) 3 >>> _vector_size(array.array('d', [1., 2., 3.])) 3 >>> _vector_size(np.zeros(3)) 3 >>> _vector_size(np.zeros((3, 1))) 3 >>> _vector_size(np.zeros((1, 3))) Traceback (most recent call last): ... ValueError: Cannot treat an ndarray of shape (1, 3) as a vector """ if isinstance(v, Vector): return len(v) elif type(v) in (array.array, list, tuple, range): return len(v) elif type(v) == np.ndarray: if v.ndim == 1 or (v.ndim == 2 and v.shape[1] == 1): return len(v) else: raise ValueError("Cannot treat an ndarray of shape %s as a vector" % str(v.shape)) elif _have_scipy and scipy.sparse.issparse(v): assert v.shape[1] == 1, "Expected column vector" return v.shape[0] else: raise TypeError("Cannot treat type %s as a vector" % type(v)) def _format_float(f, digits=4): s = str(round(f, digits)) if '.' in s: s = s[:s.index('.') + 1 + digits] return s def _format_float_list(l): return [_format_float(x) for x in l] def _double_to_long_bits(value): if np.isnan(value): value = float('nan') # pack double into 64 bits, then unpack as long int return struct.unpack('Q', struct.pack('d', value))[0] class VectorUDT(UserDefinedType): """ SQL user-defined type (UDT) for Vector. """ @classmethod def sqlType(cls): return StructType([ StructField("type", ByteType(), False), StructField("size", IntegerType(), True), StructField("indices", ArrayType(IntegerType(), False), True), StructField("values", ArrayType(DoubleType(), False), True)]) @classmethod def module(cls): return "pyspark.mllib.linalg" @classmethod def scalaUDT(cls): return "org.apache.spark.mllib.linalg.VectorUDT" def serialize(self, obj): if isinstance(obj, SparseVector): indices = [int(i) for i in obj.indices] values = [float(v) for v in obj.values] return (0, obj.size, indices, values) elif isinstance(obj, DenseVector): values = [float(v) for v in obj] return (1, None, None, values) else: raise TypeError("cannot serialize %r of type %r" % (obj, type(obj))) def deserialize(self, datum): assert len(datum) == 4, \ "VectorUDT.deserialize given row with length %d but requires 4" % len(datum) tpe = datum[0] if tpe == 0: return SparseVector(datum[1], datum[2], datum[3]) elif tpe == 1: return DenseVector(datum[3]) else: raise ValueError("do not recognize type %r" % tpe) def simpleString(self): return "vector" class MatrixUDT(UserDefinedType): """ SQL user-defined type (UDT) for Matrix. """ @classmethod def sqlType(cls): return StructType([ StructField("type", ByteType(), False), StructField("numRows", IntegerType(), False), StructField("numCols", IntegerType(), False), StructField("colPtrs", ArrayType(IntegerType(), False), True), StructField("rowIndices", ArrayType(IntegerType(), False), True), StructField("values", ArrayType(DoubleType(), False), True), StructField("isTransposed", BooleanType(), False)]) @classmethod def module(cls): return "pyspark.mllib.linalg" @classmethod def scalaUDT(cls): return "org.apache.spark.mllib.linalg.MatrixUDT" def serialize(self, obj): if isinstance(obj, SparseMatrix): colPtrs = [int(i) for i in obj.colPtrs] rowIndices = [int(i) for i in obj.rowIndices] values = [float(v) for v in obj.values] return (0, obj.numRows, obj.numCols, colPtrs, rowIndices, values, bool(obj.isTransposed)) elif isinstance(obj, DenseMatrix): values = [float(v) for v in obj.values] return (1, obj.numRows, obj.numCols, None, None, values, bool(obj.isTransposed)) else: raise TypeError("cannot serialize type %r" % (type(obj))) def deserialize(self, datum): assert len(datum) == 7, \ "MatrixUDT.deserialize given row with length %d but requires 7" % len(datum) tpe = datum[0] if tpe == 0: return SparseMatrix(*datum[1:]) elif tpe == 1: return DenseMatrix(datum[1], datum[2], datum[5], datum[6]) else: raise ValueError("do not recognize type %r" % tpe) def simpleString(self): return "matrix" class Vector(object): __UDT__ = VectorUDT() """ Abstract class for DenseVector and SparseVector """ def toArray(self): """ Convert the vector into an numpy.ndarray Returns ------- :py:class:`numpy.ndarray` """ raise NotImplementedError def asML(self): """ Convert this vector to the new mllib-local representation. This does NOT copy the data; it copies references. Returns ------- :py:class:`pyspark.ml.linalg.Vector` """ raise NotImplementedError class DenseVector(Vector): """ A dense vector represented by a value array. We use numpy array for storage and arithmetics will be delegated to the underlying numpy array. Examples -------- >>> v = Vectors.dense([1.0, 2.0]) >>> u = Vectors.dense([3.0, 4.0]) >>> v + u DenseVector([4.0, 6.0]) >>> 2 - v DenseVector([1.0, 0.0]) >>> v / 2 DenseVector([0.5, 1.0]) >>> v * u DenseVector([3.0, 8.0]) >>> u / v DenseVector([3.0, 2.0]) >>> u % 2 DenseVector([1.0, 0.0]) >>> -v DenseVector([-1.0, -2.0]) """ def __init__(self, ar): if isinstance(ar, bytes): ar = np.frombuffer(ar, dtype=np.float64) elif not isinstance(ar, np.ndarray): ar = np.array(ar, dtype=np.float64) if ar.dtype != np.float64: ar = ar.astype(np.float64) self.array = ar @staticmethod def parse(s): """ Parse string representation back into the DenseVector. Examples -------- >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]') DenseVector([0.0, 1.0, 2.0, 3.0]) """ start = s.find('[') if start == -1: raise ValueError("Array should start with '['.") end = s.find(']') if end == -1: raise ValueError("Array should end with ']'.") s = s[start + 1: end] try: values = [float(val) for val in s.split(',') if val] except ValueError: raise ValueError("Unable to parse values from %s" % s) return DenseVector(values) def __reduce__(self): return DenseVector, (self.array.tostring(),) def numNonzeros(self): """ Number of nonzero elements. This scans all active values and count non zeros """ return np.count_nonzero(self.array) def norm(self, p): """ Calculates the norm of a DenseVector. Examples -------- >>> a = DenseVector([0, -1, 2, -3]) >>> a.norm(2) 3.7... >>> a.norm(1) 6.0 """ return np.linalg.norm(self.array, p) def dot(self, other): """ Compute the dot product of two Vectors. We support (Numpy array, list, SparseVector, or SciPy sparse) and a target NumPy array that is either 1- or 2-dimensional. Equivalent to calling numpy.dot of the two vectors. Examples -------- >>> dense = DenseVector(array.array('d', [1., 2.])) >>> dense.dot(dense) 5.0 >>> dense.dot(SparseVector(2, [0, 1], [2., 1.])) 4.0 >>> dense.dot(range(1, 3)) 5.0 >>> dense.dot(np.array(range(1, 3))) 5.0 >>> dense.dot([1.,]) Traceback (most recent call last): ... AssertionError: dimension mismatch >>> dense.dot(np.reshape([1., 2., 3., 4.], (2, 2), order='F')) array([ 5., 11.]) >>> dense.dot(np.reshape([1., 2., 3.], (3, 1), order='F')) Traceback (most recent call last): ... AssertionError: dimension mismatch """ if type(other) == np.ndarray: if other.ndim > 1: assert len(self) == other.shape[0], "dimension mismatch" return np.dot(self.array, other) elif _have_scipy and scipy.sparse.issparse(other): assert len(self) == other.shape[0], "dimension mismatch" return other.transpose().dot(self.toArray()) else: assert len(self) == _vector_size(other), "dimension mismatch" if isinstance(other, SparseVector): return other.dot(self) elif isinstance(other, Vector): return np.dot(self.toArray(), other.toArray()) else: return np.dot(self.toArray(), other) def squared_distance(self, other): """ Squared distance of two Vectors. Examples -------- >>> dense1 = DenseVector(array.array('d', [1., 2.])) >>> dense1.squared_distance(dense1) 0.0 >>> dense2 = np.array([2., 1.]) >>> dense1.squared_distance(dense2) 2.0 >>> dense3 = [2., 1.] >>> dense1.squared_distance(dense3) 2.0 >>> sparse1 = SparseVector(2, [0, 1], [2., 1.]) >>> dense1.squared_distance(sparse1) 2.0 >>> dense1.squared_distance([1.,]) Traceback (most recent call last): ... AssertionError: dimension mismatch >>> dense1.squared_distance(SparseVector(1, [0,], [1.,])) Traceback (most recent call last): ... AssertionError: dimension mismatch """ assert len(self) == _vector_size(other), "dimension mismatch" if isinstance(other, SparseVector): return other.squared_distance(self) elif _have_scipy and scipy.sparse.issparse(other): return _convert_to_vector(other).squared_distance(self) if isinstance(other, Vector): other = other.toArray() elif not isinstance(other, np.ndarray): other = np.array(other) diff = self.toArray() - other return np.dot(diff, diff) def toArray(self): """ Returns an numpy.ndarray """ return self.array def asML(self): """ Convert this vector to the new mllib-local representation. This does NOT copy the data; it copies references. .. versionadded:: 2.0.0 Returns ------- :py:class:`pyspark.ml.linalg.DenseVector` """ return newlinalg.DenseVector(self.array) @property def values(self): """ Returns a list of values """ return self.array def __getitem__(self, item): return self.array[item] def __len__(self): return len(self.array) def __str__(self): return "[" + ",".join([str(v) for v in self.array]) + "]" def __repr__(self): return "DenseVector([%s])" % (', '.join(_format_float(i) for i in self.array)) def __eq__(self, other): if isinstance(other, DenseVector): return np.array_equal(self.array, other.array) elif isinstance(other, SparseVector): if len(self) != other.size: return False return Vectors._equals(list(range(len(self))), self.array, other.indices, other.values) return False def __ne__(self, other): return not self == other def __hash__(self): size = len(self) result = 31 + size nnz = 0 i = 0 while i < size and nnz < 128: if self.array[i] != 0: result = 31 * result + i bits = _double_to_long_bits(self.array[i]) result = 31 * result + (bits ^ (bits >> 32)) nnz += 1 i += 1 return result def __getattr__(self, item): return getattr(self.array, item) def __neg__(self): return DenseVector(-self.array) def _delegate(op): def func(self, other): if isinstance(other, DenseVector): other = other.array return DenseVector(getattr(self.array, op)(other)) return func __add__ = _delegate("__add__") __sub__ = _delegate("__sub__") __mul__ = _delegate("__mul__") __div__ = _delegate("__div__") __truediv__ = _delegate("__truediv__") __mod__ = _delegate("__mod__") __radd__ = _delegate("__radd__") __rsub__ = _delegate("__rsub__") __rmul__ = _delegate("__rmul__") __rdiv__ = _delegate("__rdiv__") __rtruediv__ = _delegate("__rtruediv__") __rmod__ = _delegate("__rmod__") class SparseVector(Vector): """ A simple sparse vector class for passing data to MLlib. Users may alternatively pass SciPy's {scipy.sparse} data types. """ def __init__(self, size, *args): """ Create a sparse vector, using either a dictionary, a list of (index, value) pairs, or two separate arrays of indices and values (sorted by index). Parameters ---------- size : int Size of the vector. args Active entries, as a dictionary {index: value, ...}, a list of tuples [(index, value), ...], or a list of strictly increasing indices and a list of corresponding values [index, ...], [value, ...]. Inactive entries are treated as zeros. Examples -------- >>> SparseVector(4, {1: 1.0, 3: 5.5}) SparseVector(4, {1: 1.0, 3: 5.5}) >>> SparseVector(4, [(1, 1.0), (3, 5.5)]) SparseVector(4, {1: 1.0, 3: 5.5}) >>> SparseVector(4, [1, 3], [1.0, 5.5]) SparseVector(4, {1: 1.0, 3: 5.5}) """ self.size = int(size) """ Size of the vector. """ assert 1 <= len(args) <= 2, "must pass either 2 or 3 arguments" if len(args) == 1: pairs = args[0] if type(pairs) == dict: pairs = pairs.items() pairs = sorted(pairs) self.indices = np.array([p[0] for p in pairs], dtype=np.int32) """ A list of indices corresponding to active entries. """ self.values = np.array([p[1] for p in pairs], dtype=np.float64) """ A list of values corresponding to active entries. """ else: if isinstance(args[0], bytes): assert isinstance(args[1], bytes), "values should be string too" if args[0]: self.indices = np.frombuffer(args[0], np.int32) self.values = np.frombuffer(args[1], np.float64) else: # np.frombuffer() doesn't work well with empty string in older version self.indices = np.array([], dtype=np.int32) self.values = np.array([], dtype=np.float64) else: self.indices = np.array(args[0], dtype=np.int32) self.values = np.array(args[1], dtype=np.float64) assert len(self.indices) == len(self.values), "index and value arrays not same length" for i in range(len(self.indices) - 1): if self.indices[i] >= self.indices[i + 1]: raise TypeError( "Indices %s and %s are not strictly increasing" % (self.indices[i], self.indices[i + 1])) def numNonzeros(self): """ Number of nonzero elements. This scans all active values and count non zeros. """ return np.count_nonzero(self.values) def norm(self, p): """ Calculates the norm of a SparseVector. Examples -------- >>> a = SparseVector(4, [0, 1], [3., -4.]) >>> a.norm(1) 7.0 >>> a.norm(2) 5.0 """ return np.linalg.norm(self.values, p) def __reduce__(self): return ( SparseVector, (self.size, self.indices.tostring(), self.values.tostring())) @staticmethod def parse(s): """ Parse string representation back into the SparseVector. Examples -------- >>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )') SparseVector(4, {0: 4.0, 1: 5.0}) """ start = s.find('(') if start == -1: raise ValueError("Tuple should start with '('") end = s.find(')') if end == -1: raise ValueError("Tuple should end with ')'") s = s[start + 1: end].strip() size = s[: s.find(',')] try: size = int(size) except ValueError: raise ValueError("Cannot parse size %s." % size) ind_start = s.find('[') if ind_start == -1: raise ValueError("Indices array should start with '['.") ind_end = s.find(']') if ind_end == -1: raise ValueError("Indices array should end with ']'") new_s = s[ind_start + 1: ind_end] ind_list = new_s.split(',') try: indices = [int(ind) for ind in ind_list if ind] except ValueError: raise ValueError("Unable to parse indices from %s." % new_s) s = s[ind_end + 1:].strip() val_start = s.find('[') if val_start == -1: raise ValueError("Values array should start with '['.") val_end = s.find(']') if val_end == -1: raise ValueError("Values array should end with ']'.") val_list = s[val_start + 1: val_end].split(',') try: values = [float(val) for val in val_list if val] except ValueError: raise ValueError("Unable to parse values from %s." % s) return SparseVector(size, indices, values) def dot(self, other): """ Dot product with a SparseVector or 1- or 2-dimensional Numpy array. Examples -------- >>> a = SparseVector(4, [1, 3], [3.0, 4.0]) >>> a.dot(a) 25.0 >>> a.dot(array.array('d', [1., 2., 3., 4.])) 22.0 >>> b = SparseVector(4, [2], [1.0]) >>> a.dot(b) 0.0 >>> a.dot(np.array([[1, 1], [2, 2], [3, 3], [4, 4]])) array([ 22., 22.]) >>> a.dot([1., 2., 3.]) Traceback (most recent call last): ... AssertionError: dimension mismatch >>> a.dot(np.array([1., 2.])) Traceback (most recent call last): ... AssertionError: dimension mismatch >>> a.dot(DenseVector([1., 2.])) Traceback (most recent call last): ... AssertionError: dimension mismatch >>> a.dot(np.zeros((3, 2))) Traceback (most recent call last): ... AssertionError: dimension mismatch """ if isinstance(other, np.ndarray): if other.ndim not in [2, 1]: raise ValueError("Cannot call dot with %d-dimensional array" % other.ndim) assert len(self) == other.shape[0], "dimension mismatch" return np.dot(self.values, other[self.indices]) assert len(self) == _vector_size(other), "dimension mismatch" if isinstance(other, DenseVector): return np.dot(other.array[self.indices], self.values) elif isinstance(other, SparseVector): # Find out common indices. self_cmind = np.in1d(self.indices, other.indices, assume_unique=True) self_values = self.values[self_cmind] if self_values.size == 0: return 0.0 else: other_cmind = np.in1d(other.indices, self.indices, assume_unique=True) return np.dot(self_values, other.values[other_cmind]) else: return self.dot(_convert_to_vector(other)) def squared_distance(self, other): """ Squared distance from a SparseVector or 1-dimensional NumPy array. Examples -------- >>> a = SparseVector(4, [1, 3], [3.0, 4.0]) >>> a.squared_distance(a) 0.0 >>> a.squared_distance(array.array('d', [1., 2., 3., 4.])) 11.0 >>> a.squared_distance(np.array([1., 2., 3., 4.])) 11.0 >>> b = SparseVector(4, [2], [1.0]) >>> a.squared_distance(b) 26.0 >>> b.squared_distance(a) 26.0 >>> b.squared_distance([1., 2.]) Traceback (most recent call last): ... AssertionError: dimension mismatch >>> b.squared_distance(SparseVector(3, [1,], [1.0,])) Traceback (most recent call last): ... AssertionError: dimension mismatch """ assert len(self) == _vector_size(other), "dimension mismatch" if isinstance(other, np.ndarray) or isinstance(other, DenseVector): if isinstance(other, np.ndarray) and other.ndim != 1: raise ValueError("Cannot call squared_distance with %d-dimensional array" % other.ndim) if isinstance(other, DenseVector): other = other.array sparse_ind = np.zeros(other.size, dtype=bool) sparse_ind[self.indices] = True dist = other[sparse_ind] - self.values result = np.dot(dist, dist) other_ind = other[~sparse_ind] result += np.dot(other_ind, other_ind) return result elif isinstance(other, SparseVector): result = 0.0 i, j = 0, 0 while i < len(self.indices) and j < len(other.indices): if self.indices[i] == other.indices[j]: diff = self.values[i] - other.values[j] result += diff * diff i += 1 j += 1 elif self.indices[i] < other.indices[j]: result += self.values[i] * self.values[i] i += 1 else: result += other.values[j] * other.values[j] j += 1 while i < len(self.indices): result += self.values[i] * self.values[i] i += 1 while j < len(other.indices): result += other.values[j] * other.values[j] j += 1 return result else: return self.squared_distance(_convert_to_vector(other)) def toArray(self): """ Returns a copy of this SparseVector as a 1-dimensional NumPy array. """ arr = np.zeros((self.size,), dtype=np.float64) arr[self.indices] = self.values return arr def asML(self): """ Convert this vector to the new mllib-local representation. This does NOT copy the data; it copies references. .. versionadded:: 2.0.0 Returns ------- :py:class:`pyspark.ml.linalg.SparseVector` """ return newlinalg.SparseVector(self.size, self.indices, self.values) def __len__(self): return self.size def __str__(self): inds = "[" + ",".join([str(i) for i in self.indices]) + "]" vals = "[" + ",".join([str(v) for v in self.values]) + "]" return "(" + ",".join((str(self.size), inds, vals)) + ")" def __repr__(self): inds = self.indices vals = self.values entries = ", ".join(["{0}: {1}".format(inds[i], _format_float(vals[i])) for i in range(len(inds))]) return "SparseVector({0}, {{{1}}})".format(self.size, entries) def __eq__(self, other): if isinstance(other, SparseVector): return other.size == self.size and np.array_equal(other.indices, self.indices) \ and np.array_equal(other.values, self.values) elif isinstance(other, DenseVector): if self.size != len(other): return False return Vectors._equals(self.indices, self.values, list(range(len(other))), other.array) return False def __getitem__(self, index): inds = self.indices vals = self.values if not isinstance(index, int): raise TypeError( "Indices must be of type integer, got type %s" % type(index)) if index >= self.size or index < -self.size: raise IndexError("Index %d out of bounds." % index) if index < 0: index += self.size if (inds.size == 0) or (index > inds.item(-1)): return 0. insert_index = np.searchsorted(inds, index) row_ind = inds[insert_index] if row_ind == index: return vals[insert_index] return 0. def __ne__(self, other): return not self.__eq__(other) def __hash__(self): result = 31 + self.size nnz = 0 i = 0 while i < len(self.values) and nnz < 128: if self.values[i] != 0: result = 31 * result + int(self.indices[i]) bits = _double_to_long_bits(self.values[i]) result = 31 * result + (bits ^ (bits >> 32)) nnz += 1 i += 1 return result class Vectors(object): """ Factory methods for working with vectors. Notes ----- Dense vectors are simply represented as NumPy array objects, so there is no need to covert them for use in MLlib. For sparse vectors, the factory methods in this class create an MLlib-compatible type, or users can pass in SciPy's `scipy.sparse` column vectors. """ @staticmethod def sparse(size, *args): """ Create a sparse vector, using either a dictionary, a list of (index, value) pairs, or two separate arrays of indices and values (sorted by index). Parameters ---------- size : int Size of the vector. args Non-zero entries, as a dictionary, list of tuples, or two sorted lists containing indices and values. Examples -------- >>> Vectors.sparse(4, {1: 1.0, 3: 5.5}) SparseVector(4, {1: 1.0, 3: 5.5}) >>> Vectors.sparse(4, [(1, 1.0), (3, 5.5)]) SparseVector(4, {1: 1.0, 3: 5.5}) >>> Vectors.sparse(4, [1, 3], [1.0, 5.5]) SparseVector(4, {1: 1.0, 3: 5.5}) """ return SparseVector(size, *args) @staticmethod def dense(*elements): """ Create a dense vector of 64-bit floats from a Python list or numbers. Examples -------- >>> Vectors.dense([1, 2, 3]) DenseVector([1.0, 2.0, 3.0]) >>> Vectors.dense(1.0, 2.0) DenseVector([1.0, 2.0]) """ if len(elements) == 1 and not isinstance(elements[0], (float, int)): # it's list, numpy.array or other iterable object. elements = elements[0] return DenseVector(elements) @staticmethod def fromML(vec): """ Convert a vector from the new mllib-local representation. This does NOT copy the data; it copies references. .. versionadded:: 2.0.0 Parameters ---------- vec : :py:class:`pyspark.ml.linalg.Vector` Returns ------- :py:class:`pyspark.mllib.linalg.Vector` """ if isinstance(vec, newlinalg.DenseVector): return DenseVector(vec.array) elif isinstance(vec, newlinalg.SparseVector): return SparseVector(vec.size, vec.indices, vec.values) else: raise TypeError("Unsupported vector type %s" % type(vec)) @staticmethod def stringify(vector): """ Converts a vector into a string, which can be recognized by Vectors.parse(). Examples -------- >>> Vectors.stringify(Vectors.sparse(2, [1], [1.0])) '(2,[1],[1.0])' >>> Vectors.stringify(Vectors.dense([0.0, 1.0])) '[0.0,1.0]' """ return str(vector) @staticmethod def squared_distance(v1, v2): """ Squared distance between two vectors. a and b can be of type SparseVector, DenseVector, np.ndarray or array.array. Examples -------- >>> a = Vectors.sparse(4, [(0, 1), (3, 4)]) >>> b = Vectors.dense([2, 5, 4, 1]) >>> a.squared_distance(b) 51.0 """ v1, v2 = _convert_to_vector(v1), _convert_to_vector(v2) return v1.squared_distance(v2) @staticmethod def norm(vector, p): """ Find norm of the given vector. """ return _convert_to_vector(vector).norm(p) @staticmethod def parse(s): """Parse a string representation back into the Vector. Examples -------- >>> Vectors.parse('[2,1,2 ]') DenseVector([2.0, 1.0, 2.0]) >>> Vectors.parse(' ( 100, [0], [2])') SparseVector(100, {0: 2.0}) """ if s.find('(') == -1 and s.find('[') != -1: return DenseVector.parse(s) elif s.find('(') != -1: return SparseVector.parse(s) else: raise ValueError( "Cannot find tokens '[' or '(' from the input string.") @staticmethod def zeros(size): return DenseVector(np.zeros(size)) @staticmethod def _equals(v1_indices, v1_values, v2_indices, v2_values): """ Check equality between sparse/dense vectors, v1_indices and v2_indices assume to be strictly increasing. """ v1_size = len(v1_values) v2_size = len(v2_values) k1 = 0 k2 = 0 all_equal = True while all_equal: while k1 < v1_size and v1_values[k1] == 0: k1 += 1 while k2 < v2_size and v2_values[k2] == 0: k2 += 1 if k1 >= v1_size or k2 >= v2_size: return k1 >= v1_size and k2 >= v2_size all_equal = v1_indices[k1] == v2_indices[k2] and v1_values[k1] == v2_values[k2] k1 += 1 k2 += 1 return all_equal class Matrix(object): __UDT__ = MatrixUDT() """ Represents a local matrix. """ def __init__(self, numRows, numCols, isTransposed=False): self.numRows = numRows self.numCols = numCols self.isTransposed = isTransposed def toArray(self): """ Returns its elements in a NumPy ndarray. """ raise NotImplementedError def asML(self): """ Convert this matrix to the new mllib-local representation. This does NOT copy the data; it copies references. """ raise NotImplementedError @staticmethod def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype) class DenseMatrix(Matrix): """ Column-major dense matrix. """ def __init__(self, numRows, numCols, values, isTransposed=False): Matrix.__init__(self, numRows, numCols, isTransposed) values = self._convert_to_array(values, np.float64) assert len(values) == numRows * numCols self.values = values def __reduce__(self): return DenseMatrix, ( self.numRows, self.numCols, self.values.tostring(), int(self.isTransposed)) def __str__(self): """ Pretty printing of a DenseMatrix Examples -------- >>> dm = DenseMatrix(2, 2, range(4)) >>> print(dm) DenseMatrix([[ 0., 2.], [ 1., 3.]]) >>> dm = DenseMatrix(2, 2, range(4), isTransposed=True) >>> print(dm) DenseMatrix([[ 0., 1.], [ 2., 3.]]) """ # Inspired by __repr__ in scipy matrices. array_lines = repr(self.toArray()).splitlines() # We need to adjust six spaces which is the difference in number # of letters between "DenseMatrix" and "array" x = '\n'.join([(" " * 6 + line) for line in array_lines[1:]]) return array_lines[0].replace("array", "DenseMatrix") + "\n" + x def __repr__(self): """ Representation of a DenseMatrix Examples -------- >>> dm = DenseMatrix(2, 2, range(4)) >>> dm DenseMatrix(2, 2, [0.0, 1.0, 2.0, 3.0], False) """ # If the number of values are less than seventeen then return as it is. # Else return first eight values and last eight values. if len(self.values) < 17: entries = _format_float_list(self.values) else: entries = ( _format_float_list(self.values[:8]) + ["..."] + _format_float_list(self.values[-8:]) ) entries = ", ".join(entries) return "DenseMatrix({0}, {1}, [{2}], {3})".format( self.numRows, self.numCols, entries, self.isTransposed) def toArray(self): """ Return an numpy.ndarray Examples -------- >>> m = DenseMatrix(2, 2, range(4)) >>> m.toArray() array([[ 0., 2.], [ 1., 3.]]) """ if self.isTransposed: return np.asfortranarray( self.values.reshape((self.numRows, self.numCols))) else: return self.values.reshape((self.numRows, self.numCols), order='F') def toSparse(self): """Convert to SparseMatrix""" if self.isTransposed: values = np.ravel(self.toArray(), order='F') else: values = self.values indices = np.nonzero(values)[0] colCounts = np.bincount(indices // self.numRows) colPtrs = np.cumsum(np.hstack( (0, colCounts, np.zeros(self.numCols - colCounts.size)))) values = values[indices] rowIndices = indices % self.numRows return SparseMatrix(self.numRows, self.numCols, colPtrs, rowIndices, values) def asML(self): """ Convert this matrix to the new mllib-local representation. This does NOT copy the data; it copies references. .. versionadded:: 2.0.0 Returns ------- :py:class:`pyspark.ml.linalg.DenseMatrix` """ return newlinalg.DenseMatrix(self.numRows, self.numCols, self.values, self.isTransposed) def __getitem__(self, indices): i, j = indices if i < 0 or i >= self.numRows: raise IndexError("Row index %d is out of range [0, %d)" % (i, self.numRows)) if j >= self.numCols or j < 0: raise IndexError("Column index %d is out of range [0, %d)" % (j, self.numCols)) if self.isTransposed: return self.values[i * self.numCols + j] else: return self.values[i + j * self.numRows] def __eq__(self, other): if (self.numRows != other.numRows or self.numCols != other.numCols): return False if isinstance(other, SparseMatrix): return np.all(self.toArray() == other.toArray()) self_values = np.ravel(self.toArray(), order='F') other_values = np.ravel(other.toArray(), order='F') return np.all(self_values == other_values) class SparseMatrix(Matrix): """Sparse Matrix stored in CSC format.""" def __init__(self, numRows, numCols, colPtrs, rowIndices, values, isTransposed=False): Matrix.__init__(self, numRows, numCols, isTransposed) self.colPtrs = self._convert_to_array(colPtrs, np.int32) self.rowIndices = self._convert_to_array(rowIndices, np.int32) self.values = self._convert_to_array(values, np.float64) if self.isTransposed: if self.colPtrs.size != numRows + 1: raise ValueError("Expected colPtrs of size %d, got %d." % (numRows + 1, self.colPtrs.size)) else: if self.colPtrs.size != numCols + 1: raise ValueError("Expected colPtrs of size %d, got %d." % (numCols + 1, self.colPtrs.size)) if self.rowIndices.size != self.values.size: raise ValueError("Expected rowIndices of length %d, got %d." % (self.rowIndices.size, self.values.size)) def __str__(self): """ Pretty printing of a SparseMatrix Examples -------- >>> sm1 = SparseMatrix(2, 2, [0, 2, 3], [0, 1, 1], [2, 3, 4]) >>> print(sm1) 2 X 2 CSCMatrix (0,0) 2.0 (1,0) 3.0 (1,1) 4.0 >>> sm1 = SparseMatrix(2, 2, [0, 2, 3], [0, 1, 1], [2, 3, 4], True) >>> print(sm1) 2 X 2 CSRMatrix (0,0) 2.0 (0,1) 3.0 (1,1) 4.0 """ spstr = "{0} X {1} ".format(self.numRows, self.numCols) if self.isTransposed: spstr += "CSRMatrix\n" else: spstr += "CSCMatrix\n" cur_col = 0 smlist = [] # Display first 16 values. if len(self.values) <= 16: zipindval = zip(self.rowIndices, self.values) else: zipindval = zip(self.rowIndices[:16], self.values[:16]) for i, (rowInd, value) in enumerate(zipindval): if self.colPtrs[cur_col + 1] <= i: cur_col += 1 if self.isTransposed: smlist.append('({0},{1}) {2}'.format( cur_col, rowInd, _format_float(value))) else: smlist.append('({0},{1}) {2}'.format( rowInd, cur_col, _format_float(value))) spstr += "\n".join(smlist) if len(self.values) > 16: spstr += "\n.." * 2 return spstr def __repr__(self): """ Representation of a SparseMatrix Examples -------- >>> sm1 = SparseMatrix(2, 2, [0, 2, 3], [0, 1, 1], [2, 3, 4]) >>> sm1 SparseMatrix(2, 2, [0, 2, 3], [0, 1, 1], [2.0, 3.0, 4.0], False) """ rowIndices = list(self.rowIndices) colPtrs = list(self.colPtrs) if len(self.values) <= 16: values = _format_float_list(self.values) else: values = ( _format_float_list(self.values[:8]) + ["..."] + _format_float_list(self.values[-8:]) ) rowIndices = rowIndices[:8] + ["..."] + rowIndices[-8:] if len(self.colPtrs) > 16: colPtrs = colPtrs[:8] + ["..."] + colPtrs[-8:] values = ", ".join(values) rowIndices = ", ".join([str(ind) for ind in rowIndices]) colPtrs = ", ".join([str(ptr) for ptr in colPtrs]) return "SparseMatrix({0}, {1}, [{2}], [{3}], [{4}], {5})".format( self.numRows, self.numCols, colPtrs, rowIndices, values, self.isTransposed) def __reduce__(self): return SparseMatrix, ( self.numRows, self.numCols, self.colPtrs.tostring(), self.rowIndices.tostring(), self.values.tostring(), int(self.isTransposed)) def __getitem__(self, indices): i, j = indices if i < 0 or i >= self.numRows: raise IndexError("Row index %d is out of range [0, %d)" % (i, self.numRows)) if j < 0 or j >= self.numCols: raise IndexError("Column index %d is out of range [0, %d)" % (j, self.numCols)) # If a CSR matrix is given, then the row index should be searched # for in ColPtrs, and the column index should be searched for in the # corresponding slice obtained from rowIndices. if self.isTransposed: j, i = i, j colStart = self.colPtrs[j] colEnd = self.colPtrs[j + 1] nz = self.rowIndices[colStart: colEnd] ind = np.searchsorted(nz, i) + colStart if ind < colEnd and self.rowIndices[ind] == i: return self.values[ind] else: return 0.0 def toArray(self): """ Return an numpy.ndarray """ A = np.zeros((self.numRows, self.numCols), dtype=np.float64, order='F') for k in range(self.colPtrs.size - 1): startptr = self.colPtrs[k] endptr = self.colPtrs[k + 1] if self.isTransposed: A[k, self.rowIndices[startptr:endptr]] = self.values[startptr:endptr] else: A[self.rowIndices[startptr:endptr], k] = self.values[startptr:endptr] return A def toDense(self): densevals = np.ravel(self.toArray(), order='F') return DenseMatrix(self.numRows, self.numCols, densevals) def asML(self): """ Convert this matrix to the new mllib-local representation. This does NOT copy the data; it copies references. .. versionadded:: 2.0.0 Returns ------- :py:class:`pyspark.ml.linalg.SparseMatrix` """ return newlinalg.SparseMatrix(self.numRows, self.numCols, self.colPtrs, self.rowIndices, self.values, self.isTransposed) # TODO: More efficient implementation: def __eq__(self, other): return np.all(self.toArray() == other.toArray()) class Matrices(object): @staticmethod def dense(numRows, numCols, values): """ Create a DenseMatrix """ return DenseMatrix(numRows, numCols, values) @staticmethod def sparse(numRows, numCols, colPtrs, rowIndices, values): """ Create a SparseMatrix """ return SparseMatrix(numRows, numCols, colPtrs, rowIndices, values) @staticmethod def fromML(mat): """ Convert a matrix from the new mllib-local representation. This does NOT copy the data; it copies references. .. versionadded:: 2.0.0 Parameters ---------- mat : :py:class:`pyspark.ml.linalg.Matrix` Returns ------- :py:class:`pyspark.mllib.linalg.Matrix` """ if isinstance(mat, newlinalg.DenseMatrix): return DenseMatrix(mat.numRows, mat.numCols, mat.values, mat.isTransposed) elif isinstance(mat, newlinalg.SparseMatrix): return SparseMatrix(mat.numRows, mat.numCols, mat.colPtrs, mat.rowIndices, mat.values, mat.isTransposed) else: raise TypeError("Unsupported matrix type %s" % type(mat)) class QRDecomposition(object): """ Represents QR factors. """ def __init__(self, Q, R): self._Q = Q self._R = R @property @since('2.0.0') def Q(self): """ An orthogonal matrix Q in a QR decomposition. May be null if not computed. """ return self._Q @property @since('2.0.0') def R(self): """ An upper triangular matrix R in a QR decomposition. """ return self._R def _test(): import doctest import numpy try: # Numpy 1.14+ changed it's string format. numpy.set_printoptions(legacy='1.13') except TypeError: pass (failure_count, test_count) = doctest.testmod(optionflags=doctest.ELLIPSIS) if failure_count: sys.exit(-1) if __name__ == "__main__": _test()
apache-2.0
gannetson/django
tests/forms_tests/tests/test_media.py
169
45896
# -*- coding: utf-8 -*- from django.forms import CharField, Form, Media, MultiWidget, TextInput from django.template import Context, Template from django.test import SimpleTestCase, override_settings from django.utils.encoding import force_text @override_settings( STATIC_URL=None, MEDIA_URL='http://media.example.com/media/', ) class FormsMediaTestCase(SimpleTestCase): """Tests for the media handling on widgets and forms""" def test_construction(self): # Check construction of media objects m = Media(css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')) self.assertEqual(str(m), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") class Foo: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') m3 = Media(Foo) self.assertEqual(str(m3), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # A widget can exist without a media definition class MyWidget(TextInput): pass w = MyWidget() self.assertEqual(str(w.media), '') def test_media_dsl(self): ############################################################### # DSL Class-based media definitions ############################################################### # A widget can define media if it needs to. # Any absolute path will be preserved; relative paths are combined # with the value of settings.MEDIA_URL class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') w1 = MyWidget1() self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # Media objects can be interrogated by media type self.assertEqual(str(w1.media['css']), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />""") self.assertEqual(str(w1.media['js']), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") def test_combine_media(self): # Media objects can be combined. Any given media resource will appear only # once. Duplicated media definitions are ignored. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w1 = MyWidget1() w2 = MyWidget2() w3 = MyWidget3() self.assertEqual(str(w1.media + w2.media + w3.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Check that media addition hasn't affected the original objects self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # Regression check for #12879: specifying the same CSS or JS file # multiple times in a single Media instance should result in that file # only being included once. class MyWidget4(TextInput): class Media: css = {'all': ('/path/to/css1', '/path/to/css1')} js = ('/path/to/js1', '/path/to/js1') w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script>""") def test_media_property(self): ############################################################### # Property-based media definitions ############################################################### # Widget media can be defined as a property class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js=('/some/js',)) media = property(_media) w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script>""") # Media properties can reference the media of their parents class MyWidget5(MyWidget4): def _media(self): return super(MyWidget5, self).media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) media = property(_media) w5 = MyWidget5() self.assertEqual(str(w5.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_property_parent_references(self): # Media properties can reference the media of their parents, # even if the parent media was defined using a class class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget6(MyWidget1): def _media(self): return super(MyWidget6, self).media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) media = property(_media) w6 = MyWidget6() self.assertEqual(str(w6.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_inheritance(self): ############################################################### # Inheritance of media ############################################################### # If a widget extends another but provides no media definition, it inherits the parent widget's media class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget7(MyWidget1): pass w7 = MyWidget7() self.assertEqual(str(w7.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # If a widget extends another but defines media, it extends the parent widget's media by default class MyWidget8(MyWidget1): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w8 = MyWidget8() self.assertEqual(str(w8.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_from_property(self): # If a widget extends another but defines media, it extends the parents widget's media, # even if the parent defined media using a property. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js=('/some/js',)) media = property(_media) class MyWidget9(MyWidget4): class Media: css = { 'all': ('/other/path',) } js = ('/other/js',) w9 = MyWidget9() self.assertEqual(str(w9.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): class Media: extend = False css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w10 = MyWidget10() self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_extends(self): # A widget can explicitly enable full media inheritance by specifying 'extend=True' class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget11(MyWidget1): class Media: extend = True css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w11 = MyWidget11() self.assertEqual(str(w11.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying extend as a tuple class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget12(MyWidget1): class Media: extend = ('css',) css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w12 = MyWidget12() self.assertEqual(str(w12.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_multi_media(self): ############################################################### # Multi-media handling for CSS ############################################################### # A widget can define CSS media for multiple output media types class MultimediaWidget(TextInput): class Media: css = { 'screen, print': ('/file1', '/file2'), 'screen': ('/file3',), 'print': ('/file4',) } js = ('/path/to/js1', '/path/to/js4') multimedia = MultimediaWidget() self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" /> <link href="/file3" type="text/css" media="screen" rel="stylesheet" /> <link href="/file1" type="text/css" media="screen, print" rel="stylesheet" /> <link href="/file2" type="text/css" media="screen, print" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_multi_widget(self): ############################################################### # Multiwidget media handling ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') # MultiWidgets have a default media definition that gets all the # media from the component widgets class MyMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = [MyWidget1, MyWidget2, MyWidget3] super(MyMultiWidget, self).__init__(widgets, attrs) mymulti = MyMultiWidget() self.assertEqual(str(mymulti.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_form_media(self): ############################################################### # Media processing for forms ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') # You can ask a form for the media required by its widgets. class MyForm(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) f1 = MyForm() self.assertEqual(str(f1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) f2 = AnotherForm() self.assertEqual(str(f1.media + f2.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Forms can also define media, following the same rules as widgets. class FormWithMedia(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) class Media: js = ('/some/form/javascript',) css = { 'all': ('/some/form/css',) } f3 = FormWithMedia() self.assertEqual(str(f3.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script>""") # Media works in templates self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script><link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""") def test_html_safe(self): media = Media(css={'all': ['/path/to/css']}, js=['/path/to/js']) self.assertTrue(hasattr(Media, '__html__')) self.assertEqual(force_text(media), media.__html__()) @override_settings( STATIC_URL='http://media.example.com/static/', MEDIA_URL='http://media.example.com/media/', ) class StaticFormsMediaTestCase(SimpleTestCase): """Tests for the media handling on widgets and forms""" def test_construction(self): # Check construction of media objects m = Media(css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')) self.assertEqual(str(m), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") class Foo: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') m3 = Media(Foo) self.assertEqual(str(m3), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # A widget can exist without a media definition class MyWidget(TextInput): pass w = MyWidget() self.assertEqual(str(w.media), '') def test_media_dsl(self): ############################################################### # DSL Class-based media definitions ############################################################### # A widget can define media if it needs to. # Any absolute path will be preserved; relative paths are combined # with the value of settings.MEDIA_URL class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') w1 = MyWidget1() self.assertEqual(str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # Media objects can be interrogated by media type self.assertEqual(str(w1.media['css']), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />""") self.assertEqual(str(w1.media['js']), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") def test_combine_media(self): # Media objects can be combined. Any given media resource will appear only # once. Duplicated media definitions are ignored. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w1 = MyWidget1() w2 = MyWidget2() w3 = MyWidget3() self.assertEqual(str(w1.media + w2.media + w3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Check that media addition hasn't affected the original objects self.assertEqual(str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # Regression check for #12879: specifying the same CSS or JS file # multiple times in a single Media instance should result in that file # only being included once. class MyWidget4(TextInput): class Media: css = {'all': ('/path/to/css1', '/path/to/css1')} js = ('/path/to/js1', '/path/to/js1') w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script>""") def test_media_property(self): ############################################################### # Property-based media definitions ############################################################### # Widget media can be defined as a property class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js=('/some/js',)) media = property(_media) w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script>""") # Media properties can reference the media of their parents class MyWidget5(MyWidget4): def _media(self): return super(MyWidget5, self).media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) media = property(_media) w5 = MyWidget5() self.assertEqual(str(w5.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_property_parent_references(self): # Media properties can reference the media of their parents, # even if the parent media was defined using a class class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget6(MyWidget1): def _media(self): return super(MyWidget6, self).media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) media = property(_media) w6 = MyWidget6() self.assertEqual(str(w6.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_inheritance(self): ############################################################### # Inheritance of media ############################################################### # If a widget extends another but provides no media definition, it inherits the parent widget's media class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget7(MyWidget1): pass w7 = MyWidget7() self.assertEqual(str(w7.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # If a widget extends another but defines media, it extends the parent widget's media by default class MyWidget8(MyWidget1): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w8 = MyWidget8() self.assertEqual(str(w8.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_from_property(self): # If a widget extends another but defines media, it extends the parents widget's media, # even if the parent defined media using a property. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js=('/some/js',)) media = property(_media) class MyWidget9(MyWidget4): class Media: css = { 'all': ('/other/path',) } js = ('/other/js',) w9 = MyWidget9() self.assertEqual(str(w9.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): class Media: extend = False css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w10 = MyWidget10() self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_extends(self): # A widget can explicitly enable full media inheritance by specifying 'extend=True' class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget11(MyWidget1): class Media: extend = True css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w11 = MyWidget11() self.assertEqual(str(w11.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying extend as a tuple class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget12(MyWidget1): class Media: extend = ('css',) css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') w12 = MyWidget12() self.assertEqual(str(w12.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_multi_media(self): ############################################################### # Multi-media handling for CSS ############################################################### # A widget can define CSS media for multiple output media types class MultimediaWidget(TextInput): class Media: css = { 'screen, print': ('/file1', '/file2'), 'screen': ('/file3',), 'print': ('/file4',) } js = ('/path/to/js1', '/path/to/js4') multimedia = MultimediaWidget() self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" /> <link href="/file3" type="text/css" media="screen" rel="stylesheet" /> <link href="/file1" type="text/css" media="screen, print" rel="stylesheet" /> <link href="/file2" type="text/css" media="screen, print" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_multi_widget(self): ############################################################### # Multiwidget media handling ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') # MultiWidgets have a default media definition that gets all the # media from the component widgets class MyMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = [MyWidget1, MyWidget2, MyWidget3] super(MyMultiWidget, self).__init__(widgets, attrs) mymulti = MyMultiWidget() self.assertEqual(str(mymulti.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_form_media(self): ############################################################### # Media processing for forms ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1', '/path/to/css2') } js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2', '/path/to/css3') } js = ('/path/to/js1', '/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3', 'path/to/css1') } js = ('/path/to/js1', '/path/to/js4') # You can ask a form for the media required by its widgets. class MyForm(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) f1 = MyForm() self.assertEqual(str(f1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) f2 = AnotherForm() self.assertEqual(str(f1.media + f2.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Forms can also define media, following the same rules as widgets. class FormWithMedia(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) class Media: js = ('/some/form/javascript',) css = { 'all': ('/some/form/css',) } f3 = FormWithMedia() self.assertEqual(str(f3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script>""") # Media works in templates self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script><link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""")
bsd-3-clause
BlackEarth/bl
bl/progress.py
1
2750
import inspect, logging, os, sys, traceback from time import time from bl.dict import Dict from bl.json import JSON log = logging.getLogger(__name__) class Progress(JSON): """tabulate progress statistics for given processes, and report the progress of those processes""" def __init__(self, fn=None, data=None, key=None, **params): # JSON.__init__() loads the stored progress data from the given .json file super().__init__(fn=fn, data=data, params=params) if self.data is None: self.data = Dict() self.current_times = Dict() # start times for current stack processes. self.init_key = key or self.stack_key def start(self, key=None, **params): """initialize process timing for the current stack""" self.params.update(**params) key = key or self.stack_key if key is not None: self.current_times[key] = time() def runtime(self, key=None): key = key or self.init_key if self.data.get(key) is not None: return sum([v['runtime'] for v in self.data[key]]) / len(self.data[key]) def runtimes(self): return Dict(**{key:self.runtime(key) for key in self.data.keys()}) def report(self, fraction=None): """report the total progress for the current stack, optionally given the local fraction completed. fraction=None: if given, used as the fraction of the local method so far completed. runtimes=None: if given, used as the expected runtimes for the current stack. """ r = Dict() local_key = self.stack_key if local_key is None: return {} runtimes = self.runtimes() for key in self.stack_keys: if self.current_times.get(key) is None: self.start(key=key) runtime = runtimes.get(key) or self.runtime(key) if key == local_key and fraction is not None: r[key] = fraction elif runtime is not None: r[key] = (time() - self.current_times[key]) / runtime return r def finish(self): """record the current stack process as finished""" self.report(fraction=1.0) key = self.stack_key if key is not None: if self.data.get(key) is None: self.data[key] = [] start_time = self.current_times.get(key) or time() self.data[key].append(Dict(runtime=time()-start_time, **self.params)) @property def stack_keys(self): key = self.stack_key if key is not None: l = self.stack_key.split(',') else: l = [] return [','.join(l[:i]) for i in range(1, len(l)+1)] @property def stack_key(self): try: return ','.join(list(reversed([ t.filename+':'+t.function for t in [inspect.getframeinfo(i.frame) for i in inspect.stack()] if os.path.abspath(t.filename) != os.path.abspath(__file__) # omit locations in this file and t.function != '<module>' and 'runpy.py' not in t.filename ]))) except: log.error(traceback.format_exc())
mpl-2.0
sathnaga/avocado-vt
virttest/libvirt_xml/accessors.py
1
36382
""" Specializations of base.AccessorBase for particular XML manipulation types """ import logging from virttest import xml_utils from virttest import element_tree from virttest.propcan import PropCanBase from virttest.libvirt_xml import xcepts, base def type_check(name, thing, expected): """ Check that thing is expected subclass or instance, raise ValueError if not """ is_a = type(thing) is_a_name = str(is_a) if not isinstance(expected, list): expected = [expected] for e in expected: try: it_is = issubclass(thing, e) except TypeError: it_is = isinstance(thing, e) if it_is: return raise ValueError('%s value is not any of %s, it is a %s' % (name, expected, is_a_name)) def add_to_slots(*args): """ Return list of AccessorBase.__all_slots__ + args """ for slot in args: type_check('slot name', slot, str) return AccessorBase.__all_slots__ + args class AccessorBase(PropCanBase): """ Base class for a callable operating on a LibvirtXMLBase subclass instance """ # Gets AccessorGeneratorBase subclass's required_accessor_data_keys added __slots__ = ('operation', 'property_name', 'libvirtxml') def __init__(self, operation, property_name, libvirtxml, **dargs): """ Initialize accessor to operate on lvxml with accessor_data for property :param operation: Debug String for 'Getter', 'Setter', or 'Delter' :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass :param dargs: Necessary for subclasses to extend required parameters """ type_check('Parameter property_name', property_name, str) type_check('Operation attribute', operation, str) type_check('__slots__ attribute', self.__all_slots__, [tuple, list]) type_check('Parameter libvirtxml', libvirtxml, base.LibvirtXMLBase) super(AccessorBase, self).__init__() self.__dict_set__('operation', operation) self.__dict_set__('property_name', property_name) self.__dict_set__('libvirtxml', libvirtxml) for slot in self.__all_slots__: if slot in AccessorBase.__all_slots__: continue # already checked these # Don't care about value type if slot not in dargs: raise ValueError('Required accessor generator parameter %s' % slot) self.__dict_set__(slot, dargs[slot]) # Subclass expected to override this and specify parameters __call__ = NotImplementedError def __repr__(self): return ("%s's %s for %s with %s" % (self.libvirtxml.__class__.__name__, self.operation, self.property_name, str(dict(self)))) def xmltreefile(self): """ Retrieve xmltreefile instance from libvirtxml instance """ return self.libvirtxml.xmltreefile def element_by_parent(self, parent_xpath, tag_name, create=True): """ Retrieve/create an element instance at parent_xpath/tag_name :param parent_xpath: xpath of parent element :param tag_name: name of element under parent to retrieve/create :param create: True to create new element if not exist :return: ElementTree.Element instance :raise: LibvirtXMLError: If element not exist & create=False """ type_check('parent_xpath', parent_xpath, str) type_check('tag_name', tag_name, str) parent_element = self.xmltreefile().find(parent_xpath) if (parent_element == self.xmltreefile().getroot() and parent_element.tag == tag_name): return parent_element excpt_str = ('Exception thrown from %s for property "%s" while' ' looking for element tag "%s", on parent at xpath' ' "%s", in XML\n%s\n' % (self.operation, self.property_name, tag_name, parent_xpath, str(self.xmltreefile()))) if parent_element is None: if create: # This will only work for simple XPath strings self.xmltreefile().create_by_xpath(parent_xpath) parent_element = self.xmltreefile().find(parent_xpath) # if create or not, raise if not exist if parent_element is None: raise xcepts.LibvirtXMLAccessorError(excpt_str) try: element = parent_element.find(tag_name) except Exception: logging.error(excpt_str) raise if element is None: if create: # Create the element element = xml_utils.ElementTree.SubElement(parent_element, tag_name) else: # create is False raise xcepts.LibvirtXMLNotFoundError('Error in %s for property ' '"%s", element tag "%s" not ' 'found on parent at xpath "%s"' ' in XML\n%s\n' % (self.operation, self.property_name, tag_name, parent_xpath, str(self.xmltreefile()))) return element class ForbiddenBase(AccessorBase): """ Raise LibvirtXMLAccessorError when called w/ or w/o a value arg. """ __slots__ = [] def __call__(self, value=None): if value: raise xcepts.LibvirtXMLForbiddenError("%s %s to '%s' on %s " "forbidden" % (self.operation, self.property_name, str(value), str(self))) else: raise xcepts.LibvirtXMLForbiddenError("%s %s on %s " "forbidden" % (self.operation, self.property_name, str(self))) class AccessorGeneratorBase(object): """ Accessor method/class generator for specific property name """ def __init__(self, property_name, libvirtxml, forbidden=None, **dargs): """ Initialize accessor methods, marking operations in forbidden as such :param property_name: Name of the property :param libvirtxml: Instance reference to LibvirtXMLBase subclass :param forbidden: Optional string list of 'get', 'set', and/or 'del' :param dargs: Specific AccessorGeneratorBase subclass info. """ if forbidden is None: forbidden = [] type_check('forbidden', forbidden, list) self.forbidden = forbidden type_check('libvirtxml', libvirtxml, base.LibvirtXMLBase) self.libvirtxml = libvirtxml type_check('property_name', property_name, str) self.property_name = property_name self.dargs = dargs # Lookup all property names possibly needing accessors for operation in ('get', 'set', 'del'): self.set_if_not_defined(operation) def set_if_not_defined(self, operation): """ Setup a callable instance for operation only if not already defined """ # Don't overwrite methods in libvirtxml instance if not hasattr(self.libvirtxml, self.accessor_name(operation)): if operation not in self.forbidden: self.assign_callable(operation, self.make_callable(operation)) else: # operation is forbidden self.assign_callable(operation, self.make_forbidden(operation)) def accessor_name(self, operation): """ Return instance name for operation, defined by subclass (i.e. 'get_foo') """ return "%s_%s" % (operation, self.property_name) @staticmethod def callable_name(operation): """ Return class name for operation (i.e. 'Getter'), defined by subclass. """ return operation.capitalize() + 'ter' def make_callable(self, operation): """ Return an callable instance for operation """ callable_class = getattr(self, self.callable_name(operation)) return callable_class( self.callable_name(operation), self.property_name, self.libvirtxml, **self.dargs) def make_forbidden(self, operation): """ Return a forbidden callable instance for operation """ return ForbiddenBase(operation, self.property_name, self.libvirtxml) def assign_callable(self, operation, callable_inst): """ Set reference on objectified libvirtxml instance to callable_inst """ self.libvirtxml.__super_set__(self.accessor_name(operation), callable_inst) # Implementation of specific accessor generator subclasses follows class AllForbidden(AccessorGeneratorBase): """ Class of forbidden accessor classes for those undefined on libvirtxml """ def __init__(self, property_name, libvirtxml): """ Create exception raising accessors for those undefined on libvirtxml :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass """ super(AllForbidden, self).__init__(property_name=property_name, libvirtxml=libvirtxml, forbidden=['get', 'set', 'del']) class XMLElementText(AccessorGeneratorBase): """ Class of accessor classes operating on element.text """ required_dargs = ('parent_xpath', 'tag_name') def __init__(self, property_name, libvirtxml, forbidden=None, parent_xpath=None, tag_name=None): """ Create undefined accessors on libvirt instance :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass :param forbidden: Optional list of 'get', 'set', 'del' :param parent_xpath: XPath string of parent element :param tag_name: element tag name to manipulate text attribute on. """ super(XMLElementText, self).__init__(property_name, libvirtxml, forbidden, parent_xpath=parent_xpath, tag_name=tag_name) class Getter(AccessorBase): """ Retrieve text on element """ __slots__ = add_to_slots('parent_xpath', 'tag_name') def __call__(self): return self.element_by_parent(self.parent_xpath, self.tag_name, create=False).text class Setter(AccessorBase): """ Set text to value on element """ __slots__ = add_to_slots('parent_xpath', 'tag_name') def __call__(self, value): element = self.element_by_parent(self.parent_xpath, self.tag_name, create=True) element.text = str(value) self.xmltreefile().write() class Delter(AccessorBase): """ Remove element and ignore if it doesn't exist (same as False) """ __slots__ = add_to_slots('parent_xpath', 'tag_name') def __call__(self): try: element = self.element_by_parent(self.parent_xpath, self.tag_name, create=False) except (xcepts.LibvirtXMLNotFoundError, # element doesn't exist xcepts.LibvirtXMLAccessorError): # parent doesn't exist pass # already gone else: parent = self.xmltreefile().find(self.parent_xpath) if parent is not None: parent.remove(element) self.xmltreefile().write() class XMLElementInt(AccessorGeneratorBase): """ Class of accessor classes operating on element.text as an integer """ __radix2func_dict__ = {0: int, 2: bin, 8: oct, 10: int, 16: hex} required_dargs = ('parent_xpath', 'tag_name', 'radix') def __init__(self, property_name, libvirtxml, forbidden=None, parent_xpath=None, tag_name=None, radix=10): """ Create undefined accessors on libvirt instance :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass :param forbidden: Optional list of 'Getter', 'Setter', 'Delter' :param parent_xpath: XPath string of parent element :param tag_name: element tag name to manipulate text attribute on. """ try: self.__radix2func_dict__[radix] except KeyError: raise xcepts.LibvirtXMLError("Param radix=%s for XMLElementInt " "is not accepted." % radix) super(XMLElementInt, self).__init__(property_name, libvirtxml, forbidden, parent_xpath=parent_xpath, tag_name=tag_name, radix=radix) class Getter(AccessorBase): """ Retrieve text on element and convert to int """ __slots__ = add_to_slots('parent_xpath', 'tag_name', 'radix') def __call__(self): element = self.element_by_parent(self.parent_xpath, self.tag_name, create=False) try: result = int(element.text, self.radix) except ValueError: raise xcepts.LibvirtXMLError("Value of %s in %s is %s," "not a Integer." % (self.tag_name, self.parent_xpath, element.text)) return result class Setter(AccessorBase): """ Set text on element after converting to int then to str """ __slots__ = add_to_slots('parent_xpath', 'tag_name', 'radix') def __call__(self, value): type_check(self.property_name + ' value', value, int) element = self.element_by_parent(self.parent_xpath, self.tag_name, create=True) convertFunc = XMLElementInt.__radix2func_dict__[self.radix] element.text = str(convertFunc(value)) self.xmltreefile().write() Delter = XMLElementText.Delter class XMLElementBool(AccessorGeneratorBase): """ Class of accessor classes operating purely element existence """ required_dargs = ('parent_xpath', 'tag_name') def __init__(self, property_name, libvirtxml, forbidden=None, parent_xpath=None, tag_name=None): """ Create undefined accessors on libvirt instance :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass :param forbidden: Optional list of 'get', 'set', 'del' :param parent_xpath: XPath string of parent element :param tag_name: element tag name to manipulate text attribute on. """ super(XMLElementBool, self).__init__(property_name, libvirtxml, forbidden, parent_xpath=parent_xpath, tag_name=tag_name) class Getter(AccessorBase): """ Retrieve text on element """ __slots__ = add_to_slots('parent_xpath', 'tag_name') def __call__(self): try: # Throws exception if parent path or element not exist self.element_by_parent(self.parent_xpath, self.tag_name, create=False) return True except (xcepts.LibvirtXMLAccessorError, xcepts.LibvirtXMLNotFoundError): return False class Setter(AccessorBase): """ Create element when True, delete when false """ __slots__ = add_to_slots('parent_xpath', 'tag_name') def __call__(self, value): if bool(value) is True: self.element_by_parent(self.parent_xpath, self.tag_name, create=True) else: delattr(self.libvirtxml, self.property_name) self.xmltreefile().write() Delter = XMLElementText.Delter class XMLAttribute(AccessorGeneratorBase): """ Class of accessor classes operating on an attribute of an element """ def __init__(self, property_name, libvirtxml, forbidden=None, parent_xpath=None, tag_name=None, attribute=None): """ Create undefined accessors on libvirt instance :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass :param forbidden: Optional list of 'Getter', 'Setter', 'Delter' :param parent_xpath: XPath string of parent element :param tag_name: element tag name to manipulate text attribute on. :param attribute: Attribute name to manupulate """ super(XMLAttribute, self).__init__(property_name, libvirtxml, forbidden, parent_xpath=parent_xpath, tag_name=tag_name, attribute=attribute) class Getter(AccessorBase): """ Get attribute value """ __slots__ = add_to_slots('parent_xpath', 'tag_name', 'attribute') def __call__(self): element = self.element_by_parent(self.parent_xpath, self.tag_name, create=False) value = element.get(self.attribute, None) if value is None: raise xcepts.LibvirtXMLNotFoundError("Attribute %s not found " "on element %s" % (self.attribute, element.tag)) return value class Setter(AccessorBase): """ Set attribute value """ __slots__ = add_to_slots('parent_xpath', 'tag_name', 'attribute') def __call__(self, value): element = self.element_by_parent(self.parent_xpath, self.tag_name, create=True) element.set(self.attribute, str(value)) self.xmltreefile().write() class Delter(AccessorBase): """ Remove attribute """ __slots__ = add_to_slots('parent_xpath', 'tag_name', 'attribute') def __call__(self): element = self.element_by_parent(self.parent_xpath, self.tag_name, create=False) try: del element.attrib[self.attribute] except KeyError: pass # already doesn't exist self.xmltreefile().write() class XMLElementDict(AccessorGeneratorBase): """ Class of accessor classes operating as a dictionary of attributes """ def __init__(self, property_name, libvirtxml, forbidden=None, parent_xpath=None, tag_name=None): """ Create undefined accessors on libvirt instance :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass :param forbidden: Optional list of 'Getter', 'Setter', 'Delter' :param parent_xpath: XPath string of parent element :param tag_name: element tag name to manipulate text attribute on. """ super(XMLElementDict, self).__init__(property_name, libvirtxml, forbidden, parent_xpath=parent_xpath, tag_name=tag_name) class Getter(AccessorBase): """ Retrieve attributes on element """ __slots__ = add_to_slots('parent_xpath', 'tag_name') def __call__(self): element = self.element_by_parent(self.parent_xpath, self.tag_name, create=False) return dict(list(element.items())) class Setter(AccessorBase): """ Set attributes to value on element """ __slots__ = add_to_slots('parent_xpath', 'tag_name') def __call__(self, value): type_check(self.property_name + ' value', value, dict) element = self.element_by_parent(self.parent_xpath, self.tag_name, create=True) for attr_key, attr_value in list(value.items()): element.set(str(attr_key), str(attr_value)) self.xmltreefile().write() # Inheriting from XMLElementText not work right Delter = XMLElementText.Delter class XMLElementNest(AccessorGeneratorBase): """ Class of accessor classes operating on a LibvirtXMLBase subclass """ required_dargs = ('parent_xpath', 'tag_name', 'subclass', 'subclass_dargs') def __init__(self, property_name, libvirtxml, forbidden=None, parent_xpath=None, tag_name=None, subclass=None, subclass_dargs=None): """ Create undefined accessors on libvirt instance :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass :param forbidden: Optional list of 'Getter', 'Setter', 'Delter' :param parent_xpath: XPath string of parent element :param tag_name: element tag name to manipulate text attribute on. :param subclass: A LibvirtXMLBase subclass with root tag == tag_name :param subclass_dargs: dict. to pass as kw args to subclass.__init__ N/B: Works ONLY if tag_name is unique within parent element """ type_check('subclass', subclass, base.LibvirtXMLBase) type_check('subclass_dargs', subclass_dargs, dict) super(XMLElementNest, self).__init__(property_name, libvirtxml, forbidden, parent_xpath=parent_xpath, tag_name=tag_name, subclass=subclass, subclass_dargs=subclass_dargs) class Getter(AccessorBase): """ Retrieve instance of subclass with it's xml set to rerooted xpath/tag """ __slots__ = add_to_slots('parent_xpath', 'tag_name', 'subclass', 'subclass_dargs') def __call__(self): xmltreefile = self.xmltreefile() # Don't re-invent XPath generation method/behavior nested_root_element = self.element_by_parent(self.parent_xpath, self.tag_name, create=False) nested_root_xpath = xmltreefile.get_xpath(nested_root_element) # Try to make XMLTreeFile copy, rooted at nested_root_xpath # with copies of any/all child elements also nested_xtf = xmltreefile.reroot(nested_root_xpath) # Create instance of subclass to assign nested_xtf onto nestedinst = self.subclass(**self.subclass_dargs) # nestedxml.xmltreefile.restore() will fail on nested_xtf.__del__ # set from string not filename! nestedinst.set_xml(str(nested_xtf)) return nestedinst class Setter(AccessorBase): """ Set attributes to value on element """ __slots__ = add_to_slots('parent_xpath', 'tag_name', 'subclass') def __call__(self, value): type_check('Instance of %s' % self.subclass.__name__, value, self.subclass) # Will overwrite if exists existing_element = self.element_by_parent(self.parent_xpath, self.tag_name, create=True) existing_parent = self.xmltreefile().get_parent(existing_element) self.xmltreefile().remove(existing_element) existing_parent.append(value.xmltreefile.getroot()) self.xmltreefile().write() # Nothing fancy, just make sure that part of tree doesn't exist Delter = XMLElementText.Delter class XMLElementList(AccessorGeneratorBase): """ Class of accessor classes operating on a list of child elements Other generators here have a hard-time dealing with XML that has multiple child-elements with the same tag. This class allows treating these structures as lists of arbitrary user-defined objects. User-defined marshal functions are called to perform the conversion to/from the format described in __init__. """ required_dargs = ('parent_xpath', 'tag_name', 'marshal_from', 'marshal_to') def __init__(self, property_name, libvirtxml, forbidden=None, parent_xpath=None, marshal_from=None, marshal_to=None, has_subclass=None): """ Create undefined accessors on libvirt instance :param property_name: String name of property (for exception detail) :param libvirtxml: An instance of a LibvirtXMLBase subclass :param forbidden: Optional list of 'Getter', 'Setter', 'Delter' :param parent_xpath: XPath string of parent element :param marshal_from: Callable, passed the item, index, and libvirtxml instance. Must return tuple of tag-name, an attribute-dict, and an optional text or raise ValueError exception. :param marshal_to: Callable. Passed a the item tag, attribute-dict, index, libvirtxml, and optional text instance. Returns item value accepted by marshal_from or None to skip """ if not callable(marshal_from) or not callable(marshal_to): raise ValueError("Both marshal_from and marshal_to must be " "callable") super(XMLElementList, self).__init__(property_name, libvirtxml, forbidden, parent_xpath=parent_xpath, marshal_from=marshal_from, marshal_to=marshal_to, has_subclass=has_subclass) class Getter(AccessorBase): """ Retrieve list of values as returned by the marshal_to callable """ __slots__ = add_to_slots('parent_xpath', 'marshal_to', 'has_subclass') def __call__(self): # Parent structure cannot be pre-determined as in other classes parent = self.xmltreefile().find(self.parent_xpath) if parent is None: # Used as "undefined" signal, raising exception may # not be appropriate when other accessors are used # to generate missing structure. return None result = [] # Give user-defined marshal functions a way to act on # item order if needed, and/or help with error reporting. index = 0 # user-defined marshal functions might want to use # index numbers to filter/skip certain elements # but also support specific item ordering. for child in parent.getchildren(): # Call user-defined helper to translate Element # into simple pre-defined format. # To support converting xml elements directly to a list of # xml objects, first create xmltreefile for new object if self.has_subclass: new_xmltreefile = xml_utils.XMLTreeFile( element_tree.tostring(child)) item = self.marshal_to(child.tag, new_xmltreefile, index, self.libvirtxml) else: try: # To support an optional text parameter, compatible # with no text parameter. item = self.marshal_to(child.tag, dict(list(child.items())), index, self.libvirtxml, child.text) except TypeError: item = self.marshal_to(child.tag, dict(list(child.items())), index, self.libvirtxml) if item is not None: result.append(item) # Always use absolute index (even if item was None) index += 1 return result class Setter(AccessorBase): """ Set child elements as returned by the marshal_to callable """ __slots__ = add_to_slots('parent_xpath', 'marshal_from', 'has_subclass') def __call__(self, value): type_check('value', value, list) # Allow other classes to generate parent structure parent = self.xmltreefile().find(self.parent_xpath) if parent is None: # Create parent xpath if not exists self.xmltreefile().create_by_xpath(self.parent_xpath) parent = self.xmltreefile().find(self.parent_xpath) if parent is None: raise xcepts.LibvirtXMLNotFoundError( 'Parent xpath %s not found.' % self.parent_xpath) # Remove existing by calling accessor method, allowing # any "untouchable" or "filtered" elements (by marshal) # to be ignored and left as-is. delattr(self.libvirtxml, self.property_name) # Allow user-defined marshal function to determine # if item order is important. Also give more meaningful # exception message below, if there is a problem. index = 0 for item in value: try: # Call user-defined conversion from simple # format, back to Element instances. element_tuple = self.marshal_from(item, index, self.libvirtxml) except ValueError: # Defined in marshal API, to help with error reporting # and debugging with more rich message. msg = ("Call to %s by set accessor method for property %s " "with unsupported item type %s, at index %d, " " with value %s." % (str(self.marshal_from), self.property_name, str(type(item)), index, str(item))) raise xcepts.LibvirtXMLAccessorError(msg) # Handle xml sub-element items if self.has_subclass: parent.append(element_tuple[1].xmltreefile.getroot()) self.xmltreefile().write() continue # Handle element text values in element_tuple[1]. text = None new_dict = element_tuple[1].copy() if 'text' in list(element_tuple[1].keys()): del new_dict['text'] # To support text in element, marshal_from may return an # additional text value, check the length of element tuple if len(element_tuple) == 3: text = element_tuple[2] parent_element = xml_utils.ElementTree.SubElement( parent, element_tuple[0], new_dict, text) # To support child element contains text, create sub element # with text under new created parent element. if 'text' in list(element_tuple[1].keys()): text_dict = element_tuple[1]['text'] attr_dict = {} for text_key, text_val in list(text_dict.items()): xml_utils.ElementTree.SubElement( parent_element, text_key, attr_dict, text_val) index += 1 self.xmltreefile().write() class Delter(AccessorBase): """ Remove ALL child elements for which marshal_to does NOT return None """ __slots__ = add_to_slots('parent_xpath', 'marshal_to', 'has_subclass') def __call__(self): parent = self.xmltreefile().find(self.parent_xpath) if parent is None: raise xcepts.LibvirtXMLNotFoundError("Parent element %s not " "found" % self.parent_xpath) # Don't delete while traversing list todel = [] index = 0 for child in parent.getchildren(): # To support directly deleting xml elements xml objects, # first create xmltreefile for new object if self.has_subclass: new_xmltreefile = xml_utils.XMLTreeFile( element_tree.tostring(child)) item = self.marshal_to(child.tag, new_xmltreefile, index, self.libvirtxml) else: try: # To support an optional text parameter, compatible # with no text parameter. item = self.marshal_to(child.tag, dict(list(child.items())), index, self.libvirtxml, child.text) except TypeError: item = self.marshal_to(child.tag, dict(list(child.items())), index, self.libvirtxml) # Always use absolute index (even if item was None) index += 1 # Account for case where child elements are mixed in # with other elements not supported by this class. # Also permits marshal functions to do element filtering # if the class should only address specificly attributed # elements. if item is not None: todel.append(child) for child in todel: parent.remove(child)
gpl-2.0
obeattie/sqlalchemy
lib/sqlalchemy/connectors/mxodbc.py
1
2562
import sys import re from sqlalchemy.connectors import Connector class MxODBCConnector(Connector): driver='mxodbc' supports_sane_multi_rowcount = False supports_unicode_statements = False supports_unicode_binds = False supports_native_decimal = False @classmethod def dbapi(cls): platform = sys.platform if platform == 'win32': from mx.ODBC import Windows as module # this can be the string "linux2", and possibly others elif 'linux' in platform: from mx.ODBC import unixODBC as module elif platform == 'darwin': from mx.ODBC import iODBC as module else: raise ImportError, "Unrecognized platform for mxODBC import" return module def visit_pool(self, pool): def connect(conn, rec): conn.stringformat = self.dbapi.MIXED_STRINGFORMAT conn.datetimeformat = self.dbapi.PYDATETIME_DATETIMEFORMAT #conn.bindmethod = self.dbapi.BIND_USING_PYTHONTYPE #conn.bindmethod = self.dbapi.BIND_USING_SQLTYPE pool.add_listener({'connect':connect}) def create_connect_args(self, url): """ Return a tuple of *args,**kwargs for creating a connection. The mxODBC 3.x connection constructor looks like this: connect(dsn, user='', password='', clear_auto_commit=1, errorhandler=None) This method translates the values in the provided uri into args and kwargs needed to instantiate an mxODBC Connection. The arg 'errorhandler' is not used by SQLAlchemy and will not be populated. """ opts = url.translate_connect_args(username='user') opts.update(url.query) args = opts['host'], kwargs = {'user':opts['user'], 'password': opts['password']} return args, kwargs def is_disconnect(self, e): if isinstance(e, self.dbapi.ProgrammingError): return "connection already closed" in str(e) elif isinstance(e, self.dbapi.Error): return '[08S01]' in str(e) else: return False def _get_server_version_info(self, connection): dbapi_con = connection.connection version = [] r = re.compile('[.\-]') # 18 == pyodbc.SQL_DBMS_VER for n in r.split(dbapi_con.getinfo(18)[1]): try: version.append(int(n)) except ValueError: version.append(n) return tuple(version)
mit
bart-h/linux-kernel-wm8505
scripts/gdb/linux/modules.py
1029
2597
# # gdb helper commands and functions for Linux kernel debugging # # module tools # # Copyright (c) Siemens AG, 2013 # # Authors: # Jan Kiszka <jan.kiszka@siemens.com> # # This work is licensed under the terms of the GNU GPL version 2. # import gdb from linux import cpus, utils, lists module_type = utils.CachedType("struct module") def module_list(): global module_type modules = utils.gdb_eval_or_none("modules") if modules is None: return module_ptr_type = module_type.get_type().pointer() for module in lists.list_for_each_entry(modules, module_ptr_type, "list"): yield module def find_module_by_name(name): for module in module_list(): if module['name'].string() == name: return module return None class LxModule(gdb.Function): """Find module by name and return the module variable. $lx_module("MODULE"): Given the name MODULE, iterate over all loaded modules of the target and return that module variable which MODULE matches.""" def __init__(self): super(LxModule, self).__init__("lx_module") def invoke(self, mod_name): mod_name = mod_name.string() module = find_module_by_name(mod_name) if module: return module.dereference() else: raise gdb.GdbError("Unable to find MODULE " + mod_name) LxModule() class LxLsmod(gdb.Command): """List currently loaded modules.""" _module_use_type = utils.CachedType("struct module_use") def __init__(self): super(LxLsmod, self).__init__("lx-lsmod", gdb.COMMAND_DATA) def invoke(self, arg, from_tty): gdb.write( "Address{0} Module Size Used by\n".format( " " if utils.get_long_type().sizeof == 8 else "")) for module in module_list(): layout = module['core_layout'] gdb.write("{address} {name:<19} {size:>8} {ref}".format( address=str(layout['base']).split()[0], name=module['name'].string(), size=str(layout['size']), ref=str(module['refcnt']['counter'] - 1))) t = self._module_use_type.get_type().pointer() first = True sources = module['source_list'] for use in lists.list_for_each_entry(sources, t, "source_list"): gdb.write("{separator}{name}".format( separator=" " if first else ",", name=use['source']['name'].string())) first = False gdb.write("\n") LxLsmod()
gpl-2.0
TonyThompson/fail2ban-patch
fail2ban/server/jail.py
4
6813
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Fail2Ban is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Fail2Ban; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Author: Cyril Jaquier __author__ = "Cyril Jaquier, Lee Clemens, Yaroslav Halchenko" __copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2011-2012 Lee Clemens, 2012 Yaroslav Halchenko" __license__ = "GPL" import Queue, logging from .actions import Actions from ..helpers import getLogger # Gets the instance of the logger. logSys = getLogger(__name__) class Jail: """Fail2Ban jail, which manages a filter and associated actions. The class handles the initialisation of a filter, and actions. It's role is then to act as an interface between the filter and actions, passing bans detected by the filter, for the actions to then act upon. Parameters ---------- name : str Name assigned to the jail. backend : str Backend to be used for filter. "auto" will attempt to pick the most preferred backend method. Default: "auto" db : Fail2BanDb Fail2Ban persistent database instance. Default: `None` Attributes ---------- name database filter actions idle status """ #Known backends. Each backend should have corresponding __initBackend method # yoh: stored in a list instead of a tuple since only # list had .index until 2.6 _BACKENDS = ['pyinotify', 'gamin', 'polling', 'systemd'] def __init__(self, name, backend = "auto", db=None): self.__db = db # 26 based on iptable chain name limit of 30 less len('f2b-') if len(name) >= 26: logSys.warning("Jail name %r might be too long and some commands " "might not function correctly. Please shorten" % name) self.__name = name self.__queue = Queue.Queue() self.__filter = None logSys.info("Creating new jail '%s'" % self.name) self._setBackend(backend) def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self.name) def _setBackend(self, backend): backend = backend.lower() # to assure consistent matching backends = self._BACKENDS if backend != 'auto': # we have got strict specification of the backend to use if not (backend in self._BACKENDS): logSys.error("Unknown backend %s. Must be among %s or 'auto'" % (backend, backends)) raise ValueError("Unknown backend %s. Must be among %s or 'auto'" % (backend, backends)) # so explore starting from it till the 'end' backends = backends[backends.index(backend):] for b in backends: initmethod = getattr(self, '_init%s' % b.capitalize()) try: initmethod() if backend != 'auto' and b != backend: logSys.warning("Could only initiated %r backend whenever " "%r was requested" % (b, backend)) else: logSys.info("Initiated %r backend" % b) self.__actions = Actions(self) return # we are done except ImportError, e: # Log debug if auto, but error if specific logSys.log( logging.DEBUG if backend == "auto" else logging.ERROR, "Backend %r failed to initialize due to %s" % (b, e)) # log error since runtime error message isn't printed, INVALID COMMAND logSys.error( "Failed to initialize any backend for Jail %r" % self.name) raise RuntimeError( "Failed to initialize any backend for Jail %r" % self.name) def _initPolling(self): from filterpoll import FilterPoll logSys.info("Jail '%s' uses poller" % self.name) self.__filter = FilterPoll(self) def _initGamin(self): # Try to import gamin from filtergamin import FilterGamin logSys.info("Jail '%s' uses Gamin" % self.name) self.__filter = FilterGamin(self) def _initPyinotify(self): # Try to import pyinotify from filterpyinotify import FilterPyinotify logSys.info("Jail '%s' uses pyinotify" % self.name) self.__filter = FilterPyinotify(self) def _initSystemd(self): # pragma: systemd no cover # Try to import systemd from filtersystemd import FilterSystemd logSys.info("Jail '%s' uses systemd" % self.name) self.__filter = FilterSystemd(self) @property def name(self): """Name of jail. """ return self.__name @property def database(self): """The database used to store persistent data for the jail. """ return self.__db @property def filter(self): """The filter which the jail is using to monitor log files. """ return self.__filter @property def actions(self): """Actions object used to manage actions for jail. """ return self.__actions @property def idle(self): """A boolean indicating whether jail is idle. """ return self.filter.idle or self.actions.idle @idle.setter def idle(self, value): self.filter.idle = value self.actions.idle = value @property def status(self): """The status of the jail. """ return [ ("Filter", self.filter.status), ("Actions", self.actions.status), ] def putFailTicket(self, ticket): """Add a fail ticket to the jail. Used by filter to add a failure for banning. """ self.__queue.put(ticket) if self.database is not None: self.database.addBan(self, ticket) def getFailTicket(self): """Get a fail ticket from the jail. Used by actions to get a failure for banning. """ try: return self.__queue.get(False) except Queue.Empty: return False def start(self): """Start the jail, by starting filter and actions threads. Once stated, also queries the persistent database to reinstate any valid bans. """ self.filter.start() self.actions.start() # Restore any previous valid bans from the database if self.database is not None: for ticket in self.database.getBansMerged( jail=self, bantime=self.actions.getBanTime()): if not self.filter.inIgnoreIPList(ticket.getIP()): self.__queue.put(ticket) logSys.info("Jail '%s' started" % self.name) def stop(self): """Stop the jail, by stopping filter and actions threads. """ self.filter.stop() self.actions.stop() self.filter.join() self.actions.join() logSys.info("Jail '%s' stopped" % self.name) def is_alive(self): """Check jail "is_alive" by checking filter and actions threads. """ return self.filter.is_alive() or self.actions.is_alive()
gpl-2.0
kvar/ansible
lib/ansible/modules/network/nxos/nxos_snmp_contact.py
106
3931
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = ''' --- module: nxos_snmp_contact extends_documentation_fragment: nxos version_added: "2.2" short_description: Manages SNMP contact info. description: - Manages SNMP contact information. author: - Jason Edelman (@jedelman8) - Gabriele Gerbino (@GGabriele) notes: - Tested against NXOSv 7.3.(0)D1(1) on VIRL - C(state=absent) removes the contact configuration if it is configured. options: contact: description: - Contact information. required: true state: description: - Manage the state of the resource. required: true default: present choices: ['present','absent'] ''' EXAMPLES = ''' # ensure snmp contact is configured - nxos_snmp_contact: contact: Test state: present ''' RETURN = ''' commands: description: commands sent to the device returned: always type: list sample: ["snmp-server contact New_Test"] ''' import re from ansible.module_utils.network.nxos.nxos import load_config, run_commands from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule def execute_show_command(command, module): command = { 'command': command, 'output': 'text', } return run_commands(module, command) def flatten_list(command_lists): flat_command_list = [] for command in command_lists: if isinstance(command, list): flat_command_list.extend(command) else: flat_command_list.append(command) return flat_command_list def get_snmp_contact(module): contact = {} contact_regex = r'^\s*snmp-server\scontact\s(?P<contact>.+)$' body = execute_show_command('show run snmp', module)[0] match_contact = re.search(contact_regex, body, re.M) if match_contact: contact['contact'] = match_contact.group("contact") return contact def main(): argument_spec = dict( contact=dict(required=True, type='str'), state=dict(choices=['absent', 'present'], default='present'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) results = {'changed': False, 'commands': [], 'warnings': warnings} contact = module.params['contact'] state = module.params['state'] existing = get_snmp_contact(module) commands = [] if state == 'absent': if existing and existing['contact'] == contact: commands.append('no snmp-server contact') elif state == 'present': if not existing or existing['contact'] != contact: commands.append('snmp-server contact {0}'.format(contact)) cmds = flatten_list(commands) if cmds: results['changed'] = True if not module.check_mode: load_config(module, cmds) if 'configure' in cmds: cmds.pop(0) results['commands'] = cmds module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
yunque/sms-tools
lectures/06-Harmonic-model/plots-code/monophonic-polyphonic.py
21
2258
import numpy as np import matplotlib.pyplot as plt from scipy.signal import hamming, triang, blackmanharris import sys, os, functools, time sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/')) import sineModel as SM import stft as STFT import utilFunctions as UF plt.figure(1, figsize=(9, 6)) plt.subplot(211) (fs, x) = UF.wavread(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../sounds/carnatic.wav')) x1 = x[4.35*fs:] w = np.blackman(1301) N = 2048 H = 250 t = -70 minSineDur = .02 maxnSines = 150 freqDevOffset = 20 freqDevSlope = 0.02 mX, pX = STFT.stftAnal(x, fs, w, N, H) tfreq, tmag, tphase = SM.sineModelAnal(x, fs, w, N, H, t, maxnSines, minSineDur, freqDevOffset, freqDevSlope) maxplotfreq = 3000.0 maxplotbin = int(N*maxplotfreq/fs) numFrames = int(mX[:,0].size) frmTime = H*np.arange(numFrames)/float(fs) binFreq = np.arange(maxplotbin+1)*float(fs)/N plt.pcolormesh(frmTime, binFreq, np.transpose(mX[:,:maxplotbin+1])) plt.autoscale(tight=True) tracks = tfreq*np.less(tfreq, maxplotfreq) tracks[tracks<=0] = np.nan plt.plot(frmTime, tracks, color='k', lw=1.5) plt.autoscale(tight=True) plt.title('mX + sine frequencies (carnatic.wav)') plt.subplot(212) (fs, x) = UF.wavread(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../sounds/vignesh.wav')) w = np.blackman(1101) N = 2048 H = 250 t = -90 minSineDur = .1 maxnSines = 200 freqDevOffset = 20 freqDevSlope = 0.02 mX, pX = STFT.stftAnal(x, fs, w, N, H) tfreq, tmag, tphase = SM.sineModelAnal(x, fs, w, N, H, t, maxnSines, minSineDur, freqDevOffset, freqDevSlope) maxplotfreq = 3000.0 maxplotbin = int(N*maxplotfreq/fs) numFrames = int(mX[:,0].size) frmTime = H*np.arange(numFrames)/float(fs) binFreq = np.arange(maxplotbin+1)*float(fs)/N plt.pcolormesh(frmTime, binFreq, np.transpose(mX[:,:maxplotbin+1])) plt.autoscale(tight=True) tracks = tfreq*np.less(tfreq, maxplotfreq) tracks[tracks<=0] = np.nan plt.plot(frmTime, tracks, color='k', lw=1.5) plt.autoscale(tight=True) plt.title('mX + sine frequencies (vignesh.wav)') plt.tight_layout() plt.savefig('monophonic-polyphonic.png') plt.show()
agpl-3.0
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/eggs/boto-2.27.0-py2.7.egg/boto/contrib/__init__.py
396
1107
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. #
gpl-3.0
irvingpop/digital-beer-menu
src/lib/werkzeug/testsuite/wsgi.py
54
8693
# -*- coding: utf-8 -*- """ werkzeug.testsuite.wsgi ~~~~~~~~~~~~~~~~~~~~~~~ Tests the WSGI utilities. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement import unittest from os import path from cStringIO import StringIO from werkzeug.testsuite import WerkzeugTestCase from werkzeug.wrappers import BaseResponse from werkzeug.exceptions import BadRequest, ClientDisconnected from werkzeug.test import Client, create_environ, run_wsgi_app from werkzeug import wsgi class WSGIUtilsTestCase(WerkzeugTestCase): def test_shareddatamiddleware_get_file_loader(self): app = wsgi.SharedDataMiddleware(None, {}) assert callable(app.get_file_loader('foo')) def test_shared_data_middleware(self): def null_application(environ, start_response): start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) yield 'NOT FOUND' app = wsgi.SharedDataMiddleware(null_application, { '/': path.join(path.dirname(__file__), 'res'), '/sources': path.join(path.dirname(__file__), 'res'), '/pkg': ('werkzeug.debug', 'shared') }) for p in '/test.txt', '/sources/test.txt': app_iter, status, headers = run_wsgi_app(app, create_environ(p)) assert status == '200 OK' assert ''.join(app_iter).strip() == 'FOUND' app_iter, status, headers = run_wsgi_app(app, create_environ('/pkg/debugger.js')) contents = ''.join(app_iter) assert '$(function() {' in contents app_iter, status, headers = run_wsgi_app(app, create_environ('/missing')) assert status == '404 NOT FOUND' assert ''.join(app_iter).strip() == 'NOT FOUND' def test_get_host(self): env = {'HTTP_X_FORWARDED_HOST': 'example.org', 'SERVER_NAME': 'bullshit', 'HOST_NAME': 'ignore me dammit'} assert wsgi.get_host(env) == 'example.org' assert wsgi.get_host(create_environ('/', 'http://example.org')) \ == 'example.org' def test_responder(self): def foo(environ, start_response): return BaseResponse('Test') client = Client(wsgi.responder(foo), BaseResponse) response = client.get('/') assert response.status_code == 200 assert response.data == 'Test' def test_pop_path_info(self): original_env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b///c'} # regular path info popping def assert_tuple(script_name, path_info): assert env.get('SCRIPT_NAME') == script_name assert env.get('PATH_INFO') == path_info env = original_env.copy() pop = lambda: wsgi.pop_path_info(env) assert_tuple('/foo', '/a/b///c') assert pop() == 'a' assert_tuple('/foo/a', '/b///c') assert pop() == 'b' assert_tuple('/foo/a/b', '///c') assert pop() == 'c' assert_tuple('/foo/a/b///c', '') assert pop() is None def test_peek_path_info(self): env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/aaa/b///c'} assert wsgi.peek_path_info(env) == 'aaa' assert wsgi.peek_path_info(env) == 'aaa' def test_limited_stream(self): class RaisingLimitedStream(wsgi.LimitedStream): def on_exhausted(self): raise BadRequest('input stream exhausted') io = StringIO('123456') stream = RaisingLimitedStream(io, 3) assert stream.read() == '123' self.assert_raises(BadRequest, stream.read) io = StringIO('123456') stream = RaisingLimitedStream(io, 3) assert stream.read(1) == '1' assert stream.read(1) == '2' assert stream.read(1) == '3' self.assert_raises(BadRequest, stream.read) io = StringIO('123456\nabcdefg') stream = wsgi.LimitedStream(io, 9) assert stream.readline() == '123456\n' assert stream.readline() == 'ab' io = StringIO('123456\nabcdefg') stream = wsgi.LimitedStream(io, 9) assert stream.readlines() == ['123456\n', 'ab'] io = StringIO('123456\nabcdefg') stream = wsgi.LimitedStream(io, 9) assert stream.readlines(2) == ['12'] assert stream.readlines(2) == ['34'] assert stream.readlines() == ['56\n', 'ab'] io = StringIO('123456\nabcdefg') stream = wsgi.LimitedStream(io, 9) assert stream.readline(100) == '123456\n' io = StringIO('123456\nabcdefg') stream = wsgi.LimitedStream(io, 9) assert stream.readlines(100) == ['123456\n', 'ab'] io = StringIO('123456') stream = wsgi.LimitedStream(io, 3) assert stream.read(1) == '1' assert stream.read(1) == '2' assert stream.read() == '3' assert stream.read() == '' io = StringIO('123456') stream = wsgi.LimitedStream(io, 3) assert stream.read(-1) == '123' def test_limited_stream_disconnection(self): io = StringIO('A bit of content') # disconnect detection on out of bytes stream = wsgi.LimitedStream(io, 255) with self.assert_raises(ClientDisconnected): stream.read() # disconnect detection because file close io = StringIO('x' * 255) io.close() stream = wsgi.LimitedStream(io, 255) with self.assert_raises(ClientDisconnected): stream.read() def test_path_info_extraction(self): x = wsgi.extract_path_info('http://example.com/app', '/app/hello') assert x == u'/hello' x = wsgi.extract_path_info('http://example.com/app', 'https://example.com/app/hello') assert x == u'/hello' x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app/hello') assert x == u'/hello' x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app') assert x == u'/' x = wsgi.extract_path_info(u'http://☃.net/', u'/fööbär') assert x == u'/fööbär' x = wsgi.extract_path_info(u'http://☃.net/x', u'http://☃.net/x/fööbär') assert x == u'/fööbär' env = create_environ(u'/fööbär', u'http://☃.net/x/') x = wsgi.extract_path_info(env, u'http://☃.net/x/fööbär') assert x == u'/fööbär' x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/a/hello') assert x is None x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app/hello', collapse_http_schemes=False) assert x is None def test_get_host_fallback(self): assert wsgi.get_host({ 'SERVER_NAME': 'foobar.example.com', 'wsgi.url_scheme': 'http', 'SERVER_PORT': '80' }) == 'foobar.example.com' assert wsgi.get_host({ 'SERVER_NAME': 'foobar.example.com', 'wsgi.url_scheme': 'http', 'SERVER_PORT': '81' }) == 'foobar.example.com:81' def test_multi_part_line_breaks(self): data = 'abcdef\r\nghijkl\r\nmnopqrstuvwxyz\r\nABCDEFGHIJK' test_stream = StringIO(data) lines = list(wsgi.make_line_iter(test_stream, limit=len(data), buffer_size=16)) assert lines == ['abcdef\r\n', 'ghijkl\r\n', 'mnopqrstuvwxyz\r\n', 'ABCDEFGHIJK'] data = 'abc\r\nThis line is broken by the buffer length.\r\nFoo bar baz' test_stream = StringIO(data) lines = list(wsgi.make_line_iter(test_stream, limit=len(data), buffer_size=24)) assert lines == ['abc\r\n', 'This line is broken by the buffer length.\r\n', 'Foo bar baz'] def test_multi_part_line_breaks_problematic(self): data = 'abc\rdef\r\nghi' for x in xrange(1, 10): test_stream = StringIO(data) lines = list(wsgi.make_line_iter(test_stream, limit=len(data), buffer_size=4)) assert lines == ['abc\r', 'def\r\n', 'ghi'] def test_lines_longer_buffer_size(self): data = '1234567890\n1234567890\n' for bufsize in xrange(1, 15): lines = list(wsgi.make_line_iter(StringIO(data), limit=len(data), buffer_size=4)) self.assert_equal(lines, ['1234567890\n', '1234567890\n']) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(WSGIUtilsTestCase)) return suite
gpl-2.0
tvibliani/odoo
addons/hr_attendance/wizard/__init__.py
375
1073
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import hr_attendance_error # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
kalwar/openelisglobal-core
liquibase/OE3.4/testCatalogCI_IPCI/scripts/sortSections.py
13
1111
#!/usr/bin/env python # -*- coding: utf-8 -*- def convert_to_existing_name( name ): if name == 'Hemato-immunologie' or name == 'H�mato-immunologie': return 'Hemto-Immunology' elif name == 'Biochimie': return 'Biochemistry' elif name == 'H�matologie' or name == 'Hematologie': return 'Hematology' elif name == 'Immunologie': return 'Immunology' elif name == 'Immunologie-Serologie' or name == 'Serology': return 'Serology-Immunology' elif name == 'Bacteriologie': return 'Bacteria' return name section_file = open( "testSections.txt") results = open("output/SectionOrder.sql", 'w') handled_sections = [] order = 10 for line in section_file: if len(line) > 1: line = line.strip() if line not in handled_sections: handled_sections.append(line) results.write( "update clinlims.test_section set sort_order=" + str(order) + " where name = '" + convert_to_existing_name( line ) + "';\n" ) order = order + 10 print "Done check SectionOrder.sql"
mpl-2.0
sss/calibre-at-bzr
src/cherrypy/scaffold/__init__.py
80
1859
"""<MyProject>, a CherryPy application. Use this as a base for creating new CherryPy applications. When you want to make a new app, copy and paste this folder to some other location (maybe site-packages) and rename it to the name of your project, then tweak as desired. Even before any tweaking, this should serve a few demonstration pages. Change to this directory and run: ../cherryd -c site.conf """ import cherrypy from cherrypy import tools, url import os local_dir = os.path.join(os.getcwd(), os.path.dirname(__file__)) class Root: _cp_config = {'tools.log_tracebacks.on': True, } def index(self): return """<html> <body>Try some <a href='%s?a=7'>other</a> path, or a <a href='%s?n=14'>default</a> path.<br /> Or, just look at the pretty picture:<br /> <img src='%s' /> </body></html>""" % (url("other"), url("else"), url("files/made_with_cherrypy_small.png")) index.exposed = True def default(self, *args, **kwargs): return "args: %s kwargs: %s" % (args, kwargs) default.exposed = True def other(self, a=2, b='bananas', c=None): cherrypy.response.headers['Content-Type'] = 'text/plain' if c is None: return "Have %d %s." % (int(a), b) else: return "Have %d %s, %s." % (int(a), b, c) other.exposed = True files = cherrypy.tools.staticdir.handler( section="/files", dir=os.path.join(local_dir, "static"), # Ignore .php files, etc. match=r'\.(css|gif|html?|ico|jpe?g|js|png|swf|xml)$', ) root = Root() # Uncomment the following to use your own favicon instead of CP's default. #favicon_path = os.path.join(local_dir, "favicon.ico") #root.favicon_ico = tools.staticfile.handler(filename=favicon_path)
gpl-3.0
rkhleics/wagtailmenus
wagtailmenus/models/mixins.py
2
4937
from django.template.loader import get_template, select_template from wagtailmenus.conf import settings from wagtailmenus.utils.inspection import accepts_kwarg def get_item_by_index_or_last_item(items, index): if items is None: return try: return items[index] except IndexError: return items[-1] class DefinesSubMenuTemplatesMixin: # Use to specify a single sub menu template for all levels sub_menu_template_name = None # Use to specify sub menu templates for each level sub_menu_template_names = None def _get_specified_sub_menu_template_name(self, level): """ Called by get_sub_menu_template(). Iterates through the various ways in which developers can specify potential sub menu templates for a menu, and returns the name of the most suitable template for the ``current_level``. Values are checked in the following order: 1. The ``sub_menu_template`` value passed to the template tag (if provided) 2. The most suitable template from the ``sub_menu_templates`` list passed to the template tag (if provided) 3. The ``sub_menu_template_name`` attribute set on the menu class (if set) 4. The most suitable template from a list of templates set as the ``sub_menu_template_names`` attribute on the menu class (if set) Parameters ---------- level : int The 'current_level' value from the context, indicating the depth of sub menu being rendered as part of a multi-level menu. For sub menus, the value will always be greater than or equal to 2. Returns ------- str or None A template name string (the path to a template in the file system), or None if no template has been 'specified' """ ideal_index = level - 2 return self._option_vals.sub_menu_template_name or \ get_item_by_index_or_last_item( self._option_vals.sub_menu_template_names, ideal_index) or \ self.sub_menu_template_name or \ get_item_by_index_or_last_item( self.sub_menu_template_names, ideal_index) def get_sub_menu_template(self, level=2): if not hasattr(self, '_sub_menu_template_cache'): # Initialise cache for this menu instance self._sub_menu_template_cache = {} elif level in self._sub_menu_template_cache: # Return a cached template instance return self._sub_menu_template_cache[level] template_name = self._get_specified_sub_menu_template_name(level) if template_name: # A template was specified somehow template = get_template(template_name) else: # A template wasn't specified, so search the filesystem template = select_template( self.get_sub_menu_template_names(level) ) # Cache the template instance before returning self._sub_menu_template_cache[level] = template return template sub_menu_template = property(get_sub_menu_template) def get_sub_menu_template_names(self, level=2): """Return a list of template paths/names to search for when rendering a sub menu for this menu instance at the supplied `level`. The list should be ordered with most specific names first, since the first template found to exist will be used for rendering.""" template_names = [] menu_name = self.menu_short_name site = self._contextual_vals.current_site if settings.SITE_SPECIFIC_TEMPLATE_DIRS and site: hostname = site.hostname template_names.extend([ "menus/%s/%s/level_%s.html" % (hostname, menu_name, level), "menus/%s/%s/sub_menu.html" % (hostname, menu_name), "menus/%s/%s_sub_menu.html" % (hostname, menu_name), "menus/%s/sub_menu.html" % hostname, ]) template_names.extend([ "menus/%s/level_%s.html" % (menu_name, level), "menus/%s/sub_menu.html" % menu_name, "menus/%s_sub_menu.html" % menu_name, settings.DEFAULT_SUB_MENU_TEMPLATE, ]) return template_names def get_context_data(self, **kwargs): """ Include the name of the sub menu template in the context. This is purely for backwards compatibility. Any sub menus rendered as part of this menu will call `sub_menu_template` on the original menu instance to get an actual `Template` """ data = {} if self._contextual_vals.current_level == 1 and self.max_levels > 1: data['sub_menu_template'] = self.sub_menu_template.template.name data.update(kwargs) return super().get_context_data(**data)
mit
javier3407/Plugin.Video.JavierTV
resources/tools/shidurlive.py
4
4691
# -*- coding: utf-8 -*- #------------------------------------------------------------ # Regex de Shidurlive para PalcoTV # Version 0.1 (15.10.2014) #------------------------------------------------------------ # License: GPL (http://www.gnu.org/licenses/gpl-3.0.html) # Gracias a la librería plugintools de Jesús (www.mimediacenter.info) import os import sys import urllib import urllib2 import re import shutil import zipfile import time import xbmc import xbmcgui import xbmcaddon import xbmcplugin import plugintools import json addonName = xbmcaddon.Addon().getAddonInfo("name") addonVersion = xbmcaddon.Addon().getAddonInfo("version") addonId = xbmcaddon.Addon().getAddonInfo("id") addonPath = xbmcaddon.Addon().getAddonInfo("path") home = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.palcotv/', '')) tools = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.palcotv/resources/tools', '')) addons = xbmc.translatePath(os.path.join('special://home/addons/', '')) resources = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.palcotv/resources', '')) art = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.palcotv/art', '')) tmp = xbmc.translatePath(os.path.join('special://home/addons/plugin.video.palcotv/tmp', '')) playlists = xbmc.translatePath(os.path.join('special://home/addons/playlists', '')) icon = art + 'icon.png' fanart = 'fanart.jpg' # Función que guía el proceso de elaboración de la URL original def shidurlive(params): plugintools.log('[%s %s].Regex Shidurlive %s' % (addonName, addonVersion, repr(params))) url_user = {} # Construimos diccionario... url = params.get("url") url_extracted = url.split(" ") for entry in url_extracted: if entry.startswith("rtmp"): entry = entry.replace("rtmp=", "") url_user["rtmp"]=entry elif entry.startswith("playpath"): entry = entry.replace("playpath=", "") url_user["playpath"]=entry elif entry.startswith("swfUrl"): entry = entry.replace("swfUrl=", "") url_user["swfurl"]=entry elif entry.startswith("pageUrl"): entry = entry.replace("pageUrl=", "") url_user["pageurl"]=entry elif entry.startswith("token"): entry = entry.replace("token=", "") url_user["token"]=entry elif entry.startswith("referer"): entry = entry.replace("referer=", "") url_user["referer"]=entry plugintools.log("URL_user dict= "+repr(url_user)) pageurl = url_user.get("pageurl") # Controlamos ambos casos de URL: Único link (pageUrl) o link completo rtmp://... if pageurl is None: pageurl = url_user.get("url") referer= url_user.get("referer") url_user["pageurl"]=pageurl print 'pageurl',pageurl print 'referer',referer body = gethttp_headers(pageurl, referer) plugintools.log("body= "+body) #src=http://www.shidurlive.com/stream/4e6a51324f54637a4e6a4d325a6a63324e6a55334d6a63354d7a453d/706c381d1202 src = re.compile('src=\"(.*?)\"').findall(body) print 'src',src url_user["pageurl"]=src[0] pageurl = url_user.get("pageurl") referer = url_user.get("referer") body = gethttp_headers(pageurl, referer) plugintools.log("body= "+body) getparams_shidurlive(url_user, body) url = url_user.get("rtmp") + ' playpath=' + url_user.get("playpath") + ' swfUrl=http://cdn.shidurlive.com/player.swf pageUrl=' + url_user.get("pageurl") + ' live=true timeout=15' plugintools.play_resolved_url(url) # Vamos a hacer una llamada al pageUrl def gethttp_headers(pageurl, referer): request_headers=[] request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31"]) request_headers.append(["Referer",referer]) body,response_headers = plugintools.read_body_and_headers(pageurl, headers=request_headers) plugintools.log("body= "+body) return body # Iniciamos protocolo de elaboración de la URL original # Capturamos parámetros correctos def getparams_shidurlive(url_user, body): plugintools.log('[%s %s] getparams_shidurlive %s' % (addonName, addonVersion, repr(url_user))) # Construimos el diccionario de 9stream streamer = re.compile("'streamer', '([^']*)").findall(body) url_user["rtmp"]=streamer[0] file = re.compile("'file', '([^']*)").findall(body) url_user["playpath"]=file[0]
gpl-2.0
nansencenter/nansat
nansat/tests/test_pointbrowser.py
1
3888
# ------------------------------------------------------------------------------ # Name: test_pointbrowser.py # Purpose: Test the PointBrowser class # # Author: Aleksander Vines, Anton Korosov # # Created: 2015-10-22 # Copyright: (c) NERSC # Licence: This file is part of NANSAT. You can redistribute it or modify # under the terms of GNU General Public License, v.3 # http://www.gnu.org/licenses/gpl-3.0.html # ------------------------------------------------------------------------------ import os import unittest from mock import patch, PropertyMock, Mock, MagicMock, DEFAULT import numpy as np from nansat.pointbrowser import PointBrowser try: import matplotlib import matplotlib.pyplot as plt plt.switch_backend('Agg') except ImportError: MATPLOTLIB_IS_INSTALLED = False else: MATPLOTLIB_IS_INSTALLED = True class PointBrowserTest(unittest.TestCase): @unittest.skipUnless(MATPLOTLIB_IS_INSTALLED, 'Matplotlib is required') def setUp(self): self.data = np.zeros((4, 4)) self.event = MagicMock() def test_init(self): """ Create Pointbrowser """ pb = PointBrowser(self.data, force_interactive=False) self.assertIsInstance(pb.fig, plt.Figure) self.assertTrue(np.alltrue(pb.data == self.data)) self.assertTrue(np.alltrue(pb.ax.get_images()[0].get_array() == self.data)) self.assertEqual(pb.fmt, 'x-k') self.assertEqual(pb.points, []) self.assertEqual(pb.coordinates, [[]]) def test_onclick(self): """ Mimic click """ self.event = MagicMock() self.event.xdata = 10 self.event.ydata = 10 self.event.key = None pb = PointBrowser(self.data, force_interactive=False) pb.onclick(self.event) self.assertIsInstance(pb.points[0][0], matplotlib.lines.Line2D) self.assertEqual(pb.coordinates, [[(self.event.xdata, self.event.ydata)]]) def test_onclick_none(self): """ Mimic click outside figure """ self.event.xdata = None self.event.ydata = None self.event.key = None pb = PointBrowser(self.data, force_interactive=False) pb.onclick(self.event) self.assertEqual(pb.points, []) self.assertEqual(pb.coordinates, [[]]) def test_onclick_key_z(self): """ Mimic click with 'z' pressed """ self.event.xdata = 10 self.event.ydata = 10 self.event.key = 'z' pb = PointBrowser(self.data, force_interactive=False) pb.onclick(self.event) self.assertEqual(pb.points, []) self.assertEqual(pb.coordinates, [[]]) def test_onclick_key(self): """ Mimic click with 'anykey' pressed """ self.event = MagicMock() self.event.xdata = 10 self.event.ydata = 10 self.event.key = 'newkey' pb = PointBrowser(self.data, force_interactive=False) pb.onclick(self.event) self.assertIsInstance(pb.points[0][0], matplotlib.lines.Line2D) self.assertEqual(pb.coordinates, [[],[(self.event.xdata, self.event.ydata)]]) def test_convert_coordinates(self): """ Mimic click with 'anykey' pressed """ pb = PointBrowser(self.data, force_interactive=False) pb.coordinates = [[[1,2,3],[4,5,6]]] new_coordinates = pb._convert_coordinates() self.assertTrue(np.all(new_coordinates[0] == np.array([[1,2,3], [4,5,6]]).T)) @patch('nansat.pointbrowser.plt') def test_get_points(self, plt_mock): plt_mock.show.return_value = None pb = PointBrowser(self.data, force_interactive=False) points = pb.get_points() self.assertTrue(pb.fig.canvas.mpl_connect.called) self.assertTrue(plt_mock.show.called) self.assertEqual(points, []) if __name__ == "__main__": unittest.main()
gpl-3.0
ronaldsantos63/tkGAME
tkRAD/xml/rad_xml_widget.py
1
109576
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ tkRAD - tkinter Rapid Application Development library (c) 2013+ Raphaël SEBAN <motus@laposte.net> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see: http://www.gnu.org/licenses/ """ # lib imports import re import tkinter as TK from tkinter import ttk from ..core import tools from ..core import path from . import rad_xml_widget_base as RB class RADXMLWidget (RB.RADXMLWidgetBase): r""" generic XML to tkinter widget builder; this is THE tkinter widget building processor of tkRAD; supports tkinter natives in XML script e.g. <button id="" text="OK" command="@OKClicked" .../> supports user-defined specific widgets in XML script e.g. <widget id="" class="MyClassName" .../> supports on-the-fly module imports e.g. <module import="tkinter" as="TK"/> and many, many other features (see doc for more); """ # 'anchor' XML attribute pre-compiled subs ANCHORS = ( (re.compile(r"(?i)north|top|up"), TK.N), (re.compile(r"(?i)south|bottom|down"), TK.S), (re.compile(r"(?i)east|right"), TK.E), (re.compile(r"(?i)west|left"), TK.W), (re.compile(r"\W+"), r""), (re.compile(TK.N + "+"), TK.N), (re.compile(TK.S + "+"), TK.S), (re.compile(TK.E + "+"), TK.E), (re.compile(TK.W + "+"), TK.W), (re.compile(TK.W + TK.N), TK.NW), (re.compile(TK.E + TK.N), TK.NE), (re.compile(TK.W + TK.S), TK.SW), (re.compile(TK.E + TK.S), TK.SE), ) # end of ANCHORS # default XML attribute values # overrides RADXMLWidgetBase.ATTRS ATTRS = { "common": { "id": None, }, "button": { "underline": None, }, "checkbutton": { "underline": None, }, "label": { "underline": None, }, "listbox": { #~ "name": None, "class": None, "args": None, "module": None, "choices": None, "start": None, "layout": None, # can be: None or pack|grid|place "layout_options": None, # pack_opts|grid_opts|place_opts "resizable": "no", # can be: no|yes|width|height }, "menubutton": { "underline": None, }, "optionmenu": { #~ "name": None, "listvariable": None, "variable": None, "choices": None, "start": None, "layout": None, # can be: None or pack|grid|place "layout_options": None, # pack_opts|grid_opts|place_opts "resizable": "no", # can be: no|yes|width|height }, "radiobutton": { "underline": None, }, "tkwidget": { }, "ttkbutton": { "underline": None, }, "ttkcheckbutton": { "underline": None, }, "ttklabel": { "underline": None, }, "ttkmenubutton": { "underline": None, }, "ttkradiobutton": { "underline": None, }, "ttktab": { "sticky": "all", "underline": -1, }, "widget": { #~ "name": None, "class": None, "args": None, "module": None, "layout": None, # can be: None or pack|grid|place "layout_options": None, # pack_opts|grid_opts|place_opts "resizable": "no", # can be: no|yes|width|height }, "include": { #~ "name": None, "src": None, "xml_dir": None, "xml_filename": None, "xml_file_ext": None, }, "module": { "from": None, "import": None, "as": None, }, "configure": { "widget": None, }, "layout": { "widget": None, "layout": "pack", # can be: pack|grid|place "layout_options": None, # pack_opts|grid_opts|place_opts "resizable": "no", # can be: no|yes|width|height }, "event": { "signal": None, "slot": None, }, "tkevent": { "widget": None, "bind": "bind", # can be: bind|bind_class|bind_all "class": None, "seq": None, # tk event sequence: '<modifier-type-detail>' "slot": None, # slot event handler (method or function) "add": None, # can be: None or '+' only }, } # end of ATTRS # $ 2014-02-24 RS $ # new support: # now TK and ttk are embedded in predefined classnames; CLASSES = { # tkinter native classes support "button": "TK.Button", "canvas": "TK.Canvas", "checkbutton": "TK.Checkbutton", "entry": "TK.Entry", "frame": "TK.Frame", "label": "TK.Label", "labelframe": "TK.LabelFrame", "listbox": "TK.Listbox", "menu": "TK.Menu", "menubutton": "TK.Menubutton", "message": "TK.Message", "optionmenu": "TK.OptionMenu", "panedwindow": "TK.PanedWindow", "radiobutton": "TK.Radiobutton", "scale": "TK.Scale", "scrollbar": "TK.Scrollbar", "spinbox": "TK.Spinbox", "text": "TK.Text", "toplevel": "TK.Toplevel", # ttk additional classes support "ttkbutton": "ttk.Button", "ttkcheckbutton": "ttk.Checkbutton", "ttkcombobox": "ttk.Combobox", "ttkentry": "ttk.Entry", "ttkframe": "ttk.Frame", "ttklabel": "ttk.Label", "ttklabelframe": "ttk.LabelFrame", "ttkmenubutton": "ttk.Menubutton", "ttknotebook": "ttk.Notebook", "ttkpanedwindow": "ttk.PanedWindow", "ttkprogressbar": "ttk.Progressbar", "ttkradiobutton": "ttk.Radiobutton", "ttkscale": "ttk.Scale", "ttkscrollbar": "ttk.Scrollbar", "ttkseparator": "ttk.Separator", "ttksizegrip": "ttk.Sizegrip", "ttktab": "ttk.Frame", "ttktreeview": "ttk.Treeview", } # end of CLASSES # XML tree root element # overrides RADXMLBase.DOCTYPE DOCTYPE = "tkwidget" # accepted XML child elements for XML container element DTD = { "menubutton": ("menu", "tkmenu"), "ttkmenubutton": ("menu", "tkmenu"), "ttknotebook": ("ttktab", ), "widget": ( "configure", "event", "include", "layout", "module", "style", "tkevent", "tkmenu", "ttkstyle", "ttktheme", "widget", ) + tuple(CLASSES.keys()), } # end of DTD # XML file path parts for xml_build() automatic mode # overrides RADXMLBase.XML_RC XML_RC = { "dir": "^/xml/widget", # do *NOT* define "filename" here "file_ext": ".xml", } # end of XML_RC # ------------------ XML elements building ----------------------- def _build_element_button (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_canvas (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_checkbutton (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ _ok = self._build_tk_native(xml_tag, xml_element, tk_parent) if xml_element.get("checked"): self.WIDGET.select() else: self.WIDGET.deselect() # end if return _ok # end def def _build_element_configure (self, xml_tag, xml_element, tk_parent): r""" XML element <configure> acts like tkinter.w.configure() by parsing XML attributes as if they were config options e.g. tkinter.w.configure(**options) example: <configure widget="w_id" bg="red" relief="@FLAT".../> returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) # try to retrieve concerned widget _widget = _attributes.get("widget", tk_parent) # try to configure widget (True=success, False=failure) return self._set_widget_config(_widget, self.TK_CONFIG) # end if # failed return False # end def def _build_element_entry (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_event (self, xml_tag, xml_element, tk_parent): r""" XML <event> element implements the code equivalence of get_event_manager().events.connect(signal, slot) events are always application-wide scope for RADWidgetBase subclasses and object children; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) # connecting people :-) return self.events.connect( _attributes.get("signal"), _attributes.get("slot") ) # end if # failed return False # end def def _build_element_frame (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_include (self, xml_tag, xml_element, tk_parent): r""" XML <include> element tries to include external XML file def for instant widget building at current insertion point; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) # set inclusion widget _widget = RADXMLWidget( tk_owner = tk_parent, slot_owner = self.slot_owner, **_attributes ) # ensure there won't be any unexpected inclusion /!\ _widget.XML_RC.clear() # $ 2014-02-09 RS $ # CAUTION: # removed self-inclusion security; # let Python handle this trap! # get XML tree _widget.xml_load(_attributes.get("src")) # include new XML tree to current one xml_element = _widget.get_xml_tree().getroot() # free useless memory right now /!\ del _attributes, _widget # build inclusion return self._loop_on_children( xml_element, tk_parent, accept=self.DTD.get("widget") ) # end if # failed return False # end def def _build_element_label (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_labelframe (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_layout (self, xml_tag, xml_element, tk_parent): r""" tries to set a layout to a given widget; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) # try to retrieve concerned widget _widget = _attributes.get("widget", tk_parent) # set layout self._set_layout(_widget, _attributes, tk_parent) # succeeded return True # end if # end if # failed return False # end def def _build_element_listbox (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ # param controls if self.is_tk_parent(tk_parent): # widget attribute inits _attributes = self._init_deferred_attributes( xml_tag, xml_element, tk_parent ) # class constructor args _args = str(_attributes.get("args", "")) if not _args.startswith("tk_parent"): _args = "tk_parent, " + _args # end if # widget class inits _widget = eval("TK.Listbox({args})".format(args = _args)) # $ 2014-03-10 RS $ # since v1.4: deferred tasks # flush widget section self._queue.flush("widget", widget = _widget) # ensure neutrality _attributes = _attributes.flatten() # keep a copy aboard self._register_object_by_id(_widget, _attributes.get("id")) # set widget as class member self._set_class_member(_attributes.get("name"), _widget) # prepare list of choices _widget.delete(0, TK.END) # choices inits _choices = _attributes.get("choices") if _choices: # fill up widget's list of choices _widget.insert(0, *_choices) # startup inits _start = _attributes.get("start") if tools.is_num(_start): if _start > 0: _start = min(_start, len(_choices) - 1) elif _start < 0: _start = max(0, len(_choices) + _start) # end if elif _start in _choices: _start = _choices.index(_start) else: _start = -1 # end if # set selected line _widget.selection_anchor(_start) _widget.selection_set(_start) _widget.activate(_start) _widget.see(_start) # end if # tk configure() self._set_widget_config(_widget, self.TK_CONFIG) # set layout self._set_layout(_widget, _attributes, tk_parent) # succeeded return True # unsupported else: raise TypeError( _( "Tkinter '{classname}' object is *NOT* " "insertable into {obj_type} object." ).format( classname = xml_element.get("class", self.WIDGET_CLASS), obj_type = repr(tk_parent) ) ) return False # end if # end def def _build_element_menu (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_element_tkmenu(xml_tag, xml_element, tk_parent) # end def def _build_element_menubutton (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_message (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_module (self, xml_tag, xml_element, tk_parent): r""" tries to import python libs along syntactic sugar: [from dottedURI ]import dottedURIStar[ as ALIAS] returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) _attrs = { "from": tools.str_complete( "from {} ", _attributes.get("from") ), "import": tools.str_complete( "import {}", _attributes.get("import") ), "as": tools.str_complete( " as {}", _attributes.get("as") ), } # try to import python libs with global scope exec("{from}{import}{as}".format(**_attrs), globals()) # succeeded return True # end if # failed return False # end def def _build_element_optionmenu (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ # param controls if self.is_tk_parent(tk_parent): # widget attribute inits _attributes = self._init_deferred_attributes( xml_tag, xml_element, tk_parent ) # control variable inits _cvar = tools.choose( _attributes.get("listvariable"), # $ 2014-01-11 RS $ # for retro-compatibility reasons: _attributes.get("variable"), TK.StringVar(), ) # choices inits _choices = tools.choose( _attributes.get("choices"), [_("<empty>")], ["<empty>"], ) # widget class inits _widget = TK.OptionMenu(tk_parent, _cvar, *_choices) # $ 2014-03-10 RS $ # since v1.4: deferred tasks # flush widget section self._queue.flush("widget", widget = _widget) # ensure neutrality _attributes = _attributes.flatten() # keep a copy aboard self._register_object_by_id(_widget, _attributes.get("id")) # set widget as class member self._set_class_member(_attributes.get("name"), _widget) # startup inits _start = _attributes.get("start") if tools.is_num(_start): if _start > 0: _start = min(_start, len(_choices) - 1) elif _start < 0: _start = max(0, len(_choices) + _start) # end if _start = _choices[_start] elif _start not in _choices: _start = _choices[0] # end if _cvar.set(str(_start)) # set layout self._set_layout(_widget, _attributes, tk_parent) # succeeded return True # unsupported else: raise TypeError( _( "Tkinter '{classname}' object is *NOT* " "insertable into {obj_type} object." ).format( classname = xml_element.get("class", self.WIDGET_CLASS), obj_type = repr(tk_parent) ) ) return False # end if # end def def _build_element_panedwindow (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_radiobutton (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ _ok = self._build_tk_native(xml_tag, xml_element, tk_parent) if xml_element.get("selected"): self.WIDGET.select() else: self.WIDGET.deselect() # end if return _ok # end def def _build_element_scale (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_scrollbar (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ _ok = self._build_tk_native(xml_tag, xml_element, tk_parent) # make connections _scrollbar = self.WIDGET _target = self.TK_CHILD_CONFIG.get("connect") if _target and _scrollbar: try: # connect vertically # $ 2014-02-27 RS $ # bug fix: # be careful with w.cget("..."): *NOT* string objects! # but rather TclObj.index objects (!) if str(_scrollbar.cget("orient")) == "vertical": _target.configure(yscrollcommand = _scrollbar.set) _scrollbar.configure(command = _target.yview) # connect horizontally else: _target.configure(xscrollcommand = _scrollbar.set) _scrollbar.configure(command = _target.xview) # end if except: raise TypeError( _( "cannot connect widget {w_type} " "of id '{w_id}' to scrollbar." ).format( w_type = type(_target), w_id = xml_element.get("connect") ) ) from None # end if return _ok # end def def _build_element_spinbox (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_style (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widgets style building; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) # remove XML attr id from dictionary _id = _attributes.pop("id", None) # register dictionary for XML attr 'style="style_id"' self._register_object_by_id(_attributes, _id) # succeeded return True # end if # failed return False # end def def _build_element_text (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_tkevent (self, xml_tag, xml_element, tk_parent): r""" XML <tkevent> element implements tkinter event bindings for a given tkinter widget; event binding level can be one of 'bind', 'bind_class' or 'bind_all'; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) # retrieve tkinter widget _widget = tools.choose( _attributes.get("widget"), tk_parent, ) # init bindings _bind = tools.choose_str(_attributes.get("bind")) _seq = tools.choose_str(_attributes.get("seq")) _add = tools.choose_str(_attributes.get("add")) _slot = _attributes.get("slot") _method = getattr(_widget, _bind) # special case if _bind == "bind_class": _class = tools.choose_str(_attributes.get("class")) # bind event _method(_class, _seq, _slot, _add) else: # bind event _method(_seq, _slot, _add) # end if # succeeded return True # end if # failed return False # end def def _build_element_tkmenu (self, xml_tag, xml_element, tk_parent): r""" tkinter menu defs should be written apart from a classical <tkwidget> XML script into a <tkmenu> XML script; this method tries to do this for you by emulating @xml_element param as if it were a RADXMLMenu XML tree root node; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # lib imports from . import rad_xml_menu as XM # attribute inits _attributes = self._init_deferred_attributes( xml_tag, xml_element, tk_parent ) # reset element tag xml_element.tag = "tkmenu" # widget inits _widget = XM.RADXMLMenu( tk_owner = tk_parent, slot_owner = self.slot_owner, ) # $ 2014-03-10 RS $ # since v1.4: deferred tasks # flush widget section self._queue.flush("widget", widget = _widget) # ensure neutrality _attributes = _attributes.flatten() # register widget self._register_object_by_id(_widget, _attributes.get("id")) # set widget as class member self._set_class_member(_attributes.get("name"), _widget) # reset XML tree _widget.set_xml_tree(element = xml_element) # build menu _ok = _widget.xml_build() # transfer all newly created stringvars # from menu to widget self.get_stringvars().update(_widget.get_stringvars()) # confirm op return _ok # end if # failed return False # end def def _build_element_tkwidget (self, xml_tag, xml_element, tk_parent): r""" tries to integrate subelements directly in tk_parent without creating an intermediate widget; does not manage with XML attribute 'class' as tk_parent is considered to be already a tkinter widget subclass object; returns True on build success, False otherwise; """ # param controls if self.is_tk_parent(tk_parent): # loop on XML element children - build tk child widgets # accept only following XML subelements return self._loop_on_children( xml_element, tk_parent, accept=self.DTD.get("widget"), ) # unsupported else: raise TypeError( _( "Current tkinter object is *NOT* " "insertable into {obj_type} object." ).format(obj_type = repr(tk_parent)) ) return False # end if # end def def _build_element_toplevel (self, xml_tag, xml_element, tk_parent): r""" Tkinter native widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkbutton (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkcheckbutton (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ _ok = self._build_tk_native(xml_tag, xml_element, tk_parent) if xml_element.get("checked"): self.WIDGET.invoke() # end if return _ok # end def def _build_element_ttkcombobox (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkentry (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkframe (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttklabel (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttklabelframe (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkmenubutton (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttknotebook (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkpanedwindow (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkprogressbar (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkradiobutton (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ _ok = self._build_tk_native(xml_tag, xml_element, tk_parent) if xml_element.get("selected"): self.WIDGET.invoke() # end if return _ok # end def def _build_element_ttkscale (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkscrollbar (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_element_scrollbar(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkseparator (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttksizegrip (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttkstyle (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widgets style building; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) # remove some XML attrs from dictionary _attributes.pop("id", None) _apply = _attributes.pop("apply", ".") # update ttk style defs _style = ttk.Style() # see below /!\ _style.configure(_apply, **_attributes) # CSS-like syntax if tools.is_pstr(xml_element.text): # CDATA inits _cdata = ( xml_element.text # strip unwanted chars .strip("\n\t ;") # remove line ends .replace("\n", "") # convert double quotes to single quotes .replace('"', "'") ) # remove /* ... */ comments _cdata = re.sub(r"/\*.*?\*/", "", _cdata) # ttk root style is '.', CSS is '*' _cdata = _cdata.replace("*", ".") # get def chunks # i.e. elements {**attrs} elements {**attrs} ... _cdata = list( filter( None, set( re.split(r"(.*?\{.*?\})", _cdata) ) ) ) for _def in _cdata: # def chunks init i.e. elements { **attrs } _elements, _attrs = _def.split("{") # filter elements # i.e. element:state:!state, element, ... # element:state, new.old:state, ... _elements = \ re.sub(r"[^\w,.!:]+", "", _elements).split(",") # filter and parse XML attrs # i.e. attr_key: value; ... # --> {"attr_key": "value", ...} _attrs = self._parse_xml_attributes( xml_element, tk_parent, xml_attrs = eval( "{{{}}}" .format( re.sub( r"\s*(\w+)\s*:\s*(.*?)\s*;", r'"\1":"\2",', _attrs.strip("{ };") + ";" ).strip(";") ) ), ) # got attrs? if tools.is_pdict(_attrs): for _element in _elements: # pseudo-format support # i.e. element:state:!state:... _element = _element.split(":") # got mapping? if len(_element) > 1: # inits _states = _element[1:] _element = _element[0] _mattrs = _attrs.copy() for (_key, _value) in _mattrs.items(): _map = _style.map(_element, _key) _map.insert( 0, tuple(_states + [_value]) ) _mattrs[_key] = _map # end for _style.map(_element, **_mattrs) # got configuring else: _style.configure(_element[0], **_attrs) # end if - mapping # end for - elements # end if - attrs # end for - cdata # end if - CSS-like syntax # succeeded return True # end if # failed return False # end def def _build_element_ttktab (self, xml_tag, xml_element, tk_parent): r""" <ttktab> XML element is child of <ttknotebook>; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_ttktheme (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk theme building; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # attribute inits _attributes = self._init_attributes( xml_tag, xml_element, tk_parent ) # use new theme, if any. ttk.Style().theme_use(_attributes.get("use")) return True # end if return False # end def def _build_element_ttktreeview (self, xml_tag, xml_element, tk_parent): r""" Tkinter ttk widget building; returns True on build success, False otherwise; """ return self._build_tk_native(xml_tag, xml_element, tk_parent) # end def def _build_element_widget (self, xml_tag, xml_element, tk_parent, **kw): r""" XML element <widget .../> is the generic XML declaration for any user-defined subclass of a native tkinter widget; example: <widget name="notepad123" class="MyOwnNotepad" .../> is slightly the same as: self.notepad123 = MyOwnNotepad(self, ...) with 'self' the parent widget (supported if omitted); returns True on build success, False otherwise; """ # param controls if self.is_tk_parent(tk_parent): # widget attribute inits kw.update(addon_attrs = self.ATTRS.get("widget")) _attributes = self._init_deferred_attributes( xml_tag, xml_element, tk_parent, **kw ) # widget class inits _class = eval("{module}{class}".format(**_attributes)) _args = _attributes.get("args", "") # tk widget parent autocompletion if issubclass(_class, (TK.Widget, TK.Tk)) \ and not _args.startswith("tk_parent"): _args = "tk_parent, " + _args # end if # create tkinter widget _widget = eval("_class({args})".format(args = _args)) # $ 2014-03-10 RS $ # since v1.4: deferred tasks # flush widget section self._queue.flush("widget", widget = _widget) # ensure neutrality _attributes = _attributes.flatten() # keep a copy aboard self._register_object_by_id(_widget, _attributes.get("id")) # keep a copy for specific post-implementations self.WIDGET = _widget # set widget as class member self._set_class_member(_attributes.get("name"), _widget) # configure widget self._set_widget_config(_widget, self.TK_CONFIG) # set layout self._set_layout(_widget, _attributes, tk_parent) # free useless memory right now /!\ del _class, _args, self.TK_CONFIG # loop on XML element children - build tk child widgets _build_ok = self._loop_on_children( xml_element, _widget, accept = tools.choose( self.DTD.get(xml_tag), self.DTD.get("widget"), ) ) # widget init() procedure _init = _attributes.get("init") if callable(_init): kw.update( widget = _widget, parent = tk_parent, xml_attributes = _attributes, ) _init(**kw) # end if # succeeded return _build_ok # unsupported else: raise TypeError( _( "Tkinter '{classname}' object is *NOT* " "insertable into {obj_type} object." ).format( classname = xml_element.get("class", self.WIDGET_CLASS), obj_type = repr(tk_parent) ) ) return False # end if # end def def _build_tk_native (self, xml_tag, xml_element, tk_parent): r""" protected method def; builds any tkinter native widget along its class name; returns True on build success, False otherwise; """ # param controls if self.cast_element(xml_element): # param inits _cname = tools.choose_str( self.CLASSES.get(xml_tag), xml_tag, "Frame", ) # $ 2014-02-24 RS $ # new support: # now TK and ttk are embedded in predefined classnames; _cname = _cname.strip(".").split(".") _module = tools.choose_str(xml_element.get("module")) if len(_cname) > 1: _module = _cname[0] + "." # end if # set real classname xml_element.set("class", tools.normalize_id(_cname[-1])) # must force XML attr module name xml_element.set("module", _module) # build widget return self._build_element_widget( xml_tag, xml_element, tk_parent, ) # end if # failed return False # end def def _ensure_string_value (self, attribute, **kw): r""" will set attr value at least an empty string of chars; no return value (void); """ # param controls if self._is_unparsed(attribute): # parsed attribute inits attribute.value = tools.choose_str( attribute.value, kw.get("default"), ) self._tk_config(attribute, **kw) # end if # end def def _init_attributes (self, xml_tag, xml_element, tk_parent, **kw): r""" parses @xml_element param XML attributes along @xml_tag param constraints and possible @kw["addon_attrs"]; returns parsed XML attributes in a dict() object; """ # $ 2014-03-10 RS $ # modified in v1.4 # support: deferred tasks # $ 2014-03-12 RS $ # modified again: # support: rollback to *immediate* # XML attrs parsing as in tkRAD <= v1.4 # inits _attributes = self._init_deferred_attributes( xml_tag, xml_element, tk_parent, **kw ) # flush widget section # for *immediate* attrs parsing self._queue.flush("widget", **kw) # ensure neutrality return _attributes.flatten() # end def def _init_attributes_flat (self, xml_tag, xml_element, tk_parent, **kw): r""" parses @xml_element param XML attributes along @xml_tag param constraints and possible @kw["addon_attrs"]; returns parsed XML attributes in a dict() object; """ # $ 2014-03-10 RS $ # new: created in v1.4 # support: *immediate* XML attrs parsing # $ 2014-03-12 RS $ # modified: # kept for compatibility reasons # with tkRAD v1.4 return self._init_attributes(xml_tag, xml_element, tk_parent, **kw) # end def def _init_deferred_attributes (self, xml_tag, xml_element, tk_parent, **kw): r""" parses @xml_element param XML attributes along @xml_tag param constraints and possible @kw["addon_attrs"]; returns parsed XML attributes in a dict() object; """ # $ 2014-03-12 RS $ # new: created in v1.4.1 # support: deferred tasks # deferred XML attrs parsing # inits _dicts = ( # 'common' XML attrs self.ATTRS.get("common"), # XML element's mandatory default attrs self.ATTRS.get(xml_tag), # additional external XML attrs kw.get("addon_attrs"), # override with real XML attributes # (key/value) pairs xml_element.attrib, ) _attributes = dict() # loop on dicts for _dict in _dicts: if tools.is_pdict(_dict): _attributes.update(_dict) # end if # end for # update keywords (filtered attributes) kw["xml_attrs"] = _attributes # return parsed XML attributes return self._parse_xml_attributes(xml_element, tk_parent, **kw) # end def def _layout_toplevel (self, widget, attrs, tk_parent): r""" sets Toplevel main window inits and layouts; no return value (void); """ # window state inits _wstate = tools.choose_str(attrs.get("visibility")) _resizable = tools.choose_str(attrs.get("resizable")) # set transient window widget.transient(attrs.get("transient")) # set window's title widget.title(attrs.get("title")) # set window's min size widget.minsize( width = attrs.get("minwidth"), height = attrs.get("minheight"), ) # set window's max size _maxwidth = attrs.get("maxwidth") _maxheight = attrs.get("maxheight") widget.maxsize(width = _maxwidth, height = _maxheight) # set resizable window widget.resizable( width = (_resizable in ("yes", "width")), height = (_resizable in ("yes", "height")), ) # set window state if _wstate == "maximized" and _resizable == "yes" \ and not (_maxwidth or _maxheight): widget.deiconify() widget.attributes("-zoomed", "1") elif _wstate == "minimized": widget.iconify() elif _wstate == "hidden": widget.withdraw() else: # 'normal' window state (default) widget.deiconify() # end if # end def # ----------------------- XML attributes parsing ----------------- def _parse_attr__after (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_widget_support(attribute, **kw) # end def def _parse_attr__before (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_widget_support(attribute, **kw) # end def def _parse_attr__height (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr__minsize (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr__padx (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr__pady (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr__sticky (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # param controls if self._is_new(attribute): # inits _sticky = attribute.value.lower() if not set(_sticky).issubset(set(self.STICKY_ALL)): _sticky = self.STICKY_ALL # end if # parsed attribute inits attribute.value = _sticky kw.update(tk_child_config = True) self._tk_config(attribute, **kw) # end if # end def def _parse_attr__width (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_activerelief (self, attribute, **kw): r""" relief attribute; no return value (void); """ # parsed attribute inits self._tkRAD_relief_support(attribute, **kw) # end def def _parse_attr_activestyle (self, attribute, **kw): r""" must be one of 'underline', 'dotbox', 'none'; default value is 'underline'; no return value (void); """ # parsed attribute inits kw.update( default = "dotbox", values = ("underline", "none"), ) self._fix_values(attribute, **kw) # end def def _parse_attr_add (self, attribute, **kw): r""" filters XML attr 'add' along authorized values; must be at least an empty string of chars; no return value (void); """ # param controls if tools.is_pstr(attribute.value): # force value _add = "+" else: # at least empty string _add = "" # end if # parsed attribute inits attribute.value = _add # caution: *NO* self._tk_config() by here /!\ # end def def _parse_attr_after (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits self._parse_attr__after(attribute, **kw) # end def def _parse_attr_anchor (self, attribute, **kw): r""" many location supports; supports 'north', 'top' or 'up' for TK.N; supports 'south', 'bottom' or 'down' for TK.S; supports 'east' or 'right' for TK.E; supports 'west' or 'left' for TK.W; supports 'center' for TK.CENTER; supports any consistent combination of above values for TK.NW, TK.NE, TK.SW and TK.SE, of course, e.g: anchor="top left" or anchor="down right", etc; no return value (void); """ # param controls if self._is_new(attribute): # inits _anchor = attribute.value # loop on regexps for (_search, _replace) in self.ANCHORS: _anchor = _search.sub(_replace, _anchor) # end for # set inconsistencies to default value: 'center' if _anchor not in (TK.N, TK.S, TK.E, TK.W, TK.NW, TK.NE, TK.SW, TK.SE): _anchor = TK.CENTER # end if # parsed attribute inits attribute.value = _anchor self._tk_config(attribute, **kw) # end if # end def def _parse_attr_apply (self, attribute, **kw): r""" XML attr for '<ttkstyle apply="newName.oldName".../>'; no return value (void); """ # param controls if self._is_new(attribute): # parsed attribute inits attribute.value = re.sub(r"[^\w\.]+", r"", attribute.value) # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_args (self, attribute, **kw): r""" class constructor arguments e.g. MyClass(**args); replaces "self" or "parent" defs with the correct parent definition; replaces "@" aliases with module name ref e.g. "orient=@VERTICAL" becomes "orient=TK.VERTICAL" in args if widget's module name is "TK", of course; no return value (void); """ # param controls - force to "" otherwise /!\ if tools.is_pstr(attribute.value): # replace eventual "self" or "parent" by correct param name _args = re.sub( r"(?i)\b(?:self|parent)\b", "tk_parent", attribute.value ) # replace "@" alias in value by a ref to widget's module _args = self._replace_alias(_args, **kw) else: # minimal default value _args = "" # end if # parsed attribute inits attribute.value = _args # caution: *NO* self._tk_config() by here /!\ # end def def _parse_attr_as (self, attribute, **kw): r""" conforms XML attr 'as' to language specs __identifier__; accepts only regexp("\w+") in fact; no return value (void); """ # parsed attribute inits attribute.value = tools.normalize_id(attribute.value) # caution: *NO* self._tk_config() by here /!\ # end def def _parse_attr_aspect (self, attribute, **kw): r""" attr 'aspect' ratio (integer); no return value (void); """ # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_autoseparators (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_before (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits self._parse_attr__before(attribute, **kw) # end def def _parse_attr_bind (self, attribute, **kw): r""" must be one of 'bind', 'bind_class' or 'bind_all'; default value is 'bind'; no return value (void); """ # parsed attribute inits kw.update( default = "bind", values = ("bind_class", "bind_all"), # caution: *NO* self._tk_config() by here /!\ no_tk_config = True, ) self._fix_values(attribute, **kw) # end def def _parse_attr_buttonbackground (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_buttoncursor (self, attribute, **kw): r""" cursor attribute; no return value (void); """ # parsed attribute inits self._tkRAD_cursor_support(attribute, **kw) # end def def _parse_attr_buttondownrelief (self, attribute, **kw): r""" relief attribute; no return value (void); """ # parsed attribute inits self._tkRAD_relief_support(attribute, **kw) # end def def _parse_attr_buttonup (self, attribute, **kw): r""" relief attribute; no return value (void); """ # parsed attribute inits self._tkRAD_relief_support(attribute, **kw) # end def def _parse_attr_choices (self, attribute, **kw): r""" changes string list of compound values to a well-formed list() of string values; string values *MUST* be quoted; list of values *MUST* be comma-separated; example: choices="'hello', 'good people', 123, 456.78" will become choices = ['hello', 'good people', '123', '456.78'] no return value (void); """ # param controls if self._is_new(attribute): # parsed attribute inits attribute.value = list( map( str, eval( "[{}]".format(attribute.value.strip("()[]{}")) ) ) ) # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_class (self, attribute, **kw): r""" forces XML attr 'class' name to conform to __identifier__ language semantics def i.e. accept only regexp("\w+"); no return value (void); """ # param controls - forces value clean-ups if self._is_unparsed(attribute): # param inits _class = tools.choose_str( tools.normalize_id(attribute.value), self.WIDGET_CLASS, "Frame", ) # parsed attribute inits attribute.value = _class # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_class_ (self, attribute, **kw): r""" fake classname for tkinter options database; no return value (void); """ # parsed attribute inits self._tkRAD_any_value_support(attribute, **kw) # end def def _parse_attr_closeenough (self, attribute, **kw): r""" float attribute; no return value (void); """ # parsed attribute inits self._tkRAD_float_support(attribute, **kw) # end def def _parse_attr_columns (self, attribute, **kw): r""" values attribute; no return value (void); """ # parsed attribute inits self._parse_attr_values(attribute, **kw) # end def def _parse_attr_confine (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_connect (self, attribute, **kw): r""" scrollbar attribute; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_widget_support(attribute, **kw) # end def def _parse_attr_default (self, attribute, **kw): r""" state attribute; no return value (void); """ # parsed attribute inits self._tkRAD_state_support(attribute, **kw) # end def def _parse_attr_digits (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_direction (self, attribute, **kw): r""" sets Menubutton pop-up menu showing up direction; must be one of 'above', 'below', 'flush', 'left' or 'right'; no return value (void); """ # parsed attribute inits kw.update( default = "below", values = ("above", "flush", "left", "right"), ) self._fix_values(attribute, **kw) # end def def _parse_attr_disabledbackground (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_displaycolumns (self, attribute, **kw): r""" values attribute; no return value (void); """ # parsed attribute inits self._parse_attr_values(attribute, **kw) # end def def _parse_attr_elementborderwidth (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_exportselection (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_format (self, attribute, **kw): r""" sprintf() format e.g. '%02.3f'; no return value (void); """ # param controls if self._is_new(attribute): # inits _fmt = re.search( r"\D*(\d*\.\d+)|\D*(\d*)", attribute.value ) if _fmt: _fmt = tools.str_complete( "%{}f", "".join(filter(None, _fmt.groups())) ) # end if # parsed attribute inits attribute.value = _fmt self._tk_config(attribute, **kw) # end if # end def def _parse_attr_from (self, attribute, **kw): r""" from relative.module import ...; parse relative.module string value; no return value (void); """ # param controls - forces value clean-ups if self._is_unparsed(attribute): # parsed attribute inits attribute.value = \ tools.normalize_relative_module(attribute.value) # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_from_ (self, attribute, **kw): r""" starting point float attribute; no return value (void); """ # parsed attribute inits self._tkRAD_float_support(attribute, **kw) # end def def _parse_attr_handlepad (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_handlesize (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_height (self, attribute, xml_tag, **kw): r""" integer/dimension attribute along widget type; no return value (void); """ # param controls if xml_tag in ("button", "checkbutton", "label", "listbox", "menubutton", "radiobutton", "text"): # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) else: # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end if # end def def _parse_attr_highlightbackground (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_highlightcolor (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_highlightthickness (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_import (self, attribute, **kw): r""" from ... import module; parses module string value; no return value (void); """ # param controls - forces value clean-ups if self._is_unparsed(attribute): # parsed attribute inits attribute.value = tools.normalize_import(attribute.value) # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_increment (self, attribute, **kw): r""" float attribute; no return value (void); """ # parsed attribute inits self._tkRAD_float_support(attribute, **kw) # end def def _parse_attr_indicatorcolor (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_indicatoron (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_init (self, attribute, **kw): r""" command attribute; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._tkRAD_command_support(attribute, **kw) # end def def _parse_attr_insertbackground (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_insertborderwidth (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_insertofftime (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_insertontime (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_insertwidth (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_invalidcommand (self, attribute, **kw): r""" command attribute; no return value (void); """ # parsed attribute inits self._tkRAD_command_support(attribute, **kw) # end def def _parse_attr_jump (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_justify (self, attribute, **kw): r""" must be one of 'left', 'right', 'center'; default value is 'center'; no return value (void); """ # parsed attribute inits kw.update( default = "center", values = ("left", "right"), ) self._fix_values(attribute, **kw) # end def def _parse_attr_label (self, attribute, **kw): r""" label attribute; no return value (void); """ # parsed attribute inits self._tkRAD_label_support(attribute, **kw) # end def def _parse_attr_labelanchor (self, attribute, **kw): r""" anchor attribute; no return value (void); """ # parsed attribute inits self._parse_attr_anchor(attribute, **kw) # end def def _parse_attr_labelwidget (self, attribute, **kw): r""" widget attribute; no return value (void); """ # parsed attribute inits self._tkRAD_widget_support(attribute, **kw) # end def def _parse_attr_layout (self, attribute, **kw): r""" must be one of 'pack', 'grid', 'place' or 'none'; default value is 'none' (no layout); no return value (void); """ # parsed attribute inits kw.update( default = "none", values = ("pack", "grid", "place"), # caution: *NO* self._tk_config() by here /!\ no_tk_config = True, ) self._fix_values(attribute, **kw) # end def def _parse_attr_layout_options (self, attribute, **kw): r""" 'pack', 'grid' or 'place' layout options; no return value (void); """ # param controls if self._is_unparsed(attribute): _lopts = attribute.value if tools.is_pstr(_lopts): # replace "@" alias by a ref to widget's module _lopts = self._replace_alias(_lopts, **kw) # layout options must be a dict() of options # for self._set_layout() and self._set_resizable() _lopts = eval("dict({})".format(_lopts.strip("()[]{}"))) elif not tools.is_pdict(_lopts): # minimal default value _lopts = dict() # end if # parsed attribute inits attribute.value = _lopts # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_length (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_listvariable (self, attribute, **kw): r""" control variable attribute; no return value (void); """ # parsed attribute inits self._tkRAD_cvar_support(attribute, **kw) # end def def _parse_attr_maxheight (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_maximum (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_maxundo (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_maxwidth (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_minheight (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_minsize (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits self._parse_attr__minsize(attribute, **kw) # end def def _parse_attr_minwidth (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_mode (self, attribute, **kw): r""" must be one of 'indeterminate', 'determinate'; default value is 'determinate'; no return value (void); """ # parsed attribute inits kw.update( default = "determinate", values = ("indeterminate", ), ) self._fix_values(attribute, **kw) # end def def _parse_attr_module (self, attribute, **kw): r""" tries to determine module's correct alias name; no return value (void); """ # $ 2014-01-09 RS $ # bug fix: # @attribute may be None sometimes; if self._is_new(attribute): # module id inits _module = attribute.value.lstrip(".") # predefined module name? if _module.endswith("."): # init module name _name = _module # XML source module id else: # init module name _name = "" # try to get <module> element for more info _module = self.get_element_by_id(_module) # found corresponding <module> element? if self.is_element(_module): # attribute inits _import = \ tools.normalize_import(_module.get("import")) # choose between attrs if _import != "*": _name = tools.choose_str( tools.normalize_id(_module.get("as")), _import, ) + "." # end if # module not found else: raise KeyError( _( "module of id '{mid}' has *NOT* been found." ).format(mid = attribute.value) ) # end if # end if # parsed attribute inits attribute.value = _name.lstrip(".") # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_offrelief (self, attribute, **kw): r""" relief attribute; no return value (void); """ # parsed attribute inits self._tkRAD_relief_support(attribute, **kw) # end def def _parse_attr_opaqueresize (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_orient (self, attribute, attrs, xml_tag, **kw): r""" must be one of 'vertical', 'horizontal'; default value is 'vertical'; no return value (void); """ # parsed attribute inits kw.update( default = "vertical", values = ("horizontal", ), ) self._fix_values(attribute, **kw) # $ 2014-02-27 RS $ # special case for ttk.PanedWindow if xml_tag == "ttkpanedwindow" and "args" in attrs: # in a ttk.PanedWindow object: # must init 'orient' attr in class constructor's 'args' # because 'orient' is *READ-ONLY* in configure() _args = tools.choose_str(attrs["args"]).split(",") _args.append("orient='{}'".format(attribute.value)) attrs["args"] = ",".join(filter(None, _args)) self.TK_CONFIG.pop("orient", None) # end if # end def def _parse_attr_overrelief (self, attribute, **kw): r""" relief attribute; no return value (void); """ # parsed attribute inits self._tkRAD_relief_support(attribute, **kw) # end def def _parse_attr_padding (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_padx (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_pady (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_readonlybackground (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_repeatdelay (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_repeatinterval (self, attribute, **kw): r""" integer attribute; no return value (void); """ # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_resizable (self, attribute, **kw): r""" must be one of 'yes', 'no', 'width', 'height'; default value is 'no'; no return value (void); """ # parsed attribute inits kw.update( default = "no", values = ("yes", "width", "height"), # caution: *NO* self._tk_config() by here /!\ no_tk_config = True, ) self._fix_values(attribute, **kw) # end def def _parse_attr_resolution (self, attribute, **kw): r""" float attribute; no return value (void); """ # parsed attribute inits self._tkRAD_float_support(attribute, **kw) # end def def _parse_attr_sashpad (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_sashrelief (self, attribute, **kw): r""" relief attribute; no return value (void); """ # parsed attribute inits self._tkRAD_relief_support(attribute, **kw) # end def def _parse_attr_sashwidth (self, attribute, **kw): r""" dimension attribute no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_scrollregion (self, attribute, **kw): r""" must be a 4-tuple of integers; values are (left, top, right, bottom); no return value (void); """ # param controls if self._is_new(attribute): # parsed attribute inits attribute.value = tuple( map( tools.ensure_int, eval( "[{}]".format(attribute.value.strip("(){}[]")) ) ) ) self._tk_config(attribute, **kw) # end if # end def def _parse_attr_selectbackground (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_selectborderwidth (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_selectforeground (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_selectmode (self, attribute, xml_tag, **kw): r""" must be one of 'browse', 'single', 'multiple', 'extended'; default value is 'browse'; no return value (void); """ # parsed attribute inits # $ 2014-02-27 RS $ # new support: # ttk.Treeview hasn't # the same point of view! if xml_tag == "ttktreeview": kw.update( default = "extended", values = ("none", "browse"), ) else: kw.update( default = "browse", values = ("single", "multiple", "extended"), ) # end if self._fix_values(attribute, **kw) # end def def _parse_attr_seq (self, attribute, **kw): r""" admits simplified tkinter.Event sequence (no <>); e.g. seq="Control-s" instead of seq="&lt;Control-s&gt;"; no return value (void); """ # param controls if self._is_new(attribute): # inits - stri _seq = attribute.value.replace("<", "", 1) _seq = _seq.replace(">", "", 1) # parsed attribute inits attribute.value = "<" + _seq + ">" # CAUTION: *NO* self.tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_show (self, attribute, xml_tag, **kw): r""" password echo character to show in entry box; headings/tree ttk.Treeview display off mode; no return value (void); """ # parsed attribute inits # $ 2014-02-27 RS $ # new support: # ttk.Treeview hasn't # the same point of view! if xml_tag == "ttktreeview": kw.update( default = "headings", values = ("tree", ), ) self._fix_values(attribute, **kw) else: self._tkRAD_any_value_support(attribute, **kw) # end if # end def def _parse_attr_showhandle (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_showvalue (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_signal (self, attribute, **kw): r""" must be at least an empty string of chars; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._ensure_string_value(attribute, **kw) # end def def _parse_attr_sliderlength (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_sliderrelief (self, attribute, **kw): r""" relief attribute; no return value (void); """ # parsed attribute inits self._tkRAD_relief_support(attribute, **kw) # end def def _parse_attr_slot (self, attribute, **kw): r""" command attribute; no return value (void); """ # parsed attribute inits self._tkRAD_command_support(attribute, **kw) # end def def _parse_attr_spacing1 (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_spacing2 (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_spacing3 (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_src (self, attribute, **kw): r""" normalizes path in XML attr 'src'; no return value (void); """ # param controls if self._is_new(attribute): # parsed attribute inits attribute.value = path.normalize(attribute.value) # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_start (self, attribute, **kw): r""" defines starting point for attr 'choices' items list; can be either litteral value or '@integer' list index position; admits negative index values; example: start="@0" will indicate choices[0]; example: start="@-1" will indicate choices[-1]; no return value (void); """ # param controls if self._is_new(attribute): # starting point inits _start = attribute.value # got indexed integer value? if _start.startswith("@"): _start = tools.ensure_int(_start.lstrip("@")) else: # make some string clean-ups _start = re.sub(r"\\([@'])", r"\1", _start) # end if # parsed attribute inits attribute.value = _start # caution: *NO* self._tk_config() by here /!\ attribute.parsed = True # end if # end def def _parse_attr_state (self, attribute, xml_tag, **kw): r""" must be one of 'normal' or 'disabled'; must be one of 'normal', 'disabled' or 'readonly' when XML element is one of 'entry', 'spinbox'; default value is 'normal'; no return value (void); """ # $ 2014-01-16 RS $ # new support: # special case for '<entry>' and '<spinbox>': if xml_tag in ("entry", "spinbox"): _values = ("disabled", "readonly", ) else: _values = ("disabled", ) # end if # parsed attribute inits kw.update(default = "normal", values = _values) self._fix_values(attribute, **kw) # end def def _parse_attr_sticky (self, attribute, **kw): r""" PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits self._parse_attr__sticky(attribute, **kw) # end def def _parse_attr_style (self, attribute, **kw): r""" tkinter/ttk XML attr style def; no return value (void); """ # param controls if self._is_new(attribute): # style id inits _style = attribute.value if "." not in _style: _style = self.get_object_by_id(_style, _style) # end if # parsed attribute inits attribute.value = _style self._tk_config(attribute) # end if # end def def _parse_attr_tabs (self, attribute, **kw): r""" choices attribute; no return value (void); """ # parsed attribute inits self._parse_attr_choices(attribute, **kw) self._tk_config(attribute, **kw) # end def def _parse_attr_takefocus (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_text (self, attribute, **kw): r""" label attribute; no return value (void); """ # parsed attribute inits self._tkRAD_label_support(attribute, **kw) # end def def _parse_attr_textvariable (self, attribute, **kw): r""" control variable attribute; no return value (void); """ # parsed attribute inits self._tkRAD_cvar_support(attribute, **kw) # end def def _parse_attr_tickinterval (self, attribute, **kw): r""" float attribute; no return value (void); """ # parsed attribute inits self._tkRAD_float_support(attribute, **kw) # end def def _parse_attr_title (self, attribute, **kw): r""" label attribute; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._tkRAD_label_support(attribute, **kw) # end def def _parse_attr_to (self, attribute, **kw): r""" float attribute; no return value (void); """ # parsed attribute inits self._tkRAD_float_support(attribute, **kw) # end def def _parse_attr_transient (self, attribute, **kw): r""" widget attribute; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._tkRAD_widget_support(attribute, **kw) # end def def _parse_attr_troughcolor (self, attribute, **kw): r""" color attribute; no return value (void); """ # parsed attribute inits self._tkRAD_color_support(attribute, **kw) # end def def _parse_attr_undo (self, attribute, **kw): r""" boolean attribute; no return value (void); """ # parsed attribute inits self._tkRAD_boolean_support(attribute, **kw) # end def def _parse_attr_use (self, attribute, **kw): r""" must be one of ttk.Style().theme_use() list; default value is 'default'; no return value (void); """ # parsed attribute inits kw.update( default = "default", values = ttk.Style().theme_names(), ) self._fix_values(attribute, **kw) # end def def _parse_attr_validate (self, attribute, **kw): r""" must be one of 'focus', 'focusin', 'focusout', 'key', 'all' or 'none'; default value is 'none'; no return value (void); """ # parsed attribute inits kw.update( default = "none", values = ("focus", "focusin", "focusout", "key", "all"), ) self._fix_values(attribute, **kw) # end def def _parse_attr_validatecommand (self, attribute, **kw): r""" command attribute; no return value (void); """ # parsed attribute inits self._tkRAD_command_support(attribute, **kw) # end def def _parse_attr_value (self, attribute, xml_tag, **kw): r""" any/float attribute; no return value (void); """ # parsed attribute inits if xml_tag == "ttkscale": self._tkRAD_float_support(attribute, **kw) else: self._tkRAD_any_value_support(attribute, **kw) # end if # end def def _parse_attr_values (self, attribute, **kw): r""" choices attribute; no return value (void); """ # parsed attribute inits self._parse_attr_choices(attribute, **kw) self._tk_config(attribute, **kw) # end def def _parse_attr_visibility (self, attribute, **kw): r""" must be one of 'normal', 'maximized', 'minimized' or 'hidden'; default value is 'normal'; no return value (void); """ # parsed attribute inits kw.update( no_tk_config = True, default = "normal", values = ("maximized", "minimized", "hidden"), ) self._fix_values(attribute, **kw) # end def def _parse_attr_weight (self, attribute, **kw): r""" ttk.PanedWindow child configuration attr; no return value (void); """ # parsed attribute inits kw.update(tk_child_config = True) self._tkRAD_integer_support(attribute, **kw) # end def def _parse_attr_width (self, attribute, xml_tag, **kw): r""" integer/dimension attribute along widget type; no return value (void); """ # param controls if xml_tag in ("button", "checkbutton", "entry", "label", "listbox", "menubutton", "radiobutton", "spinbox", "text"): # parsed attribute inits self._tkRAD_integer_support(attribute, **kw) else: # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end if # end def def _parse_attr_wrap (self, attribute, xml_tag, **kw): r""" boolean attribute; must be 'char', 'word' or 'none' if XML element is 'text'; no return value (void); """ # parsed attribute inits if xml_tag == "text": kw.update( default = "none", values = ("char", "word"), ) self._fix_values(attribute, **kw) else: self._tkRAD_boolean_support(attribute, **kw) # end if # end def def _parse_attr_wraplength (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_xml_dir (self, attribute, **kw): r""" must be at least an empty string of chars; no return value (void); """ # parsed attribute inits kw.update( no_tk_config = True, default = self.XML_RC.get("dir") ) self._ensure_string_value(attribute, **kw) # end def def _parse_attr_xml_file_ext (self, attribute, **kw): r""" must be at least an empty string of chars; no return value (void); """ # parsed attribute inits kw.update( no_tk_config = True, default = self.XML_RC.get("file_ext") ) self._ensure_string_value(attribute, **kw) # end def def _parse_attr_xml_filename (self, attribute, **kw): r""" must be at least an empty string of chars; no return value (void); """ # parsed attribute inits kw.update(no_tk_config = True) self._ensure_string_value(attribute, **kw) # end def def _parse_attr_xscrollcommand (self, attribute, **kw): r""" command attribute; no return value (void); """ # parsed attribute inits self._tkRAD_command_support(attribute, **kw) # end def def _parse_attr_xscrollincrement (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _parse_attr_yscrollcommand (self, attribute, **kw): r""" command attribute; no return value (void); """ # parsed attribute inits self._tkRAD_command_support(attribute, **kw) # end def def _parse_attr_yscrollincrement (self, attribute, **kw): r""" dimension attribute; no return value (void); """ # parsed attribute inits self._tkRAD_dimension_support(attribute, **kw) # end def def _replace_alias (self, str_value, attrs, **kw): r""" protected method def; tries to retrieve widget's module alias name and replaces '@' module alias in XML attribute's value; returns parsed string of chars on success, empty string otherwise; """ # param controls if tools.is_pstr(str_value): r""" $ 2013-12-18 RS $ new support: attrs = RADXMLAttributesDict by now; """ # try to get widget's module self._parse_attr_module(attrs.get_item("module"), **kw) # replace "@" alias in string of chars # by a ref to widget's module return str_value.replace("@", attrs.get("module", "")) # end if # unsupported - empty string return "" # end def def _set_layout (self, widget, attrs, tk_parent): r""" protected method def; pack(), grid() or place() tkinter widget; supports XML attribute 'resizable' horizontally, vertically or both axis; no return value (void); """ # $ 2014-01-17 RS $ # special case of Toplevel window if isinstance(widget, TK.Toplevel): # Toplevel window layout inits self._layout_toplevel(widget, attrs, tk_parent) # $ 2014-02-27 RS $ # special case of ttk.Notebook children elif isinstance(tk_parent, ttk.Notebook): # add child instead of laying it out tk_parent.add( widget, **tools.dict_only_keys( attrs, "compound", "image", "padding", "sticky", "text", "underline", ) ) # $ 2014-02-27 RS $ # special case of ttk.PanedWindow children elif isinstance(tk_parent, ttk.PanedWindow): # add child instead of laying it out tk_parent.add( widget, weight=self.TK_CHILD_CONFIG.get("weight") ) # $ 2014-01-15 RS $ # special case of PanedWindow children elif isinstance(tk_parent, TK.PanedWindow): # got to lay out? if attrs.get("layout") in ("pack", "grid", "place"): # init resizable _sticky = { "width": TK.E + TK.W, "height": TK.N + TK.S, "yes": TK.N + TK.S + TK.E + TK.W, }.get(attrs.get("resizable")) self.TK_CHILD_CONFIG.setdefault("sticky", _sticky) # add child instead of laying it out tk_parent.add(widget, **self.TK_CHILD_CONFIG) # end if # widget exists and layout is asked? elif hasattr(widget, str(attrs.get("layout"))): # try to make widget resizable along params self._set_resizable(widget, attrs, tk_parent) # lay widget out exec("widget.{layout}(**{layout_options})".format(**attrs)) # end if # end def def _set_resizable (self, widget, attrs, tk_parent): r""" protected method def; tries to set up tkinter widget's layout resizable along XML attribute 'resizable' either horizontally, vertically or both axis; no return value (void); """ # param inits _resizable = tools.choose_str( attrs.get("resizable"), "no", ).lower() # layout method init _layout = attrs.get("layout") # layout options init _lopts = attrs.get("layout_options", dict()) # param controls if _layout and _resizable in ("yes", "width", "height"): # pack() method if _layout == "pack": # option inits _lopts.update( { "yes": dict(expand=1, fill=TK.BOTH), "width": dict(expand=0, fill=TK.X), "height": dict(expand=1, fill=TK.Y), }.get(_resizable) ) # grid() method elif _layout == "grid": # option inits _lopts["sticky"] = { "width": TK.W + TK.E, "height": TK.N + TK.S, }.get(_resizable, self.STICKY_ALL) # column configure if _resizable in ("yes", "width"): # make parent's column resizable tk_parent.columnconfigure( tools.ensure_int(_lopts.get("column", 0)), weight = 1 ) # end if # row configure if _resizable in ("yes", "height"): # make parent's row resizable tk_parent.rowconfigure( tools.ensure_int(_lopts.get("row", 0)), weight = 1 ) # end if # place() method elif _layout == "place": # option inits _lopts.update( { "yes": dict(relwidth=1, relheight=1), "width": dict(relwidth=1, relheight=None), "height": dict(relwidth=None, relheight=1), }.get(_resizable) ) # end if # end if # update layout options attrs["layout_options"] = _lopts # end def def _set_widget_config (self, widget, config): r""" protected method def; tries to set up tkinter @widget's attributes along with @config param; returns True on success, False otherwise; """ # param controls if hasattr(widget, "configure") and isinstance(config, dict): # $ 2014-02-25 RS $ # New support: # style profile default inits _attrs = config.get("style") if not tools.is_pdict(_attrs): _attrs = dict() # end if # override with XML element specific XML attr defs _attrs.update(config) # got tk configure() attrs? if tools.is_pdict(widget.configure()): # filter TK attrs along with configure() keys _attrs = tools.dict_only_keys( _attrs, *widget.configure().keys() ) # end if # configure widget widget.configure(**_attrs) # succeeded return True # end if # failed return False # end def # end class RADXMLWidget
gpl-3.0
elewis33/doorstop
doorstop/core/vcs/test/test_base.py
1
1655
"""Unit tests for the doorstop.vcs.base module.""" import unittest from unittest.mock import patch from doorstop.core.vcs.base import BaseWorkingCopy class SampleWorkingCopy(BaseWorkingCopy): """Sample WorkingCopy implementation.""" def __init__(self, path): super().__init__(path) self._ignores_cache = ["*build*", "ignored.*", "*published*"] def lock(self, *args, **kwargs): pass # no implementation def edit(self, *args, **kwargs): pass # no implementation def add(self, *args, **kwargs): pass # no implementation def delete(self, *args, **kwargs): pass # no implementation def commit(self, *args, **kwargs): pass # no implementation class TestSampleWorkingCopy(unittest.TestCase): """Tests for the doorstop.vcs.base module.""" def setUp(self): self.wc = SampleWorkingCopy(None) @patch('os.environ', {}) def test_ignored(self): """Verify ignored paths are detected.""" self.assertTrue(self.wc.ignored("ignored.txt")) self.assertFalse(self.wc.ignored("not_ignored.txt")) self.assertTrue(self.wc.ignored("path/to/published.html")) self.assertTrue(self.wc.ignored("build/path/to/anything")) @patch('os.environ', {'CI': 'true'}) def test_ignored_on_ci(self): """Verify the build directory is not ignored during CI.""" self.assertTrue(self.wc.ignored("ignored.txt")) self.assertFalse(self.wc.ignored("not_ignored.txt")) self.assertTrue(self.wc.ignored("path/to/published.html")) self.assertFalse(self.wc.ignored("build/path/to/anything"))
lgpl-3.0
rosudrag/Freemium-winner
VirtualEnvironment/Lib/site-packages/oauthlib/oauth2/rfc6749/clients/backend_application.py
87
2498
# -*- coding: utf-8 -*- """ oauthlib.oauth2.rfc6749 ~~~~~~~~~~~~~~~~~~~~~~~ This module is an implementation of various logic needed for consuming and providing OAuth 2.0 RFC6749. """ from __future__ import absolute_import, unicode_literals from .base import Client from ..parameters import prepare_token_request from ..parameters import parse_token_response class BackendApplicationClient(Client): """A public client utilizing the client credentials grant workflow. The client can request an access token using only its client credentials (or other supported means of authentication) when the client is requesting access to the protected resources under its control, or those of another resource owner which has been previously arranged with the authorization server (the method of which is beyond the scope of this specification). The client credentials grant type MUST only be used by confidential clients. Since the client authentication is used as the authorization grant, no additional authorization request is needed. """ def prepare_request_body(self, body='', scope=None, **kwargs): """Add the client credentials to the request body. The client makes a request to the token endpoint by adding the following parameters using the "application/x-www-form-urlencoded" format per `Appendix B`_ in the HTTP request entity-body: :param scope: The scope of the access request as described by `Section 3.3`_. :param kwargs: Extra credentials to include in the token request. The client MUST authenticate with the authorization server as described in `Section 3.2.1`_. The prepared body will include all provided credentials as well as the ``grant_type`` parameter set to ``client_credentials``:: >>> from oauthlib.oauth2 import BackendApplicationClient >>> client = BackendApplicationClient('your_id') >>> client.prepare_request_body(scope=['hello', 'world']) 'grant_type=client_credentials&scope=hello+world' .. _`Appendix B`: http://tools.ietf.org/html/rfc6749#appendix-B .. _`Section 3.3`: http://tools.ietf.org/html/rfc6749#section-3.3 .. _`Section 3.2.1`: http://tools.ietf.org/html/rfc6749#section-3.2.1 """ return prepare_token_request('client_credentials', body=body, scope=scope, **kwargs)
mit
rlowrance/dot-vimrc
.vim/ftplugin/orgmode/plugins/ShowHide.py
9
4095
# -*- coding: utf-8 -*- from orgmode import settings from orgmode import ORGMODE, apply_count from orgmode.menu import Submenu, ActionEntry from orgmode.keybinding import Keybinding, Plug, MODE_NORMAL import vim class ShowHide(object): u""" Show Hide plugin """ def __init__(self): u""" Initialize plugin """ object.__init__(self) # menu entries this plugin should create self.menu = ORGMODE.orgmenu + Submenu(u'&Show Hide') # key bindings for this plugin # key bindings are also registered through the menu so only additional # bindings should be put in this variable self.keybindings = [] @classmethod @apply_count def toggle_folding(cls, reverse=False): u""" Toggle folding similar to the way orgmode does This is just a convenience function, don't hesitate to use the z* keybindings vim offers to deal with folding! :reverse: If False open folding by one level otherwise close it by one. """ d = ORGMODE.get_document() heading = d.current_heading() if not heading: vim.eval(u'feedkeys("<Tab>", "n")'.encode(u'utf-8')) return cursor = vim.current.window.cursor[:] if int(vim.eval((u'foldclosed(%d)' % heading.start_vim).encode(u'utf-8'))) != -1: if not reverse: # open closed fold p = heading.number_of_parents if not p: p = heading.level vim.command((u'normal! %dzo' % p).encode(u'utf-8')) else: # reverse folding opens all folds under the cursor vim.command((u'%d,%dfoldopen!' % (heading.start_vim, heading.end_of_last_child_vim)).encode(u'utf-8')) vim.current.window.cursor = cursor return heading def fold_depth(h): if int(vim.eval((u'foldclosed(%d)' % h.start_vim).encode(u'utf-8'))) != -1: return (h.number_of_parents, True) else: res = [h.number_of_parents + 1] found = False for c in h.children: d, f = fold_depth(c) res.append(d) found |= f return (max(res), found) def open_fold(h): if h.number_of_parents <= open_depth: vim.command((u'normal! %dgg%dzo' % (h.start_vim, open_depth)).encode(u'utf-8')) for c in h.children: open_fold(c) def close_fold(h): for c in h.children: close_fold(c) if h.number_of_parents >= open_depth - 1 and \ int(vim.eval((u'foldclosed(%d)' % h.start_vim).encode(u'utf-8'))) == -1: vim.command((u'normal! %dggzc' % (h.start_vim, )).encode(u'utf-8')) # find deepest fold open_depth, found_fold = fold_depth(heading) if not reverse: # recursively open folds if found_fold: for child in heading.children: open_fold(child) else: vim.command((u'%d,%dfoldclose!' % (heading.start_vim, heading.end_of_last_child_vim)).encode(u'utf-8')) if heading.number_of_parents: # restore cursor position, it might have been changed by open_fold vim.current.window.cursor = cursor p = heading.number_of_parents if not p: p = heading.level # reopen fold again beacause the former closing of the fold closed all levels, including parents! vim.command((u'normal! %dzo' % (p, )).encode(u'utf-8')) else: # close the last level of folds close_fold(heading) # restore cursor position vim.current.window.cursor = cursor return heading def register(self): u""" Registration of plugin. Key bindings and other initialization should be done. """ # register plug self.keybindings.append(Keybinding(u'<Tab>', Plug(u'OrgToggleFoldingNormal', u':py ORGMODE.plugins[u"ShowHide"].toggle_folding()<CR>'))) self.menu + ActionEntry(u'&Cycle Visibility', self.keybindings[-1]) self.keybindings.append(Keybinding(u'<S-Tab>', Plug(u'OrgToggleFoldingReverse', u':py ORGMODE.plugins[u"ShowHide"].toggle_folding(reverse=True)<CR>'))) self.menu + ActionEntry(u'Cycle Visibility &Reverse', self.keybindings[-1]) self.keybindings.append(Keybinding(u'<localleader>,', u'zr', mode=MODE_NORMAL)) self.keybindings.append(Keybinding(u'<localleader>.', u'zm', mode=MODE_NORMAL)) for i in xrange(0, 10): self.keybindings.append(Keybinding(u'<localleader>%d' % (i, ), u'zM:set fdl=%d<CR>' % i, mode=MODE_NORMAL))
gpl-3.0
Jionglun/2015
2015-master/static/Brython3.1.1-20150328-091302/Lib/_io.py
629
72610
""" Python implementation of the io module. """ import os import abc import codecs import errno # Import _thread instead of threading to reduce startup cost try: from _thread import allocate_lock as Lock except ImportError: from _dummy_thread import allocate_lock as Lock import io #brython fix me #from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END) SEEK_SET=0 SEEK_CUR=1 SEEK_END=2 valid_seek_flags = {0, 1, 2} # Hardwired values if hasattr(os, 'SEEK_HOLE') : valid_seek_flags.add(os.SEEK_HOLE) valid_seek_flags.add(os.SEEK_DATA) # open() uses st_blksize whenever we can DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes # NOTE: Base classes defined here are registered with the "official" ABCs # defined in io.py. We don't use real inheritance though, because we don't # want to inherit the C implementations. # Rebind for compatibility BlockingIOError = BlockingIOError def __open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): r"""Open file and return a stream. Raise IOError upon failure. file is either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.) mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation of a new file, and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (for backwards compatibility; unneeded for new code) ========= =============================================================== The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation. The 'x' mode implies 'w' and raises an `FileExistsError` if the file already exists. Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode (appending 'b' to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given. buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`. On many systems, the buffer will typically be 4096 or 8192 bytes long. * "Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files. encoding is the str name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings. errors is an optional string that specifies how encoding errors are to be handled---this argument should not be used in binary mode. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register for a list of the permitted encoding error strings. newline is a string controlling how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. closedfd is a bool. If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case. A custom opener can be used by passing a callable as *opener*. The underlying file descriptor for the file object is then obtained by calling *opener* with (*file*, *flags*). *opener* must return an open file descriptor (passing os.open as *opener* results in functionality similar to passing None). open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom. It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode. """ if not isinstance(file, (str, bytes, int)): raise TypeError("invalid file: %r" % file) if not isinstance(mode, str): raise TypeError("invalid mode: %r" % mode) if not isinstance(buffering, int): raise TypeError("invalid buffering: %r" % buffering) if encoding is not None and not isinstance(encoding, str): raise TypeError("invalid encoding: %r" % encoding) if errors is not None and not isinstance(errors, str): raise TypeError("invalid errors: %r" % errors) modes = set(mode) if modes - set("axrwb+tU") or len(mode) > len(modes): raise ValueError("invalid mode: %r" % mode) creating = "x" in modes reading = "r" in modes writing = "w" in modes appending = "a" in modes updating = "+" in modes text = "t" in modes binary = "b" in modes if "U" in modes: if creating or writing or appending: raise ValueError("can't use U and writing mode at once") reading = True if text and binary: raise ValueError("can't have text and binary mode at once") if creating + reading + writing + appending > 1: raise ValueError("can't have read/write/append mode at once") if not (creating or reading or writing or appending): raise ValueError("must have exactly one of read/write/append mode") if binary and encoding is not None: raise ValueError("binary mode doesn't take an encoding argument") if binary and errors is not None: raise ValueError("binary mode doesn't take an errors argument") if binary and newline is not None: raise ValueError("binary mode doesn't take a newline argument") raw = FileIO(file, (creating and "x" or "") + (reading and "r" or "") + (writing and "w" or "") + (appending and "a" or "") + (updating and "+" or ""), closefd, opener=opener) line_buffering = False if buffering == 1 or buffering < 0 and raw.isatty(): buffering = -1 line_buffering = True if buffering < 0: buffering = DEFAULT_BUFFER_SIZE try: bs = os.fstat(raw.fileno()).st_blksize except (os.error, AttributeError): pass else: if bs > 1: buffering = bs if buffering < 0: raise ValueError("invalid buffering size") if buffering == 0: if binary: return raw raise ValueError("can't have unbuffered text I/O") if updating: buffer = BufferedRandom(raw, buffering) elif creating or writing or appending: buffer = BufferedWriter(raw, buffering) elif reading: buffer = BufferedReader(raw, buffering) else: raise ValueError("unknown mode: %r" % mode) if binary: return buffer text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering) text.mode = mode return text class DocDescriptor: """Helper for builtins.open.__doc__ """ def __get__(self, obj, typ): return ( "open(file, mode='r', buffering=-1, encoding=None, " "errors=None, newline=None, closefd=True)\n\n" + open.__doc__) class OpenWrapper: """Wrapper for builtins.open Trick so that open won't become a bound method when stored as a class variable (as dbm.dumb does). See initstdio() in Python/pythonrun.c. """ __doc__ = DocDescriptor() def __new__(cls, *args, **kwargs): return open(*args, **kwargs) # In normal operation, both `UnsupportedOperation`s should be bound to the # same object. try: UnsupportedOperation = io.UnsupportedOperation except AttributeError: class UnsupportedOperation(ValueError, IOError): pass class IOBase(metaclass=abc.ABCMeta): """The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor. This class provides dummy implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked. Even though IOBase does not declare read, readinto, or write because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise UnsupportedOperation when operations they do not support are called. The basic type used for binary data read from or written to a file is bytes. bytearrays are accepted too, and in some cases (such as readinto) needed. Text I/O classes work with str data. Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise IOError in this case. IOBase (and its subclasses) support the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream. IOBase also supports the :keyword:`with` statement. In this example, fp is closed after the suite of the with statement is complete: with open('spam.txt', 'r') as fp: fp.write('Spam and eggs!') """ ### Internal ### def _unsupported(self, name): """Internal: raise an IOError exception for unsupported operations.""" raise UnsupportedOperation("%s.%s() not supported" % (self.__class__.__name__, name)) ### Positioning ### def seek(self, pos, whence=0): """Change stream position. Change the stream position to byte offset pos. Argument pos is interpreted relative to the position indicated by whence. Values for whence are ints: * 0 -- start of stream (the default); offset should be zero or positive * 1 -- current stream position; offset may be negative * 2 -- end of stream; offset is usually negative Some operating systems / file systems could provide additional values. Return an int indicating the new absolute position. """ self._unsupported("seek") def tell(self): """Return an int indicating the current stream position.""" return self.seek(0, 1) def truncate(self, pos=None): """Truncate file to size bytes. Size defaults to the current IO position as reported by tell(). Return the new size. """ self._unsupported("truncate") ### Flush and close ### def flush(self): """Flush write buffers, if applicable. This is not implemented for read-only and non-blocking streams. """ self._checkClosed() # XXX Should this return the number of bytes written??? __closed = False def close(self): """Flush and close the IO object. This method has no effect if the file is already closed. """ if not self.__closed: try: self.flush() finally: self.__closed = True def __del__(self): """Destructor. Calls close().""" # The try/except block is in case this is called at program # exit time, when it's possible that globals have already been # deleted, and then the close() call might fail. Since # there's nothing we can do about such failures and they annoy # the end users, we suppress the traceback. try: self.close() except: pass ### Inquiries ### def seekable(self): """Return a bool indicating whether object supports random access. If False, seek(), tell() and truncate() will raise UnsupportedOperation. This method may need to do a test seek(). """ return False def _checkSeekable(self, msg=None): """Internal: raise UnsupportedOperation if file is not seekable """ if not self.seekable(): raise UnsupportedOperation("File or stream is not seekable." if msg is None else msg) def readable(self): """Return a bool indicating whether object was opened for reading. If False, read() will raise UnsupportedOperation. """ return False def _checkReadable(self, msg=None): """Internal: raise UnsupportedOperation if file is not readable """ if not self.readable(): raise UnsupportedOperation("File or stream is not readable." if msg is None else msg) def writable(self): """Return a bool indicating whether object was opened for writing. If False, write() and truncate() will raise UnsupportedOperation. """ return False def _checkWritable(self, msg=None): """Internal: raise UnsupportedOperation if file is not writable """ if not self.writable(): raise UnsupportedOperation("File or stream is not writable." if msg is None else msg) @property def closed(self): """closed: bool. True iff the file has been closed. For backwards compatibility, this is a property, not a predicate. """ return self.__closed def _checkClosed(self, msg=None): """Internal: raise an ValueError if file is closed """ if self.closed: raise ValueError("I/O operation on closed file." if msg is None else msg) ### Context manager ### def __enter__(self): # That's a forward reference """Context management protocol. Returns self (an instance of IOBase).""" self._checkClosed() return self def __exit__(self, *args): """Context management protocol. Calls close()""" self.close() ### Lower-level APIs ### # XXX Should these be present even if unimplemented? def fileno(self): """Returns underlying file descriptor (an int) if one exists. An IOError is raised if the IO object does not use a file descriptor. """ self._unsupported("fileno") def isatty(self): """Return a bool indicating whether this is an 'interactive' stream. Return False if it can't be determined. """ self._checkClosed() return False ### Readline[s] and writelines ### def readline(self, limit=-1): r"""Read and return a line of bytes from the stream. If limit is specified, at most limit bytes will be read. Limit should be an int. The line terminator is always b'\n' for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized. """ # For backwards compatibility, a (slowish) readline(). if hasattr(self, "peek"): def nreadahead(): readahead = self.peek(1) if not readahead: return 1 n = (readahead.find(b"\n") + 1) or len(readahead) if limit >= 0: n = min(n, limit) return n else: def nreadahead(): return 1 if limit is None: limit = -1 elif not isinstance(limit, int): raise TypeError("limit must be an integer") res = bytearray() while limit < 0 or len(res) < limit: b = self.read(nreadahead()) if not b: break res += b if res.endswith(b"\n"): break return bytes(res) def __iter__(self): self._checkClosed() return self def __next__(self): line = self.readline() if not line: raise StopIteration return line def readlines(self, hint=None): """Return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint. """ if hint is None or hint <= 0: return list(self) n = 0 lines = [] for line in self: lines.append(line) n += len(line) if n >= hint: break return lines def writelines(self, lines): self._checkClosed() for line in lines: self.write(line) #fix me brython #io.IOBase.register(IOBase) class RawIOBase(IOBase): """Base class for raw binary I/O.""" # The read() method is implemented by calling readinto(); derived # classes that want to support read() only need to implement # readinto() as a primitive operation. In general, readinto() can be # more efficient than read(). # (It would be tempting to also provide an implementation of # readinto() in terms of read(), in case the latter is a more suitable # primitive operation, but that would lead to nasty recursion in case # a subclass doesn't implement either.) def read(self, n=-1): """Read and return up to n bytes, where n is an int. Returns an empty bytes object on EOF, or None if the object is set not to block and has no data to read. """ if n is None: n = -1 if n < 0: return self.readall() b = bytearray(n.__index__()) n = self.readinto(b) if n is None: return None del b[n:] return bytes(b) def readall(self): """Read until EOF, using multiple read() call.""" res = bytearray() while True: data = self.read(DEFAULT_BUFFER_SIZE) if not data: break res += data if res: return bytes(res) else: # b'' or None return data def readinto(self, b): """Read up to len(b) bytes into bytearray b. Returns an int representing the number of bytes read (0 for EOF), or None if the object is set not to block and has no data to read. """ self._unsupported("readinto") def write(self, b): """Write the given buffer to the IO stream. Returns the number of bytes written, which may be less than len(b). """ self._unsupported("write") #io.RawIOBase.register(RawIOBase) #fix me brython #from _io import FileIO #RawIOBase.register(FileIO) class BufferedIOBase(IOBase): """Base class for buffered IO objects. The main difference with RawIOBase is that the read() method supports omitting the size argument, and does not have a default implementation that defers to readinto(). In addition, read(), readinto() and write() may raise BlockingIOError if the underlying raw stream is in non-blocking mode and not ready; unlike their raw counterparts, they will never return None. A typical implementation should not inherit from a RawIOBase implementation, but wrap one. """ def read(self, n=None): """Read and return up to n bytes, where n is an int. If the argument is omitted, None, or negative, reads and returns all data until EOF. If the argument is positive, and the underlying raw stream is not 'interactive', multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams (XXX and for pipes?), at most one raw read will be issued, and a short result does not imply that EOF is imminent. Returns an empty bytes array on EOF. Raises BlockingIOError if the underlying raw stream has no data at the moment. """ self._unsupported("read") def read1(self, n=None): """Read up to n bytes with at most one read() system call, where n is an int. """ self._unsupported("read1") def readinto(self, b): """Read up to len(b) bytes into bytearray b. Like read(), this may issue multiple reads to the underlying raw stream, unless the latter is 'interactive'. Returns an int representing the number of bytes read (0 for EOF). Raises BlockingIOError if the underlying raw stream has no data at the moment. """ # XXX This ought to work with anything that supports the buffer API data = self.read(len(b)) n = len(data) try: b[:n] = data except TypeError as err: import array if not isinstance(b, array.array): raise err b[:n] = array.array('b', data) return n def write(self, b): """Write the given bytes buffer to the IO stream. Return the number of bytes written, which is never less than len(b). Raises BlockingIOError if the buffer is full and the underlying raw stream cannot accept more data at the moment. """ self._unsupported("write") def detach(self): """ Separate the underlying raw stream from the buffer and return it. After the raw stream has been detached, the buffer is in an unusable state. """ self._unsupported("detach") #fix me brython #io.BufferedIOBase.register(BufferedIOBase) class _BufferedIOMixin(BufferedIOBase): """A mixin implementation of BufferedIOBase with an underlying raw stream. This passes most requests on to the underlying raw stream. It does *not* provide implementations of read(), readinto() or write(). """ def __init__(self, raw): self._raw = raw ### Positioning ### def seek(self, pos, whence=0): new_position = self.raw.seek(pos, whence) if new_position < 0: raise IOError("seek() returned an invalid position") return new_position def tell(self): pos = self.raw.tell() if pos < 0: raise IOError("tell() returned an invalid position") return pos def truncate(self, pos=None): # Flush the stream. We're mixing buffered I/O with lower-level I/O, # and a flush may be necessary to synch both views of the current # file state. self.flush() if pos is None: pos = self.tell() # XXX: Should seek() be used, instead of passing the position # XXX directly to truncate? return self.raw.truncate(pos) ### Flush and close ### def flush(self): if self.closed: raise ValueError("flush of closed file") self.raw.flush() def close(self): if self.raw is not None and not self.closed: try: # may raise BlockingIOError or BrokenPipeError etc self.flush() finally: self.raw.close() def detach(self): if self.raw is None: raise ValueError("raw stream already detached") self.flush() raw = self._raw self._raw = None return raw ### Inquiries ### def seekable(self): return self.raw.seekable() def readable(self): return self.raw.readable() def writable(self): return self.raw.writable() @property def raw(self): return self._raw @property def closed(self): return self.raw.closed @property def name(self): return self.raw.name @property def mode(self): return self.raw.mode def __getstate__(self): raise TypeError("can not serialize a '{0}' object" .format(self.__class__.__name__)) def __repr__(self): clsname = self.__class__.__name__ try: name = self.name except AttributeError: return "<_io.{0}>".format(clsname) else: return "<_io.{0} name={1!r}>".format(clsname, name) ### Lower-level APIs ### def fileno(self): return self.raw.fileno() def isatty(self): return self.raw.isatty() class BytesIO(BufferedIOBase): """Buffered I/O implementation using an in-memory bytes buffer.""" def __init__(self, initial_bytes=None): buf = bytearray() if initial_bytes is not None: buf += initial_bytes self._buffer = buf self._pos = 0 def __getstate__(self): if self.closed: raise ValueError("__getstate__ on closed file") return self.__dict__.copy() def getvalue(self): """Return the bytes value (contents) of the buffer """ if self.closed: raise ValueError("getvalue on closed file") return bytes(self._buffer) def getbuffer(self): """Return a readable and writable view of the buffer. """ return memoryview(self._buffer) def read(self, n=None): if self.closed: raise ValueError("read from closed file") if n is None: n = -1 if n < 0: n = len(self._buffer) if len(self._buffer) <= self._pos: return b"" newpos = min(len(self._buffer), self._pos + n) b = self._buffer[self._pos : newpos] self._pos = newpos return bytes(b) def read1(self, n): """This is the same as read. """ return self.read(n) def write(self, b): if self.closed: raise ValueError("write to closed file") if isinstance(b, str): raise TypeError("can't write str to binary stream") n = len(b) if n == 0: return 0 pos = self._pos if pos > len(self._buffer): # Inserts null bytes between the current end of the file # and the new write position. padding = b'\x00' * (pos - len(self._buffer)) self._buffer += padding self._buffer[pos:pos + n] = b self._pos += n return n def seek(self, pos, whence=0): if self.closed: raise ValueError("seek on closed file") try: pos.__index__ except AttributeError as err: raise TypeError("an integer is required") from err if whence == 0: if pos < 0: raise ValueError("negative seek position %r" % (pos,)) self._pos = pos elif whence == 1: self._pos = max(0, self._pos + pos) elif whence == 2: self._pos = max(0, len(self._buffer) + pos) else: raise ValueError("unsupported whence value") return self._pos def tell(self): if self.closed: raise ValueError("tell on closed file") return self._pos def truncate(self, pos=None): if self.closed: raise ValueError("truncate on closed file") if pos is None: pos = self._pos else: try: pos.__index__ except AttributeError as err: raise TypeError("an integer is required") from err if pos < 0: raise ValueError("negative truncate position %r" % (pos,)) del self._buffer[pos:] return pos def readable(self): if self.closed: raise ValueError("I/O operation on closed file.") return True def writable(self): if self.closed: raise ValueError("I/O operation on closed file.") return True def seekable(self): if self.closed: raise ValueError("I/O operation on closed file.") return True class BufferedReader(_BufferedIOMixin): """BufferedReader(raw[, buffer_size]) A buffer for a readable, sequential BaseRawIO object. The constructor creates a BufferedReader for the given readable raw stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE is used. """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): """Create a new buffered reader using the given readable raw IO object. """ if not raw.readable(): raise IOError('"raw" argument must be readable.') _BufferedIOMixin.__init__(self, raw) if buffer_size <= 0: raise ValueError("invalid buffer size") self.buffer_size = buffer_size self._reset_read_buf() self._read_lock = Lock() def _reset_read_buf(self): self._read_buf = b"" self._read_pos = 0 def read(self, n=None): """Read n bytes. Returns exactly n bytes of data unless the underlying raw IO stream reaches EOF or if the call would block in non-blocking mode. If n is negative, read until EOF or until read() would block. """ if n is not None and n < -1: raise ValueError("invalid number of bytes to read") with self._read_lock: return self._read_unlocked(n) def _read_unlocked(self, n=None): nodata_val = b"" empty_values = (b"", None) buf = self._read_buf pos = self._read_pos # Special case for when the number of bytes to read is unspecified. if n is None or n == -1: self._reset_read_buf() if hasattr(self.raw, 'readall'): chunk = self.raw.readall() if chunk is None: return buf[pos:] or None else: return buf[pos:] + chunk chunks = [buf[pos:]] # Strip the consumed bytes. current_size = 0 while True: # Read until EOF or until read() would block. try: chunk = self.raw.read() except InterruptedError: continue if chunk in empty_values: nodata_val = chunk break current_size += len(chunk) chunks.append(chunk) return b"".join(chunks) or nodata_val # The number of bytes to read is specified, return at most n bytes. avail = len(buf) - pos # Length of the available buffered data. if n <= avail: # Fast path: the data to read is fully buffered. self._read_pos += n return buf[pos:pos+n] # Slow path: read from the stream until enough bytes are read, # or until an EOF occurs or until read() would block. chunks = [buf[pos:]] wanted = max(self.buffer_size, n) while avail < n: try: chunk = self.raw.read(wanted) except InterruptedError: continue if chunk in empty_values: nodata_val = chunk break avail += len(chunk) chunks.append(chunk) # n is more then avail only when an EOF occurred or when # read() would have blocked. n = min(n, avail) out = b"".join(chunks) self._read_buf = out[n:] # Save the extra data in the buffer. self._read_pos = 0 return out[:n] if out else nodata_val def peek(self, n=0): """Returns buffered bytes without advancing the position. The argument indicates a desired minimal number of bytes; we do at most one raw read to satisfy it. We never return more than self.buffer_size. """ with self._read_lock: return self._peek_unlocked(n) def _peek_unlocked(self, n=0): want = min(n, self.buffer_size) have = len(self._read_buf) - self._read_pos if have < want or have <= 0: to_read = self.buffer_size - have while True: try: current = self.raw.read(to_read) except InterruptedError: continue break if current: self._read_buf = self._read_buf[self._read_pos:] + current self._read_pos = 0 return self._read_buf[self._read_pos:] def read1(self, n): """Reads up to n bytes, with at most one read() system call.""" # Returns up to n bytes. If at least one byte is buffered, we # only return buffered bytes. Otherwise, we do one raw read. if n < 0: raise ValueError("number of bytes to read must be positive") if n == 0: return b"" with self._read_lock: self._peek_unlocked(1) return self._read_unlocked( min(n, len(self._read_buf) - self._read_pos)) def tell(self): return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos def seek(self, pos, whence=0): if whence not in valid_seek_flags: raise ValueError("invalid whence value") with self._read_lock: if whence == 1: pos -= len(self._read_buf) - self._read_pos pos = _BufferedIOMixin.seek(self, pos, whence) self._reset_read_buf() return pos class BufferedWriter(_BufferedIOMixin): """A buffer for a writeable sequential RawIO object. The constructor creates a BufferedWriter for the given writeable raw stream. If the buffer_size is not given, it defaults to DEFAULT_BUFFER_SIZE. """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): if not raw.writable(): raise IOError('"raw" argument must be writable.') _BufferedIOMixin.__init__(self, raw) if buffer_size <= 0: raise ValueError("invalid buffer size") self.buffer_size = buffer_size self._write_buf = bytearray() self._write_lock = Lock() def write(self, b): if self.closed: raise ValueError("write to closed file") if isinstance(b, str): raise TypeError("can't write str to binary stream") with self._write_lock: # XXX we can implement some more tricks to try and avoid # partial writes if len(self._write_buf) > self.buffer_size: # We're full, so let's pre-flush the buffer. (This may # raise BlockingIOError with characters_written == 0.) self._flush_unlocked() before = len(self._write_buf) self._write_buf.extend(b) written = len(self._write_buf) - before if len(self._write_buf) > self.buffer_size: try: self._flush_unlocked() except BlockingIOError as e: if len(self._write_buf) > self.buffer_size: # We've hit the buffer_size. We have to accept a partial # write and cut back our buffer. overage = len(self._write_buf) - self.buffer_size written -= overage self._write_buf = self._write_buf[:self.buffer_size] raise BlockingIOError(e.errno, e.strerror, written) return written def truncate(self, pos=None): with self._write_lock: self._flush_unlocked() if pos is None: pos = self.raw.tell() return self.raw.truncate(pos) def flush(self): with self._write_lock: self._flush_unlocked() def _flush_unlocked(self): if self.closed: raise ValueError("flush of closed file") while self._write_buf: try: n = self.raw.write(self._write_buf) except InterruptedError: continue except BlockingIOError: raise RuntimeError("self.raw should implement RawIOBase: it " "should not raise BlockingIOError") if n is None: raise BlockingIOError( errno.EAGAIN, "write could not complete without blocking", 0) if n > len(self._write_buf) or n < 0: raise IOError("write() returned incorrect number of bytes") del self._write_buf[:n] def tell(self): return _BufferedIOMixin.tell(self) + len(self._write_buf) def seek(self, pos, whence=0): if whence not in valid_seek_flags: raise ValueError("invalid whence value") with self._write_lock: self._flush_unlocked() return _BufferedIOMixin.seek(self, pos, whence) class BufferedRWPair(BufferedIOBase): """A buffered reader and writer object together. A buffered reader object and buffered writer object put together to form a sequential IO object that can read and write. This is typically used with a socket or two-way pipe. reader and writer are RawIOBase objects that are readable and writeable respectively. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE. """ # XXX The usefulness of this (compared to having two separate IO # objects) is questionable. def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE): """Constructor. The arguments are two RawIO instances. """ if not reader.readable(): raise IOError('"reader" argument must be readable.') if not writer.writable(): raise IOError('"writer" argument must be writable.') self.reader = BufferedReader(reader, buffer_size) self.writer = BufferedWriter(writer, buffer_size) def read(self, n=None): if n is None: n = -1 return self.reader.read(n) def readinto(self, b): return self.reader.readinto(b) def write(self, b): return self.writer.write(b) def peek(self, n=0): return self.reader.peek(n) def read1(self, n): return self.reader.read1(n) def readable(self): return self.reader.readable() def writable(self): return self.writer.writable() def flush(self): return self.writer.flush() def close(self): self.writer.close() self.reader.close() def isatty(self): return self.reader.isatty() or self.writer.isatty() @property def closed(self): return self.writer.closed class BufferedRandom(BufferedWriter, BufferedReader): """A buffered interface to random access streams. The constructor creates a reader and writer for a seekable stream, raw, given in the first argument. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE. """ def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE): raw._checkSeekable() BufferedReader.__init__(self, raw, buffer_size) BufferedWriter.__init__(self, raw, buffer_size) def seek(self, pos, whence=0): if whence not in valid_seek_flags: raise ValueError("invalid whence value") self.flush() if self._read_buf: # Undo read ahead. with self._read_lock: self.raw.seek(self._read_pos - len(self._read_buf), 1) # First do the raw seek, then empty the read buffer, so that # if the raw seek fails, we don't lose buffered data forever. pos = self.raw.seek(pos, whence) with self._read_lock: self._reset_read_buf() if pos < 0: raise IOError("seek() returned invalid position") return pos def tell(self): if self._write_buf: return BufferedWriter.tell(self) else: return BufferedReader.tell(self) def truncate(self, pos=None): if pos is None: pos = self.tell() # Use seek to flush the read buffer. return BufferedWriter.truncate(self, pos) def read(self, n=None): if n is None: n = -1 self.flush() return BufferedReader.read(self, n) def readinto(self, b): self.flush() return BufferedReader.readinto(self, b) def peek(self, n=0): self.flush() return BufferedReader.peek(self, n) def read1(self, n): self.flush() return BufferedReader.read1(self, n) def write(self, b): if self._read_buf: # Undo readahead with self._read_lock: self.raw.seek(self._read_pos - len(self._read_buf), 1) self._reset_read_buf() return BufferedWriter.write(self, b) class TextIOBase(IOBase): """Base class for text I/O. This class provides a character and line based interface to stream I/O. There is no readinto method because Python's character strings are immutable. There is no public constructor. """ def read(self, n=-1): """Read at most n characters from stream, where n is an int. Read from underlying buffer until we have n characters or we hit EOF. If n is negative or omitted, read until EOF. Returns a string. """ self._unsupported("read") def write(self, s): """Write string s to stream and returning an int.""" self._unsupported("write") def truncate(self, pos=None): """Truncate size to pos, where pos is an int.""" self._unsupported("truncate") def readline(self): """Read until newline or EOF. Returns an empty string if EOF is hit immediately. """ self._unsupported("readline") def detach(self): """ Separate the underlying buffer from the TextIOBase and return it. After the underlying buffer has been detached, the TextIO is in an unusable state. """ self._unsupported("detach") @property def encoding(self): """Subclasses should override.""" return None @property def newlines(self): """Line endings translated so far. Only line endings translated during reading are considered. Subclasses should override. """ return None @property def errors(self): """Error setting of the decoder or encoder. Subclasses should override.""" return None #fix me brython #io.TextIOBase.register(TextIOBase) class IncrementalNewlineDecoder(codecs.IncrementalDecoder): r"""Codec used when reading a file in universal newlines mode. It wraps another incremental decoder, translating \r\n and \r into \n. It also records the types of newlines encountered. When used with translate=False, it ensures that the newline sequence is returned in one piece. """ def __init__(self, decoder, translate, errors='strict'): codecs.IncrementalDecoder.__init__(self, errors=errors) self.translate = translate self.decoder = decoder self.seennl = 0 self.pendingcr = False def decode(self, input, final=False): # decode input (with the eventual \r from a previous pass) if self.decoder is None: output = input else: output = self.decoder.decode(input, final=final) if self.pendingcr and (output or final): output = "\r" + output self.pendingcr = False # retain last \r even when not translating data: # then readline() is sure to get \r\n in one pass if output.endswith("\r") and not final: output = output[:-1] self.pendingcr = True # Record which newlines are read crlf = output.count('\r\n') cr = output.count('\r') - crlf lf = output.count('\n') - crlf self.seennl |= (lf and self._LF) | (cr and self._CR) \ | (crlf and self._CRLF) if self.translate: if crlf: output = output.replace("\r\n", "\n") if cr: output = output.replace("\r", "\n") return output def getstate(self): if self.decoder is None: buf = b"" flag = 0 else: buf, flag = self.decoder.getstate() flag <<= 1 if self.pendingcr: flag |= 1 return buf, flag def setstate(self, state): buf, flag = state self.pendingcr = bool(flag & 1) if self.decoder is not None: self.decoder.setstate((buf, flag >> 1)) def reset(self): self.seennl = 0 self.pendingcr = False if self.decoder is not None: self.decoder.reset() _LF = 1 _CR = 2 _CRLF = 4 @property def newlines(self): return (None, "\n", "\r", ("\r", "\n"), "\r\n", ("\n", "\r\n"), ("\r", "\r\n"), ("\r", "\n", "\r\n") )[self.seennl] class TextIOWrapper(TextIOBase): r"""Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see the codecs.register) and defaults to "strict". newline can be None, '', '\n', '\r', or '\r\n'. It controls the handling of line endings. If it is None, universal newlines is enabled. With this enabled, on input, the lines endings '\n', '\r', or '\r\n' are translated to '\n' before being returned to the caller. Conversely, on output, '\n' is translated to the system default line separator, os.linesep. If newline is any other of its legal values, that newline becomes the newline when the file is read and it is returned untranslated. On output, '\n' is converted to the newline. If line_buffering is True, a call to flush is implied when a call to write contains a newline character. """ _CHUNK_SIZE = 2048 # The write_through argument has no effect here since this # implementation always writes through. The argument is present only # so that the signature can match the signature of the C version. def __init__(self, buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False): if newline is not None and not isinstance(newline, str): raise TypeError("illegal newline type: %r" % (type(newline),)) if newline not in (None, "", "\n", "\r", "\r\n"): raise ValueError("illegal newline value: %r" % (newline,)) if encoding is None: try: encoding = os.device_encoding(buffer.fileno()) except (AttributeError, UnsupportedOperation): pass if encoding is None: try: import locale except ImportError: # Importing locale may fail if Python is being built encoding = "ascii" else: encoding = locale.getpreferredencoding(False) if not isinstance(encoding, str): raise ValueError("invalid encoding: %r" % encoding) if errors is None: errors = "strict" else: if not isinstance(errors, str): raise ValueError("invalid errors: %r" % errors) self._buffer = buffer self._line_buffering = line_buffering self._encoding = encoding self._errors = errors self._readuniversal = not newline self._readtranslate = newline is None self._readnl = newline self._writetranslate = newline != '' self._writenl = newline or os.linesep self._encoder = None self._decoder = None self._decoded_chars = '' # buffer for text returned from decoder self._decoded_chars_used = 0 # offset into _decoded_chars for read() self._snapshot = None # info for reconstructing decoder state self._seekable = self._telling = self.buffer.seekable() self._has_read1 = hasattr(self.buffer, 'read1') self._b2cratio = 0.0 if self._seekable and self.writable(): position = self.buffer.tell() if position != 0: try: self._get_encoder().setstate(0) except LookupError: # Sometimes the encoder doesn't exist pass # self._snapshot is either None, or a tuple (dec_flags, next_input) # where dec_flags is the second (integer) item of the decoder state # and next_input is the chunk of input bytes that comes next after the # snapshot point. We use this to reconstruct decoder states in tell(). # Naming convention: # - "bytes_..." for integer variables that count input bytes # - "chars_..." for integer variables that count decoded characters def __repr__(self): result = "<_io.TextIOWrapper" try: name = self.name except AttributeError: pass else: result += " name={0!r}".format(name) try: mode = self.mode except AttributeError: pass else: result += " mode={0!r}".format(mode) return result + " encoding={0!r}>".format(self.encoding) @property def encoding(self): return self._encoding @property def errors(self): return self._errors @property def line_buffering(self): return self._line_buffering @property def buffer(self): return self._buffer def seekable(self): if self.closed: raise ValueError("I/O operation on closed file.") return self._seekable def readable(self): return self.buffer.readable() def writable(self): return self.buffer.writable() def flush(self): self.buffer.flush() self._telling = self._seekable def close(self): if self.buffer is not None and not self.closed: try: self.flush() finally: self.buffer.close() @property def closed(self): return self.buffer.closed @property def name(self): return self.buffer.name def fileno(self): return self.buffer.fileno() def isatty(self): return self.buffer.isatty() def write(self, s): 'Write data, where s is a str' if self.closed: raise ValueError("write to closed file") if not isinstance(s, str): raise TypeError("can't write %s to text stream" % s.__class__.__name__) length = len(s) haslf = (self._writetranslate or self._line_buffering) and "\n" in s if haslf and self._writetranslate and self._writenl != "\n": s = s.replace("\n", self._writenl) encoder = self._encoder or self._get_encoder() # XXX What if we were just reading? b = encoder.encode(s) self.buffer.write(b) if self._line_buffering and (haslf or "\r" in s): self.flush() self._snapshot = None if self._decoder: self._decoder.reset() return length def _get_encoder(self): make_encoder = codecs.getincrementalencoder(self._encoding) self._encoder = make_encoder(self._errors) return self._encoder def _get_decoder(self): make_decoder = codecs.getincrementaldecoder(self._encoding) decoder = make_decoder(self._errors) if self._readuniversal: decoder = IncrementalNewlineDecoder(decoder, self._readtranslate) self._decoder = decoder return decoder # The following three methods implement an ADT for _decoded_chars. # Text returned from the decoder is buffered here until the client # requests it by calling our read() or readline() method. def _set_decoded_chars(self, chars): """Set the _decoded_chars buffer.""" self._decoded_chars = chars self._decoded_chars_used = 0 def _get_decoded_chars(self, n=None): """Advance into the _decoded_chars buffer.""" offset = self._decoded_chars_used if n is None: chars = self._decoded_chars[offset:] else: chars = self._decoded_chars[offset:offset + n] self._decoded_chars_used += len(chars) return chars def _rewind_decoded_chars(self, n): """Rewind the _decoded_chars buffer.""" if self._decoded_chars_used < n: raise AssertionError("rewind decoded_chars out of bounds") self._decoded_chars_used -= n def _read_chunk(self): """ Read and decode the next chunk of data from the BufferedReader. """ # The return value is True unless EOF was reached. The decoded # string is placed in self._decoded_chars (replacing its previous # value). The entire input chunk is sent to the decoder, though # some of it may remain buffered in the decoder, yet to be # converted. if self._decoder is None: raise ValueError("no decoder") if self._telling: # To prepare for tell(), we need to snapshot a point in the # file where the decoder's input buffer is empty. dec_buffer, dec_flags = self._decoder.getstate() # Given this, we know there was a valid snapshot point # len(dec_buffer) bytes ago with decoder state (b'', dec_flags). # Read a chunk, decode it, and put the result in self._decoded_chars. if self._has_read1: input_chunk = self.buffer.read1(self._CHUNK_SIZE) else: input_chunk = self.buffer.read(self._CHUNK_SIZE) eof = not input_chunk decoded_chars = self._decoder.decode(input_chunk, eof) self._set_decoded_chars(decoded_chars) if decoded_chars: self._b2cratio = len(input_chunk) / len(self._decoded_chars) else: self._b2cratio = 0.0 if self._telling: # At the snapshot point, len(dec_buffer) bytes before the read, # the next input to be decoded is dec_buffer + input_chunk. self._snapshot = (dec_flags, dec_buffer + input_chunk) return not eof def _pack_cookie(self, position, dec_flags=0, bytes_to_feed=0, need_eof=0, chars_to_skip=0): # The meaning of a tell() cookie is: seek to position, set the # decoder flags to dec_flags, read bytes_to_feed bytes, feed them # into the decoder with need_eof as the EOF flag, then skip # chars_to_skip characters of the decoded result. For most simple # decoders, tell() will often just give a byte offset in the file. return (position | (dec_flags<<64) | (bytes_to_feed<<128) | (chars_to_skip<<192) | bool(need_eof)<<256) def _unpack_cookie(self, bigint): rest, position = divmod(bigint, 1<<64) rest, dec_flags = divmod(rest, 1<<64) rest, bytes_to_feed = divmod(rest, 1<<64) need_eof, chars_to_skip = divmod(rest, 1<<64) return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip def tell(self): if not self._seekable: raise UnsupportedOperation("underlying stream is not seekable") if not self._telling: raise IOError("telling position disabled by next() call") self.flush() position = self.buffer.tell() decoder = self._decoder if decoder is None or self._snapshot is None: if self._decoded_chars: # This should never happen. raise AssertionError("pending decoded text") return position # Skip backward to the snapshot point (see _read_chunk). dec_flags, next_input = self._snapshot position -= len(next_input) # How many decoded characters have been used up since the snapshot? chars_to_skip = self._decoded_chars_used if chars_to_skip == 0: # We haven't moved from the snapshot point. return self._pack_cookie(position, dec_flags) # Starting from the snapshot position, we will walk the decoder # forward until it gives us enough decoded characters. saved_state = decoder.getstate() try: # Fast search for an acceptable start point, close to our # current pos. # Rationale: calling decoder.decode() has a large overhead # regardless of chunk size; we want the number of such calls to # be O(1) in most situations (common decoders, non-crazy input). # Actually, it will be exactly 1 for fixed-size codecs (all # 8-bit codecs, also UTF-16 and UTF-32). skip_bytes = int(self._b2cratio * chars_to_skip) skip_back = 1 assert skip_bytes <= len(next_input) while skip_bytes > 0: decoder.setstate((b'', dec_flags)) # Decode up to temptative start point n = len(decoder.decode(next_input[:skip_bytes])) if n <= chars_to_skip: b, d = decoder.getstate() if not b: # Before pos and no bytes buffered in decoder => OK dec_flags = d chars_to_skip -= n break # Skip back by buffered amount and reset heuristic skip_bytes -= len(b) skip_back = 1 else: # We're too far ahead, skip back a bit skip_bytes -= skip_back skip_back = skip_back * 2 else: skip_bytes = 0 decoder.setstate((b'', dec_flags)) # Note our initial start point. start_pos = position + skip_bytes start_flags = dec_flags if chars_to_skip == 0: # We haven't moved from the start point. return self._pack_cookie(start_pos, start_flags) # Feed the decoder one byte at a time. As we go, note the # nearest "safe start point" before the current location # (a point where the decoder has nothing buffered, so seek() # can safely start from there and advance to this location). bytes_fed = 0 need_eof = 0 # Chars decoded since `start_pos` chars_decoded = 0 for i in range(skip_bytes, len(next_input)): bytes_fed += 1 chars_decoded += len(decoder.decode(next_input[i:i+1])) dec_buffer, dec_flags = decoder.getstate() if not dec_buffer and chars_decoded <= chars_to_skip: # Decoder buffer is empty, so this is a safe start point. start_pos += bytes_fed chars_to_skip -= chars_decoded start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0 if chars_decoded >= chars_to_skip: break else: # We didn't get enough decoded data; signal EOF to get more. chars_decoded += len(decoder.decode(b'', final=True)) need_eof = 1 if chars_decoded < chars_to_skip: raise IOError("can't reconstruct logical file position") # The returned cookie corresponds to the last safe start point. return self._pack_cookie( start_pos, start_flags, bytes_fed, need_eof, chars_to_skip) finally: decoder.setstate(saved_state) def truncate(self, pos=None): self.flush() if pos is None: pos = self.tell() return self.buffer.truncate(pos) def detach(self): if self.buffer is None: raise ValueError("buffer is already detached") self.flush() buffer = self._buffer self._buffer = None return buffer def seek(self, cookie, whence=0): if self.closed: raise ValueError("tell on closed file") if not self._seekable: raise UnsupportedOperation("underlying stream is not seekable") if whence == 1: # seek relative to current position if cookie != 0: raise UnsupportedOperation("can't do nonzero cur-relative seeks") # Seeking to the current position should attempt to # sync the underlying buffer with the current position. whence = 0 cookie = self.tell() if whence == 2: # seek relative to end of file if cookie != 0: raise UnsupportedOperation("can't do nonzero end-relative seeks") self.flush() position = self.buffer.seek(0, 2) self._set_decoded_chars('') self._snapshot = None if self._decoder: self._decoder.reset() return position if whence != 0: raise ValueError("unsupported whence (%r)" % (whence,)) if cookie < 0: raise ValueError("negative seek position %r" % (cookie,)) self.flush() # The strategy of seek() is to go back to the safe start point # and replay the effect of read(chars_to_skip) from there. start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \ self._unpack_cookie(cookie) # Seek back to the safe start point. self.buffer.seek(start_pos) self._set_decoded_chars('') self._snapshot = None # Restore the decoder to its state from the safe start point. if cookie == 0 and self._decoder: self._decoder.reset() elif self._decoder or dec_flags or chars_to_skip: self._decoder = self._decoder or self._get_decoder() self._decoder.setstate((b'', dec_flags)) self._snapshot = (dec_flags, b'') if chars_to_skip: # Just like _read_chunk, feed the decoder and save a snapshot. input_chunk = self.buffer.read(bytes_to_feed) self._set_decoded_chars( self._decoder.decode(input_chunk, need_eof)) self._snapshot = (dec_flags, input_chunk) # Skip chars_to_skip of the decoded characters. if len(self._decoded_chars) < chars_to_skip: raise IOError("can't restore logical file position") self._decoded_chars_used = chars_to_skip # Finally, reset the encoder (merely useful for proper BOM handling) try: encoder = self._encoder or self._get_encoder() except LookupError: # Sometimes the encoder doesn't exist pass else: if cookie != 0: encoder.setstate(0) else: encoder.reset() return cookie def read(self, n=None): self._checkReadable() if n is None: n = -1 decoder = self._decoder or self._get_decoder() try: n.__index__ except AttributeError as err: raise TypeError("an integer is required") from err if n < 0: # Read everything. result = (self._get_decoded_chars() + decoder.decode(self.buffer.read(), final=True)) self._set_decoded_chars('') self._snapshot = None return result else: # Keep reading chunks until we have n characters to return. eof = False result = self._get_decoded_chars(n) while len(result) < n and not eof: eof = not self._read_chunk() result += self._get_decoded_chars(n - len(result)) return result def __next__(self): self._telling = False line = self.readline() if not line: self._snapshot = None self._telling = self._seekable raise StopIteration return line def readline(self, limit=None): if self.closed: raise ValueError("read from closed file") if limit is None: limit = -1 elif not isinstance(limit, int): raise TypeError("limit must be an integer") # Grab all the decoded text (we will rewind any extra bits later). line = self._get_decoded_chars() start = 0 # Make the decoder if it doesn't already exist. if not self._decoder: self._get_decoder() pos = endpos = None while True: if self._readtranslate: # Newlines are already translated, only search for \n pos = line.find('\n', start) if pos >= 0: endpos = pos + 1 break else: start = len(line) elif self._readuniversal: # Universal newline search. Find any of \r, \r\n, \n # The decoder ensures that \r\n are not split in two pieces # In C we'd look for these in parallel of course. nlpos = line.find("\n", start) crpos = line.find("\r", start) if crpos == -1: if nlpos == -1: # Nothing found start = len(line) else: # Found \n endpos = nlpos + 1 break elif nlpos == -1: # Found lone \r endpos = crpos + 1 break elif nlpos < crpos: # Found \n endpos = nlpos + 1 break elif nlpos == crpos + 1: # Found \r\n endpos = crpos + 2 break else: # Found \r endpos = crpos + 1 break else: # non-universal pos = line.find(self._readnl) if pos >= 0: endpos = pos + len(self._readnl) break if limit >= 0 and len(line) >= limit: endpos = limit # reached length limit break # No line ending seen yet - get more data' while self._read_chunk(): if self._decoded_chars: break if self._decoded_chars: line += self._get_decoded_chars() else: # end of file self._set_decoded_chars('') self._snapshot = None return line if limit >= 0 and endpos > limit: endpos = limit # don't exceed limit # Rewind _decoded_chars to just after the line ending we found. self._rewind_decoded_chars(len(line) - endpos) return line[:endpos] @property def newlines(self): return self._decoder.newlines if self._decoder else None class StringIO(TextIOWrapper): """Text I/O implementation using an in-memory buffer. The initial_value argument sets the value of object. The newline argument is like the one of TextIOWrapper's constructor. """ def __init__(self, initial_value="", newline="\n"): super(StringIO, self).__init__(BytesIO(), encoding="utf-8", errors="strict", newline=newline) # Issue #5645: make universal newlines semantics the same as in the # C version, even under Windows. if newline is None: self._writetranslate = False if initial_value is not None: if not isinstance(initial_value, str): raise TypeError("initial_value must be str or None, not {0}" .format(type(initial_value).__name__)) initial_value = str(initial_value) self.write(initial_value) self.seek(0) def getvalue(self): self.flush() return self.buffer.getvalue().decode(self._encoding, self._errors) def __repr__(self): # TextIOWrapper tells the encoding in its repr. In StringIO, # that's a implementation detail. return object.__repr__(self) @property def errors(self): return None @property def encoding(self): return None def detach(self): # This doesn't make sense on StringIO. self._unsupported("detach")
gpl-3.0
sharad/calibre
src/calibre/devices/mtp/books.py
9
2346
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from calibre.devices.interface import BookList as BL from calibre.ebooks.metadata import title_sort from calibre.ebooks.metadata.book.base import Metadata from calibre.ebooks.metadata.book.json_codec import JsonCodec from calibre.utils.date import utcnow class BookList(BL): def __init__(self, storage_id): self.storage_id = storage_id def supports_collections(self): return False def add_book(self, book, replace_metadata=True): try: b = self.index(book) except (ValueError, IndexError): b = None if b is None: self.append(book) return book if replace_metadata: self[b].smart_update(book, replace_metadata=True) return self[b] return None def remove_book(self, book): self.remove(book) class Book(Metadata): def __init__(self, storage_id, lpath, other=None): Metadata.__init__(self, _('Unknown'), other=other) self.storage_id, self.lpath = storage_id, lpath self.lpath = self.path = self.lpath.replace(os.sep, '/') self.mtp_relpath = tuple([icu_lower(x) for x in self.lpath.split('/')]) self.datetime = utcnow().timetuple() self.thumbail = None def matches_file(self, mtp_file): return (self.storage_id == mtp_file.storage_id and self.mtp_relpath == mtp_file.mtp_relpath) def __eq__(self, other): return (isinstance(other, self.__class__) and (self.storage_id == other.storage_id and self.mtp_relpath == other.mtp_relpath)) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash((self.storage_id, self.mtp_relpath)) @property def title_sorter(self): ans = getattr(self, 'title_sort', None) if not ans or self.is_null('title_sort') or ans == _('Unknown'): ans = '' return ans or title_sort(self.title or '') class JSONCodec(JsonCodec): pass
gpl-3.0
toshywoshy/ansible
lib/ansible/modules/cloud/amazon/ec2_group_info.py
8
5352
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ec2_group_info short_description: Gather information about ec2 security groups in AWS. description: - Gather information about ec2 security groups in AWS. - This module was called C(ec2_group_facts) before Ansible 2.9. The usage did not change. version_added: "2.3" requirements: [ boto3 ] author: - Henrique Rodrigues (@Sodki) options: filters: description: - A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSecurityGroups.html) for possible filters. Filter names and values are case sensitive. You can also use underscores (_) instead of dashes (-) in the filter keys, which will take precedence in case of conflict. required: false default: {} type: dict notes: - By default, the module will return all security groups. To limit results use the appropriate filters. extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Gather information about all security groups - ec2_group_info: # Gather information about all security groups in a specific VPC - ec2_group_info: filters: vpc-id: vpc-12345678 # Gather information about all security groups in a specific VPC - ec2_group_info: filters: vpc-id: vpc-12345678 # Gather information about a security group - ec2_group_info: filters: group-name: example-1 # Gather information about a security group by id - ec2_group_info: filters: group-id: sg-12345678 # Gather information about a security group with multiple filters, also mixing the use of underscores as filter keys - ec2_group_info: filters: group_id: sg-12345678 vpc-id: vpc-12345678 # Gather information about various security groups - ec2_group_info: filters: group-name: - example-1 - example-2 - example-3 # Gather information about any security group with a tag key Name and value Example. # The quotes around 'tag:name' are important because of the colon in the value - ec2_group_info: filters: "tag:Name": Example ''' RETURN = ''' security_groups: description: Security groups that match the provided filters. Each element consists of a dict with all the information related to that security group. type: list returned: always sample: ''' import traceback try: from botocore.exceptions import ClientError except ImportError: pass # caught by imported HAS_BOTO3 from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import (ec2_argument_spec, boto3_conn, HAS_BOTO3, get_aws_connection_info, boto3_tag_list_to_ansible_dict, ansible_dict_to_boto3_filter_list, camel_dict_to_snake_dict) def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( filters=dict(default={}, type='dict') ) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'ec2_group_facts': module.deprecate("The 'ec2_group_facts' module has been renamed to 'ec2_group_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: connection = boto3_conn( module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params ) else: module.fail_json(msg="region must be specified") # Replace filter key underscores with dashes, for compatibility, except if we're dealing with tags sanitized_filters = module.params.get("filters") for key in list(sanitized_filters): if not key.startswith("tag:"): sanitized_filters[key.replace("_", "-")] = sanitized_filters.pop(key) try: security_groups = connection.describe_security_groups( Filters=ansible_dict_to_boto3_filter_list(sanitized_filters) ) except ClientError as e: module.fail_json(msg=e.message, exception=traceback.format_exc()) snaked_security_groups = [] for security_group in security_groups['SecurityGroups']: # Modify boto3 tags list to be ansible friendly dict # but don't camel case tags security_group = camel_dict_to_snake_dict(security_group) security_group['tags'] = boto3_tag_list_to_ansible_dict(security_group.get('tags', {}), tag_name_key_name='key', tag_value_key_name='value') snaked_security_groups.append(security_group) module.exit_json(security_groups=snaked_security_groups) if __name__ == '__main__': main()
gpl-3.0
librasungirl/openthread
tools/harness-automation/cases/router_5_1_1.py
18
1877
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import unittest from autothreadharness.harness_case import HarnessCase class Router_5_1_1(HarnessCase): role = HarnessCase.ROLE_ROUTER case = '5 1 1' golden_devices_required = 1 def on_dialog(self, dialog, title): pass if __name__ == '__main__': unittest.main()
bsd-3-clause
lidakanari/NeuroM
neurom/check/morphtree.py
4
9010
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project # All rights reserved. # # This file is part of NeuroM <https://github.com/BlueBrain/NeuroM> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of # its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' Python module of NeuroM to check neuronal trees. ''' import numpy as np from neurom.core.dataformat import COLS from neurom import morphmath as mm from neurom.morphmath import principal_direction_extent from neurom._compat import range, filter def is_monotonic(neurite, tol): '''Check if neurite tree is monotonic If each child has smaller or equal diameters from its parent Args: neurite(Neurite): neurite to operate on tol(float): tolerance Returns: True if neurite monotonic ''' for node in neurite.iter_sections(): # check that points in section satisfy monotonicity sec = node.points for point_id in range(len(sec) - 1): if sec[point_id + 1][COLS.R] > sec[point_id][COLS.R] + tol: return False # Check that section boundary points satisfy monotonicity if(node.parent is not None and sec[0][COLS.R] > node.parent.points[-1][COLS.R] + tol): return False return True def is_flat(neurite, tol, method='tolerance'): '''Check if neurite is flat using the given method Args: neurite(Neurite): neurite to operate on tol(float): tolerance method(string): the method of flatness estimation: 'tolerance' returns true if any extent of the tree is smaller than the given tolerance 'ratio' returns true if the ratio of the smallest directions is smaller than tol. e.g. [1,2,3] -> 1/2 < tol Returns: True if neurite is flat ''' ext = principal_direction_extent(neurite.points[:, COLS.XYZ]) assert method in ('tolerance', 'ratio'), "Method must be one of 'tolerance', 'ratio'" if method == 'ratio': sorted_ext = np.sort(ext) return sorted_ext[0] / sorted_ext[1] < float(tol) return any(ext < float(tol)) def is_back_tracking(neurite): ''' Check if a neurite process backtracks to a previous node. Back-tracking takes place when a daughter of a branching process goes back and either overlaps with a previous point, or lies inside the cylindrical volume of the latter. Args: neurite(Neurite): neurite to operate on Returns: True Under the following scenaria: 1. A segment endpoint falls back and overlaps with a previous segment's point 2. The geometry of a segment overlaps with a previous one in the section ''' def pair(segs): ''' Pairs the input list into triplets''' return zip(segs, segs[1:]) def coords(node): ''' Returns the first three values of the tree that correspond to the x, y, z coordinates''' return node[COLS.XYZ] def max_radius(seg): ''' Returns maximum radius from the two segment endpoints''' return max(seg[0][COLS.R], seg[1][COLS.R]) def is_not_zero_seg(seg): ''' Returns True if segment has zero length''' return not np.allclose(coords(seg[0]), coords(seg[1])) def is_in_the_same_verse(seg1, seg2): ''' Checks if the vectors face the same direction. This is true if their dot product is greater than zero. ''' v1 = coords(seg2[1]) - coords(seg2[0]) v2 = coords(seg1[1]) - coords(seg1[0]) return np.dot(v1, v2) >= 0 def is_seg2_within_seg1_radius(dist, seg1, seg2): ''' Checks whether the orthogonal distance from the point at the end of seg1 to seg2 segment body is smaller than the sum of their radii ''' return dist <= max_radius(seg1) + max_radius(seg2) def is_seg1_overlapping_with_seg2(seg1, seg2): '''Checks if a segment is in proximity of another one upstream''' # get the coordinates of seg2 (from the origin) s1 = coords(seg2[0]) s2 = coords(seg2[1]) # vector of the center of seg2 (from the origin) C = 0.5 * (s1 + s2) # endpoint of seg1 (from the origin) P = coords(seg1[1]) # vector from the center C of seg2 to the endpoint P of seg1 CP = P - C # vector of seg2 S1S2 = s2 - s1 # projection of CP upon seg2 prj = mm.vector_projection(CP, S1S2) # check if the distance of the orthogonal complement of CP projection on S1S2 # (vertical distance from P to seg2) is smaller than the sum of the radii. (overlap) # If not exit early, because there is no way that backtracking can feasible if not is_seg2_within_seg1_radius(np.linalg.norm(CP - prj), seg1, seg2): return False # projection lies within the length of the cylinder. Check if the distance between # the center C of seg2 and the projection of the end point of seg1, P is smaller than # half of the others length plus a 5% tolerance return np.linalg.norm(prj) < 0.55 * np.linalg.norm(S1S2) def is_inside_cylinder(seg1, seg2): ''' Checks if seg2 approximately lies within a cylindrical volume of seg1. Two conditions must be satisfied: 1. The two segments are not facing the same direction (seg2 comes back to seg1) 2. seg2 is overlaping with seg1 ''' return not is_in_the_same_verse(seg1, seg2) and is_seg1_overlapping_with_seg2(seg1, seg2) # filter out single segment sections section_itr = (snode for snode in neurite.iter_sections() if snode.points.shape[0] > 2) for snode in section_itr: # group each section's points intro triplets segment_pairs = list(filter(is_not_zero_seg, pair(snode.points))) # filter out zero length segments for i, seg1 in enumerate(segment_pairs[1:]): # check if the end point of the segment lies within the previous # ones in the current sectionmake for seg2 in segment_pairs[0: i + 1]: if is_inside_cylinder(seg1, seg2): return True return False def get_flat_neurites(neuron, tol=0.1, method='ratio'): '''Check if a neuron has neurites that are flat within a tolerance Args: neurite(Neurite): neurite to operate on tol(float): the tolerance or the ratio method(string): 'tolerance' or 'ratio' described in :meth:`is_flat` Returns: Bool list corresponding to the flatness check for each neurite in neuron neurites with respect to the given criteria ''' return [n for n in neuron.neurites if is_flat(n, tol, method)] def get_nonmonotonic_neurites(neuron, tol=1e-6): '''Get neurites that are not monotonic Args: neurite(Neurite): neurite to operate on tol(float): the tolerance or the ratio Returns: list of neurites that do not satisfy monotonicity test ''' return [n for n in neuron.neurites if not is_monotonic(n, tol)] def get_back_tracking_neurites(neuron): '''Get neurites that have back-tracks. A back-track is the placement of a point near a previous segment during the reconstruction, causing a zigzag jump in the morphology which can cause issues with meshing algorithms. Args: neurite(Neurite): neurite to operate on Returns: List of neurons with backtracks ''' return [n for n in neuron.neurites if is_back_tracking(n)]
bsd-3-clause
Kazade/NeHe-Website
django/contrib/gis/geos/prototypes/__init__.py
244
1319
""" This module contains all of the GEOS ctypes function prototypes. Each prototype handles the interaction between the GEOS library and Python via ctypes. """ # Coordinate sequence routines. from django.contrib.gis.geos.prototypes.coordseq import create_cs, get_cs, \ cs_clone, cs_getordinate, cs_setordinate, cs_getx, cs_gety, cs_getz, \ cs_setx, cs_sety, cs_setz, cs_getsize, cs_getdims # Geometry routines. from django.contrib.gis.geos.prototypes.geom import from_hex, from_wkb, from_wkt, \ create_point, create_linestring, create_linearring, create_polygon, create_collection, \ destroy_geom, get_extring, get_intring, get_nrings, get_geomn, geom_clone, \ geos_normalize, geos_type, geos_typeid, geos_get_srid, geos_set_srid, \ get_dims, get_num_coords, get_num_geoms, \ to_hex, to_wkb, to_wkt # Miscellaneous routines. from django.contrib.gis.geos.prototypes.misc import * # Predicates from django.contrib.gis.geos.prototypes.predicates import geos_hasz, geos_isempty, \ geos_isring, geos_issimple, geos_isvalid, geos_contains, geos_crosses, \ geos_disjoint, geos_equals, geos_equalsexact, geos_intersects, \ geos_intersects, geos_overlaps, geos_relatepattern, geos_touches, geos_within # Topology routines from django.contrib.gis.geos.prototypes.topology import *
bsd-3-clause
lifeinoppo/littlefishlet-scode
RES/REF/python_sourcecode/ipython-master/IPython/terminal/embed.py
1
10539
# encoding: utf-8 """ An embedded IPython shell. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import with_statement from __future__ import print_function import sys import warnings from IPython.core import ultratb, compilerop from IPython.core.magic import Magics, magics_class, line_magic from IPython.core.interactiveshell import DummyMod from IPython.core.interactiveshell import InteractiveShell from IPython.terminal.interactiveshell import TerminalInteractiveShell from IPython.terminal.ipapp import load_default_config from traitlets import Bool, CBool, Unicode from IPython.utils.io import ask_yes_no # This is an additional magic that is exposed in embedded shells. @magics_class class EmbeddedMagics(Magics): @line_magic def kill_embedded(self, parameter_s=''): """%kill_embedded : deactivate for good the current embedded IPython. This function (after asking for confirmation) sets an internal flag so that an embedded IPython will never activate again. This is useful to permanently disable a shell that is being called inside a loop: once you've figured out what you needed from it, you may then kill it and the program will then continue to run without the interactive shell interfering again. """ kill = ask_yes_no("Are you sure you want to kill this embedded instance " "(y/n)? [y/N] ",'n') if kill: self.shell.embedded_active = False print ("This embedded IPython will not reactivate anymore " "once you exit.") class InteractiveShellEmbed(TerminalInteractiveShell): dummy_mode = Bool(False) exit_msg = Unicode('') embedded = CBool(True) embedded_active = CBool(True) # Like the base class display_banner is not configurable, but here it # is True by default. display_banner = CBool(True) exit_msg = Unicode() def __init__(self, **kw): if kw.get('user_global_ns', None) is not None: warnings.warn("user_global_ns has been replaced by user_module. The\ parameter will be ignored, and removed in IPython 5.0", DeprecationWarning) super(InteractiveShellEmbed,self).__init__(**kw) # don't use the ipython crash handler so that user exceptions aren't # trapped sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, mode=self.xmode, call_pdb=self.pdb) def init_sys_modules(self): pass def init_magics(self): super(InteractiveShellEmbed, self).init_magics() self.register_magics(EmbeddedMagics) def __call__(self, header='', local_ns=None, module=None, dummy=None, stack_depth=1, global_ns=None, compile_flags=None): """Activate the interactive interpreter. __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start the interpreter shell with the given local and global namespaces, and optionally print a header string at startup. The shell can be globally activated/deactivated using the dummy_mode attribute. This allows you to turn off a shell used for debugging globally. However, *each* time you call the shell you can override the current state of dummy_mode with the optional keyword parameter 'dummy'. For example, if you set dummy mode on with IPShell.dummy_mode = True, you can still have a specific call work by making it as IPShell(dummy=False). """ # If the user has turned it off, go away if not self.embedded_active: return # Normal exits from interactive mode set this flag, so the shell can't # re-enter (it checks this variable at the start of interactive mode). self.exit_now = False # Allow the dummy parameter to override the global __dummy_mode if dummy or (dummy != 0 and self.dummy_mode): return if self.has_readline: self.set_readline_completer() # self.banner is auto computed if header: self.old_banner2 = self.banner2 self.banner2 = self.banner2 + '\n' + header + '\n' else: self.old_banner2 = '' # Call the embedding code with a stack depth of 1 so it can skip over # our call and get the original caller's namespaces. self.mainloop(local_ns, module, stack_depth=stack_depth, global_ns=global_ns, compile_flags=compile_flags) self.banner2 = self.old_banner2 if self.exit_msg is not None: print(self.exit_msg) def mainloop(self, local_ns=None, module=None, stack_depth=0, display_banner=None, global_ns=None, compile_flags=None): """Embeds IPython into a running python program. Parameters ---------- local_ns, module Working local namespace (a dict) and module (a module or similar object). If given as None, they are automatically taken from the scope where the shell was called, so that program variables become visible. stack_depth : int How many levels in the stack to go to looking for namespaces (when local_ns or module is None). This allows an intermediate caller to make sure that this function gets the namespace from the intended level in the stack. By default (0) it will get its locals and globals from the immediate caller. compile_flags A bit field identifying the __future__ features that are enabled, as passed to the builtin :func:`compile` function. If given as None, they are automatically taken from the scope where the shell was called. """ if (global_ns is not None) and (module is None): warnings.warn("global_ns is deprecated, and will be removed in IPython 5.0 use module instead.", DeprecationWarning) module = DummyMod() module.__dict__ = global_ns # Get locals and globals from caller if ((local_ns is None or module is None or compile_flags is None) and self.default_user_namespaces): call_frame = sys._getframe(stack_depth).f_back if local_ns is None: local_ns = call_frame.f_locals if module is None: global_ns = call_frame.f_globals module = sys.modules[global_ns['__name__']] if compile_flags is None: compile_flags = (call_frame.f_code.co_flags & compilerop.PyCF_MASK) # Save original namespace and module so we can restore them after # embedding; otherwise the shell doesn't shut down correctly. orig_user_module = self.user_module orig_user_ns = self.user_ns orig_compile_flags = self.compile.flags # Update namespaces and fire up interpreter # The global one is easy, we can just throw it in if module is not None: self.user_module = module # But the user/local one is tricky: ipython needs it to store internal # data, but we also need the locals. We'll throw our hidden variables # like _ih and get_ipython() into the local namespace, but delete them # later. if local_ns is not None: reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} self.user_ns = reentrant_local_ns self.init_user_ns() # Compiler flags if compile_flags is not None: self.compile.flags = compile_flags # make sure the tab-completer has the correct frame information, so it # actually completes using the frame's locals/globals self.set_completer_frame() with self.builtin_trap, self.display_trap: self.interact(display_banner=display_banner) # now, purge out the local namespace of IPython's hidden variables. if local_ns is not None: local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) # Restore original namespace so shell can shut down when we exit. self.user_module = orig_user_module self.user_ns = orig_user_ns self.compile.flags = orig_compile_flags def embed(**kwargs): """Call this to embed IPython at the current point in your program. The first invocation of this will create an :class:`InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. If you don't want the kernel to initialize the namespace from the scope of the surrounding function, and/or you want to load full IPython configuration, you probably want `IPython.start_ipython()` instead. Here is a simple example:: from IPython import embed a = 10 b = 20 embed(header='First time') c = 30 d = 40 embed() Full customization can be done by passing a :class:`Config` in as the config argument. """ config = kwargs.get('config') header = kwargs.pop('header', u'') compile_flags = kwargs.pop('compile_flags', None) if config is None: config = load_default_config() config.InteractiveShellEmbed = config.TerminalInteractiveShell kwargs['config'] = config #save ps1/ps2 if defined ps1 = None ps2 = None try: ps1 = sys.ps1 ps2 = sys.ps2 except AttributeError: pass #save previous instance saved_shell_instance = InteractiveShell._instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() shell = InteractiveShellEmbed.instance(**kwargs) shell(header=header, stack_depth=2, compile_flags=compile_flags) InteractiveShellEmbed.clear_instance() #restore previous instance if saved_shell_instance is not None: cls = type(saved_shell_instance) cls.clear_instance() for subclass in cls._walk_mro(): subclass._instance = saved_shell_instance if ps1 is not None: sys.ps1 = ps1 sys.ps2 = ps2
gpl-2.0
2947721120/thumbor
thumbor/error_handlers/sentry.py
6
2455
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com import pkgutil import pkg_resources from thumbor import __version__ class ErrorHandler(object): def __init__(self, config, client=None): import raven dsn = config.SENTRY_DSN_URL if not dsn: raise RuntimeError( "If you set USE_CUSTOM_ERROR_HANDLING to True, and you are using thumbor.error_handlers.sentry, " + "then you must specify the Sentry DSN using the SENTRY_DSN_URL configuration." ) self.sentry = client or raven.Client(dsn) self.modules = self.get_modules() def get_modules(self): resolved = {} modules = [mod[1] for mod in tuple(pkgutil.iter_modules())] for module in modules: try: res_mod = pkg_resources.get_distribution(module) if res_mod is not None: resolved[module] = res_mod.version except pkg_resources.DistributionNotFound: pass return resolved def handle_error(self, context, handler, exception): req = handler.request extra = { 'thumbor-version': __version__ } extra.update({ 'Headers': req.headers }) cookies_header = extra.get('Headers', {}).get('Cookie', {}) if isinstance(cookies_header, basestring): cookies = {} for cookie in cookies_header.split(';'): if not cookie: continue values = cookie.strip().split('=') key, val = values[0], "".join(values[1:]) cookies[key] = val else: cookies = cookies_header extra['Headers']['Cookie'] = cookies data = { 'sentry.interfaces.Http': { 'url': req.full_url(), 'method': req.method, 'data': req.arguments, 'body': req.body, 'query_string': req.query }, 'sentry.interfaces.User': { 'ip': req.remote_ip, }, 'modules': self.modules } self.sentry.captureException(exception, extra=extra, data=data)
mit
neerajvashistha/pa-dude
lib/python2.7/site-packages/xlsxwriter/chart_scatter.py
1
9950
############################################################################### # # ChartScatter - A class for writing the Excel XLSX Scatter charts. # # Copyright 2013-2016, John McNamara, jmcnamara@cpan.org # from . import chart class ChartScatter(chart.Chart): """ A class for writing the Excel XLSX Scatter charts. """ ########################################################################### # # Public API. # ########################################################################### def __init__(self, options=None): """ Constructor. """ super(ChartScatter, self).__init__() if options is None: options = {} self.subtype = options.get('subtype') if not self.subtype: self.subtype = 'marker_only' self.cross_between = 'midCat' self.horiz_val_axis = 0 self.val_axis_position = 'b' self.smooth_allowed = True self.requires_category = True # Set the available data label positions for this chart type. self.label_position_default = 'right' self.label_positions = { 'center': 'ctr', 'right': 'r', 'left': 'l', 'above': 't', 'below': 'b', # For backward compatibility. 'top': 't', 'bottom': 'b'} def combine(self, chart=None): """ Create a combination chart with a secondary chart. Note: Override parent method to add a warning. Args: chart: The secondary chart to combine with the primary chart. Returns: Nothing. """ if chart is None: return warn('Combined chart not currently supported with scatter chart ' 'as the primary chart') ########################################################################### # # Private API. # ########################################################################### def _write_chart_type(self, args): # Override the virtual superclass method with a chart specific method. # Write the c:scatterChart element. self._write_scatter_chart(args) ########################################################################### # # XML methods. # ########################################################################### def _write_scatter_chart(self, args): # Write the <c:scatterChart> element. if args['primary_axes']: series = self._get_primary_axes_series() else: series = self._get_secondary_axes_series() if not len(series): return style = 'lineMarker' subtype = self.subtype # Set the user defined chart subtype. if subtype == 'marker_only': style = 'lineMarker' if subtype == 'straight_with_markers': style = 'lineMarker' if subtype == 'straight': style = 'lineMarker' if subtype == 'smooth_with_markers': style = 'smoothMarker' if subtype == 'smooth': style = 'smoothMarker' # Add default formatting to the series data. self._modify_series_formatting() self._xml_start_tag('c:scatterChart') # Write the c:scatterStyle element. self._write_scatter_style(style) # Write the series elements. for data in series: self._write_ser(data) # Write the c:marker element. self._write_marker_value() # Write the c:axId elements self._write_axis_ids(args) self._xml_end_tag('c:scatterChart') def _write_ser(self, series): # Over-ridden to write c:xVal/c:yVal instead of c:cat/c:val elements. # Write the <c:ser> element. index = self.series_index self.series_index += 1 self._xml_start_tag('c:ser') # Write the c:idx element. self._write_idx(index) # Write the c:order element. self._write_order(index) # Write the series name. self._write_series_name(series) # Write the c:spPr element. self._write_sp_pr(series) # Write the c:marker element. self._write_marker(series.get('marker')) # Write the c:dPt element. self._write_d_pt(series.get('points')) # Write the c:dLbls element. self._write_d_lbls(series.get('labels')) # Write the c:trendline element. self._write_trendline(series.get('trendline')) # Write the c:errBars element. self._write_error_bars(series.get('error_bars')) # Write the c:xVal element. self._write_x_val(series) # Write the c:yVal element. self._write_y_val(series) # Write the c:smooth element. if 'smooth' in self.subtype and series['smooth'] is None: # Default is on for smooth scatter charts. self._write_c_smooth(True) else: self._write_c_smooth(series['smooth']) self._xml_end_tag('c:ser') def _write_plot_area(self): # Over-ridden to have 2 valAx elements for scatter charts instead # of catAx/valAx. # # Write the <c:plotArea> element. self._xml_start_tag('c:plotArea') # Write the c:layout element. self._write_layout(self.plotarea.get('layout'), 'plot') # Write the subclass chart elements for primary and secondary axes. self._write_chart_type({'primary_axes': 1}) self._write_chart_type({'primary_axes': 0}) # Write c:catAx and c:valAx elements for series using primary axes. self._write_cat_val_axis({'x_axis': self.x_axis, 'y_axis': self.y_axis, 'axis_ids': self.axis_ids, 'position': 'b', }) tmp = self.horiz_val_axis self.horiz_val_axis = 1 self._write_val_axis({'x_axis': self.x_axis, 'y_axis': self.y_axis, 'axis_ids': self.axis_ids, 'position': 'l', }) self.horiz_val_axis = tmp # Write c:valAx and c:catAx elements for series using secondary axes self._write_cat_val_axis({'x_axis': self.x2_axis, 'y_axis': self.y2_axis, 'axis_ids': self.axis2_ids, 'position': 'b', }) self.horiz_val_axis = 1 self._write_val_axis({'x_axis': self.x2_axis, 'y_axis': self.y2_axis, 'axis_ids': self.axis2_ids, 'position': 'l', }) # Write the c:spPr element for the plotarea formatting. self._write_sp_pr(self.plotarea) self._xml_end_tag('c:plotArea') def _write_x_val(self, series): # Write the <c:xVal> element. formula = series.get('categories') data_id = series.get('cat_data_id') data = self.formula_data[data_id] self._xml_start_tag('c:xVal') # Check the type of cached data. data_type = self._get_data_type(data) # TODO. Can a scatter plot have non-numeric data. if data_type == 'str': # Write the c:numRef element. self._write_str_ref(formula, data, data_type) else: # Write the c:numRef element. self._write_num_ref(formula, data, data_type) self._xml_end_tag('c:xVal') def _write_y_val(self, series): # Write the <c:yVal> element. formula = series.get('values') data_id = series.get('val_data_id') data = self.formula_data[data_id] self._xml_start_tag('c:yVal') # Unlike Cat axes data should only be numeric. # Write the c:numRef element. self._write_num_ref(formula, data, 'num') self._xml_end_tag('c:yVal') def _write_scatter_style(self, val): # Write the <c:scatterStyle> element. attributes = [('val', val)] self._xml_empty_tag('c:scatterStyle', attributes) def _modify_series_formatting(self): # Add default formatting to the series data unless it has already been # specified by the user. subtype = self.subtype # The default scatter style "markers only" requires a line type. if subtype == 'marker_only': # Go through each series and define default values. for series in self.series: # Set a line type unless there is already a user defined type. if not series['line']['defined']: series['line'] = {'width': 2.25, 'none': 1, 'defined': 1, } # Turn markers off for subtypes that don't have them. if 'marker' not in subtype: # Go through each series and define default values. for series in self.series: # Set a marker type unless there is a user defined type. if not series.get('marker'): series['marker'] = {'type': 'none', 'defined': 1} def _write_d_pt_point(self, index, point): # Write an individual <c:dPt> element. Override the parent method to # add markers. self._xml_start_tag('c:dPt') # Write the c:idx element. self._write_idx(index) self._xml_start_tag('c:marker') # Write the c:spPr element. self._write_sp_pr(point) self._xml_end_tag('c:marker') self._xml_end_tag('c:dPt')
mit
sub77/kernel_msm
scripts/tracing/draw_functrace.py
14676
3560
#!/usr/bin/python """ Copyright 2008 (c) Frederic Weisbecker <fweisbec@gmail.com> Licensed under the terms of the GNU GPL License version 2 This script parses a trace provided by the function tracer in kernel/trace/trace_functions.c The resulted trace is processed into a tree to produce a more human view of the call stack by drawing textual but hierarchical tree of calls. Only the functions's names and the the call time are provided. Usage: Be sure that you have CONFIG_FUNCTION_TRACER # mount -t debugfs nodev /sys/kernel/debug # echo function > /sys/kernel/debug/tracing/current_tracer $ cat /sys/kernel/debug/tracing/trace_pipe > ~/raw_trace_func Wait some times but not too much, the script is a bit slow. Break the pipe (Ctrl + Z) $ scripts/draw_functrace.py < raw_trace_func > draw_functrace Then you have your drawn trace in draw_functrace """ import sys, re class CallTree: """ This class provides a tree representation of the functions call stack. If a function has no parent in the kernel (interrupt, syscall, kernel thread...) then it is attached to a virtual parent called ROOT. """ ROOT = None def __init__(self, func, time = None, parent = None): self._func = func self._time = time if parent is None: self._parent = CallTree.ROOT else: self._parent = parent self._children = [] def calls(self, func, calltime): """ If a function calls another one, call this method to insert it into the tree at the appropriate place. @return: A reference to the newly created child node. """ child = CallTree(func, calltime, self) self._children.append(child) return child def getParent(self, func): """ Retrieve the last parent of the current node that has the name given by func. If this function is not on a parent, then create it as new child of root @return: A reference to the parent. """ tree = self while tree != CallTree.ROOT and tree._func != func: tree = tree._parent if tree == CallTree.ROOT: child = CallTree.ROOT.calls(func, None) return child return tree def __repr__(self): return self.__toString("", True) def __toString(self, branch, lastChild): if self._time is not None: s = "%s----%s (%s)\n" % (branch, self._func, self._time) else: s = "%s----%s\n" % (branch, self._func) i = 0 if lastChild: branch = branch[:-1] + " " while i < len(self._children): if i != len(self._children) - 1: s += "%s" % self._children[i].__toString(branch +\ " |", False) else: s += "%s" % self._children[i].__toString(branch +\ " |", True) i += 1 return s class BrokenLineException(Exception): """If the last line is not complete because of the pipe breakage, we want to stop the processing and ignore this line. """ pass class CommentLineException(Exception): """ If the line is a comment (as in the beginning of the trace file), just ignore it. """ pass def parseLine(line): line = line.strip() if line.startswith("#"): raise CommentLineException m = re.match("[^]]+?\\] +([0-9.]+): (\\w+) <-(\\w+)", line) if m is None: raise BrokenLineException return (m.group(1), m.group(2), m.group(3)) def main(): CallTree.ROOT = CallTree("Root (Nowhere)", None, None) tree = CallTree.ROOT for line in sys.stdin: try: calltime, callee, caller = parseLine(line) except BrokenLineException: break except CommentLineException: continue tree = tree.getParent(caller) tree = tree.calls(callee, calltime) print CallTree.ROOT if __name__ == "__main__": main()
gpl-2.0
neos/neos-development-collection
Neos.Neos/Documentation/conf.py
8
10221
# -*- coding: utf-8 -*- # # Neos CMS documentation build configuration file, created by # sphinx-quickstart on Wed May 20 21:31:09 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.ifconfig' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Neos CMS' copyright = u'2006 and onwards by the authors' author = u'Neos Team and Contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = 'dev-master' # The full version, including alpha/beta/rc tags. release = 'dev-master' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # otherwise, readthedocs.org uses their theme by default, so no need to specify it # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'NeosCMSdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). 'papersize': 'a4paper', # The font size ('10pt', '11pt' or '12pt'). 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'NeosCMS.tex', u'Neos CMS Documentation', u'The Neos Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'neoscms', u'Neos CMS Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'NeosCMS', u'Neos CMS Documentation', author, 'NeosCMS', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None} # load PhpLexer from sphinx.highlighting import lexers from pygments.lexers.web import PhpLexer # enable highlighting for PHP code not between <?php ... ?> by default lexers['php'] = PhpLexer(startinline=True) lexers['php-annotations'] = PhpLexer(startinline=True) # Use PHP syntax highlighting in code examples by default highlight_language='php'
gpl-3.0
manuelfelipe/openstack-ansible
scripts/pw-token-gen.py
25
7433
#!/usr/bin/env python # Copyright 2014, Rackspace US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # (c) 2014, Kevin Carter <kevin.carter@rackspace.com> import argparse import datetime import hashlib import os import random import tarfile import uuid from Crypto import Random try: import yaml except ImportError: raise SystemExit('Missing Dependency, "PyYAML"') class CredentialGenerator(object): """Credential generator class. This class is simply a method to generate random secrets. This class will NOT encrypt values rather it creates the values which will be used as secrets within an application. The credential generator will return strings in various sizes based on the requested secret type. There are four secret types that can be used within the class; `password`, `token`, 'secret', and `key`. These types return variable lengths of data. password: 16 - 64 character string secret: 16 - 64 character string token: 64 - 72 character string key: 24, or 32 character string (Needs to be AES compatible) Usage: >>> generator = CredentialGenerator() >>> token = generator.generator('token') """ def generator(self, pw_type): """Generate new secret string. The generator method will check for a known method type and if found generates a hashed string which is then routed to the appropriate method. :param pw_type: ``str`` Type of secret to generate. :returns: ``str`` """ if hasattr(self, '_%s_gen' % pw_type): encoded_bytes = self._encode_bytes() func = getattr(self, '_%s_gen' % pw_type) return func(encoded_bytes=encoded_bytes) else: raise SystemExit('Unknown secret type passed. [ %s ]' % pw_type) @staticmethod def _random_bytes(): """Returns 1024 random bytes of data.""" return Random.get_random_bytes(1024) def _encode_bytes(self): """Builds random strings based on random data. `_encode_bytes` will ensure that there's never an opportunity for duplicate data. Once the bytes are generated, they are hashed using SHA512 and the returned as a **hex** digest. """ random_bytes = self._random_bytes() hash_obj = hashlib.sha512(random_bytes) return hash_obj.hexdigest() def _password_gen(self, encoded_bytes): """Returns ``str`` with a length between 16 and 64. :param encoded_bytes: ``str`` must be at least 64 charters long """ return encoded_bytes[:random.randrange(16, 64)] def _token_gen(self, encoded_bytes): """Returns ``str`` with a length between 48 and 64. :param encoded_bytes: ``str`` must be at least 72 charters long """ return encoded_bytes[:random.randrange(64, 72)] def _key_gen(self, encoded_bytes): """Returns ``str`` with a length of 24 or 32. Length restriction are required for key type secrets because of requirements in AES. :param encoded_bytes: ``str`` must be at least 32 charters long """ return encoded_bytes[:random.choice([24, 32])] def args(): """Setup argument Parsing.""" parser = argparse.ArgumentParser( usage='%(prog)s', description='OpenStack Token Password and Key Generator', epilog='Inventory Generator Licensed "Apache 2.0"' ) parser.add_argument( '--file', help='User defined configuration file', required=True, default=None ) parser.add_argument( '--regen', help='Regenerate all passwords', action='store_true', default=False ) return vars(parser.parse_args()) def main(): """Run the main Application. This will open a file that was specified on the command line. The file specified is assumed to be in valid YAML format, which is used in ansible. When the YAML file will be processed and any key with a null value that ends with 'password', 'token', 'key' or 'uuid' will have a generated password set as the value. The main function will create a backup of all changes in the file as a tarball in the same directory as the file specified. Command line usage has one required argument and one optional. The argument ``--file`` is used to specify the file which passwords will be generated within. The argument ``--regen`` is used to regenerate all secrets within a file even if they were already set. """ all_args = args() user_vars_file = all_args['file'] user_vars_file = os.path.abspath( os.path.expanduser( user_vars_file ) ) with open(user_vars_file, 'rb') as f: user_vars = yaml.safe_load(f.read()) if not user_vars: raise SystemExit( 'FAIL: The variable file provided [ %s ] is empty.' % user_vars_file ) changed = False generator = CredentialGenerator() for entry, value in user_vars.iteritems(): if value is None or all_args['regen'] is True: if entry.endswith('password') or entry.endswith('secret'): changed = True user_vars[entry] = generator.generator(pw_type='password') elif entry.endswith('token'): changed = True user_vars[entry] = generator.generator(pw_type='token') elif entry.endswith('key'): changed = True user_vars[entry] = generator.generator(pw_type='key') elif entry.endswith('uuid'): changed = True user_vars[entry] = str(uuid.uuid4()) elif entry.startswith('swift_hash_path'): changed = True user_vars[entry] = generator.generator(pw_type='key') # If changed is set to True, this will archive the old passwords if changed is True: user_vars_tar_file = '%s.tar' % user_vars_file print('Creating backup file [ %s ]' % user_vars_tar_file) # Create a tarball if needed with tarfile.open(user_vars_tar_file, 'a') as tar: os.chmod(user_vars_tar_file, 0o600) basename = os.path.basename(user_vars_file) # Time stamp the password file in UTC utctime = datetime.datetime.utcnow() utctime = utctime.strftime('%Y%m%d_%H%M%S') backup_name = '%s-%s' % (basename, utctime) tar.add(user_vars_file, arcname=backup_name) with open(user_vars_file, 'wb') as f: os.chmod(user_vars_file, 0o600) f.write( yaml.safe_dump( user_vars, default_flow_style=False, width=1000 ) ) print('Operation Complete, [ %s ] is ready' % user_vars_file) if __name__ == '__main__': main()
apache-2.0
appleseedhq/gaffer
python/GafferUITest/LinearContainerTest.py
4
10687
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2012-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import unittest import imath import IECore import Gaffer import GafferUI import GafferUITest class LinearContainerTest( GafferUITest.TestCase ) : def testConstruction( self ) : c = GafferUI.LinearContainer() self.assertEqual( c.getName(), "LinearContainer" ) self.assertEqual( c.getOrientation(), GafferUI.LinearContainer.Orientation.X ) self.assertEqual( c.getAlignment(), GafferUI.LinearContainer.Alignment.Centre ) self.assertEqual( c.getSpacing(), 0 ) self.assertEqual( c.getDirection(), GafferUI.LinearContainer.Direction.Increasing ) c = GafferUI.LinearContainer( name="a" ) self.assertEqual( c.getName(), "a" ) self.assertEqual( c.getOrientation(), GafferUI.LinearContainer.Orientation.X ) self.assertEqual( c.getAlignment(), GafferUI.LinearContainer.Alignment.Centre ) self.assertEqual( c.getSpacing(), 0 ) self.assertEqual( c.getDirection(), GafferUI.LinearContainer.Direction.Increasing ) c = GafferUI.LinearContainer( spacing=10 ) self.assertEqual( c.getName(), "LinearContainer" ) self.assertEqual( c.getOrientation(), GafferUI.LinearContainer.Orientation.X ) self.assertEqual( c.getAlignment(), GafferUI.LinearContainer.Alignment.Centre ) self.assertEqual( c.getSpacing(), 10 ) self.assertEqual( c.getDirection(), GafferUI.LinearContainer.Direction.Increasing ) c = GafferUI.LinearContainer( orientation=GafferUI.LinearContainer.Orientation.Y ) self.assertEqual( c.getName(), "LinearContainer" ) self.assertEqual( c.getOrientation(), GafferUI.LinearContainer.Orientation.Y ) self.assertEqual( c.getAlignment(), GafferUI.LinearContainer.Alignment.Centre ) self.assertEqual( c.getSpacing(), 0 ) self.assertEqual( c.getDirection(), GafferUI.LinearContainer.Direction.Increasing ) c = GafferUI.LinearContainer( alignment=GafferUI.LinearContainer.Alignment.Min ) self.assertEqual( c.getName(), "LinearContainer" ) self.assertEqual( c.getOrientation(), GafferUI.LinearContainer.Orientation.X ) self.assertEqual( c.getAlignment(), GafferUI.LinearContainer.Alignment.Min ) self.assertEqual( c.getSpacing(), 0 ) self.assertEqual( c.getDirection(), GafferUI.LinearContainer.Direction.Increasing ) c = GafferUI.LinearContainer( direction=GafferUI.LinearContainer.Direction.Decreasing ) self.assertEqual( c.getName(), "LinearContainer" ) self.assertEqual( c.getOrientation(), GafferUI.LinearContainer.Orientation.X ) self.assertEqual( c.getAlignment(), GafferUI.LinearContainer.Alignment.Centre ) self.assertEqual( c.getSpacing(), 0 ) self.assertEqual( c.getDirection(), GafferUI.LinearContainer.Direction.Decreasing ) self.assert_( c.bound().isEmpty() ) def testHorizontalCentred( self ) : twoByFour = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) fourByFour = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -2, -2, 0 ), imath.V3f( 2, 2, 0 ) ) ) fourByTwo = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -2, -1, 0 ), imath.V3f( 2, 1, 0 ) ) ) c = GafferUI.LinearContainer() c["c1"] = twoByFour self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) self.assertEqual( twoByFour.getTransform(), imath.M44f().translate( imath.V3f( 0 ) ) ) c["c2"] = fourByFour self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -3, -2, 0 ), imath.V3f( 3, 2, 0 ) ) ) self.assertEqual( twoByFour.getTransform(), imath.M44f().translate( imath.V3f( -2, 0, 0 ) ) ) self.assertEqual( fourByFour.getTransform(), imath.M44f().translate( imath.V3f( 1, 0, 0 ) ) ) c["c3"] = fourByTwo self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -5, -2, 0 ), imath.V3f( 5, 2, 0 ) ) ) self.assertEqual( twoByFour.getTransform(), imath.M44f().translate( imath.V3f( -4, 0, 0 ) ) ) self.assertEqual( fourByFour.getTransform(), imath.M44f().translate( imath.V3f( -1, 0, 0 ) ) ) self.assertEqual( fourByTwo.getTransform(), imath.M44f().translate( imath.V3f( 3, 0, 0 ) ) ) def testVerticalMin( self ) : twoByFour = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) fourByFour = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -2, -2, 0 ), imath.V3f( 2, 2, 0 ) ) ) fourByTwo = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -2, -1, 0 ), imath.V3f( 2, 1, 0 ) ) ) c = GafferUI.LinearContainer( orientation=GafferUI.LinearContainer.Orientation.Y, alignment=GafferUI.LinearContainer.Alignment.Min) c["c1"] = twoByFour self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) self.assertEqual( twoByFour.getTransform(), imath.M44f().translate( imath.V3f( 0 ) ) ) c["c2"] = fourByFour self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -2, -4, 0 ), imath.V3f( 2, 4, 0 ) ) ) self.assertEqual( twoByFour.getTransform(), imath.M44f().translate( imath.V3f( -1, -2, 0 ) ) ) self.assertEqual( fourByFour.getTransform(), imath.M44f().translate( imath.V3f( 0, 2, 0 ) ) ) c["c3"] = fourByTwo self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -2, -5, 0 ), imath.V3f( 2, 5, 0 ) ) ) self.assertEqual( twoByFour.getTransform(), imath.M44f().translate( imath.V3f( -1, -3, 0 ) ) ) self.assertEqual( fourByFour.getTransform(), imath.M44f().translate( imath.V3f( 0, 1, 0 ) ) ) self.assertEqual( fourByTwo.getTransform(), imath.M44f().translate( imath.V3f( 0, 4, 0 ) ) ) def testPadding( self ) : twoByFour = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) c = GafferUI.LinearContainer( orientation=GafferUI.LinearContainer.Orientation.Y ) c.addChild( twoByFour ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) self.assertEqual( c.getPadding(), imath.Box3f( imath.V3f( 0 ), imath.V3f( 0 ) ) ) c.setPadding( imath.Box3f( imath.V3f( -1, -2, -3 ), imath.V3f( 1, 2, 3 ) ) ) self.assertEqual( c.getPadding(), imath.Box3f( imath.V3f( -1, -2, -3 ), imath.V3f( 1, 2, 3 ) ) ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -2, -4, -3 ), imath.V3f( 2, 4, 3 ) ) ) def testDirection( self ) : first = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) second = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) c = GafferUI.LinearContainer( orientation=GafferUI.LinearContainer.Orientation.Y ) c["c1"] = first c["c2"] = second self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -1, -4, 0 ), imath.V3f( 1, 4, 0 ) ) ) self.assertEqual( first.getTransform(), imath.M44f().translate( imath.V3f( 0, -2, 0 ) ) ) self.assertEqual( second.getTransform(), imath.M44f().translate( imath.V3f( 0, 2, 0 ) ) ) c.setDirection( GafferUI.LinearContainer.Direction.Decreasing ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -1, -4, 0 ), imath.V3f( 1, 4, 0 ) ) ) self.assertEqual( first.getTransform(), imath.M44f().translate( imath.V3f( 0, 2, 0 ) ) ) self.assertEqual( second.getTransform(), imath.M44f().translate( imath.V3f( 0, -2, 0 ) ) ) def testDirectionAndSpacing( self ) : c = GafferUI.LinearContainer( orientation = GafferUI.LinearContainer.Orientation.Y ) c["g1"] = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -1, -1, 0 ), imath.V3f( 1, 1, 0 ) ) ) c["g2"] = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( -1, -1, 0 ), imath.V3f( 1, 1, 0 ) ) ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -1, -2, 0 ), imath.V3f( 1, 2, 0 ) ) ) c.setSpacing( 2 ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -1, -3, 0 ), imath.V3f( 1, 3, 0 ) ) ) c.setDirection( GafferUI.LinearContainer.Direction.Decreasing ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -1, -3, 0 ), imath.V3f( 1, 3, 0 ) ) ) def testChildVisibility( self ) : g1 = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( 0 ), imath.V3f( 1, 1, 0 ) ) ) g2 = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( 0 ), imath.V3f( 2, 1, 0 ) ) ) g3 = GafferUI.SpacerGadget( imath.Box3f( imath.V3f( 0 ), imath.V3f( 5, 1, 0 ) ) ) c = GafferUI.LinearContainer( spacing = 1 ) c.addChild( g1 ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -0.5, -0.5, 0 ), imath.V3f( 0.5, 0.5, 0 ) ) ) c.addChild( g2 ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -2, -0.5, 0 ), imath.V3f( 2, 0.5, 0 ) ) ) g2.setVisible( False ) # should be as if the child didn't exist self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -0.5, -0.5, 0 ), imath.V3f( 0.5, 0.5, 0 ) ) ) g2.setVisible( True ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -2, -0.5, 0 ), imath.V3f( 2, 0.5, 0 ) ) ) c.addChild( g3 ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -5, -0.5, 0 ), imath.V3f( 5, 0.5, 0 ) ) ) g1.setVisible( False ) self.assertEqual( c.bound(), imath.Box3f( imath.V3f( -4, -0.5, 0 ), imath.V3f( 4, 0.5, 0 ) ) ) if __name__ == "__main__": unittest.main()
bsd-3-clause
rhyolight/nupic
tests/integration/nupic/opf/opf_checkpoint_stress_test.py
10
4775
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ This is a stress test that saves and loads an OPF checkpoint multiple times, doing one compute step in between. This test was put in place to catch a crash bug. """ import datetime import numpy.random import os import shutil import tempfile import unittest2 as unittest from nupic.frameworks.opf.model_factory import ModelFactory from nupic.support.unittesthelpers.testcasebase import TestCaseBase # Model parameters derived from the Hotgym anomaly example. This example was # used because it uses the most components. Some of the parameters, such # as columnCount were reduced to make the test run faster. MODEL_PARAMS = { 'model': "HTMPrediction", 'version': 1, 'aggregationInfo': { 'days': 0, 'fields': [(u'c1', 'sum'), (u'c0', 'first')], 'hours': 1, 'microseconds': 0, 'milliseconds': 0, 'minutes': 0, 'months': 0, 'seconds': 0, 'weeks': 0, 'years': 0}, 'predictAheadTime': None, 'modelParams': { 'inferenceType': 'TemporalAnomaly', 'sensorParams': { 'verbosity' : 0, 'encoders': { u'consumption': { 'clipInput': True, 'fieldname': u'consumption', 'maxval': 100.0, 'minval': 0.0, 'n': 50, 'name': u'c1', 'type': 'ScalarEncoder', 'w': 21},}, 'sensorAutoReset' : None, }, 'spEnable': True, 'spParams': { 'spVerbosity' : 0, 'globalInhibition': 1, 'spatialImp' : 'cpp', 'columnCount': 512, 'inputWidth': 0, 'numActiveColumnsPerInhArea': 20, 'seed': 1956, 'potentialPct': 0.5, 'synPermConnected': 0.1, 'synPermActiveInc': 0.1, 'synPermInactiveDec': 0.005, }, 'tmEnable' : True, 'tmParams': { 'verbosity': 0, 'columnCount': 512, 'cellsPerColumn': 8, 'inputWidth': 512, 'seed': 1960, 'temporalImp': 'cpp', 'newSynapseCount': 10, 'maxSynapsesPerSegment': 20, 'maxSegmentsPerCell': 32, 'initialPerm': 0.21, 'permanenceInc': 0.1, 'permanenceDec' : 0.1, 'globalDecay': 0.0, 'maxAge': 0, 'minThreshold': 4, 'activationThreshold': 6, 'outputType': 'normal', 'pamLength': 1, }, 'clParams': { 'regionName' : 'SDRClassifierRegion', 'verbosity' : 0, 'alpha': 0.005, 'steps': '1,5', }, 'anomalyParams': { u'anomalyCacheRecords': None, u'autoDetectThreshold': None, u'autoDetectWaitRecords': 2184}, 'trainSPNetOnlyIfRequested': False, }, } class CheckpointStressTest(TestCaseBase): def testCheckpoint(self): tmpDir = tempfile.mkdtemp() model = ModelFactory.create(MODEL_PARAMS) model.enableInference({'predictedField': 'consumption'}) headers = ['timestamp', 'consumption'] # Now do a bunch of small load/train/save batches for _ in range(20): for _ in range(2): record = [datetime.datetime(2013, 12, 12), numpy.random.uniform(100)] modelInput = dict(zip(headers, record)) model.run(modelInput) # Save and load a checkpoint after each batch. Clean up. tmpBundleName = os.path.join(tmpDir, "test_checkpoint") self.assertIs(model.save(tmpBundleName), None, "Save command failed.") model = ModelFactory.loadFromCheckpoint(tmpBundleName) shutil.rmtree(tmpBundleName) if __name__ == "__main__": unittest.main()
agpl-3.0
wskplho/sl4a
python/src/Lib/encodings/mac_latin2.py
647
8565
""" Python Character Mapping Codec generated from 'LATIN2.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_map)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='mac-latin2', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0081: 0x0100, # LATIN CAPITAL LETTER A WITH MACRON 0x0082: 0x0101, # LATIN SMALL LETTER A WITH MACRON 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0084: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0088: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x0089: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x008b: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x008c: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x008d: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x008f: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x0090: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x0091: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0093: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x0094: 0x0112, # LATIN CAPITAL LETTER E WITH MACRON 0x0095: 0x0113, # LATIN SMALL LETTER E WITH MACRON 0x0096: 0x0116, # LATIN CAPITAL LETTER E WITH DOT ABOVE 0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x0098: 0x0117, # LATIN SMALL LETTER E WITH DOT ABOVE 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x009b: 0x00f5, # LATIN SMALL LETTER O WITH TILDE 0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x009d: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x009e: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00a0: 0x2020, # DAGGER 0x00a1: 0x00b0, # DEGREE SIGN 0x00a2: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00a4: 0x00a7, # SECTION SIGN 0x00a5: 0x2022, # BULLET 0x00a6: 0x00b6, # PILCROW SIGN 0x00a7: 0x00df, # LATIN SMALL LETTER SHARP S 0x00a8: 0x00ae, # REGISTERED SIGN 0x00aa: 0x2122, # TRADE MARK SIGN 0x00ab: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00ac: 0x00a8, # DIAERESIS 0x00ad: 0x2260, # NOT EQUAL TO 0x00ae: 0x0123, # LATIN SMALL LETTER G WITH CEDILLA 0x00af: 0x012e, # LATIN CAPITAL LETTER I WITH OGONEK 0x00b0: 0x012f, # LATIN SMALL LETTER I WITH OGONEK 0x00b1: 0x012a, # LATIN CAPITAL LETTER I WITH MACRON 0x00b2: 0x2264, # LESS-THAN OR EQUAL TO 0x00b3: 0x2265, # GREATER-THAN OR EQUAL TO 0x00b4: 0x012b, # LATIN SMALL LETTER I WITH MACRON 0x00b5: 0x0136, # LATIN CAPITAL LETTER K WITH CEDILLA 0x00b6: 0x2202, # PARTIAL DIFFERENTIAL 0x00b7: 0x2211, # N-ARY SUMMATION 0x00b8: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x00b9: 0x013b, # LATIN CAPITAL LETTER L WITH CEDILLA 0x00ba: 0x013c, # LATIN SMALL LETTER L WITH CEDILLA 0x00bb: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x00bc: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x00bd: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x00be: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x00bf: 0x0145, # LATIN CAPITAL LETTER N WITH CEDILLA 0x00c0: 0x0146, # LATIN SMALL LETTER N WITH CEDILLA 0x00c1: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00c2: 0x00ac, # NOT SIGN 0x00c3: 0x221a, # SQUARE ROOT 0x00c4: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00c5: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00c6: 0x2206, # INCREMENT 0x00c7: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c8: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c9: 0x2026, # HORIZONTAL ELLIPSIS 0x00ca: 0x00a0, # NO-BREAK SPACE 0x00cb: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00cc: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x00cd: 0x00d5, # LATIN CAPITAL LETTER O WITH TILDE 0x00ce: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x00cf: 0x014c, # LATIN CAPITAL LETTER O WITH MACRON 0x00d0: 0x2013, # EN DASH 0x00d1: 0x2014, # EM DASH 0x00d2: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x00d3: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x00d4: 0x2018, # LEFT SINGLE QUOTATION MARK 0x00d5: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x00d6: 0x00f7, # DIVISION SIGN 0x00d7: 0x25ca, # LOZENGE 0x00d8: 0x014d, # LATIN SMALL LETTER O WITH MACRON 0x00d9: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00da: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00db: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00dc: 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x00dd: 0x203a, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x00de: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00df: 0x0156, # LATIN CAPITAL LETTER R WITH CEDILLA 0x00e0: 0x0157, # LATIN SMALL LETTER R WITH CEDILLA 0x00e1: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00e2: 0x201a, # SINGLE LOW-9 QUOTATION MARK 0x00e3: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x00e4: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00e5: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x00e6: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x00e7: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00e8: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x00e9: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x00ea: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00eb: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00ec: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00ed: 0x016a, # LATIN CAPITAL LETTER U WITH MACRON 0x00ee: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00ef: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00f0: 0x016b, # LATIN SMALL LETTER U WITH MACRON 0x00f1: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00f2: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00f3: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x00f4: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00f5: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00f6: 0x0172, # LATIN CAPITAL LETTER U WITH OGONEK 0x00f7: 0x0173, # LATIN SMALL LETTER U WITH OGONEK 0x00f8: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00f9: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00fa: 0x0137, # LATIN SMALL LETTER K WITH CEDILLA 0x00fb: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00fc: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x00fd: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00fe: 0x0122, # LATIN CAPITAL LETTER G WITH CEDILLA 0x00ff: 0x02c7, # CARON }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
apache-2.0
softDi/clusim
ns3/ns-3.26/src/dsdv/bindings/modulegen__gcc_ILP32.py
30
524972
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.dsdv', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class] module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer [class] module.add_class('Timer', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::State [enumeration] module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer-impl.h (module 'core'): ns3::TimerImpl [class] module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core') ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['unsigned int']) ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## dsdv-helper.h (module 'dsdv'): ns3::DsdvHelper [class] module.add_class('DsdvHelper', parent=root_module['ns3::Ipv4RoutingHelper']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## packet-filter.h (module 'traffic-control'): ns3::PacketFilter [class] module.add_class('PacketFilter', import_from_module='ns.traffic_control', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::Queue [class] module.add_class('Queue', import_from_module='ns.network', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::Queue::QueueMode [enumeration] module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::Queue'], import_from_module='ns.network') ## queue-disc.h (module 'traffic-control'): ns3::QueueDisc [class] module.add_class('QueueDisc', import_from_module='ns.traffic_control', parent=root_module['ns3::Object']) ## queue-disc.h (module 'traffic-control'): ns3::QueueDisc::WakeMode [enumeration] module.add_enum('WakeMode', ['WAKE_ROOT', 'WAKE_CHILD'], outer_class=root_module['ns3::QueueDisc'], import_from_module='ns.traffic-control') ## queue-disc.h (module 'traffic-control'): ns3::QueueDiscClass [class] module.add_class('QueueDiscClass', import_from_module='ns.traffic_control', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketPriorityTag [class] module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## traffic-control-layer.h (module 'traffic-control'): ns3::TrafficControlLayer [class] module.add_class('TrafficControlLayer', import_from_module='ns.traffic_control', parent=root_module['ns3::Object']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## boolean.h (module 'core'): ns3::BooleanChecker [class] module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## boolean.h (module 'core'): ns3::BooleanValue [class] module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## double.h (module 'core'): ns3::DoubleValue [class] module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## enum.h (module 'core'): ns3::EnumChecker [class] module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## enum.h (module 'core'): ns3::EnumValue [class] module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class] module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## integer.h (module 'core'): ns3::IntegerValue [class] module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface [class] module.add_class('Ipv4Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## net-device.h (module 'network'): ns3::NetDeviceQueue [class] module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface [class] module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object']) ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## net-device.h (module 'network'): ns3::QueueItem [class] module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) ## net-device.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration] module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## uinteger.h (module 'core'): ns3::UintegerValue [class] module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting [class] module.add_class('Ipv4ListRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol']) ## queue-disc.h (module 'traffic-control'): ns3::QueueDiscItem [class] module.add_class('QueueDiscItem', import_from_module='ns.traffic_control', parent=root_module['ns3::QueueItem']) module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector') module.add_container('std::vector< ns3::Ptr< ns3::QueueDisc > >', 'ns3::Ptr< ns3::QueueDisc >', container_type=u'vector') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) ## Register a nested module for the namespace dsdv nested_module = module.add_cpp_namespace('dsdv') register_types_ns3_dsdv(nested_module) ## Register a nested module for the namespace internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *', u'ns3::TracedValueCallback::Uint8') typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) **', u'ns3::TracedValueCallback::Uint8*') typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *&', u'ns3::TracedValueCallback::Uint8&') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *', u'ns3::TracedValueCallback::Int8') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) **', u'ns3::TracedValueCallback::Int8*') typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *&', u'ns3::TracedValueCallback::Int8&') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *', u'ns3::TracedValueCallback::Uint16') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) **', u'ns3::TracedValueCallback::Uint16*') typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *&', u'ns3::TracedValueCallback::Uint16&') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *', u'ns3::TracedValueCallback::Uint32') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) **', u'ns3::TracedValueCallback::Uint32*') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *&', u'ns3::TracedValueCallback::Uint32&') typehandlers.add_type_alias(u'void ( * ) ( double, double ) *', u'ns3::TracedValueCallback::Double') typehandlers.add_type_alias(u'void ( * ) ( double, double ) **', u'ns3::TracedValueCallback::Double*') typehandlers.add_type_alias(u'void ( * ) ( double, double ) *&', u'ns3::TracedValueCallback::Double&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&') typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *', u'ns3::TracedValueCallback::Bool') typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) **', u'ns3::TracedValueCallback::Bool*') typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *&', u'ns3::TracedValueCallback::Bool&') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *', u'ns3::TracedValueCallback::Int16') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) **', u'ns3::TracedValueCallback::Int16*') typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *&', u'ns3::TracedValueCallback::Int16&') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *', u'ns3::TracedValueCallback::Int32') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) **', u'ns3::TracedValueCallback::Int32*') typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *&', u'ns3::TracedValueCallback::Int32&') typehandlers.add_type_alias(u'void ( * ) ( ) *', u'ns3::TracedValueCallback::Void') typehandlers.add_type_alias(u'void ( * ) ( ) **', u'ns3::TracedValueCallback::Void*') typehandlers.add_type_alias(u'void ( * ) ( ) *&', u'ns3::TracedValueCallback::Void&') def register_types_ns3_dsdv(module): root_module = module.get_root() ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RouteFlags [enumeration] module.add_enum('RouteFlags', ['VALID', 'INVALID']) ## dsdv-packet.h (module 'dsdv'): ns3::dsdv::DsdvHeader [class] module.add_class('DsdvHeader', parent=root_module['ns3::Header']) ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::PacketQueue [class] module.add_class('PacketQueue') ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::QueueEntry [class] module.add_class('QueueEntry') ## dsdv-routing-protocol.h (module 'dsdv'): ns3::dsdv::RoutingProtocol [class] module.add_class('RoutingProtocol', parent=root_module['ns3::Ipv4RoutingProtocol']) ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTable [class] module.add_class('RoutingTable') ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTableEntry [class] module.add_class('RoutingTableEntry') module.add_container('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry >', ('ns3::Ipv4Address', 'ns3::dsdv::RoutingTableEntry'), container_type=u'map') def register_types_ns3_internal(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3Timer_methods(root_module, root_module['ns3::Timer']) register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) register_Ns3TracedValue__Unsigned_int_methods(root_module, root_module['ns3::TracedValue< unsigned int >']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3DsdvHelper_methods(root_module, root_module['ns3::DsdvHelper']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PacketFilter_methods(root_module, root_module['ns3::PacketFilter']) register_Ns3Queue_methods(root_module, root_module['ns3::Queue']) register_Ns3QueueDisc_methods(root_module, root_module['ns3::QueueDisc']) register_Ns3QueueDiscClass_methods(root_module, root_module['ns3::QueueDiscClass']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3TrafficControlLayer_methods(root_module, root_module['ns3::TrafficControlLayer']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker']) register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker']) register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4Interface_methods(root_module, root_module['ns3::Ipv4Interface']) register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue']) register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3Ipv4ListRouting_methods(root_module, root_module['ns3::Ipv4ListRouting']) register_Ns3QueueDiscItem_methods(root_module, root_module['ns3::QueueDiscItem']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) register_Ns3DsdvDsdvHeader_methods(root_module, root_module['ns3::dsdv::DsdvHeader']) register_Ns3DsdvPacketQueue_methods(root_module, root_module['ns3::dsdv::PacketQueue']) register_Ns3DsdvQueueEntry_methods(root_module, root_module['ns3::dsdv::QueueEntry']) register_Ns3DsdvRoutingProtocol_methods(root_module, root_module['ns3::dsdv::RoutingProtocol']) register_Ns3DsdvRoutingTable_methods(root_module, root_module['ns3::dsdv::RoutingTable']) register_Ns3DsdvRoutingTableEntry_methods(root_module, root_module['ns3::dsdv::RoutingTableEntry']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): uint8_t ns3::InetSocketAddress::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3IntToType__0_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) return def register_Ns3IntToType__1_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) return def register_Ns3IntToType__2_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) return def register_Ns3IntToType__3_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) return def register_Ns3IntToType__4_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) return def register_Ns3IntToType__5_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) return def register_Ns3IntToType__6_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv4RoutingHelper_methods(root_module, cls): ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper() [constructor] cls.add_constructor([]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper(ns3::Ipv4RoutingHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingHelper const &', 'arg0')]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper * ns3::Ipv4RoutingHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4RoutingHelper *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4RoutingHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintRoutingTableAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintRoutingTableAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintRoutingTableAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintRoutingTableEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], deprecated=True, is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 21 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'delay')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3Timer_methods(root_module, cls): ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Timer const &', 'arg0')]) ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] cls.add_constructor([]) ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] cls.add_method('GetState', 'ns3::Timer::State', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] cls.add_method('IsSuspended', 'bool', [], is_const=True) ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] cls.add_method('Remove', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] cls.add_method('Resume', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] cls.add_method('Schedule', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] cls.add_method('Schedule', 'void', [param('ns3::Time', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] cls.add_method('SetDelay', 'void', [param('ns3::Time const &', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] cls.add_method('Suspend', 'void', []) return def register_Ns3TimerImpl_methods(root_module, cls): ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] cls.add_constructor([]) ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] cls.add_method('Invoke', 'void', [], is_pure_virtual=True, is_virtual=True) ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] cls.add_method('Schedule', 'ns3::EventId', [param('ns3::Time const &', 'delay')], is_pure_virtual=True, is_virtual=True) return def register_Ns3TracedValue__Unsigned_int_methods(root_module, cls): ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue() [constructor] cls.add_constructor([]) ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(ns3::TracedValue<unsigned int> const & o) [copy constructor] cls.add_constructor([param('ns3::TracedValue< unsigned int > const &', 'o')]) ## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(unsigned int const & v) [constructor] cls.add_constructor([param('unsigned int const &', 'v')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Connect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('ConnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Disconnect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('DisconnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): unsigned int ns3::TracedValue<unsigned int>::Get() const [member function] cls.add_method('Get', 'unsigned int', [], is_const=True) ## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Set(unsigned int const & v) [member function] cls.add_method('Set', 'void', [param('unsigned int const &', 'v')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')], deprecated=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function] cls.add_method('GetSize', 'std::size_t', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'uid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3DsdvHelper_methods(root_module, cls): ## dsdv-helper.h (module 'dsdv'): ns3::DsdvHelper::DsdvHelper(ns3::DsdvHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::DsdvHelper const &', 'arg0')]) ## dsdv-helper.h (module 'dsdv'): ns3::DsdvHelper::DsdvHelper() [constructor] cls.add_constructor([]) ## dsdv-helper.h (module 'dsdv'): ns3::DsdvHelper * ns3::DsdvHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::DsdvHelper *', [], is_const=True, is_virtual=True) ## dsdv-helper.h (module 'dsdv'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::DsdvHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True, is_virtual=True) ## dsdv-helper.h (module 'dsdv'): void ns3::DsdvHelper::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3PacketFilter_methods(root_module, cls): ## packet-filter.h (module 'traffic-control'): ns3::PacketFilter::PacketFilter(ns3::PacketFilter const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketFilter const &', 'arg0')]) ## packet-filter.h (module 'traffic-control'): ns3::PacketFilter::PacketFilter() [constructor] cls.add_constructor([]) ## packet-filter.h (module 'traffic-control'): int32_t ns3::PacketFilter::Classify(ns3::Ptr<ns3::QueueDiscItem> item) const [member function] cls.add_method('Classify', 'int32_t', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], is_const=True) ## packet-filter.h (module 'traffic-control'): static ns3::TypeId ns3::PacketFilter::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-filter.h (module 'traffic-control'): ns3::PacketFilter::PF_NO_MATCH [variable] cls.add_static_attribute('PF_NO_MATCH', 'int const', is_const=True) ## packet-filter.h (module 'traffic-control'): bool ns3::PacketFilter::CheckProtocol(ns3::Ptr<ns3::QueueDiscItem> item) const [member function] cls.add_method('CheckProtocol', 'bool', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## packet-filter.h (module 'traffic-control'): int32_t ns3::PacketFilter::DoClassify(ns3::Ptr<ns3::QueueDiscItem> item) const [member function] cls.add_method('DoClassify', 'int32_t', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3Queue_methods(root_module, cls): ## queue.h (module 'network'): ns3::Queue::Queue(ns3::Queue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Queue const &', 'arg0')]) ## queue.h (module 'network'): ns3::Queue::Queue() [constructor] cls.add_constructor([]) ## queue.h (module 'network'): ns3::Ptr<ns3::QueueItem> ns3::Queue::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::QueueItem >', []) ## queue.h (module 'network'): void ns3::Queue::DequeueAll() [member function] cls.add_method('DequeueAll', 'void', []) ## queue.h (module 'network'): bool ns3::Queue::Enqueue(ns3::Ptr<ns3::QueueItem> item) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::QueueItem >', 'item')]) ## queue.h (module 'network'): uint32_t ns3::Queue::GetMaxBytes() const [member function] cls.add_method('GetMaxBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetMaxPackets() const [member function] cls.add_method('GetMaxPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): ns3::Queue::QueueMode ns3::Queue::GetMode() const [member function] cls.add_method('GetMode', 'ns3::Queue::QueueMode', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedBytes() const [member function] cls.add_method('GetTotalDroppedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedPackets() const [member function] cls.add_method('GetTotalDroppedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedBytes() const [member function] cls.add_method('GetTotalReceivedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedPackets() const [member function] cls.add_method('GetTotalReceivedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): static ns3::TypeId ns3::Queue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue.h (module 'network'): bool ns3::Queue::IsEmpty() const [member function] cls.add_method('IsEmpty', 'bool', [], is_const=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::QueueItem> ns3::Queue::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::QueueItem const >', [], is_const=True) ## queue.h (module 'network'): ns3::Ptr<ns3::QueueItem> ns3::Queue::Remove() [member function] cls.add_method('Remove', 'ns3::Ptr< ns3::QueueItem >', []) ## queue.h (module 'network'): void ns3::Queue::ResetStatistics() [member function] cls.add_method('ResetStatistics', 'void', []) ## queue.h (module 'network'): void ns3::Queue::SetDropCallback(ns3::Callback<void, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetDropCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## queue.h (module 'network'): void ns3::Queue::SetMaxBytes(uint32_t maxBytes) [member function] cls.add_method('SetMaxBytes', 'void', [param('uint32_t', 'maxBytes')]) ## queue.h (module 'network'): void ns3::Queue::SetMaxPackets(uint32_t maxPackets) [member function] cls.add_method('SetMaxPackets', 'void', [param('uint32_t', 'maxPackets')]) ## queue.h (module 'network'): void ns3::Queue::SetMode(ns3::Queue::QueueMode mode) [member function] cls.add_method('SetMode', 'void', [param('ns3::Queue::QueueMode', 'mode')]) ## queue.h (module 'network'): void ns3::Queue::Drop(ns3::Ptr<ns3::QueueItem> item) [member function] cls.add_method('Drop', 'void', [param('ns3::Ptr< ns3::QueueItem >', 'item')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<ns3::QueueItem> ns3::Queue::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::QueueItem >', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): bool ns3::Queue::DoEnqueue(ns3::Ptr<ns3::QueueItem> item) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::QueueItem >', 'item')], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::QueueItem> ns3::Queue::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::QueueItem const >', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<ns3::QueueItem> ns3::Queue::DoRemove() [member function] cls.add_method('DoRemove', 'ns3::Ptr< ns3::QueueItem >', [], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3QueueDisc_methods(root_module, cls): ## queue-disc.h (module 'traffic-control'): ns3::QueueDisc::QueueDisc(ns3::QueueDisc const & arg0) [copy constructor] cls.add_constructor([param('ns3::QueueDisc const &', 'arg0')]) ## queue-disc.h (module 'traffic-control'): ns3::QueueDisc::QueueDisc() [constructor] cls.add_constructor([]) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::AddInternalQueue(ns3::Ptr<ns3::Queue> queue) [member function] cls.add_method('AddInternalQueue', 'void', [param('ns3::Ptr< ns3::Queue >', 'queue')]) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::AddPacketFilter(ns3::Ptr<ns3::PacketFilter> filter) [member function] cls.add_method('AddPacketFilter', 'void', [param('ns3::Ptr< ns3::PacketFilter >', 'filter')]) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::AddQueueDiscClass(ns3::Ptr<ns3::QueueDiscClass> qdClass) [member function] cls.add_method('AddQueueDiscClass', 'void', [param('ns3::Ptr< ns3::QueueDiscClass >', 'qdClass')]) ## queue-disc.h (module 'traffic-control'): int32_t ns3::QueueDisc::Classify(ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('Classify', 'int32_t', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')]) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<ns3::QueueDiscItem> ns3::QueueDisc::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::QueueDiscItem >', []) ## queue-disc.h (module 'traffic-control'): bool ns3::QueueDisc::Enqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')]) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<ns3::Queue> ns3::QueueDisc::GetInternalQueue(uint32_t i) const [member function] cls.add_method('GetInternalQueue', 'ns3::Ptr< ns3::Queue >', [param('uint32_t', 'i')], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetNInternalQueues() const [member function] cls.add_method('GetNInternalQueues', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetNPacketFilters() const [member function] cls.add_method('GetNPacketFilters', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetNQueueDiscClasses() const [member function] cls.add_method('GetNQueueDiscClasses', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<ns3::NetDevice> ns3::QueueDisc::GetNetDevice() const [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<ns3::PacketFilter> ns3::QueueDisc::GetPacketFilter(uint32_t i) const [member function] cls.add_method('GetPacketFilter', 'ns3::Ptr< ns3::PacketFilter >', [param('uint32_t', 'i')], is_const=True) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<ns3::QueueDiscClass> ns3::QueueDisc::GetQueueDiscClass(uint32_t i) const [member function] cls.add_method('GetQueueDiscClass', 'ns3::Ptr< ns3::QueueDiscClass >', [param('uint32_t', 'i')], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetQuota() const [member function] cls.add_method('GetQuota', 'uint32_t', [], is_const=True, is_virtual=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetTotalDroppedBytes() const [member function] cls.add_method('GetTotalDroppedBytes', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetTotalDroppedPackets() const [member function] cls.add_method('GetTotalDroppedPackets', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetTotalReceivedBytes() const [member function] cls.add_method('GetTotalReceivedBytes', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetTotalReceivedPackets() const [member function] cls.add_method('GetTotalReceivedPackets', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetTotalRequeuedBytes() const [member function] cls.add_method('GetTotalRequeuedBytes', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint32_t ns3::QueueDisc::GetTotalRequeuedPackets() const [member function] cls.add_method('GetTotalRequeuedPackets', 'uint32_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): static ns3::TypeId ns3::QueueDisc::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue-disc.h (module 'traffic-control'): ns3::QueueDisc::WakeMode ns3::QueueDisc::GetWakeMode() [member function] cls.add_method('GetWakeMode', 'ns3::QueueDisc::WakeMode', []) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<const ns3::QueueDiscItem> ns3::QueueDisc::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::QueueDiscItem const >', [], is_const=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::Run() [member function] cls.add_method('Run', 'void', []) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::SetNetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::SetParentDropCallback(ns3::Callback<void, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetParentDropCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::SetQuota(uint32_t const quota) [member function] cls.add_method('SetQuota', 'void', [param('uint32_t const', 'quota')], is_virtual=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::Drop(ns3::Ptr<ns3::QueueItem> item) [member function] cls.add_method('Drop', 'void', [param('ns3::Ptr< ns3::QueueItem >', 'item')], visibility='protected') ## queue-disc.h (module 'traffic-control'): bool ns3::QueueDisc::CheckConfig() [member function] cls.add_method('CheckConfig', 'bool', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<ns3::QueueDiscItem> ns3::QueueDisc::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::QueueDiscItem >', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue-disc.h (module 'traffic-control'): bool ns3::QueueDisc::DoEnqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<const ns3::QueueDiscItem> ns3::QueueDisc::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::QueueDiscItem const >', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDisc::InitializeParams() [member function] cls.add_method('InitializeParams', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3QueueDiscClass_methods(root_module, cls): ## queue-disc.h (module 'traffic-control'): ns3::QueueDiscClass::QueueDiscClass(ns3::QueueDiscClass const & arg0) [copy constructor] cls.add_constructor([param('ns3::QueueDiscClass const &', 'arg0')]) ## queue-disc.h (module 'traffic-control'): ns3::QueueDiscClass::QueueDiscClass() [constructor] cls.add_constructor([]) ## queue-disc.h (module 'traffic-control'): ns3::Ptr<ns3::QueueDisc> ns3::QueueDiscClass::GetQueueDisc() const [member function] cls.add_method('GetQueueDisc', 'ns3::Ptr< ns3::QueueDisc >', [], is_const=True) ## queue-disc.h (module 'traffic-control'): static ns3::TypeId ns3::QueueDiscClass::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDiscClass::SetQueueDisc(ns3::Ptr<ns3::QueueDisc> qd) [member function] cls.add_method('SetQueueDisc', 'void', [param('ns3::Ptr< ns3::QueueDisc >', 'qd')]) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDiscClass::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3RandomVariableStream_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function] cls.add_method('SetStream', 'void', [param('int64_t', 'stream')]) ## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function] cls.add_method('GetStream', 'int64_t', [], is_const=True) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function] cls.add_method('SetAntithetic', 'void', [param('bool', 'isAntithetic')]) ## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function] cls.add_method('IsAntithetic', 'bool', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function] cls.add_method('Peek', 'ns3::RngStream *', [], is_const=True, visibility='protected') return def register_Ns3SequentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function] cls.add_method('GetIncrement', 'ns3::Ptr< ns3::RandomVariableStream >', [], is_const=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function] cls.add_method('GetConsecutive', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function] cls.add_method('GetPeerName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function] cls.add_method('IpTos2Priority', 'uint8_t', [param('uint8_t', 'ipTos')], is_static=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address,std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function] cls.add_method('Ipv6LeaveGroup', 'void', [], is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketPriorityTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TrafficControlLayer_methods(root_module, cls): ## traffic-control-layer.h (module 'traffic-control'): ns3::TrafficControlLayer::TrafficControlLayer() [constructor] cls.add_constructor([]) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::DeleteRootQueueDiscOnDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('DeleteRootQueueDiscOnDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): ns3::TypeId ns3::TrafficControlLayer::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): ns3::Ptr<ns3::QueueDisc> ns3::TrafficControlLayer::GetRootQueueDiscOnDevice(ns3::Ptr<ns3::NetDevice> device) const [member function] cls.add_method('GetRootQueueDiscOnDevice', 'ns3::Ptr< ns3::QueueDisc >', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_const=True, is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): static ns3::TypeId ns3::TrafficControlLayer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::Packet const> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')], is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::Send(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::QueueDiscItem> item) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::QueueDiscItem >', 'item')], is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::SetRootQueueDiscOnDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::QueueDisc> qDisc) [member function] cls.add_method('SetRootQueueDiscOnDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::QueueDisc >', 'qDisc')], is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::SetupDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetupDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## traffic-control-layer.h (module 'traffic-control'): void ns3::TrafficControlLayer::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TriangularRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3BooleanChecker_methods(root_module, cls): ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')]) return def register_Ns3BooleanValue_methods(root_module, cls): cls.add_output_stream_operator() ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor] cls.add_constructor([param('bool', 'value')]) ## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function] cls.add_method('Get', 'bool', [], is_const=True) ## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function] cls.add_method('Set', 'void', [param('bool', 'value')]) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3ConstantRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function] cls.add_method('GetConstant', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function] cls.add_method('GetValue', 'double', [param('double', 'constant')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'constant')]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3DeterministicRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function] cls.add_method('SetValueArray', 'void', [param('double *', 'values'), param('uint64_t', 'length')]) ## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3DoubleValue_methods(root_module, cls): ## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor] cls.add_constructor([]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor] cls.add_constructor([param('double const &', 'value')]) ## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## double.h (module 'core'): bool ns3::DoubleValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function] cls.add_method('Get', 'double', [], is_const=True) ## double.h (module 'core'): std::string ns3::DoubleValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function] cls.add_method('Set', 'void', [param('double const &', 'value')]) return def register_Ns3EmpiricalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function] cls.add_method('CDF', 'void', [param('double', 'v'), param('double', 'c')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double c1, double c2, double v1, double v2, double r) [member function] cls.add_method('Interpolate', 'double', [param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')], visibility='private', is_virtual=True) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function] cls.add_method('Validate', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EmptyAttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EnumChecker_methods(root_module, cls): ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')]) ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor] cls.add_constructor([]) ## enum.h (module 'core'): void ns3::EnumChecker::Add(int value, std::string name) [member function] cls.add_method('Add', 'void', [param('int', 'value'), param('std::string', 'name')]) ## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function] cls.add_method('AddDefault', 'void', [param('int', 'value'), param('std::string', 'name')]) ## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')], is_const=True, is_virtual=True) ## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EnumValue_methods(root_module, cls): ## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnumValue const &', 'arg0')]) ## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor] cls.add_constructor([]) ## enum.h (module 'core'): ns3::EnumValue::EnumValue(int value) [constructor] cls.add_constructor([param('int', 'value')]) ## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function] cls.add_method('Get', 'int', [], is_const=True) ## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## enum.h (module 'core'): void ns3::EnumValue::Set(int value) [member function] cls.add_method('Set', 'void', [param('int', 'value')]) return def register_Ns3ErlangRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function] cls.add_method('GetK', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function] cls.add_method('GetLambda', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'k'), param('double', 'lambda')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'k'), param('uint32_t', 'lambda')]) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3ExponentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3GammaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha'), param('uint32_t', 'beta')]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3IntegerValue_methods(root_module, cls): ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor] cls.add_constructor([]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor] cls.add_constructor([param('int64_t const &', 'value')]) ## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function] cls.add_method('Get', 'int64_t', [], is_const=True) ## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function] cls.add_method('Set', 'void', [param('int64_t const &', 'value')]) return def register_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4Interface_methods(root_module, cls): ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface::Ipv4Interface(ns3::Ipv4Interface const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Interface const &', 'arg0')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface::Ipv4Interface() [constructor] cls.add_constructor([]) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::AddAddress(ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv4InterfaceAddress', 'address')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::ArpCache> ns3::Ipv4Interface::GetArpCache() const [member function] cls.add_method('GetArpCache', 'ns3::Ptr< ns3::ArpCache >', [], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-interface.h (module 'internet'): uint16_t ns3::Ipv4Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv4-interface.h (module 'internet'): uint32_t ns3::Ipv4Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv4-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv4Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'index')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv4InterfaceAddress', [param('ns3::Ipv4Address', 'address')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & hdr, ns3::Ipv4Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'hdr'), param('ns3::Ipv4Address', 'dest')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetArpCache(ns3::Ptr<ns3::ArpCache> arpCache) [member function] cls.add_method('SetArpCache', 'void', [param('ns3::Ptr< ns3::ArpCache >', 'arpCache')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetForwarding(bool val) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'val')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetTrafficControl(ns3::Ptr<ns3::TrafficControlLayer> tc) [member function] cls.add_method('SetTrafficControl', 'void', [param('ns3::Ptr< ns3::TrafficControlLayer >', 'tc')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv4L3Protocol_methods(root_module, cls): ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor] cls.add_constructor([]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUnicast(ns3::Ipv4Address ad) const [member function] cls.add_method('IsUnicast', 'bool', [param('ns3::Ipv4Address', 'ad')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::Packet const> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], visibility='private', is_virtual=True) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3LogNormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function] cls.add_method('GetMu', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function] cls.add_method('GetSigma', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function] cls.add_method('GetValue', 'double', [param('double', 'mu'), param('double', 'sigma')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mu'), param('uint32_t', 'sigma')]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NetDeviceQueue_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function] cls.add_method('GetQueueLimits', 'ns3::Ptr< ns3::QueueLimits >', []) ## net-device.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function] cls.add_method('IsStopped', 'bool', [], is_const=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function] cls.add_method('NotifyQueuedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function] cls.add_method('NotifyTransmittedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function] cls.add_method('ResetQueueLimits', 'void', []) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetQueueLimits(ns3::Ptr<ns3::QueueLimits> ql) [member function] cls.add_method('SetQueueLimits', 'void', [param('ns3::Ptr< ns3::QueueLimits >', 'ql')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetWakeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function] cls.add_method('Wake', 'void', [], is_virtual=True) return def register_Ns3NetDeviceQueueInterface_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function] cls.add_method('CreateTxQueues', 'void', []) ## net-device.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function] cls.add_method('GetNTxQueues', 'uint8_t', [], is_const=True) ## net-device.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function] cls.add_method('GetSelectQueueCallback', 'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function] cls.add_method('GetTxQueue', 'ns3::Ptr< ns3::NetDeviceQueue >', [param('uint8_t', 'i')], is_const=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetSelectQueueCallback', 'void', [param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function] cls.add_method('SetTxQueuesN', 'void', [param('uint8_t', 'numTxQueues')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable] cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function] cls.add_method('GetVariance', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_Ns3ParetoRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3QueueItem_methods(root_module, cls): cls.add_output_stream_operator() ## net-device.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')]) ## net-device.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## net-device.h (module 'network'): uint32_t ns3::QueueItem::GetPacketSize() const [member function] cls.add_method('GetPacketSize', 'uint32_t', [], is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function] cls.add_method('GetUint8Value', 'bool', [param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')], is_const=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3UintegerValue_methods(root_module, cls): ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor] cls.add_constructor([]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor] cls.add_constructor([param('uint64_t const &', 'value')]) ## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function] cls.add_method('Get', 'uint64_t', [], is_const=True) ## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function] cls.add_method('Set', 'void', [param('uint64_t const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3Ipv4ListRouting_methods(root_module, cls): ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting(ns3::Ipv4ListRouting const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4ListRouting const &', 'arg0')]) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting() [constructor] cls.add_constructor([]) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::AddRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol, int16_t priority) [member function] cls.add_method('AddRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol'), param('int16_t', 'priority')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): uint32_t ns3::Ipv4ListRouting::GetNRoutingProtocols() const [member function] cls.add_method('GetNRoutingProtocols', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4ListRouting::GetRoutingProtocol(uint32_t index, int16_t & priority) const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('uint32_t', 'index'), param('int16_t &', 'priority', direction=2)], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): static ns3::TypeId ns3::Ipv4ListRouting::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): bool ns3::Ipv4ListRouting::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4ListRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3QueueDiscItem_methods(root_module, cls): ## queue-disc.h (module 'traffic-control'): ns3::QueueDiscItem::QueueDiscItem(ns3::Ptr<ns3::Packet> p, ns3::Address const & addr, uint16_t protocol) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Address const &', 'addr'), param('uint16_t', 'protocol')]) ## queue-disc.h (module 'traffic-control'): ns3::Address ns3::QueueDiscItem::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint16_t ns3::QueueDiscItem::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint16_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): uint8_t ns3::QueueDiscItem::GetTxQueueIndex() const [member function] cls.add_method('GetTxQueueIndex', 'uint8_t', [], is_const=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDiscItem::SetTxQueueIndex(uint8_t txq) [member function] cls.add_method('SetTxQueueIndex', 'void', [param('uint8_t', 'txq')]) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDiscItem::AddHeader() [member function] cls.add_method('AddHeader', 'void', [], is_pure_virtual=True, is_virtual=True) ## queue-disc.h (module 'traffic-control'): void ns3::QueueDiscItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3DsdvDsdvHeader_methods(root_module, cls): cls.add_output_stream_operator() ## dsdv-packet.h (module 'dsdv'): ns3::dsdv::DsdvHeader::DsdvHeader(ns3::dsdv::DsdvHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::dsdv::DsdvHeader const &', 'arg0')]) ## dsdv-packet.h (module 'dsdv'): ns3::dsdv::DsdvHeader::DsdvHeader(ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t hopcount=0, uint32_t dstSeqNo=0) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'hopcount', default_value='0'), param('uint32_t', 'dstSeqNo', default_value='0')]) ## dsdv-packet.h (module 'dsdv'): uint32_t ns3::dsdv::DsdvHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## dsdv-packet.h (module 'dsdv'): ns3::Ipv4Address ns3::dsdv::DsdvHeader::GetDst() const [member function] cls.add_method('GetDst', 'ns3::Ipv4Address', [], is_const=True) ## dsdv-packet.h (module 'dsdv'): uint32_t ns3::dsdv::DsdvHeader::GetDstSeqno() const [member function] cls.add_method('GetDstSeqno', 'uint32_t', [], is_const=True) ## dsdv-packet.h (module 'dsdv'): uint32_t ns3::dsdv::DsdvHeader::GetHopCount() const [member function] cls.add_method('GetHopCount', 'uint32_t', [], is_const=True) ## dsdv-packet.h (module 'dsdv'): ns3::TypeId ns3::dsdv::DsdvHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## dsdv-packet.h (module 'dsdv'): uint32_t ns3::dsdv::DsdvHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## dsdv-packet.h (module 'dsdv'): static ns3::TypeId ns3::dsdv::DsdvHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::SetDst(ns3::Ipv4Address destination) [member function] cls.add_method('SetDst', 'void', [param('ns3::Ipv4Address', 'destination')]) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::SetDstSeqno(uint32_t sequenceNumber) [member function] cls.add_method('SetDstSeqno', 'void', [param('uint32_t', 'sequenceNumber')]) ## dsdv-packet.h (module 'dsdv'): void ns3::dsdv::DsdvHeader::SetHopCount(uint32_t hopCount) [member function] cls.add_method('SetHopCount', 'void', [param('uint32_t', 'hopCount')]) return def register_Ns3DsdvPacketQueue_methods(root_module, cls): ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::PacketQueue::PacketQueue(ns3::dsdv::PacketQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::dsdv::PacketQueue const &', 'arg0')]) ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::PacketQueue::PacketQueue() [constructor] cls.add_constructor([]) ## dsdv-packet-queue.h (module 'dsdv'): bool ns3::dsdv::PacketQueue::Dequeue(ns3::Ipv4Address dst, ns3::dsdv::QueueEntry & entry) [member function] cls.add_method('Dequeue', 'bool', [param('ns3::Ipv4Address', 'dst'), param('ns3::dsdv::QueueEntry &', 'entry')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::PacketQueue::DropPacketWithDst(ns3::Ipv4Address dst) [member function] cls.add_method('DropPacketWithDst', 'void', [param('ns3::Ipv4Address', 'dst')]) ## dsdv-packet-queue.h (module 'dsdv'): bool ns3::dsdv::PacketQueue::Enqueue(ns3::dsdv::QueueEntry & entry) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::dsdv::QueueEntry &', 'entry')]) ## dsdv-packet-queue.h (module 'dsdv'): bool ns3::dsdv::PacketQueue::Find(ns3::Ipv4Address dst) [member function] cls.add_method('Find', 'bool', [param('ns3::Ipv4Address', 'dst')]) ## dsdv-packet-queue.h (module 'dsdv'): uint32_t ns3::dsdv::PacketQueue::GetCountForPacketsWithDst(ns3::Ipv4Address dst) [member function] cls.add_method('GetCountForPacketsWithDst', 'uint32_t', [param('ns3::Ipv4Address', 'dst')]) ## dsdv-packet-queue.h (module 'dsdv'): uint32_t ns3::dsdv::PacketQueue::GetMaxPacketsPerDst() const [member function] cls.add_method('GetMaxPacketsPerDst', 'uint32_t', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): uint32_t ns3::dsdv::PacketQueue::GetMaxQueueLen() const [member function] cls.add_method('GetMaxQueueLen', 'uint32_t', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Time ns3::dsdv::PacketQueue::GetQueueTimeout() const [member function] cls.add_method('GetQueueTimeout', 'ns3::Time', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): uint32_t ns3::dsdv::PacketQueue::GetSize() [member function] cls.add_method('GetSize', 'uint32_t', []) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::PacketQueue::SetMaxPacketsPerDst(uint32_t len) [member function] cls.add_method('SetMaxPacketsPerDst', 'void', [param('uint32_t', 'len')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::PacketQueue::SetMaxQueueLen(uint32_t len) [member function] cls.add_method('SetMaxQueueLen', 'void', [param('uint32_t', 'len')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::PacketQueue::SetQueueTimeout(ns3::Time t) [member function] cls.add_method('SetQueueTimeout', 'void', [param('ns3::Time', 't')]) return def register_Ns3DsdvQueueEntry_methods(root_module, cls): cls.add_binary_comparison_operator('==') ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::QueueEntry::QueueEntry(ns3::dsdv::QueueEntry const & arg0) [copy constructor] cls.add_constructor([param('ns3::dsdv::QueueEntry const &', 'arg0')]) ## dsdv-packet-queue.h (module 'dsdv'): ns3::dsdv::QueueEntry::QueueEntry(ns3::Ptr<ns3::Packet const> pa=0, ns3::Ipv4Header const & h=ns3::Ipv4Header(), ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb=ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>(), ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb=ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>()) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Header const &', 'h', default_value='ns3::Ipv4Header()'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb', default_value='ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>()'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb', default_value='ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>()')]) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::dsdv::QueueEntry::GetErrorCallback() const [member function] cls.add_method('GetErrorCallback', 'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Time ns3::dsdv::QueueEntry::GetExpireTime() const [member function] cls.add_method('GetExpireTime', 'ns3::Time', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Ipv4Header ns3::dsdv::QueueEntry::GetIpv4Header() const [member function] cls.add_method('GetIpv4Header', 'ns3::Ipv4Header', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Ptr<ns3::Packet const> ns3::dsdv::QueueEntry::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet const >', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::dsdv::QueueEntry::GetUnicastForwardCallback() const [member function] cls.add_method('GetUnicastForwardCallback', 'ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetErrorCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb) [member function] cls.add_method('SetErrorCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetExpireTime(ns3::Time exp) [member function] cls.add_method('SetExpireTime', 'void', [param('ns3::Time', 'exp')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetIpv4Header(ns3::Ipv4Header h) [member function] cls.add_method('SetIpv4Header', 'void', [param('ns3::Ipv4Header', 'h')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetPacket(ns3::Ptr<ns3::Packet const> p) [member function] cls.add_method('SetPacket', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')]) ## dsdv-packet-queue.h (module 'dsdv'): void ns3::dsdv::QueueEntry::SetUnicastForwardCallback(ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb) [member function] cls.add_method('SetUnicastForwardCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb')]) return def register_Ns3DsdvRoutingProtocol_methods(root_module, cls): ## dsdv-routing-protocol.h (module 'dsdv'): ns3::dsdv::RoutingProtocol::RoutingProtocol(ns3::dsdv::RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::dsdv::RoutingProtocol const &', 'arg0')]) ## dsdv-routing-protocol.h (module 'dsdv'): ns3::dsdv::RoutingProtocol::RoutingProtocol() [constructor] cls.add_constructor([]) ## dsdv-routing-protocol.h (module 'dsdv'): int64_t ns3::dsdv::RoutingProtocol::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): bool ns3::dsdv::RoutingProtocol::GetEnableBufferFlag() const [member function] cls.add_method('GetEnableBufferFlag', 'bool', [], is_const=True) ## dsdv-routing-protocol.h (module 'dsdv'): bool ns3::dsdv::RoutingProtocol::GetEnableRAFlag() const [member function] cls.add_method('GetEnableRAFlag', 'bool', [], is_const=True) ## dsdv-routing-protocol.h (module 'dsdv'): static ns3::TypeId ns3::dsdv::RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dsdv-routing-protocol.h (module 'dsdv'): bool ns3::dsdv::RoutingProtocol::GetWSTFlag() const [member function] cls.add_method('GetWSTFlag', 'bool', [], is_const=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True, is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): bool ns3::dsdv::RoutingProtocol::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): ns3::Ptr<ns3::Ipv4Route> ns3::dsdv::RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::SetEnableBufferFlag(bool f) [member function] cls.add_method('SetEnableBufferFlag', 'void', [param('bool', 'f')]) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::SetEnableRAFlag(bool f) [member function] cls.add_method('SetEnableRAFlag', 'void', [param('bool', 'f')]) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_virtual=True) ## dsdv-routing-protocol.h (module 'dsdv'): void ns3::dsdv::RoutingProtocol::SetWSTFlag(bool f) [member function] cls.add_method('SetWSTFlag', 'void', [param('bool', 'f')]) ## dsdv-routing-protocol.h (module 'dsdv'): ns3::dsdv::RoutingProtocol::DSDV_PORT [variable] cls.add_static_attribute('DSDV_PORT', 'uint32_t const', is_const=True) return def register_Ns3DsdvRoutingTable_methods(root_module, cls): ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTable::RoutingTable(ns3::dsdv::RoutingTable const & arg0) [copy constructor] cls.add_constructor([param('ns3::dsdv::RoutingTable const &', 'arg0')]) ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTable::RoutingTable() [constructor] cls.add_constructor([]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::AddIpv4Event(ns3::Ipv4Address address, ns3::EventId id) [member function] cls.add_method('AddIpv4Event', 'bool', [param('ns3::Ipv4Address', 'address'), param('ns3::EventId', 'id')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::AddRoute(ns3::dsdv::RoutingTableEntry & r) [member function] cls.add_method('AddRoute', 'bool', [param('ns3::dsdv::RoutingTableEntry &', 'r')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::AnyRunningEvent(ns3::Ipv4Address address) [member function] cls.add_method('AnyRunningEvent', 'bool', [param('ns3::Ipv4Address', 'address')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::Clear() [member function] cls.add_method('Clear', 'void', []) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::DeleteAllRoutesFromInterface(ns3::Ipv4InterfaceAddress iface) [member function] cls.add_method('DeleteAllRoutesFromInterface', 'void', [param('ns3::Ipv4InterfaceAddress', 'iface')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::DeleteIpv4Event(ns3::Ipv4Address address) [member function] cls.add_method('DeleteIpv4Event', 'bool', [param('ns3::Ipv4Address', 'address')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::DeleteRoute(ns3::Ipv4Address dst) [member function] cls.add_method('DeleteRoute', 'bool', [param('ns3::Ipv4Address', 'dst')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::ForceDeleteIpv4Event(ns3::Ipv4Address address) [member function] cls.add_method('ForceDeleteIpv4Event', 'bool', [param('ns3::Ipv4Address', 'address')]) ## dsdv-rtable.h (module 'dsdv'): ns3::EventId ns3::dsdv::RoutingTable::GetEventId(ns3::Ipv4Address address) [member function] cls.add_method('GetEventId', 'ns3::EventId', [param('ns3::Ipv4Address', 'address')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::GetListOfAllRoutes(std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, ns3::dsdv::RoutingTableEntry> > > & allRoutes) [member function] cls.add_method('GetListOfAllRoutes', 'void', [param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'allRoutes')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::GetListOfDestinationWithNextHop(ns3::Ipv4Address nxtHp, std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, ns3::dsdv::RoutingTableEntry> > > & dstList) [member function] cls.add_method('GetListOfDestinationWithNextHop', 'void', [param('ns3::Ipv4Address', 'nxtHp'), param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'dstList')]) ## dsdv-rtable.h (module 'dsdv'): ns3::Time ns3::dsdv::RoutingTable::Getholddowntime() const [member function] cls.add_method('Getholddowntime', 'ns3::Time', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::LookupRoute(ns3::Ipv4Address dst, ns3::dsdv::RoutingTableEntry & rt) [member function] cls.add_method('LookupRoute', 'bool', [param('ns3::Ipv4Address', 'dst'), param('ns3::dsdv::RoutingTableEntry &', 'rt')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::LookupRoute(ns3::Ipv4Address id, ns3::dsdv::RoutingTableEntry & rt, bool forRouteInput) [member function] cls.add_method('LookupRoute', 'bool', [param('ns3::Ipv4Address', 'id'), param('ns3::dsdv::RoutingTableEntry &', 'rt'), param('bool', 'forRouteInput')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('Print', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::Purge(std::map<ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry, std::less<ns3::Ipv4Address>, std::allocator<std::pair<ns3::Ipv4Address const, ns3::dsdv::RoutingTableEntry> > > & removedAddresses) [member function] cls.add_method('Purge', 'void', [param('std::map< ns3::Ipv4Address, ns3::dsdv::RoutingTableEntry > &', 'removedAddresses')]) ## dsdv-rtable.h (module 'dsdv'): uint32_t ns3::dsdv::RoutingTable::RoutingTableSize() [member function] cls.add_method('RoutingTableSize', 'uint32_t', []) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTable::Setholddowntime(ns3::Time t) [member function] cls.add_method('Setholddowntime', 'void', [param('ns3::Time', 't')]) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTable::Update(ns3::dsdv::RoutingTableEntry & rt) [member function] cls.add_method('Update', 'bool', [param('ns3::dsdv::RoutingTableEntry &', 'rt')]) return def register_Ns3DsdvRoutingTableEntry_methods(root_module, cls): ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTableEntry::RoutingTableEntry(ns3::dsdv::RoutingTableEntry const & arg0) [copy constructor] cls.add_constructor([param('ns3::dsdv::RoutingTableEntry const &', 'arg0')]) ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RoutingTableEntry::RoutingTableEntry(ns3::Ptr<ns3::NetDevice> dev=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t m_seqNo=0, ns3::Ipv4InterfaceAddress iface=ns3::Ipv4InterfaceAddress(), uint32_t hops=0, ns3::Ipv4Address nextHop=ns3::Ipv4Address(), ns3::Time lifetime=ns3::Simulator::Now( ), ns3::Time SettlingTime=ns3::Simulator::Now( ), bool changedEntries=false) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'm_seqNo', default_value='0'), param('ns3::Ipv4InterfaceAddress', 'iface', default_value='ns3::Ipv4InterfaceAddress()'), param('uint32_t', 'hops', default_value='0'), param('ns3::Ipv4Address', 'nextHop', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'lifetime', default_value='ns3::Simulator::Now( )'), param('ns3::Time', 'SettlingTime', default_value='ns3::Simulator::Now( )'), param('bool', 'changedEntries', default_value='false')]) ## dsdv-rtable.h (module 'dsdv'): ns3::Ipv4Address ns3::dsdv::RoutingTableEntry::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): bool ns3::dsdv::RoutingTableEntry::GetEntriesChanged() const [member function] cls.add_method('GetEntriesChanged', 'bool', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::dsdv::RouteFlags ns3::dsdv::RoutingTableEntry::GetFlag() const [member function] cls.add_method('GetFlag', 'ns3::dsdv::RouteFlags', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): uint32_t ns3::dsdv::RoutingTableEntry::GetHop() const [member function] cls.add_method('GetHop', 'uint32_t', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Ipv4InterfaceAddress ns3::dsdv::RoutingTableEntry::GetInterface() const [member function] cls.add_method('GetInterface', 'ns3::Ipv4InterfaceAddress', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Time ns3::dsdv::RoutingTableEntry::GetLifeTime() const [member function] cls.add_method('GetLifeTime', 'ns3::Time', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Ipv4Address ns3::dsdv::RoutingTableEntry::GetNextHop() const [member function] cls.add_method('GetNextHop', 'ns3::Ipv4Address', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Ptr<ns3::NetDevice> ns3::dsdv::RoutingTableEntry::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Ptr<ns3::Ipv4Route> ns3::dsdv::RoutingTableEntry::GetRoute() const [member function] cls.add_method('GetRoute', 'ns3::Ptr< ns3::Ipv4Route >', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): uint32_t ns3::dsdv::RoutingTableEntry::GetSeqNo() const [member function] cls.add_method('GetSeqNo', 'uint32_t', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): ns3::Time ns3::dsdv::RoutingTableEntry::GetSettlingTime() const [member function] cls.add_method('GetSettlingTime', 'ns3::Time', [], is_const=True) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('Print', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetEntriesChanged(bool entriesChanged) [member function] cls.add_method('SetEntriesChanged', 'void', [param('bool', 'entriesChanged')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetFlag(ns3::dsdv::RouteFlags flag) [member function] cls.add_method('SetFlag', 'void', [param('ns3::dsdv::RouteFlags', 'flag')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetHop(uint32_t hopCount) [member function] cls.add_method('SetHop', 'void', [param('uint32_t', 'hopCount')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetInterface(ns3::Ipv4InterfaceAddress iface) [member function] cls.add_method('SetInterface', 'void', [param('ns3::Ipv4InterfaceAddress', 'iface')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetLifeTime(ns3::Time lifeTime) [member function] cls.add_method('SetLifeTime', 'void', [param('ns3::Time', 'lifeTime')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetNextHop(ns3::Ipv4Address nextHop) [member function] cls.add_method('SetNextHop', 'void', [param('ns3::Ipv4Address', 'nextHop')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetOutputDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetRoute(ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SetRoute', 'void', [param('ns3::Ptr< ns3::Ipv4Route >', 'route')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetSeqNo(uint32_t sequenceNumber) [member function] cls.add_method('SetSeqNo', 'void', [param('uint32_t', 'sequenceNumber')]) ## dsdv-rtable.h (module 'dsdv'): void ns3::dsdv::RoutingTableEntry::SetSettlingTime(ns3::Time settlingTime) [member function] cls.add_method('SetSettlingTime', 'void', [param('ns3::Time', 'settlingTime')]) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) register_functions_ns3_dsdv(module.get_submodule('dsdv'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def register_functions_ns3_dsdv(module, root_module): return def register_functions_ns3_internal(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
apache-2.0
tanghaibao/jcvi
jcvi/formats/contig.py
1
4644
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ TIGR contig format, see spec: <http://www.cbcb.umd.edu/research/contig_representation.shtml#contig> """ import sys import logging from jcvi.formats.base import BaseFile, read_block from jcvi.apps.base import OptionParser, ActionDispatcher class ReadLine(object): def __init__(self, row, contig): # '#16(0) [RC] 3046 bases, 00000000 checksum. {3046 1} <1 3046>' assert row[0] == "#" self.id = row.strip("#").split("(")[0] coords = row.split("<")[1].split(">")[0] start, end = coords.split() self.contig = contig self.start = int(start) self.end = int(end) if self.start > self.end: self.start, self.end = self.end, self.start self.orientation = "-" if "[RC]" in row else "+" def __str__(self): return self.id @property def bedline(self): return "\t".join( str(x) for x in ( self.contig, self.start - 1, self.end, self.id, "0", self.orientation, ) ) __repr__ = __str__ class ContigLine(object): def __init__(self, row): # '##1 6 8914 bases, 00000000 checksum.' assert row[:2] == "##" self.id = row.strip("#").split()[0] self.reads = [] def __str__(self): return ":".join((self.id, str(self.reads))) __repr__ = __str__ class ContigFile(BaseFile): def __init__(self, filename): super(ContigFile, self).__init__(filename) self.fp = open(filename) def iter_records(self): c = None for a, b in read_block(self.fp, "#"): if a[:2] == "##": if c: yield c c = ContigLine(a) else: c.reads.append(ReadLine(a, c.id)) if c: # last one yield c def main(): actions = ( ("bed", "convert read membership to bed format"), ("frombed", "convert read placement to contig format"), ) p = ActionDispatcher(actions) p.dispatch(globals()) def frombed(args): """ %prog frombed bedfile contigfasta readfasta Convert read placement to contig format. This is useful before running BAMBUS. """ from jcvi.formats.fasta import Fasta from jcvi.formats.bed import Bed from jcvi.utils.cbook import fill p = OptionParser(frombed.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) bedfile, contigfasta, readfasta = args prefix = bedfile.rsplit(".", 1)[0] contigfile = prefix + ".contig" idsfile = prefix + ".ids" contigfasta = Fasta(contigfasta) readfasta = Fasta(readfasta) bed = Bed(bedfile) checksum = "00000000 checksum." fw_ids = open(idsfile, "w") fw = open(contigfile, "w") for ctg, reads in bed.sub_beds(): ctgseq = contigfasta[ctg] ctgline = "##{0} {1} {2} bases, {3}".format( ctg, len(reads), len(ctgseq), checksum ) print(ctg, file=fw_ids) print(ctgline, file=fw) print(fill(ctgseq.seq), file=fw) for b in reads: read = b.accn strand = b.strand readseq = readfasta[read] rc = " [RC]" if strand == "-" else "" readlen = len(readseq) rstart, rend = 1, readlen if strand == "-": rstart, rend = rend, rstart readrange = "{{{0} {1}}}".format(rstart, rend) conrange = "<{0} {1}>".format(b.start, b.end) readline = "#{0}(0){1} {2} bases, {3} {4} {5}".format( read, rc, readlen, checksum, readrange, conrange ) print(readline, file=fw) print(fill(readseq.seq), file=fw) logging.debug("Mapped contigs written to `{0}`.".format(contigfile)) logging.debug("Contig IDs written to `{0}`.".format(idsfile)) def bed(args): """ %prog bed contigfile Prints out the contigs and their associated reads. """ p = OptionParser(main.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (contigfile,) = args bedfile = contigfile.rsplit(".", 1)[0] + ".bed" fw = open(bedfile, "w") c = ContigFile(contigfile) for rec in c.iter_records(): for r in rec.reads: print(r.bedline, file=fw) logging.debug("File written to `%s`.", bedfile) return bedfile if __name__ == "__main__": main()
bsd-2-clause
yunfeilu/scikit-learn
examples/manifold/plot_lle_digits.py
59
8576
""" ============================================================================= Manifold learning on handwritten digits: Locally Linear Embedding, Isomap... ============================================================================= An illustration of various embeddings on the digits dataset. The RandomTreesEmbedding, from the :mod:`sklearn.ensemble` module, is not technically a manifold embedding method, as it learn a high-dimensional representation on which we apply a dimensionality reduction method. However, it is often useful to cast a dataset into a representation in which the classes are linearly-separable. t-SNE will be initialized with the embedding that is generated by PCA in this example, which is not the default setting. It ensures global stability of the embedding, i.e., the embedding does not depend on random initialization. """ # Authors: Fabian Pedregosa <fabian.pedregosa@inria.fr> # Olivier Grisel <olivier.grisel@ensta.org> # Mathieu Blondel <mathieu@mblondel.org> # Gael Varoquaux # License: BSD 3 clause (C) INRIA 2011 print(__doc__) from time import time import numpy as np import matplotlib.pyplot as plt from matplotlib import offsetbox from sklearn import (manifold, datasets, decomposition, ensemble, lda, random_projection) digits = datasets.load_digits(n_class=6) X = digits.data y = digits.target n_samples, n_features = X.shape n_neighbors = 30 #---------------------------------------------------------------------- # Scale and visualize the embedding vectors def plot_embedding(X, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(digits.target[i]), color=plt.cm.Set1(y[i] / 10.), fontdict={'weight': 'bold', 'size': 9}) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(digits.data.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 4e-3: # don't show points that are too close continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title) #---------------------------------------------------------------------- # Plot images of the digits n_img_per_row = 20 img = np.zeros((10 * n_img_per_row, 10 * n_img_per_row)) for i in range(n_img_per_row): ix = 10 * i + 1 for j in range(n_img_per_row): iy = 10 * j + 1 img[ix:ix + 8, iy:iy + 8] = X[i * n_img_per_row + j].reshape((8, 8)) plt.imshow(img, cmap=plt.cm.binary) plt.xticks([]) plt.yticks([]) plt.title('A selection from the 64-dimensional digits dataset') #---------------------------------------------------------------------- # Random 2D projection using a random unitary matrix print("Computing random projection") rp = random_projection.SparseRandomProjection(n_components=2, random_state=42) X_projected = rp.fit_transform(X) plot_embedding(X_projected, "Random Projection of the digits") #---------------------------------------------------------------------- # Projection on to the first 2 principal components print("Computing PCA projection") t0 = time() X_pca = decomposition.TruncatedSVD(n_components=2).fit_transform(X) plot_embedding(X_pca, "Principal Components projection of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # Projection on to the first 2 linear discriminant components print("Computing Linear Discriminant Analysis projection") X2 = X.copy() X2.flat[::X.shape[1] + 1] += 0.01 # Make X invertible t0 = time() X_lda = discriminant_analysis.LinearDiscriminantAnalysis(n_components=2).fit_transform(X2, y) plot_embedding(X_lda, "Linear Discriminant projection of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # Isomap projection of the digits dataset print("Computing Isomap embedding") t0 = time() X_iso = manifold.Isomap(n_neighbors, n_components=2).fit_transform(X) print("Done.") plot_embedding(X_iso, "Isomap projection of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # Locally linear embedding of the digits dataset print("Computing LLE embedding") clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='standard') t0 = time() X_lle = clf.fit_transform(X) print("Done. Reconstruction error: %g" % clf.reconstruction_error_) plot_embedding(X_lle, "Locally Linear Embedding of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # Modified Locally linear embedding of the digits dataset print("Computing modified LLE embedding") clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='modified') t0 = time() X_mlle = clf.fit_transform(X) print("Done. Reconstruction error: %g" % clf.reconstruction_error_) plot_embedding(X_mlle, "Modified Locally Linear Embedding of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # HLLE embedding of the digits dataset print("Computing Hessian LLE embedding") clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='hessian') t0 = time() X_hlle = clf.fit_transform(X) print("Done. Reconstruction error: %g" % clf.reconstruction_error_) plot_embedding(X_hlle, "Hessian Locally Linear Embedding of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # LTSA embedding of the digits dataset print("Computing LTSA embedding") clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='ltsa') t0 = time() X_ltsa = clf.fit_transform(X) print("Done. Reconstruction error: %g" % clf.reconstruction_error_) plot_embedding(X_ltsa, "Local Tangent Space Alignment of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # MDS embedding of the digits dataset print("Computing MDS embedding") clf = manifold.MDS(n_components=2, n_init=1, max_iter=100) t0 = time() X_mds = clf.fit_transform(X) print("Done. Stress: %f" % clf.stress_) plot_embedding(X_mds, "MDS embedding of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # Random Trees embedding of the digits dataset print("Computing Totally Random Trees embedding") hasher = ensemble.RandomTreesEmbedding(n_estimators=200, random_state=0, max_depth=5) t0 = time() X_transformed = hasher.fit_transform(X) pca = decomposition.TruncatedSVD(n_components=2) X_reduced = pca.fit_transform(X_transformed) plot_embedding(X_reduced, "Random forest embedding of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # Spectral embedding of the digits dataset print("Computing Spectral embedding") embedder = manifold.SpectralEmbedding(n_components=2, random_state=0, eigen_solver="arpack") t0 = time() X_se = embedder.fit_transform(X) plot_embedding(X_se, "Spectral embedding of the digits (time %.2fs)" % (time() - t0)) #---------------------------------------------------------------------- # t-SNE embedding of the digits dataset print("Computing t-SNE embedding") tsne = manifold.TSNE(n_components=2, init='pca', random_state=0) t0 = time() X_tsne = tsne.fit_transform(X) plot_embedding(X_tsne, "t-SNE embedding of the digits (time %.2fs)" % (time() - t0)) plt.show()
bsd-3-clause
40223250/w16b_test
static/Brython3.1.1-20150328-091302/Lib/unittest/result.py
727
6397
"""Test result object""" import io import sys import traceback from . import util from functools import wraps __unittest = True def failfast(method): @wraps(method) def inner(self, *args, **kw): if getattr(self, 'failfast', False): self.stop() return method(self, *args, **kw) return inner STDOUT_LINE = '\nStdout:\n%s' STDERR_LINE = '\nStderr:\n%s' class TestResult(object): """Holder for test result information. Test results are automatically managed by the TestCase and TestSuite classes, and do not need to be explicitly manipulated by writers of tests. Each instance holds the total number of tests run, and collections of failures and errors that occurred among those test runs. The collections contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred. """ _previousTestClass = None _testRunEntered = False _moduleSetUpFailed = False def __init__(self, stream=None, descriptions=None, verbosity=None): self.failfast = False self.failures = [] self.errors = [] self.testsRun = 0 self.skipped = [] self.expectedFailures = [] self.unexpectedSuccesses = [] self.shouldStop = False self.buffer = False self._stdout_buffer = None self._stderr_buffer = None self._original_stdout = sys.stdout self._original_stderr = sys.stderr self._mirrorOutput = False def printErrors(self): "Called by TestRunner after test run" #fixme brython pass def startTest(self, test): "Called when the given test is about to be run" self.testsRun += 1 self._mirrorOutput = False self._setupStdout() def _setupStdout(self): if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = io.StringIO() self._stdout_buffer = io.StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def startTestRun(self): """Called once before any tests are executed. See startTest for a method called before each test. """ def stopTest(self, test): """Called when the given test has been run""" self._restoreStdout() self._mirrorOutput = False def _restoreStdout(self): if self.buffer: if self._mirrorOutput: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def stopTestRun(self): """Called once after all tests are executed. See stopTest for a method called after each test. """ @failfast def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ self.errors.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True @failfast def addFailure(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().""" self.failures.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True def addSuccess(self, test): "Called when a test has completed successfully" pass def addSkip(self, test, reason): """Called when a test is skipped.""" self.skipped.append((test, reason)) def addExpectedFailure(self, test, err): """Called when an expected failure/error occured.""" self.expectedFailures.append( (test, self._exc_info_to_string(err, test))) @failfast def addUnexpectedSuccess(self, test): """Called when a test was expected to fail, but succeed.""" self.unexpectedSuccesses.append(test) def wasSuccessful(self): "Tells whether or not this result was a success" return len(self.failures) == len(self.errors) == 0 def stop(self): "Indicates that the tests should be aborted" self.shouldStop = True def _exc_info_to_string(self, err, test): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next if exctype is test.failureException: # Skip assert*() traceback levels length = self._count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, length) else: msgLines = traceback.format_exception(exctype, value, tb) if self.buffer: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' msgLines.append(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' msgLines.append(STDERR_LINE % error) return ''.join(msgLines) def _is_relevant_tb_level(self, tb): #fix me brython #return '__unittest' in tb.tb_frame.f_globals return True #for now, lets just return False def _count_relevant_tb_levels(self, tb): length = 0 while tb and not self._is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length def __repr__(self): return ("<%s run=%i errors=%i failures=%i>" % (util.strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures)))
agpl-3.0
ezequielfreire007/proyectoIonic
mypiano/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py
2767
2174
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Applies a fix to CR LF TAB handling in xml.dom. Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293 Working around this: http://bugs.python.org/issue5752 TODO(bradnelson): Consider dropping this when we drop XP support. """ import xml.dom.minidom def _Replacement_write_data(writer, data, is_attrib=False): """Writes datachars to writer.""" data = data.replace("&", "&amp;").replace("<", "&lt;") data = data.replace("\"", "&quot;").replace(">", "&gt;") if is_attrib: data = data.replace( "\r", "&#xD;").replace( "\n", "&#xA;").replace( "\t", "&#x9;") writer.write(data) def _Replacement_writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() a_names = attrs.keys() a_names.sort() for a_name in a_names: writer.write(" %s=\"" % a_name) _Replacement_write_data(writer, attrs[a_name].value, is_attrib=True) writer.write("\"") if self.childNodes: writer.write(">%s" % newl) for node in self.childNodes: node.writexml(writer, indent + addindent, addindent, newl) writer.write("%s</%s>%s" % (indent, self.tagName, newl)) else: writer.write("/>%s" % newl) class XmlFix(object): """Object to manage temporary patching of xml.dom.minidom.""" def __init__(self): # Preserve current xml.dom.minidom functions. self.write_data = xml.dom.minidom._write_data self.writexml = xml.dom.minidom.Element.writexml # Inject replacement versions of a function and a method. xml.dom.minidom._write_data = _Replacement_write_data xml.dom.minidom.Element.writexml = _Replacement_writexml def Cleanup(self): if self.write_data: xml.dom.minidom._write_data = self.write_data xml.dom.minidom.Element.writexml = self.writexml self.write_data = None def __del__(self): self.Cleanup()
mit
smart-developerr/my-first-blog
Lib/site-packages/django/utils/text.py
52
14636
from __future__ import unicode_literals import re import unicodedata from gzip import GzipFile from io import BytesIO from django.utils import six from django.utils.encoding import force_text from django.utils.functional import SimpleLazyObject, keep_lazy, keep_lazy_text from django.utils.safestring import SafeText, mark_safe from django.utils.six.moves import html_entities from django.utils.translation import pgettext, ugettext as _, ugettext_lazy if six.PY2: # Import force_unicode even though this module doesn't use it, because some # people rely on it being here. from django.utils.encoding import force_unicode # NOQA # Capitalizes the first letter of a string. def capfirst(x): return x and force_text(x)[0].upper() + force_text(x)[1:] capfirst = keep_lazy_text(capfirst) # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S) re_chars = re.compile(r'<.*?>|(.)', re.U | re.S) re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))') @keep_lazy_text def wrap(text, width): """ A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. All white space is preserved except added line breaks consume the space on which they break the line. Long words are not wrapped, so the output text may have lines longer than ``width``. """ text = force_text(text) def _generator(): for line in text.splitlines(True): # True keeps trailing linebreaks max_width = min((line.endswith('\n') and width + 1 or width), width) while len(line) > max_width: space = line[:max_width + 1].rfind(' ') + 1 if space == 0: space = line.find(' ') + 1 if space == 0: yield line line = '' break yield '%s\n' % line[:space - 1] line = line[space:] max_width = min((line.endswith('\n') and width + 1 or width), width) if line: yield line return ''.join(_generator()) class Truncator(SimpleLazyObject): """ An object used to truncate text, either by characters or words. """ def __init__(self, text): super(Truncator, self).__init__(lambda: force_text(text)) def add_truncation_text(self, text, truncate=None): if truncate is None: truncate = pgettext( 'String to return when truncating text', '%(truncated_text)s...') truncate = force_text(truncate) if '%(truncated_text)s' in truncate: return truncate % {'truncated_text': text} # The truncation text didn't contain the %(truncated_text)s string # replacement argument so just append it to the text. if text.endswith(truncate): # But don't append the truncation text if the current text already # ends in this. return text return '%s%s' % (text, truncate) def chars(self, num, truncate=None, html=False): """ Returns the text truncated to be no longer than the specified number of characters. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to a translatable string of an ellipsis (...). """ self._setup() length = int(num) text = unicodedata.normalize('NFC', self._wrapped) # Calculate the length to truncate to (max length - end_text length) truncate_len = length for char in self.add_truncation_text('', truncate): if not unicodedata.combining(char): truncate_len -= 1 if truncate_len == 0: break if html: return self._truncate_html(length, truncate, text, truncate_len, False) return self._text_chars(length, truncate, text, truncate_len) def _text_chars(self, length, truncate, text, truncate_len): """ Truncates a string after a certain number of chars. """ s_len = 0 end_index = None for i, char in enumerate(text): if unicodedata.combining(char): # Don't consider combining characters # as adding to the string length continue s_len += 1 if end_index is None and s_len > truncate_len: end_index = i if s_len > length: # Return the truncated string return self.add_truncation_text(text[:end_index or 0], truncate) # Return the original string since no truncation was necessary return text def words(self, num, truncate=None, html=False): """ Truncates a string after a certain number of words. Takes an optional argument of what should be used to notify that the string has been truncated, defaulting to ellipsis (...). """ self._setup() length = int(num) if html: return self._truncate_html(length, truncate, self._wrapped, length, True) return self._text_words(length, truncate) def _text_words(self, length, truncate): """ Truncates a string after a certain number of words. Newlines in the string will be stripped. """ words = self._wrapped.split() if len(words) > length: words = words[:length] return self.add_truncation_text(' '.join(words), truncate) return ' '.join(words) def _truncate_html(self, length, truncate, text, truncate_len, words): """ Truncates HTML to a certain number of chars (not counting tags and comments), or, if words is True, then to a certain number of words. Closes opened tags if they were correctly closed in the given HTML. Newlines in the HTML are preserved. """ if words and length <= 0: return '' html4_singlets = ( 'br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input' ) # Count non-HTML chars/words and keep note of open tags pos = 0 end_text_pos = 0 current_len = 0 open_tags = [] regex = re_words if words else re_chars while current_len <= length: m = regex.search(text, pos) if not m: # Checked through whole string break pos = m.end(0) if m.group(1): # It's an actual non-HTML word or char current_len += 1 if current_len == truncate_len: end_text_pos = pos continue # Check for tag tag = re_tag.match(m.group(0)) if not tag or current_len >= truncate_len: # Don't worry about non tags or tags after our truncate point continue closing_tag, tagname, self_closing = tag.groups() # Element names are always case-insensitive tagname = tagname.lower() if self_closing or tagname in html4_singlets: pass elif closing_tag: # Check for match in open tags list try: i = open_tags.index(tagname) except ValueError: pass else: # SGML: An end tag closes, back to the matching start tag, # all unclosed intervening start tags with omitted end tags open_tags = open_tags[i + 1:] else: # Add it to the start of the open tags list open_tags.insert(0, tagname) if current_len <= length: return text out = text[:end_text_pos] truncate_text = self.add_truncation_text('', truncate) if truncate_text: out += truncate_text # Close any tags still open for tag in open_tags: out += '</%s>' % tag # Return string return out @keep_lazy_text def get_valid_filename(s): """ Returns the given string converted to a string that can be used for a clean filename. Specifically, leading and trailing spaces are removed; other spaces are converted to underscores; and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' """ s = force_text(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s) @keep_lazy_text def get_text_list(list_, last_word=ugettext_lazy('or')): """ >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' """ if len(list_) == 0: return '' if len(list_) == 1: return force_text(list_[0]) return '%s %s %s' % ( # Translators: This string is used as a separator between list elements _(', ').join(force_text(i) for i in list_[:-1]), force_text(last_word), force_text(list_[-1])) @keep_lazy_text def normalize_newlines(text): """Normalizes CRLF and CR newlines to just LF.""" text = force_text(text) return re_newlines.sub('\n', text) @keep_lazy_text def phone2numeric(phone): """Converts a phone number with letters into its numeric equivalent.""" char2number = { 'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9', } return ''.join(char2number.get(c, c) for c in phone.lower()) # From http://www.xhaus.com/alan/python/httpcomp.html#gzip # Used with permission. def compress_string(s): zbuf = BytesIO() zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf) zfile.write(s) zfile.close() return zbuf.getvalue() class StreamingBuffer(object): def __init__(self): self.vals = [] def write(self, val): self.vals.append(val) def read(self): if not self.vals: return b'' ret = b''.join(self.vals) self.vals = [] return ret def flush(self): return def close(self): return # Like compress_string, but for iterators of strings. def compress_sequence(sequence): buf = StreamingBuffer() zfile = GzipFile(mode='wb', compresslevel=6, fileobj=buf) # Output headers... yield buf.read() for item in sequence: zfile.write(item) data = buf.read() if data: yield data zfile.close() yield buf.read() # Expression to match some_token and some_token="with spaces" (and similarly # for single-quoted strings). smart_split_re = re.compile(r""" ((?: [^\s'"]* (?: (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*') [^\s'"]* )+ ) | \S+) """, re.VERBOSE) def smart_split(text): r""" Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped (the results can then be further processed with unescape_string_literal()). >>> list(smart_split(r'This is "a person\'s" test.')) ['This', 'is', '"a person\\\'s"', 'test.'] >>> list(smart_split(r"Another 'person\'s' test.")) ['Another', "'person\\'s'", 'test.'] >>> list(smart_split(r'A "\"funky\" style" test.')) ['A', '"\\"funky\\" style"', 'test.'] """ text = force_text(text) for bit in smart_split_re.finditer(text): yield bit.group(0) def _replace_entity(match): text = match.group(1) if text[0] == '#': text = text[1:] try: if text[0] in 'xX': c = int(text[1:], 16) else: c = int(text) return six.unichr(c) except ValueError: return match.group(0) else: try: return six.unichr(html_entities.name2codepoint[text]) except (ValueError, KeyError): return match.group(0) _entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));") @keep_lazy_text def unescape_entities(text): return _entity_re.sub(_replace_entity, force_text(text)) @keep_lazy_text def unescape_string_literal(s): r""" Convert quoted string literals to unquoted strings with escaped quotes and backslashes unquoted:: >>> unescape_string_literal('"abc"') 'abc' >>> unescape_string_literal("'abc'") 'abc' >>> unescape_string_literal('"a \"bc\""') 'a "bc"' >>> unescape_string_literal("'\'ab\' c'") "'ab' c" """ if s[0] not in "\"'" or s[-1] != s[0]: raise ValueError("Not a string literal: %r" % s) quote = s[0] return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\') @keep_lazy(six.text_type, SafeText) def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. """ value = force_text(value) if allow_unicode: value = unicodedata.normalize('NFKC', value) value = re.sub('[^\w\s-]', '', value, flags=re.U).strip().lower() return mark_safe(re.sub('[-\s]+', '-', value, flags=re.U)) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub('[^\w\s-]', '', value).strip().lower() return mark_safe(re.sub('[-\s]+', '-', value)) def camel_case_to_spaces(value): """ Splits CamelCase and converts to lower case. Also strips leading and trailing whitespace. """ return re_camel_case.sub(r' \1', value).strip().lower()
gpl-3.0
msotov/SPECIES
PhotometricRelations_class.py
1
51670
from __future__ import print_function from __future__ import division from builtins import str from builtins import zip from builtins import range from dataclasses import dataclass, field from typing import List import warnings import numpy as np from astroquery.vizier import Vizier from astropy import units as u from astropy.coordinates import SkyCoord import shapely.geometry as geom from scipy import interpolate from uncertainties import ufloat, unumpy import mwdust warnings.simplefilter("ignore") @dataclass class Quantity: name: str value: float = np.nan error: float = np.nan source: str = 'unknown' def setval(self, v, e, s, condition=True): if hasattr(v, 'value'): if ~np.isnan(float(v.value)) and ~np.isnan(float(e.value)) and condition: self.value = v self.error = e self.source = s else: if ~np.isnan(float(v)) and ~np.isnan(float(e)) and condition: self.value = v self.error = e self.source = s @property def isvalid(self): return self.source != 'unknown' def totuple(self): return [self.value, self.error, self.source] @dataclass class Magnitude(Quantity): pfilter: str = 'unknown' Av: float = 0.0 def setmag(self, v, e, s, f, condition=True): self.setval(v, max(e, 0.01), s, condition=condition) if ~np.isnan(self.value): self.pfilter = f def totuplemag(self): return self.totuple()+[self.pfilter, self.Av] def setAv(self, v): if ~np.isnan(self.value) and ~np.isnan(float(v)) and (v >= 0.0): self.Av = v _magnitudes = ['V', 'B', 'Bt', 'Vt', 'J', 'H', 'K', 'b', 'y', 'm1', 'c1',\ 'G', 'W1', 'W2', 'W3', 'R', 'I', 'BP', 'RP', 'E_BPRP'] def _make_mag_list(): return [Magnitude(s) for s in _magnitudes] def _make_coord_list(): return [Quantity('RA'), Quantity('DEC')] def _make_proper_motion_list(): return [Quantity('pmRA'), Quantity('pmDEC')] @dataclass class Star: name: str magnitudes: List[Magnitude] = field(default_factory=_make_mag_list) coordinates: List[Quantity] = field(default_factory=_make_coord_list) propermotion: List[Quantity] = field(default_factory=_make_proper_motion_list) parallax: Quantity = Quantity('Parallax') galactic_coords: List[float] = field(default_factory=list) def getmag(self, mag): return self.magnitudes[_magnitudes.index(mag)] def getmags(self, mags): return [self.getmag(m) for m in mags] @property def validmags(self): return [self.getmag(m).name for m in _magnitudes if self.getmag(m).isvalid] def change_coords(self, ra, dec, s): [RA, DEC] = self.coordinates RA.setval(ra, 0.0, s) DEC.setval(dec, 0.0, s) def change_propermotion(self, pmra, pmdec, err_ra, err_dec, s): if ~np.isnan(pmra) and ~np.isnan(pmdec) and ~np.isnan(err_ra) and ~np.isnan(err_dec): pmRA, pmDEC = self.propermotion pmRA.setval(pmra, err_ra, s) pmDEC.setval(pmdec, err_dec, s) def todict(self): d = {'name': self.name} if all([c.isvalid for c in self.coordinates]): d['RA'] = [self.coordinates[0].value, self.coordinates[0].source] d['DEC'] = [self.coordinates[1].value, self.coordinates[1].source] if all([c.isvalid for c in self.propermotion]): d['pmRA'] = self.propermotion[0].totuple() d['pmDEC'] = self.propermotion[1].totuple() if self.parallax.isvalid: d['parallax'] = self.parallax.totuple() valid = self.validmags for v in valid: d[v] = self.getmag(v).totuplemag() if self.galactic_coords: d['galactic_coords'] = self.galactic_coords return d def search_catalog_name(starname, vizier_object, catlist, catname): def _look_r(starname, catname, catlist, rlist, restrict=False): for r in rlist: result = vizier_object.query_object(starname, catalog=[catname], radius=r*u.arcsec) if str(result) != 'Empty TableList': if restrict: p = result[0]['Plx'] if any(p >= 2.0): catlist.append(result) break else: catlist.append(result) break return catlist if catname == "I/345/gaia2": catlist = _look_r(starname, catname, catlist, [15., 25., 50.], restrict=True) elif catname == "I/284/out": catlist = _look_r(starname, catname, catlist, [10., 20.]) elif catname == "I/311/hip2": catlist = _look_r(starname, catname, catlist, [5., 10., 20., 30.]) else: catlist = _look_r(starname, catname, catlist, [5., 10., 20., 30., 50.]) return catlist def search_catalog_coords(RA, DEC, vizier_object, catlist, catname): def _look_r(C, catname, catlist, rlist, restrict=False): for r in rlist: result = vizier_object.query_region(SkyCoord(ra=C[0], dec=C[1], unit=(u.deg, u.deg), frame='icrs'),\ width=r, catalog=[catname]) if str(result) != 'Empty TableList': if restrict: p = result[0]['Plx'] if any(p >= 2.0): catlist.append(result) break else: catlist.append(result) break return catlist if catname == "I/345/gaia2": catlist = _look_r([RA, DEC], catname, catlist, ['15s', '25s', '50s'], restrict=True) elif catname == "I/284/out": catlist = _look_r([RA, DEC], catname, catlist, ['10s', '20s']) elif catname == "I/311/hip2": catlist = _look_r([RA, DEC], catname, catlist, ['5s', '10s', '20s', '30s']) else: catlist = _look_r([RA, DEC], catname, catlist, ['5s', '10s', '20s', '30s', '50s']) return catlist def retrieve_catalogs(starname, vizier_object, use_coords=False, RA=None, DEC=None): result = [] catalogues = ["II/246/out", "I/311/hip2", "I/259/tyc2", "J/MNRAS/373/13/table1", "J/ApJS/168/128/survey", "II/215/catalog", "V/130/gcs3", "J/MNRAS/403/1949/ubvri", "I/337/tgas", "II/237/colors", "I/345/gaia2", "II/336/apass9", "I/284/out", "II/328/allwise"] if use_coords: for c in catalogues: result = search_catalog_coords(RA, DEC, vizier_object, result, c) else: starname = starname.replace('A', '').replace('-', ' ').replace('_', ' ') for c in catalogues: result = search_catalog_name(starname, vizier_object, result, c) return result def vizier_params(starname, use_coords=False, RA=None, DEC=None): star = Star(starname) V, B, Bt, Vt, J, H, K, b, y, m1, c1, G, W1, W2, W3, R, I, BP, RP, E_BPRP = star.getmags(_magnitudes) if use_coords: star.change_coords(RA, DEC, "from user or fits header") try: e_hpmag = 0.01 v = Vizier(columns=["**"]) result = retrieve_catalogs(starname, v, use_coords, RA, DEC) if result: if len(result[0][0].columns) < 5: v = Vizier(columns=["*"]) result = retrieve_catalogs(starname, v, use_coords, RA, DEC) name_cats = [list(r.keys())[0] for r in result] # 2MASS if "II/246/out" in name_cats: r = result[name_cats.index("II/246/out")][0] if len(r['Jmag']) > 1: nA = np.zeros(len(r['Qflg'])) for k, q in enumerate(r['Qflg']): nA[k] = q.count('A') maxA = np.argmax(nA) else: maxA = 0 if r['Qflg'][maxA].count('U') == 0: J.setmag(r['Jmag'][maxA], r['e_Jmag'][maxA], "II/246/out", '2MASS J',\ condition=r['Qflg'][maxA][0] != 'U') H.setmag(r['Hmag'][maxA], r['e_Hmag'][maxA], "II/246/out", '2MASS H',\ condition=r['Qflg'][maxA][1] != 'U') K.setmag(r['Kmag'][maxA], r['e_Kmag'][maxA], "II/246/out", '2MASS Ks',\ condition=r['Qflg'][maxA][2] != 'U') star.change_coords(r['RAJ2000'][maxA], r['DEJ2000'][maxA], "II/246/out") # GAIA DR2 if "I/345/gaia2" in name_cats: r = result[name_cats.index("I/345/gaia2")][0] i2 = np.where(r['Teff'] > 0.0)[0] if len(r['Plx'][i2]) >= 1: if len(r['Plx'][i2]) > 1: i0 = np.where(r['Plx'][i2] > 2.0)[0] if len(i0) > 1: iav0 = np.where(np.abs(r['RV'][i2][i0]) > 0.0)[0] if len(iav0) > 1: itemp = np.argmax(r['Teff'][i2][i0[iav0]]) i0 = int(i0[iav0[itemp]]) elif len(iav0) == 1: i0 = int(i0[iav0]) else: i0 = int(i0[0]) elif len(i0) == 1: i0 = int(i0[0]) else: i0 = 0 else: i0 = 0 if r['Plx'][i2][i0] > 2.0: star.parallax.setval(r['Plx'][i2][i0]*u.mas, r['e_Plx'][i2][i0]*u.mas, "I/345/gaia2") star.change_coords(r['RA_ICRS'][i2][i0], r['DE_ICRS'][i2][i0], "I/345/gaia2") G.setmag(r['Gmag'][i2][i0], r['e_Gmag'][i2][i0], "I/345/gaia2", "GAIA G") G.setAv(r['AG'][i2][i0]) star.change_propermotion(r['pmRA'][i2][i0], r['pmDE'][i2][i0], r['e_pmRA'][i2][i0], r['e_pmDE'][i2][i0], "I/345/gaia2") BP.setmag(r['BPmag'][i2][i0], r['e_BPmag'][i2][i0], "I/345/gaia2", "GAIA BP") RP.setmag(r['RPmag'][i2][i0], r['e_RPmag'][i2][i0], "I/345/gaia2", "GAIA RP") E_BPRP.setmag(r['E_BP-RP_'][i2][i0], 0.1, "I/345/gaia2", "GAIA E(BP-RP)") elif r['Plx'][0] > 2.0: star.parallax.setval(r['Plx'][0]*u.mas, r['e_Plx'][0]*u.mas, "I/345/gaia2", condition=r['Plx'][0] > 0.0) star.change_coords(r['RA_ICRS'][0], r['DE_ICRS'][0], "I/345/gaia2") G.setmag(r['Gmag'][0], r['e_Gmag'][0], "I/345/gaia2", "GAIA G") G.setAv(r['AG'][0]) star.change_propermotion(r['pmRA'][0], r['pmDE'][0], r['e_pmRA'][0], r['e_pmDE'][0], "I/345/gaia2") BP.setmag(r['BPmag'][0], r['e_BPmag'][0], "I/345/gaia2", "GAIA BP") RP.setmag(r['RPmag'][0], r['e_RPmag'][0], "I/345/gaia2", "GAIA RP") E_BPRP.setmag(r['E_BP-RP_'][0], 0.1, "I/345/gaia2", "GAIA E(BP-RP)") # Correct for the systematic from Stassun & Torres 2018 if star.parallax.isvalid: plx_corr = ufloat(star.parallax.value.value, star.parallax.error.value)\ + ufloat(82, 33)*1e-3 star.parallax.setval(plx_corr.n*u.mas, plx_corr.s*u.mas, "I/345/gaia2") # GAIA elif "I/337/tgas" in name_cats: r = result[name_cats.index("I/337/tgas")][0] star.parallax.setval(r['Plx'][0]*u.mas, r['e_Plx'][0]*u.mas, "I/337/tgas", condition=r['Plx'][0] > 0.0) star.change_coords(r['RA_ICRS'][0], r['DE_ICRS'][0], "I/337/tgas") # HIPPARCOS if ("I/311/hip2" in name_cats) and (not star.parallax.isvalid): r = result[name_cats.index("I/311/hip2")][0] star.parallax.setval(r['Plx'][0]*u.mas, r['e_Plx'][0]*u.mas, "I/311/hip2", condition=r['Plx'][0] > 0.0) star.change_coords(r['RArad'][0], r['DErad'][0], "I/311/hip2") if all([c.isvalid is False for c in star.propermotion]): star.change_propermotion(r['pmRA'][0], r['pmDE'][0], r['e_pmRA'][0], r['e_pmDE'][0], "I/311/hip2") e_hpmag = r['e_Hpmag'][0] if r['e_Hpmag'][0] != 0.0 else 0.01 # USNO-B1.0 (Monet+ 2003) for proper motions if "I/284/out" in name_cats: r = result[name_cats.index("I/284/out")][0] if all([c.isvalid is False for c in star.propermotion]): star.change_propermotion(r['pmRA'][0], r['pmDE'][0], r['e_pmRA'][0], r['e_pmDE'][0], "I/284/out") # WISE if "II/328/allwise" in name_cats: r = result[name_cats.index("II/328/allwise")][0] if len(r['qph']) > 1: counts = np.zeros(len(r['qph'])) flag_vals = {'A':6, 'B':5, 'C':4, 'U':3, 'X':2, 'Z':1} for q, q_val in enumerate(r['qph']): counts[q] = sum([flag_vals[l]*q_val.count(l) for l in flag_vals]) i0 = np.argmax(counts) del counts else: i0 = 0 if all([~np.isnan(float(r['e_%smag' % k][i0])) for k in ['W1', 'W2', 'W3']]): W1.setmag(r['W1mag'][i0], r['e_W1mag'][i0], "II/328/allwise", 'WISE-1') W2.setmag(r['W2mag'][i0], r['e_W2mag'][i0], "II/328/allwise", 'WISE-2') W3.setmag(r['W3mag'][i0], r['e_W3mag'][i0], "II/328/allwise", 'WISE-3') # The Tycho-2 Catalogue (Hog+ 2000) if "I/259/tyc2" in name_cats: r = result[name_cats.index("I/259/tyc2")][0] Bt.setmag(r['BTmag'][0], r['e_BTmag'][0], "I/259/tyc2", 'HIPPARCOS BT') Vt.setmag(r['VTmag'][0], r['e_VTmag'][0], "I/259/tyc2", 'HIPPARCOS VT') star.change_coords(r['RA_ICRS_'][0], r['DE_ICRS_'][0], "I/259/tyc2") # Koen et al. 2010 if "J/MNRAS/403/1949/ubvri" in name_cats: r = result[name_cats.index("J/MNRAS/403/1949/ubvri")][0] V.setmag(r['Vmag'][0], 0.01, "J/MNRAS/403/1949/ubvri", 'Landolt V') B.setmag(r['B-V'][0] + r['Vmag'][0], 0.01, "J/MNRAS/403/1949/ubvri", 'Landolt B') R.setmag(r['Vmag'][0] - r['V-Rc'][0], 0.01, "J/MNRAS/403/1949/ubvri", 'Landolt R') I.setmag(r['Vmag'][0] - r['V-Ic'][0], 0.01, "J/MNRAS/403/1949/ubvri", 'Landolt I') else: # Casagrande et al. 2006 if "J/MNRAS/373/13/table1" in name_cats: r = result[name_cats.index("J/MNRAS/373/13/table1")][0] V.setmag(r['Vmag'][0], 0.01, "J/MNRAS/373/13/table1", 'Landolt V') B.setmag(r['B-V'][0] + r['Vmag'][0], 0.01, "J/MNRAS/373/13/table1", 'Landolt B') R.setmag(r['Vmag'][0] - r['V-Rc'][0], 0.01, "J/MNRAS/373/13/table1", 'Landolt R') I.setmag(r['Vmag'][0] - r['V-Rc'][0] - r['R-Ic'][0], 0.01, "J/MNRAS/373/13/table1", 'Landolt I') J.setmag(r['Jmag'][0], r['e_Jmag'][0], "J/MNRAS/373/13/table1", '2MASS J') H.setmag(r['Hmag'][0], r['e_Hmag'][0], "J/MNRAS/373/13/table1", '2MASS H') K.setmag(r['Ksmag'][0], r['e_Ksmag'][0], "J/MNRAS/373/13/table1", '2MASS Ks') if not star.parallax.isvalid: star.parallax.setval(r['Plx'][0]*u.mas, r['e_Plx'][0]*u.mas, "J/MNRAS/373/13/table1", condition=r['Plx'][0] > 0.0) # Beers et al. 2007 elif "J/ApJS/168/128/survey" in name_cats: r = result[name_cats.index("J/ApJS/168/128/survey")][0] V.setmag(r['Vmag'][0], r['e_Vmag'][0], "J/ApJS/168/128/survey", 'Landolt V') B.setmag(r['B-V'][0] + r['Vmag'][0], np.sqrt(r['e_Vmag'][0]**2 + r['e_B-V'][0]**2), "J/ApJS/168/128/survey", 'Landolt B') R.setmag(r['Vmag'][0] - r['V-Rc'][0], np.sqrt(r['e_Vmag'][0]**2. + r['e_V-Rc'][0]**2.), "J/ApJS/168/128/survey", 'Landolt R') I.setmag(r['Vmag'][0] - r['V-Ic'][0], np.sqrt(r['e_Vmag'][0]**2. + r['e_V-Ic'][0]**2.), "J/ApJS/168/128/survey", 'Landolt I') J.setmag(r['Jmag'][0], r['e_Jmag'][0], "J/ApJS/168/128/survey", '2MASS J') H.setmag(r['Hmag'][0], r['e_Hmag'][0], "J/ApJS/168/128/survey", '2MASS H') K.setmag(r['Ksmag'][0], r['e_Ksmag'][0], "J/ApJS/168/128/survey", '2MASS Ks') # HAUCK if "II/215/catalog" in name_cats: r = result[name_cats.index("II/215/catalog")][0] if not V.isvalid: V.setmag(r['Vmag'][0], r['e_Vmag'][0], "II/215/catalog", 'Landolt V') b.setmag(r['b-y'][0], r['e_b-y'][0], "II/215/catalog", 'Stromgren b') y.setmag(0., r['e_b-y'][0], "II/215/catalog", 'Stromgren y') m1.setmag(r['m1'][0], r['e_m1'][0], "II/215/catalog", 'f') c1.setmag(r['c1'][0], r['e_c1'][0], "II/215/catalog", 'f') else: # GENEVA if "V/130/gcs3" in name_cats: r = result[name_cats.index("V/130/gcs3")][0] if not V.isvalid: V.setmag(r['Vmag'][0], 0.01, "V/130/gcs3", 'Landolt V') b.setmag(r['b-y'][0], 0.01, "V/130/gcs3", 'Stromgren b') y.setmag(0., e_hpmag, "V/130/gcs3", 'Stromgren y') m1.setmag(r['m1'][0], 0.01, "V/130/gcs3", 'f') c1.setmag(r['c1'][0], 0.01, "V/130/gcs3", 'f') if all([not M.isvalid for M in [R, I, V, B]]) or\ any([M.error > 0.2 for M in [J, H, K]]) or\ all([not M.isvalid for M in [R, I, B]]): # Ducati 2002 if "II/237/colors" in name_cats: r = result[name_cats.index("II/237/colors")][0] V.setmag(r['Vmag'][0], e_hpmag, "II/237/colors", 'Landolt V') B.setmag(r['B-V'][0] + r['Vmag'][0], 0.01, "II/237/colors", 'Landolt B') R.setmag(r['R-V'][0] + r['Vmag'][0], 0.01, "II/237/colors", 'Landolt R') I.setmag(r['I-V'][0] + r['Vmag'][0], 0.01, "II/237/colors", 'Landolt I') if any([M.error > 0.2 for M in [J, H, K]]): J.setmag(r['J-V'][0] + r['Vmag'][0], r['Jsig'][0]*1e-2, "II/237/colors", '2MASS J') H.setmag(r['H-V'][0] + r['Vmag'][0], r['Hsig'][0]*1e-2, "II/237/colors", '2MASS H') K.setmag(r['K-V'][0] + r['Vmag'][0], r['Ksig'][0]*1e-2, "II/237/colors", '2MASS Ks') elif "II/336/apass9" in name_cats: r = result[name_cats.index("II/336/apass9")][0] if Vt.isvalid: V.setmag(r['Vmag'][0], r['e_Vmag'][0], "II/336/apass9", 'Landolt V', condition=np.abs(Vt.value - r['Vmag'][0]) < 0.25) else: V.setmag(r['Vmag'][0], r['e_Vmag'][0], "II/336/apass9", 'Landolt V') if Bt.isvalid: B.setmag(r['Bmag'][0], r['e_Bmag'][0], "II/336/apass9", 'Landolt B', condition=np.abs(Bt.value - r['e_Bmag'][0]) < 0.25) else: B.setmag(r['Bmag'][0], r['e_Bmag'][0], "II/336/apass9", 'Landolt B') del result except Exception as e: print('error', e) # Get galactic coordinates if possible if all([c.isvalid for c in star.coordinates]): ra, dec = star.coordinates l, b = get_galactic_coords(ra, dec) star.galactic_coords = [l, b] photometry = star.todict() photometry = correct_extinction(photometry) del star return photometry #****************************************************************************** #****************************************************************************** def get_galactic_coords(ra, dec): c = SkyCoord(ra=ra.value*u.deg, dec=dec.value*u.deg, frame='icrs') l = c.galactic.l.degree b = c.galactic.b.degree del c return l, b def get_Av(photometry): A_V = 0.0 if 'galactic_coords' in photometry: l, b = photometry['galactic_coords'] if 'parallax' in photometry: p = photometry['parallax'][0] d = p.to(u.pc, equivalencies=u.parallax()).value/1000. # in Kpc ext_map = mwdust.Combined15() else: d = 1. ext_map = mwdust.SFD() A_V = 2.742*ext_map(l, b, d) del ext_map return A_V def correct_extinction(photometry): def _correct_wave(l, b, d, wave, ext_map): if wave in ('HIPPARCOS BT', 'HIPPARCOS VT'): ext_map._filter = 'Landolt B' A_B = ext_map(l, b, d) ext_map._filter = 'Landolt V' A_V = ext_map(l, b, d) # Transform A_wave to the Hipparcos system if wave == 'HIPPARCOS BT': A_wave = 1.090/0.850*(A_B-A_V) + A_V else: A_wave = A_V + 0.090/0.850*(A_B-A_V) else: ext_map._filter = wave A_wave = ext_map(l, b, d) return max(A_wave[0], 0.0) mag = ['B', 'V', 'R', 'I', 'J', 'H', 'K', 'b', 'y', 'Bt', 'Vt', 'W1', 'W2'] if 'galactic_coords' in photometry: l, b = photometry['galactic_coords'] d = 1.0 if 'parallax' in photometry: p = photometry['parallax'][0] d = p.to(u.pc, equivalencies=u.parallax()).value/1000. # in Kpc ext_map = mwdust.Combined15() else: ext_map = mwdust.SFD() for m in mag: if m in photometry: wave = photometry[m][3] A_wave = _correct_wave(l, b, d, wave, ext_map) if not np.isnan(A_wave) and\ (np.isnan(photometry[m][4]) or photometry[m][4] == 0.0): photometry[m][4] = A_wave if 'G' in photometry: ext_map._filter=None E_BV = ext_map(l, b, d)[0] if not np.isnan(E_BV): photometry['G'][4] = max(2.35*E_BV, 0.0) if all([m in photometry for m in ['BP', 'RP', 'E_BPRP', 'G']]): ext_map._filter=None E_BV = ext_map(l, b, d)[0] A0 = 3.1*E_BV G_BVRPm = photometry['BP'][0]-photometry['RP'][0] E_BPRP = photometry['E_BPRP'][0] G_BVRP0 = G_BVRPm-E_BPRP c_BP = [1.1517, -0.0871, -0.0333, 0.0173, -0.0230, 0.0006, 0.0043] c_RP = [0.6104, -0.0170, -0.0026, -0.0017, -0.0078, 0.00005, 0.0006] c_G = [0.9761, -0.1704, 0.0086, 0.0011, -0.0438, 0.0013, 0.0099] def Ax(c1, c2, c3, c4, c5, c6, c7): return c1 + c2*G_BVRP0 + c3*G_BVRP0**2 + c4*G_BVRP0**3 + c5*A0 + c6*A0**2 + c7*G_BVRP0*A0 A_BP = Ax(*c_BP)*A0 A_RP = Ax(*c_RP)*A0 A_G = Ax(*c_G)*A0 photometry['BP'][4] = A_BP photometry['RP'][4] = A_RP #print(photometry['G'][4], A_G, E_BV*2.35) photometry['G'][4] = A_G del ext_map return photometry #****************************************************************************** #****************************************************************************** def stellar_class(photometry): # Intrinsic colors of dwarf and giant stars, for different spectral types. # From Bessell and Brett 1988 JH_dwarfs = np.array([-0.05, 0.0, 0.02, 0.06, 0.09, 0.13, 0.165, 0.23, 0.285, 0.305, 0.32,\ 0.33, 0.37, 0.45, 0.5, 0.58, 0.61, 0.66, 0.695, 0.68, 0.665, 0.62,\ 0.60, 0.62, 0.66]) HK_dwarfs = np.array([-0.035, 0.00, 0.005, 0.015, 0.025, 0.03, 0.035, 0.04, 0.045, 0.05,\ 0.052, 0.055, 0.06, 0.075, 0.09, 0.105, 0.11, 0.13, 0.165, 0.20, 0.21,\ 0.25, 0.275, 0.32, 0.37]) JH_giants = np.array([0.37, 0.47, 0.50, 0.50, 0.54, 0.58, 0.63, 0.68, 0.73, 0.79, 0.83, 0.85,\ 0.87, 0.90, 0.93, 0.95, 0.96, 0.96]) HK_giants = np.array([0.065, 0.08, 0.085, 0.085, 0.095, 0.10, 0.115, 0.14, 0.15, 0.165, 0.19,\ 0.205, 0.215, 0.235, 0.245, 0.285, 0.30, 0.31]) # Cenvert the Bessell and Brett magnitudes to 2mass filters using the # relationships from Carpenter 2001 i_dwarfs = np.where(HK_dwarfs > 0.14)[0] i_giants = np.where(HK_giants > 0.14)[0] JH_dwarfs_2mass = 0.990*JH_dwarfs[i_dwarfs] - 0.049 JH_giants_2mass = 0.990*JH_giants[i_giants] - 0.049 HK_dwarfs_2mass = 1.00*HK_dwarfs[i_dwarfs] + 0.034 HK_giants_2mass = 1.00*HK_giants[i_giants] + 0.034 line_dwarfs = geom.LineString(list(zip(HK_dwarfs_2mass, JH_dwarfs_2mass))) line_giants = geom.LineString(list(zip(HK_giants_2mass, JH_giants_2mass))) sp_class = 'dwarf' # Detect if JHK are present if ('J' in photometry) and ('H' in photometry) and ('K' in photometry): J = photometry['J'][0] - photometry['J'][4] H = photometry['H'][0] - photometry['H'][4] K = photometry['K'][0] - photometry['K'][4] JH = J-H HK = H-K # Compute distance from curves if HK > 0.14: point = geom.Point(HK, JH) d_dwarf = point.distance(line_dwarfs) d_giant = point.distance(line_giants) del point if d_giant < d_dwarf: sp_class = 'giant' del line_dwarfs, line_giants return sp_class def stellar_class_pm(photometry): # Use the proper motion of the star for classification, following # Collier Cameron et al. 2007 sp_class = 'dwarf' if all([k in photometry for k in ['J', 'H', 'pmRA', 'pmDEC']]): try: pmRA = photometry['pmRA'][0]/1000. pmDEC = photometry['pmDEC'][0]/1000. mu = np.sqrt(pmRA**2. + pmDEC**2.) J = photometry['J'][0] - photometry['J'][4] H = photometry['H'][0] - photometry['H'][4] RPM = J + 5.*np.log10(mu) if (-15. <= RPM <= 10.) and (0.0 <= (J-H) <= 1.0): ycurve = -141.25*(J-H)**4. + 473.18*(J-H)**3.\ -583.60*(J-H)**2. + 313.42*(J-H) - 58. if RPM < ycurve: sp_class = 'giant' else: return stellar_class(photometry) except: return stellar_class(photometry) else: return stellar_class(photometry) return sp_class def ini_logg(T, sp_type): if sp_type == 'dwarf': return 4.68*1e-8*T**2. - 8.33*1e-4*T + 7.547 return max(1.0, -5.82*1e-7*T**2. + 6.73*1e-3*T - 10.65) def ini_met(photometry): met = 0.0 # From Martell & Laughlin 2002 if 'b' in photometry and 'y' in photometry and 'm1' in photometry and 'c1' in photometry: b = photometry['b'][0] - photometry['b'][4] y = photometry['y'][0] - photometry['y'][4] by = b-y m1 = photometry['m1'][0] c1 = photometry['c1'][0] if (0.288 < by < 0.571) and (0.058 < m1 < 0.497) and (0.116 < c1 < 0.745): met = -10.424602 + 31.059003*by + 42.184476*m1 + 15.351995*c1 \ -11.239435*by**2. - 29.218135*m1**2. - 11.457610*c1**2. \ -138.92376*by*m1 - 52.033290*by*c1 + 11.259341*m1*c1 \ -46.087731*by**3. + 26.065099*m1**3. - 1.1017830*c1**3. \ +138.48588*by**2.*m1 + 39.012001*by**2.*c1 \ +23.225562*m1**2.*by - 69.146876*m1**2.*c1 \ +20.456093*c1**2.*by - 3.3302478*c1**2.*m1 \ +70.168761*by*m1*c1 if (met > 0.5) or (met < -2.0): met = 0.0 return met #****************************************************************************** #****************************************************************************** def correct_mamajek(Tc, color, inst): # harps, feros, hires, uves corrections = {'B-V': (-3.67, 54.8, -15.79, -6.12),\ 'V-K': (15.23, 11.03, 43.25, 42.25),\ 'J-H': (15.47, 32.62, 78.61, 59.06),\ 'Bt-Vt': (64.61, 84.23, 108.15, 71.98)} x = 0 if inst in ['harps', 'feros', 'hires', 'uves']: x = corrections[color][['harps', 'feros', 'hires', 'uves'].index(inst)] return Tc + x def mamajek(photometry, inst): # Define the spline representations tck_bv = (np.array([3000., 3000., 3000., 3000., 3100., 3200., 3250., 3410., 3500., 3550., 3650., 3700., 3850., 3880., 3970., 4050., 4230., 4410., 4620., 4840., 5040., 5170., 5280., 5340., 5490., 5530., 5590., 5660., 5680., 5720., 5770., 5880., 5920., 6040., 6170., 6240., 6340., 6510., 6640., 6720., 6810., 7030., 7200., 7440., 7500., 7800., 8000., 8080., 8270., 8550., 8840., 9200., 9700., 10400., 10700., 12500., 14500., 14500., 14500., 14500.]),\ np.array([1.91, 1.89889695, 1.64625059, 1.69918967, 1.53801881, 1.55319352, 1.53106075, 1.48801053, 1.48838346, 1.47779774, 1.44527783, 1.4129107, 1.3861779, 1.30383319, 1.24749974, 1.12702398, 1.12023921, 0.98822216, 0.90145692, 0.84143165, 0.83585252, 0.74482766, 0.76955031, 0.70259105, 0.7107385, 0.68402323, 0.67252669, 0.657925, 0.65103668, 0.60442773, 0.5946758, 0.53880897, 0.53974386, 0.5054044, 0.48018914, 0.43561453, 0.42026151, 0.38487402, 0.36939307, 0.34017362, 0.28593417, 0.25906698, 0.24421401, 0.22166016, 0.17370659, 0.15529447, 0.14294398, 0.07675079, 0.07944651, 0.03617357, -0.00639459, -0.04057817, -0.10613727, -0.10490602, -0.1217432, -0.14, 0., 0., 0., 0.]), 3) tck_vks = (np.array([3000., 3000., 3000., 3000., 3100., 3200., 3250., 3410., 3500., 3550., 3650., 3700., 3850., 3880., 3970., 4050., 4230., 4410., 4620., 4840., 5040., 5170., 5280., 5340., 5490., 5530., 5590., 5660., 5680., 5720., 5770., 5880., 5920., 6040., 6170., 6240., 6340., 6510., 6640., 6720., 6810., 7030., 7200., 7440., 7500., 7800., 8000., 8080., 8270., 8550., 8840., 9200., 9700., 10400., 10700., 12500., 14500., 14500., 14500., 14500.]),\ np.array([6.50000000e+00, 5.62931496e+00, 5.75367026e+00, 5.34076308e+00, 4.79071352e+00, 4.61391909e+00, 4.51720164e+00, 4.13159547e+00, 4.14709596e+00, 4.03097681e+00, 3.85578132e+00, 3.70546709e+00, 3.54424972e+00, 3.31949749e+00, 3.16721742e+00, 2.81656851e+00, 2.79358299e+00, 2.39537651e+00, 2.17786419e+00, 2.02134802e+00, 1.99884413e+00, 1.78559326e+00, 1.84401087e+00, 1.68769762e+00, 1.70675113e+00, 1.64431540e+00, 1.61765528e+00, 1.58260890e+00, 1.56619519e+00, 1.45865442e+00, 1.43726664e+00, 1.30978554e+00, 1.31255319e+00, 1.23323500e+00, 1.17676105e+00, 1.07373032e+00, 1.03727999e+00, 9.50782384e-01, 9.14314901e-01, 8.42414011e-01, 7.12893077e-01, 6.47709841e-01, 6.12165798e-01, 5.57520113e-01, 4.37245386e-01, 3.91233825e-01, 3.60535900e-01, 1.93847001e-01, 2.05967449e-01, 6.93649668e-02, 3.93919827e-02, -5.51783950e-03, -2.63670696e-01, -2.23184229e-01, -3.14197676e-01, -3.58000000e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00]), 3) tck_jh = (np.array([3000., 3000., 3000., 3000., 3100., 3200., 3250., 3410., 3500., 3550., 3650., 3700., 3850., 3880., 3970., 4050., 4230., 4410., 4620., 4840., 5040., 5170., 5280., 5340., 5490., 5530., 5590., 5660., 5680., 5720., 5770., 5880., 5920., 6040., 6170., 6240., 6340., 6510., 6640., 6720., 6810., 7030., 7200., 7440., 7500., 7800., 8000., 8080., 8270., 8550., 8840., 9200., 9700., 10400., 10700., 12500., 14500., 14500., 14500., 14500.]),\ np.array([0.588, 0.57925679, 0.55974591, 0.55662775, 0.55739209, 0.58028578, 0.58376255, 0.60634672, 0.60546662, 0.6120368, 0.61989396, 0.62481195, 0.63594655, 0.61500676, 0.60674412, 0.55966082, 0.55230917, 0.49293409, 0.43609132, 0.40202698, 0.39806407, 0.34706382, 0.35960846, 0.32332711, 0.3280911, 0.31165243, 0.30654383, 0.29678003, 0.29401661, 0.26762904, 0.26081307, 0.22934639, 0.23111651, 0.20988225, 0.19754575, 0.17130757, 0.16340732, 0.1446157, 0.13839745, 0.12210648, 0.09356932, 0.08068036, 0.07127585, 0.06038954, 0.03801209, 0.02849096, 0.02386206, -0.00845365, -0.00723668, -0.02947868, -0.0309659, -0.04121424, -0.06064657, -0.06648605, -0.07545834, -0.081, 0., 0., 0., 0.]), 3) tck_btvt = (np.array([3850., 3850., 3850., 3850., 3970., 4050., 4230., 4410., 4620., 4840., 5040., 5170., 5280., 5340., 5490., 5530., 5590., 5660., 5680., 5720., 5770., 5880., 5920., 6040., 6170., 6240., 6340., 6510., 6640., 6720., 6810., 7030., 7200., 7440., 7500., 7800., 8000., 8080., 8270., 8550., 8840., 9200., 9700., 10400., 10700., 12500., 14500., 14500., 14500., 14500.]),\ np.array([1.65, 1.62529982, 1.61107882, 1.49837621, 1.4387566, 1.36306363, 1.32576584, 1.16207044, 1.06271882, 0.97207866, 0.97009969, 0.85213091, 0.88670237, 0.79478911, 0.8051525, 0.76802269, 0.75579062, 0.73434453, 0.72579215, 0.66145907, 0.64843825, 0.567861, 0.56983969, 0.52834313, 0.4990927, 0.4526401, 0.43614294, 0.40085542, 0.38573171, 0.3529186, 0.31238673, 0.28288031, 0.26840011, 0.24412267, 0.19710763, 0.18078778, 0.17080152, 0.09332344, 0.09761852, 0.04697616, 0.00787136, -0.02889995, -0.10493612, -0.10123972, -0.12268253, -0.142, 0., 0., 0., 0.]), 3) T = np.array([]) err_mag = np.array([]) mult_zeros = [] colors = ['B-V', 'V-K', 'J-H', 'Bt-Vt'] tcks = [tck_bv, tck_vks, tck_jh, tck_btvt] for i in range(4): c1, c2 = colors[i].split('-') if (c1 in photometry) and (c2 in photometry): C1 = photometry[c1][0] - photometry[c1][4] C2 = photometry[c2][0] - photometry[c2][4] C = C1-C2 e_C = np.sqrt(photometry[c1][1]**2. + photometry[c2][1]**2.) tck_new = (tcks[i][0], tcks[i][1]-C, tcks[i][2]) zeros = interpolate.sproot(tck_new) correction = correct_mamajek(0.0, colors[i], inst) zeros = zeros + correction if len(zeros) == 1: T = np.append(T, zeros[0]) err_mag = np.append(err_mag, e_C) if len(zeros) > 1: mult_zeros.append((i, colors[i], zeros, e_C)) if T.size > 0: T_average = np.average(T, weights=1./err_mag) if mult_zeros: for m in mult_zeros: d = np.abs(m[2]-T_average) T = np.append(T, m[2][np.argmin(d)]) err_mag = np.append(err_mag, m[3]) T_average = np.average(T, weights=1./err_mag) err_T_average = np.sqrt(np.average((T - T_average)**2., weights=1./err_mag)) if err_T_average == 0.0: err_T_average = 100. else: T_average = 0.0 err_T_average = 0.0 return T_average, err_T_average def alonso1999(photometry, met): colors = np.array(['V-K', 'V-K', 'J-H', 'J-K']) coefficients = [[0.5558, 0.2105, 0.001981, -0.009965, 0.01325, -0.002726],\ [0.3770, 0.3660, -0.03170, -0.003074, -0.002765, -0.002973],\ [0.5977, 1.015, -0.1020, -0.01029, 0.03006, 0.01013],\ [0.5816, 0.9134, -0.1443, 0.0000, 0.0000, 0.0000]] e_Teff = np.array([40., 25., 170., 125.]) color_ranges = {'V-K':[{'FeH': [-0.5, 0.2], 'color': [0.20, 2.50], 'r': 0}, {'FeH': [-1.5, -0.5], 'color': [1.00, 2.50], 'r': 0}, {'FeH': [-2.5, -1.5], 'color': [1.20, 2.50], 'r': 0}, {'FeH': [-3.0, -2.5], 'color': [1.70, 2.50], 'r': 0}, {'FeH': [-0.5, 0.2], 'color': [2.00, 4.90], 'r': 1}, {'FeH': [-1.5, -0.5], 'color': [2.00, 4.60], 'r': 1}, {'FeH': [-2.5, -1.5], 'color': [2.00, 3.40], 'r': 1}, {'FeH': [-3.0, -2.5], 'color': [2.00, 2.80], 'r': 1}], 'J-H':[{'FeH': [-0.5, 0.2], 'color': [0.00, 0.90]}, {'FeH': [-1.5, -0.5], 'color': [0.20, 0.80]}, {'FeH': [-2.5, -1.5], 'color': [0.30, 0.70]}, {'FeH': [-3.0, -2.5], 'color': [0.35, 0.65]}], 'J-K':[{'FeH': [-0.5, 0.2], 'color': [0.00, 1.10]}, {'FeH': [-1.5, -0.5], 'color': [0.20, 1.00]}, {'FeH': [-2.5, -1.5], 'color': [0.30, 0.90]}, {'FeH': [-3.0, -2.5], 'color': [0.40, 0.80]}]} #corrections = np.array([0.0, 0.0, 0.0, 0.0]) a_corr = np.array([2.70107158e-01, 8.86192858e-02, 2.57890150e-01]) b_corr = np.array([3.58390280e+03, 4.48537163e+03, 3.72508078e+03]) list_colors = ['V-K', 'J-H', 'J-K'] T_array = np.ones(len(list_colors))*np.nan err_T_array = np.ones(len(list_colors))*np.nan T_final = 0.0 err_T_final = 0.0 for i, lc in enumerate(list_colors): c1, c2 = lc.split('-') if (c1 in photometry) and (c2 in photometry): C1 = photometry[c1][0] - photometry[c1][4] C2 = photometry[c2][0] - photometry[c2][4] C = C1-C2 icolor = np.where(colors == lc)[0] coefs = None err_T_int = None # If there is only one relation for the color if len(icolor) == 1: # Check metallicity and color ranges in_ranges = 0 for k in color_ranges[lc]: range_m = k['FeH'] range_c = k['color'] if (range_m[0] <= met <= range_m[1]) and (range_c[0] <= C <= range_c[1]): in_ranges = 1 if in_ranges > 0: coefs = coefficients[int(icolor)] err_T_int = e_Teff[int(icolor)] # There are two equations for the color, depending on the color value else: in_ranges = 0 r = -99 for k in color_ranges[lc]: range_m = k['FeH'] range_c = k['color'] range_r = k['r'] if (range_m[0] <= met <= range_m[1]) and (range_c[0] <= C <= range_c[1]): in_ranges += 1 r = range_r if in_ranges == 1: coefs = coefficients[icolor[r]] err_T_int = e_Teff[icolor[r]] elif in_ranges > 1: imin = np.argmin(e_Teff[icolor]) coefs = coefficients[icolor[imin]] err_T_int = e_Teff[icolor[imin]] if coefs is not None and err_T_int is not None: theta = coefs[0] + coefs[1]*C + coefs[2]*C**2 + coefs[3]*C*met\ + coefs[4]*met + coefs[5]*met**2 if theta != 0.0: Teff = 5040./theta + ufloat(0.0, err_T_int) T_array[i] = Teff.n err_T_array[i] = Teff.s ii = np.where(~np.isnan(T_array))[0] if ii.size > 0: Tcorr = [np.polyval([a_corr[ii][i_], b_corr[ii][i_]], T_array[ii][i_])\ for i_ in range(len(ii))] Tmean = unumpy.uarray(Tcorr, err_T_array[ii]) #T_final = np.average(T_array[ii], weights=1./err_T_array[ii]) T_final = np.average(Tcorr, weights=1./err_T_array[ii]) #T_final = np.median(T_array[ii]) err_T_final = np.median(Tmean).s #Tmean = unumpy.uarray(T_array[ii]+corrections[ii], err_T_array[ii]) #T_final = np.median(Tmean).n #err_T_final = np.median(Tmean).s return T_final, err_T_final #****************************************************************************** #****************************************************************************** def correct_mann(Tc, color, inst, met): # harps, feros, hires, uves corrections = {'V-J': ((41.3, 26.3, 89.7, 53.4), (-87.8, -73.3, -87.8, -48.2)),\ 'V-I': ((0.0, 0.0, 0.0, 0.0), (0.0, 0.0, 0.0, 0.0))} m = 0 if met else 1 x = 0 if inst in ['harps', 'feros', 'hires', 'uves']: x = corrections[m][color][['harps', 'feros', 'hires', 'uves'].index(inst)] return Tc + x def coefs_mann(type_color, met=True): if met: if type_color == 'V-J': return [2.515, -1.054, 0.2965, -0.04150, 0.002245, 0.05262] if type_color == 'V-I': return [1.901, -0.6564, 0.1471, -0.01274, 0.0, 0.04697] return [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] if type_color == 'V-J': return [2.769, -1.421, 0.4284, -0.06133, 0.003310, 0.1333, 0.05416] if type_color == 'V-I': return [1.568, -0.4381, 0.07749, -0.005610, 0.0, 0.2441, -0.09257] return [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] def mann(photometry, met): if met is not None: if ('V' in photometry) and ('J' in photometry): i = coefs_mann('V-J', met=True) C1 = photometry['V'][0] - photometry['V'][4] C2 = photometry['J'][0] - photometry['J'][4] c = C1-C2 err_c = np.sqrt(photometry['J'][1]**2. + photometry['V'][1]**2.) color = ufloat(c, err_c) elif ('V' in photometry) and ('I' in photometry): i = coefs_mann('V-I', met=True) C1 = photometry['V'][0] - photometry['V'][4] C2 = photometry['I'][0] - photometry['I'][4] c = C1-C2 err_c = np.sqrt(photometry['I'][1]**2. + photometry['V'][1]**2.) color = ufloat(c, err_c) else: i = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] c = 0.0 color = ufloat(c, 999.0) T = i[0] + i[1]*color + i[2]*color**2 + i[3]*color**3 + i[4]*color**4 + i[5]*met else: if ('V' in photometry) and ('J' in photometry): i = coefs_mann('V-J', met=False) C1 = photometry['V'][0] - photometry['V'][4] C2 = photometry['J'][0] - photometry['J'][4] c = C1-C2 err_c = np.sqrt(photometry['J'][1]**2. + photometry['V'][1]**2.) color = ufloat(c, err_c) elif ('V' in photometry) and ('I' in photometry): i = coefs_mann('V-I', met=False) C1 = photometry['V'][0] - photometry['V'][4] C2 = photometry['I'][0] - photometry['I'][4] c = C1-C2 err_c = np.sqrt(photometry['I'][1]**2. + photometry['V'][1]**2.) color = ufloat(c, err_c) else: i = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] c = 0.0 color = ufloat(c, 999.0) if ('J' in photometry) and ('H' in photometry): C1 = photometry['J'][0] - photometry['J'][4] C2 = photometry['H'][0] - photometry['H'][4] c2 = C1-C2 err_c2 = np.sqrt(photometry['J'][1]**2. + photometry['H'][1]**2.) color2 = ufloat(c2, err_c2) T = i[0] + i[1]*color + i[2]*color**2 + i[3]*color**2 + i[4]*color**3 +\ i[5]*color2 + i[6]*color2**2 else: T = 0.0 T = T*3500. return T.n, T.s #****************************************************************************** #****************************************************************************** def coefs_casagrande(type_color, color): coefs = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] if type_color == 'B-V' and (0.18 <= color.n <= 1.29): coefs = [0.5665, 0.4809, -0.0060, -0.0613, -0.0042, -0.0055] elif type_color == 'V-J' and (0.61 <= color.n <= 2.44): coefs = [0.4669, 0.3849, -0.0350, -0.0140, 0.0225, 0.0011] elif type_color == 'V-H' and (0.67 <= color.n <= 3.01): coefs = [0.5251, 0.2553, -0.0119, -0.0187, 0.0410, 0.0025] elif type_color == 'V-K' and (0.78 <= color.n <= 3.15): coefs = [0.5057, 0.2600, -0.0146, -0.0131, 0.0288, 0.0016] elif type_color == 'J-K' and (0.07 <= color.n <= 0.80): coefs = [0.6393, 0.6104, 0.0920, -0.0330, 0.0291, 0.0020] elif type_color == 'Bt-Vt' and (0.19 <= color.n <= 1.49): coefs = [0.5839, 0.4000, -0.0067, -0.0282, -0.0346, -0.0087] elif type_color == 'Vt-J' and (0.77 <= color.n <= 2.56): coefs = [0.4525, 0.3797, -0.0357, -0.0082, 0.0123, -0.0009] elif type_color == 'Vt-H' and (0.77 <= color.n <= 3.16): coefs = [0.5286, 0.2354, -0.0073, -0.0182, 0.0401, 0.0021] elif type_color == 'Vt-K' and (0.99 <= color.n <= 3.29): coefs = [0.4892, 0.2634, -0.0165, -0.0121, 0.0249, -0.0001] elif type_color == 'b-y' and (0.18 <= color.n <= 0.72): coefs = [0.5796, 0.4812, 0.5747, -0.0633, 0.0042, -0.0055] return coefs def correct_casagrande(Tc, color, inst): # harps, feros, hires, uves corrections = {'Vt-K': [16.66, 25.67, 34.48, 31.58], 'V-K': [23.26, 26.81, 47.89, 52.3], 'Vt-H': [11.48, 18.96, 35.03, 45.29], 'V-H': [21.02, 23.92, 55.81, 53.8], 'V-J': [-7.26, -17.38, -10.37, 25.0], 'Vt-J': [-18.77, -4.76, -16.9, 13.75], 'b-y': [14.09, 24.5, 44.49, 29.27], 'B-V': [36.54, 65.18, 37.37, 19.43], 'Bt-Vt': [19.56, 19.39, 23.88, 11.53], 'J-K': [85.5, 124.89, 191.43, 120.83]} x = 0 if inst in ['harps', 'feros', 'hires', 'uves']: x = corrections[color][['harps', 'feros', 'hires', 'uves'].index(inst)] return Tc + x def casagrande(photometry, met, inst): possible_colors = ['Vt-K', 'V-K', 'Vt-H', 'V-H', 'V-J', 'Vt-J',\ 'b-y', 'B-V', 'Bt-Vt', 'J-K'] T_final = 0.0 err_T_final = 100000. color_p_final = [] T_array = [] for c in possible_colors: c1, c2 = c.split('-') if (c1 in photometry) and (c2 in photometry): C1 = ufloat(photometry[c1][0] - photometry[c1][4], photometry[c1][1]) C2 = ufloat(photometry[c2][0] - photometry[c2][4], photometry[c2][1]) color = C1-C2 i = coefs_casagrande(c, color) t = i[0] + i[1]*color + i[2]*color**2. + i[3]*color*met + i[4]*met + i[5]*met**2. if t.n != 0.0 and (t.n < 5040./3500.) and (t.n > 5040./10000.): T_array_v1 = (5040./t).n err_T_array_v1 = (5040./t).s T_corrected = correct_casagrande(T_array_v1, c, inst) T_array.append(ufloat(T_corrected, err_T_array_v1)) color_p_final.append('%s: %.1f +- %.1f' % (c, T_corrected, err_T_array_v1)) del t T_array = np.array(T_array) if T_array.size > 0: T_mean = np.mean(T_array) T_final = T_mean.n err_T_final = T_mean.s color_p_final = ", ".join(color_p_final)# color_p_final[:-2] del possible_colors, photometry return T_final, err_T_final, color_p_final #****************************************************************************** #****************************************************************************** def use_relation(photometry): limit_colors = {'B-V': 1.340, 'Bt-Vt': 1.543, 'V-R': 0.826, 'V-I': 1.580,\ 'V-K': 3.418, 'J-H': 0.557, 'H-K': 0.169} use_mann = False for c in list(limit_colors.keys()): c1, c2 = c.split('-') if (c1 in photometry) and (c2 in photometry): C1 = photometry[c1][0] - photometry[c1][4] C2 = photometry[c2][0] - photometry[c2][4] val = C1-C2 if val >= limit_colors[c]: use_mann = True break if use_mann: return 'mann' return 'casagrande' #****************************************************************************** #****************************************************************************** def check_relation(photometry, xmetal, exception, inst): relation = use_relation(photometry) T_c = 0.0 if relation == 'casagrande': T_c, err_T_c, color_c = casagrande(photometry, xmetal, inst) if (T_c == 0.0) or (relation == 'mann'): if exception == 1: T_c, err_T_c = mann(photometry, xmetal) else: T_c, err_T_c = mann(photometry, met=None) if T_c == 0.0 or T_c > 4000.: T_c, err_T_c, color_c = casagrande(photometry, xmetal, inst) relation = 'casagrande' else: color_c = 'any' return T_c, err_T_c, color_c, relation
mit
BradburyLab/pyvalidator
abst.py
1
19145
#!/usr/bin/env python3 # coding: utf-8 # Copyright (c) 2013-2014 Bradbury Lab # Author: Ilya Murav'jov <muravyev@bradburylab.com> # # This software is licensed under the # GNU General Public License version 3 (see the file LICENSE). # :TRYCKY: хоть и некрасиво ("#byte#"), зато # единообразно def make_byte_fmt(*lst): return ["-", "#byte#", lst] AbstFormat = { "res": [ ["abst", "BOXHEADER", [ ["Version", "UI8"], ["Flags", "UI24"], ["BootstrapinfoVersion", "UI32"], make_byte_fmt( ["Profile", "UI2"], ["Live", "UI1"], ["Update", "UI1"], ["Reserved", "UI4"], ), ["TimeScale", "UI32"], ["CurrentMediaTime", "UI64"], ["SmpteTimeCodeOffset", "UI64"], ["MovieIdentifier", "STRING"], ["ServerEntryCount", "UI8"], ["ServerEntryTable", "SERVERENTRY[ServerEntryCount]"], ["QualityEntryCount", "UI8"], ["QualityEntryTable", "QUALITYENTRY[QualityEntryCount]"], ["DrmData", "STRING"], ["MetaData", "STRING"], ["SegmentRunTableCount", "UI8"], ["SegmentRunTableEntries", "SegmentRunTable[SegmentRunTableCount]"], ["FragmentRunTableCount", "UI8"], ["FragmentRunTableEntries", "FragmentRunTable[FragmentRunTableCount]"], ]], ], "SERVERENTRY": [ ["ServerBaseURL", "STRING"], ], "QUALITYENTRY": [ ["QualitySegmentUrlModifier", "STRING"], ], "SegmentRunTable": [ ["asrt", "BOXHEADER", [ ["Version", "UI8"], ["Flags", "UI24"], ["QualityEntryCount", "UI8"], ["QualitySegmentUrlModifiers", "STRING[QualityEntryCount]"], ["SegmentRunEntryCount", "UI32"], ["SegmentRunEntryTable", "SEGMENTRUNENTRY[SegmentRunEntryCount]"], ]], ], "SEGMENTRUNENTRY": [ ["FirstSegment", "UI32"], ["FragmentsPerSegment", "UI32"] ], "FragmentRunTable": [ ["afrt", "BOXHEADER", [ ["Version", "UI8"], ["Flags", "UI24"], ["TimeScale", "UI32"], ["QualityEntryCount", "UI8"], ["QualitySegmentUrlModifiers", "STRING[QualityEntryCount]"], ["FragmentRunEntryCount", "UI32"], ["FragmentRunEntryTable", "FRAGMENTRUNENTRY[FragmentRunEntryCount]"], ]], ], "FRAGMENTRUNENTRY": [ ["FirstFragment", "UI32"], ["FirstFragmentTimestamp", "UI64"], ["FragmentDuration", "UI32"], # :TRICKY: не используем, поэтому не встретится #["DiscontinuityIndicator", "IF FragmentDuration == 0 UI8"], ], } def check_read(f, ln): dat = f.read(ln) assert len(dat) == ln return dat import struct def check_parse(f, fmt): ln = struct.calcsize(fmt) dat = check_read(f, ln) return struct.unpack(fmt, dat) def make_parse_int(struct_name): fmt = ">" + struct_name def do(f): return check_parse(f, fmt)[0] return do parse_byte = make_parse_int("B") parse_short = make_parse_int("H") def parse_int24(f): h = parse_byte(f) l = parse_short(f) return (h << 16) + l def parse_string(f): res = b'' while True: c = check_read(f, 1) if c == b'\0': break else: res += c return res elementary_types = { "UI8": parse_byte, "UI16": parse_short, "UI24": parse_int24, "UI32": make_parse_int("L"), "UI64": make_parse_int("Q"), "STRING": parse_string } def is_eof(f): res = f.read(1) == b'' if not res: f.seek(f.tell() - 1) return res def check_end(f): # в конце ничего не осталось assert f.read(1) == b'' def get_struct(fmt): return fmt[2] def get_name_type(fmt): return fmt[:2] def get_data_dict(fmt, strict_check=True): res = None if len(fmt) >= 3: res = fmt[2] # считаем, что атрибут, которому # явно присваивается значение, должен # быть отформатирован с третьим параметром # как словарь (например, когда есть условие/ограничение) is_dct = type(res) == dict if not is_dct: assert not strict_check res = None return res def is_data_dict(obj): """ Для различения None и пустого словаря """ return obj is not None def check_condition(cnd, typ, expr_dct): exists, val = False, None prefix = typ + ":" if cnd.startswith(prefix): cnd = cnd[len(prefix):] exists = True val = eval(cnd, {}, expr_dct) return exists, val def set_fmt_value(fmt, val, errors): obj = get_data_dict(fmt) if is_data_dict(obj): assert not("value" in obj) obj["value"] = val cnd = obj.get("condition") if cnd: name = get_name_type(fmt)[0] set_exists, set_val = check_condition(cnd, "set", {"value": val}) if set_exists: if not set_val: errors.append("Attribute %s' value is bad" % name) elif cnd == "0": if val != 0: errors.append("Attribute value %s is not 0" % name) else: # :TODO: отфильтровывать "if:" и говорить, непонятно, как обрабатывать # это условие pass else: fmt.append(val) def find_fld_ex(fmt_lst, fld_name): is_found = False val = None for fmt in fmt_lst: name, typ = get_name_type(fmt) if typ == "#byte#": is_found, val = find_fld_ex(get_struct(fmt), fld_name) elif name == fld_name: obj = get_data_dict(fmt, False) if is_data_dict(obj): val = obj["value"] else: assert len(fmt) >= 2 val = fmt[2] is_found = True if is_found: break return is_found, val def find_fld(fmt_lst, fld_name): is_found, val = find_fld_ex(fmt_lst, fld_name) assert is_found return val import io import re import collections # узел спецификации FSClass = collections.namedtuple('FSClass', ['fmt_lst', 'spec', 'errors', "parent_fs"]) import copy def make_fs_from_parent(fmt_lst, parent_fs): return FSClass(fmt_lst, parent_fs.spec, parent_fs.errors, parent_fs) def make_format(typ_name, spec): return copy.deepcopy(spec[typ_name]) def parse_struct(f, typ_name, fs): elem_fs = make_fs_from_parent(make_format(typ_name, fs.spec), fs) parse(f, elem_fs, False) return elem_fs.fmt_lst class EvalAttr: def __init__(self, fs): self.fs = fs def __getitem__(self, key): is_found, val = False, None fs = self.fs while fs: is_found, val = find_fld_ex(fs.fmt_lst, key) if is_found: break fs = fs.parent_fs return val def find_data_for_key(fmt, key): is_found, dat = False, None d_dct = get_data_dict(fmt, False) if is_data_dict(d_dct) and (key in d_dct): dat = d_dct.get(key) is_found = True return is_found, dat def parse_child_fmt(dat, ch_fmt, fs, till_end=True): parse(io.BytesIO(dat), make_fs_from_parent(ch_fmt, fs), till_end=till_end) def parse(f, fs, till_end=True): fmt_lst = fs.fmt_lst errors = fs.errors for fmt in fmt_lst: name, typ = get_name_type(fmt) # проверяем, существует ли атрибут attr_exists = True is_found, cnd = find_data_for_key(fmt, "condition") if is_found: exists, if_val = check_condition(cnd, "if", EvalAttr(fs)) if exists: attr_exists = if_val if not attr_exists: continue pat = re.compile("(?P<struct_name>.*)\[(?P<count>.*)\]") def try_parse_arr(): res = False m = pat.match(typ) if m: res = True # узнаем длину массива из предыдущих элементов cnt_str = m.group("count") if cnt_str == '': # читать пока можно читать cnt = None import itertools rng = itertools.count() else: cnt = find_fld(fmt_lst, cnt_str) assert type(cnt) == int rng = range(cnt) if cnt != 0: typ_name = m.group("struct_name") if typ_name == "UI8": # может быть None! if cnt: dat = check_read(f, cnt) else: dat = f.read() is_found, header_fmt = find_data_for_key(fmt, "header") if is_found: parse_child_fmt(dat, header_fmt, fs, False) set_fmt_value(fmt, dat, errors) else: lst = [] set_fmt_value(fmt, lst, errors) elem_parser = elementary_types.get(typ_name) for i in rng: if cnt is None and is_eof(f): break if elem_parser: elem = elem_parser(f) else: elem = parse_struct(f, typ_name, fs) lst.append(elem) return res if typ == "BOXHEADER": box_fmt = ">I4s" sz, name_val = check_parse(f, box_fmt) # :TODO: размер может быть больше, чем 32bit, # по формату assert sz != 1 assert name == name_val.decode("utf-8") # :TODO: правильней читать не всю структуру, # а запретить читать для вложенного вызова больше, # чем sz байт if sz: sz -= struct.calcsize(box_fmt) dat = check_read(f, sz) else: dat = f.read() parse_child_fmt(dat, get_struct(fmt), fs) elif typ in elementary_types: set_fmt_value(fmt, elementary_types[typ](f), errors) elif typ == "#byte#": lst = get_struct(fmt) num = parse_byte(f) lvl = 0 for bfmt in reversed(lst): bname, btyp = get_name_type(bfmt) m = re.match("UI([1-7])", btyp) assert m sz = int(m.group(1)) lvl += sz assert lvl <= 8 mask = (2 << (sz-1)) - 1 set_fmt_value(bfmt, mask & num, errors) num >>= sz elif typ in fs.spec: set_fmt_value(fmt, parse_struct(f, typ, fs), errors) elif try_parse_arr(): pass else: assert False if till_end: check_end(f) def parse_from_str(s, spec, errors=None): f = io.BytesIO(s) if errors is None: errors = [] res = FSClass(make_format("res", spec), spec, errors, None) parse(f, res) return res.fmt_lst def parse_abst(s): return parse_from_str(s, AbstFormat) def parse_n_print(s, spec): errors = [] res = parse_from_str(s, spec, errors) if not errors: print("Data is valid with respect to the spec.") else: print("Data is not valid with respect to the spec:") for err in errors: print("\t", err) print("###") import pprint pprint.pprint(res) def parse_n_print_abst(s): return parse_n_print(s, AbstFormat) import base64 def from_base64(b64_encoded): return base64.b64decode(bytes(b64_encoded, "ascii")) def parse_seg_frg_tbl(s): res = parse_abst(s) def box_content(box): return get_struct(box[0]) abst_content = box_content(res) def get_tbl_content(tbl_name): box_lst = find_fld(abst_content, tbl_name) # только одна таблица фрагментов всегда return box_content(box_lst[0]) asrt_content = get_tbl_content("SegmentRunTableEntries") seg_tbl = find_fld(asrt_content, "SegmentRunEntryTable") assert len(seg_tbl) == 1 seg1 = seg_tbl[0] cnt = find_fld(seg1, "FragmentsPerSegment") afrt_content = get_tbl_content("FragmentRunTableEntries") tscale = find_fld(afrt_content, "TimeScale") frg_tbl = find_fld(afrt_content, "FragmentRunEntryTable") def as_seconds(frg_item, fld_name): return float(find_fld(frg_item, fld_name) / tscale) lst = [] for frg_item in frg_tbl: lst.append([ find_fld(frg_item, "FirstFragment"), as_seconds(frg_item, "FirstFragmentTimestamp"), as_seconds(frg_item, "FragmentDuration"), ]) return cnt, lst def parse_frg_tbl(s): return parse_seg_frg_tbl(s)[1] def get_frg_base(frg_tbl): return frg_tbl[0][0] # # для разработки/тестов # def ohs_vod_abst_sample(): b64_encoded = """AAAKWmFic3QAAAAAAAAADgAAAAPoAAAAAAAHUIAAAAAAAAAAAAAAAAAAAQAAABlhc3J0AAAAAAAAAAABAAAAAQAAAKABAAAKFWFmcnQAAAAAAAAD6AAAAACgAAAAAQAAAAAAAAAAAAALuAAAAAIAAAAAAAALuAAAC7gAAAADAAAAAAAAF3AAAAu4AAAABAAAAAAAACMoAAALuAAAAAUAAAAAAAAu4AAAC7gAAAAGAAAAAAAAOpgAAAu4AAAABwAAAAAAAEZQAAALuAAAAAgAAAAAAABSCAAAC7gAAAAJAAAAAAAAXcAAAAu4AAAACgAAAAAAAGl4AAALuAAAAAsAAAAAAAB1MAAAC7gAAAAMAAAAAAAAgOgAAAu4AAAADQAAAAAAAIygAAALuAAAAA4AAAAAAACYWAAAC7gAAAAPAAAAAAAApBAAAAu4AAAAEAAAAAAAAK/IAAALuAAAABEAAAAAAAC7gAAAC7gAAAASAAAAAAAAxzgAAAu4AAAAEwAAAAAAANLwAAALuAAAABQAAAAAAADeqAAAC7gAAAAVAAAAAAAA6mAAAAu4AAAAFgAAAAAAAPYYAAALuAAAABcAAAAAAAEB0AAAC7gAAAAYAAAAAAABDYgAAAu4AAAAGQAAAAAAARlAAAALuAAAABoAAAAAAAEk+AAAC7gAAAAbAAAAAAABMLAAAAu4AAAAHAAAAAAAATxoAAALuAAAAB0AAAAAAAFIIAAAC7gAAAAeAAAAAAABU9gAAAu4AAAAHwAAAAAAAV+QAAALuAAAACAAAAAAAAFrSAAAC7gAAAAhAAAAAAABdwAAAAu4AAAAIgAAAAAAAYK4AAALuAAAACMAAAAAAAGOcAAAC7gAAAAkAAAAAAABmigAAAu4AAAAJQAAAAAAAaXgAAALuAAAACYAAAAAAAGxmAAAC7gAAAAnAAAAAAABvVAAAAu4AAAAKAAAAAAAAckIAAALuAAAACkAAAAAAAHUwAAAC7gAAAAqAAAAAAAB4HgAAAu4AAAAKwAAAAAAAewwAAALuAAAACwAAAAAAAH36AAAC7gAAAAtAAAAAAACA6AAAAu4AAAALgAAAAAAAg9YAAALuAAAAC8AAAAAAAIbEAAAC7gAAAAwAAAAAAACJsgAAAu4AAAAMQAAAAAAAjKAAAALuAAAADIAAAAAAAI+OAAAC7gAAAAzAAAAAAACSfAAAAu4AAAANAAAAAAAAlWoAAALuAAAADUAAAAAAAJhYAAAC7gAAAA2AAAAAAACbRgAAAu4AAAANwAAAAAAAnjQAAALuAAAADgAAAAAAAKEiAAAC7gAAAA5AAAAAAACkEAAAAu4AAAAOgAAAAAAApv4AAALuAAAADsAAAAAAAKnsAAAC7gAAAA8AAAAAAACs2gAAAu4AAAAPQAAAAAAAr8gAAALuAAAAD4AAAAAAALK2AAAC7gAAAA/AAAAAAAC1pAAAAu4AAAAQAAAAAAAAuJIAAALuAAAAEEAAAAAAALuAAAAC7gAAABCAAAAAAAC+bgAAAu4AAAAQwAAAAAAAwVwAAALuAAAAEQAAAAAAAMRKAAAC7gAAABFAAAAAAADHOAAAAu4AAAARgAAAAAAAyiYAAALuAAAAEcAAAAAAAM0UAAAC7gAAABIAAAAAAADQAgAAAu4AAAASQAAAAAAA0vAAAALuAAAAEoAAAAAAANXeAAAC7gAAABLAAAAAAADYzAAAAu4AAAATAAAAAAAA27oAAALuAAAAE0AAAAAAAN6oAAAC7gAAABOAAAAAAADhlgAAAu4AAAATwAAAAAAA5IQAAALuAAAAFAAAAAAAAOdyAAAC7gAAABRAAAAAAADqYAAAAu4AAAAUgAAAAAAA7U4AAALuAAAAFMAAAAAAAPA8AAAC7gAAABUAAAAAAADzKgAAAu4AAAAVQAAAAAAA9hgAAALuAAAAFYAAAAAAAPkGAAAC7gAAABXAAAAAAAD79AAAAu4AAAAWAAAAAAAA/uIAAALuAAAAFkAAAAAAAQHQAAAC7gAAABaAAAAAAAEEvgAAAu4AAAAWwAAAAAABB6wAAALuAAAAFwAAAAAAAQqaAAAC7gAAABdAAAAAAAENiAAAAu4AAAAXgAAAAAABEHYAAALuAAAAF8AAAAAAARNkAAAC7gAAABgAAAAAAAEWUgAAAu4AAAAYQAAAAAABGUAAAALuAAAAGIAAAAAAARwuAAAC7gAAABjAAAAAAAEfHAAAAu4AAAAZAAAAAAABIgoAAALuAAAAGUAAAAAAAST4AAAC7gAAABmAAAAAAAEn5gAAAu4AAAAZwAAAAAABKtQAAALuAAAAGgAAAAAAAS3CAAAC7gAAABpAAAAAAAEwsAAAAu4AAAAagAAAAAABM54AAALuAAAAGsAAAAAAATaMAAAC7gAAABsAAAAAAAE5egAAAu4AAAAbQAAAAAABPGgAAALuAAAAG4AAAAAAAT9WAAAC7gAAABvAAAAAAAFCRAAAAu4AAAAcAAAAAAABRTIAAALuAAAAHEAAAAAAAUggAAAC7gAAAByAAAAAAAFLDgAAAu4AAAAcwAAAAAABTfwAAALuAAAAHQAAAAAAAVDqAAAC7gAAAB1AAAAAAAFT2AAAAu4AAAAdgAAAAAABVsYAAALuAAAAHcAAAAAAAVm0AAAC7gAAAB4AAAAAAAFcogAAAu4AAAAeQAAAAAABX5AAAALuAAAAHoAAAAAAAWJ+AAAC7gAAAB7AAAAAAAFlbAAAAu4AAAAfAAAAAAABaFoAAALuAAAAH0AAAAAAAWtIAAAC7gAAAB+AAAAAAAFuNgAAAu4AAAAfwAAAAAABcSQAAALuAAAAIAAAAAAAAXQSAAAC7gAAACBAAAAAAAF3AAAAAu4AAAAggAAAAAABee4AAALuAAAAIMAAAAAAAXzcAAAC7gAAACEAAAAAAAF/ygAAAu4AAAAhQAAAAAABgrgAAALuAAAAIYAAAAAAAYWmAAAC7gAAACHAAAAAAAGIlAAAAu4AAAAiAAAAAAABi4IAAALuAAAAIkAAAAAAAY5wAAAC7gAAACKAAAAAAAGRXgAAAu4AAAAiwAAAAAABlEwAAALuAAAAIwAAAAAAAZc6AAAC7gAAACNAAAAAAAGaKAAAAu4AAAAjgAAAAAABnRYAAALuAAAAI8AAAAAAAaAEAAAC7gAAACQAAAAAAAGi8gAAAu4AAAAkQAAAAAABpeAAAALuAAAAJIAAAAAAAajOAAAC7gAAACTAAAAAAAGrvAAAAu4AAAAlAAAAAAABrqoAAALuAAAAJUAAAAAAAbGYAAAC7gAAACWAAAAAAAG0hgAAAu4AAAAlwAAAAAABt3QAAALuAAAAJgAAAAAAAbpiAAAC7gAAACZAAAAAAAG9UAAAAu4AAAAmgAAAAAABwD4AAALuAAAAJsAAAAAAAcMsAAAC7gAAACcAAAAAAAHGGgAAAu4AAAAnQAAAAAAByQgAAALuAAAAJ4AAAAAAAcv2AAAC7gAAACfAAAAAAAHO5AAAAu4AAAAoAAAAAAAB0dIAAAJOA==""" return from_base64(b64_encoded) if __name__ == "__main__": import os if True: if True: from_f4m = False # True # import sys if from_f4m: s = parse_bi_from_f4m(sys.stdin.read()) else: # :TRICKY: в Py3 стандартные ввод/выводы автоматом переводят # байты в строки (в соответ. с кодировкой платформы), если требуется # читать бинарные файлы, то отключаем и читаем напрямую # # При открытии с помощью open() флаг "b" получает новое значение для Python-экосистемы, # - чтение в бинарном/байтовом режиме, без перевода в Unicode-строки с помощью заданной # кодировки (которую можно сменить, при потребности, с помощью параметра encoding) sys.stdin = sys.stdin.detach() s = sys.stdin.read() elif False: with open(os.path.expanduser("~/opt/bl/f451/tmp/pervyj.abst"), 'rb') as f: s = f.read() else: s = ohs_vod_abst_sample() parse_n_print_abst(s) if False: print(parse_frg_tbl(ohs_vod_abst_sample()))
gpl-3.0
nickdex/cosmos
code/artificial_intelligence/src/logistic_regression/logistic_regression.py
3
1825
# Logistic regression implemented from Scratch in Python import numpy as np import matplotlib.pyplot as plt def sigmoid(scores): return 1 / (1 + np.exp(-scores)) def log_likelihood(features, target, weights): scores = np.dot(features, weights) ll = np.sum(target * scores - np.log(1 + np.exp(scores))) return ll def logistic_regression( features, target, num_steps, learning_rate, add_intercept=False ): if add_intercept: intercept = np.ones((features.shape[0], 1)) features = np.hstack((intercept, features)) weights = np.zeros(features.shape[1]) for step in range(num_steps): scores = np.dot(features, weights) predictions = sigmoid(scores) # Update weights with gradient output_error_signal = target - predictions gradient = np.dot(features.T, output_error_signal) weights += learning_rate * gradient # Print log-likelihood every so often if step % 10000 == 0: print(log_likelihood(features, target, weights)) return weights np.random.seed(12) num_observations = 5000 x1 = np.random.multivariate_normal([0, 0], [[1, 0.75], [0.75, 1]], num_observations) x2 = np.random.multivariate_normal([1, 4], [[1, 0.75], [0.75, 1]], num_observations) simulated_separableish_features = np.vstack((x1, x2)).astype(np.float32) simulated_labels = np.hstack((np.zeros(num_observations), np.ones(num_observations))) plt.figure(figsize=(12, 8)) plt.scatter( simulated_separableish_features[:, 0], simulated_separableish_features[:, 1], c=simulated_labels, alpha=0.4, ) plt.show() # Running the model weights = logistic_regression( simulated_separableish_features, simulated_labels, num_steps=300000, learning_rate=5e-5, add_intercept=True, ) print(weights)
gpl-3.0
falbassini/Samples
python/v2.1/run_report.py
3
1930
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example illustrates how to run a report.""" import argparse import sys from apiclient import sample_tools from oauth2client import client # Declare command-line flags. argparser = argparse.ArgumentParser(add_help=False) argparser.add_argument( 'profile_id', type=int, help='The ID of the profile to use') argparser.add_argument( 'report_id', type=int, help='The ID of the report to run') def main(argv): # Authenticate and construct service. service, flags = sample_tools.init( argv, 'dfareporting', 'v2.1', __doc__, __file__, parents=[argparser], scope=['https://www.googleapis.com/auth/dfareporting', 'https://www.googleapis.com/auth/dfatrafficking']) profile_id = flags.profile_id report_id = flags.report_id try: # Construct a get request for the specified report. request = service.reports().run(profileId=profile_id, reportId=report_id) # Execute request and print response. result = request.execute() print ('Report file with ID %s is currently in status "%s".' % (result['id'], result['status'])) except client.AccessTokenRefreshError: print ('The credentials have been revoked or expired, please re-run the ' 'application to re-authorize') if __name__ == '__main__': main(sys.argv)
apache-2.0
primoz-k/parilis
config/settings/local.py
1
1840
# -*- coding: utf-8 -*- ''' Local settings - Run in Debug mode - Use console backend for emails - Add Django Debug Toolbar - Add django-extensions as app ''' from .common import * # noqa # DEBUG # ------------------------------------------------------------------------------ DEBUG = env.bool('DJANGO_DEBUG', default=True) TEMPLATES[0]['OPTIONS']['debug'] = DEBUG # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Note: This key only used for development and testing. SECRET_KEY = env("DJANGO_SECRET_KEY", default='CHANGEME!!!12$#w4t#z2nt&#*)-6(yt*ght5&%)4%3)2n42z81lp+hw!5$rr') # Mail settings # ------------------------------------------------------------------------------ EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 # CACHING # ------------------------------------------------------------------------------ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '' } } # django-debug-toolbar # ------------------------------------------------------------------------------ MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INSTALLED_APPS += ('debug_toolbar', ) INTERNAL_IPS = ('127.0.0.1', '10.0.2.2',) DEBUG_TOOLBAR_CONFIG = { 'DISABLE_PANELS': [ 'debug_toolbar.panels.redirects.RedirectsPanel', ], 'SHOW_TEMPLATE_CONTEXT': True, } # django-extensions # ------------------------------------------------------------------------------ INSTALLED_APPS += ('django_extensions', ) # TESTING # ------------------------------------------------------------------------------ TEST_RUNNER = 'django.test.runner.DiscoverRunner' # Your local stuff: Below this line define 3rd party library settings
bsd-3-clause
yamada-h/ryu
ryu/log.py
5
3342
# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from ryu import cfg import inspect import platform import logging import logging.config import logging.handlers import os import sys import ConfigParser CONF = cfg.CONF CONF.register_cli_opts([ cfg.IntOpt('default-log-level', default=None, help='default log level'), cfg.BoolOpt('verbose', default=False, help='show debug output'), cfg.BoolOpt('use-stderr', default=True, help='log to standard error'), cfg.BoolOpt('use-syslog', default=False, help='output to syslog'), cfg.StrOpt('log-dir', default=None, help='log file directory'), cfg.StrOpt('log-file', default=None, help='log file name'), cfg.StrOpt('log-file-mode', default='0644', help='default log file permission'), cfg.StrOpt('log-config-file', default=None, help='Path to a logging config file to use') ]) _EARLY_LOG_HANDLER = None def early_init_log(level=None): global _EARLY_LOG_HANDLER _EARLY_LOG_HANDLER = logging.StreamHandler(sys.stderr) log = logging.getLogger() log.addHandler(_EARLY_LOG_HANDLER) if level is not None: log.setLevel(level) def _get_log_file(): if CONF.log_file: return CONF.log_file if CONF.log_dir: return os.path.join(CONF.log_dir, os.path.basename(inspect.stack()[-1][1])) + '.log' return None def init_log(): global _EARLY_LOG_HANDLER log = logging.getLogger() if CONF.log_config_file: try: logging.config.fileConfig(CONF.log_config_file, disable_existing_loggers=True) except ConfigParser.Error as e: print('Failed to parse %s: %s' % (CONF.log_config_file, e), file=sys.stderr) sys.exit(2) return if CONF.use_stderr: log.addHandler(logging.StreamHandler(sys.stderr)) if _EARLY_LOG_HANDLER is not None: log.removeHandler(_EARLY_LOG_HANDLER) _EARLY_LOG_HANDLER = None if CONF.use_syslog: if platform.system() == 'Darwin': address = '/var/run/syslog' else: address = '/dev/log' syslog = logging.handlers.SysLogHandler(address=address) log.addHandler(syslog) log_file = _get_log_file() if log_file is not None: log.addHandler(logging.handlers.WatchedFileHandler(log_file)) mode = int(CONF.log_file_mode, 8) os.chmod(log_file, mode) if CONF.default_log_level is not None: log.setLevel(CONF.default_log_level) elif CONF.verbose: log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO)
apache-2.0
rooshilp/CMPUT410Lab5
env-lab5/lib/python2.7/site-packages/flask/module.py
850
1363
# -*- coding: utf-8 -*- """ flask.module ~~~~~~~~~~~~ Implements a class that represents module blueprints. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os from .blueprints import Blueprint def blueprint_is_module(bp): """Used to figure out if something is actually a module""" return isinstance(bp, Module) class Module(Blueprint): """Deprecated module support. Until Flask 0.6 modules were a different name of the concept now available as blueprints in Flask. They are essentially doing the same but have some bad semantics for templates and static files that were fixed with blueprints. .. versionchanged:: 0.7 Modules were deprecated in favor for blueprints. """ def __init__(self, import_name, name=None, url_prefix=None, static_path=None, subdomain=None): if name is None: assert '.' in import_name, 'name required if package name ' \ 'does not point to a submodule' name = import_name.rsplit('.', 1)[1] Blueprint.__init__(self, name, import_name, url_prefix=url_prefix, subdomain=subdomain, template_folder='templates') if os.path.isdir(os.path.join(self.root_path, 'static')): self._static_folder = 'static'
apache-2.0
40223145c2g18/c2g18
exts/wsgi/static/Brython2.1.0-20140419-113919/Lib/browser/markdown.py
53
11306
import browser.html import _jsre as re import __random as random letters = 'abcdefghijklmnopqrstuvwxyz' letters += letters.upper()+'0123456789' class URL: def __init__(self,src): elts = src.split(maxsplit=1) self.href = elts[0] self.alt = '' if len(elts)==2: alt = elts[1] if alt[0]=='"' and alt[-1]=='"':self.alt=alt[1:-1] elif alt[0]=="'" and alt[-1]=="'":self.alt=alt[1:-1] elif alt[0]=="(" and alt[-1]==")":self.alt=alt[1:-1] class CodeBlock: def __init__(self,line): self.lines = [line] def to_html(self): if self.lines[0].startswith("`"): self.lines.pop(0) res = escape('\n'.join(self.lines)) res = unmark(res) res = '<pre class="marked">%s</pre>\n' %res return res,[] class HtmlBlock: def __init__(self, src): self.src = src def to_html(self): return self.src class Marked: def __init__(self, line=''): self.line = line self.children = [] def to_html(self): return apply_markdown(self.line) # get references refs = {} ref_pattern = r"^\[(.*)\]:\s+(.*)" def mark(src): global refs refs = {} # split source in sections # sections can be : # - a block-level HTML element (markdown syntax will not be processed) # - a script # - a span-level HTML tag (markdown syntax will be processed) # - a code block # normalise line feeds src = src.replace('\r\n','\n') # lines followed by dashes src = re.sub(r'(.*?)\n=+\n', '\n# \\1\n', src) src = re.sub(r'(.*?)\n-+\n', '\n## \\1\n', src) lines = src.split('\n')+[''] i = bq = 0 ul = ol = 0 while i<len(lines): # enclose lines starting by > in a blockquote if lines[i].startswith('>'): nb = 1 while nb<len(lines[i]) and lines[i][nb]=='>': nb += 1 lines[i] = lines[i][nb:] if nb>bq: lines.insert(i,'<blockquote>'*(nb-bq)) i += 1 bq = nb elif nb<bq: lines.insert(i,'</blockquote>'*(bq-nb)) i += 1 bq = nb elif bq>0: lines.insert(i,'</blockquote>'*bq) i += 1 bq = 0 # unordered lists if lines[i].strip() and lines[i].lstrip()[0] in '-+*' \ and len(lines[i].lstrip())>1 \ and lines[i].lstrip()[1]==' ' \ and (i==0 or ul or not lines[i-1].strip()): # line indentation indicates nesting level nb = 1+len(lines[i])-len(lines[i].lstrip()) lines[i] = '<li>'+lines[i][nb:] if nb>ul: lines.insert(i,'<ul>'*(nb-ul)) i += 1 elif nb<ul: lines.insert(i,'</ul>'*(ul-nb)) i += 1 ul = nb elif ul and not lines[i].strip(): lines.insert(i,'</ul>'*ul) i += 1 ul = 0 # ordered lists mo = re.search(r'^(\d+\.)',lines[i]) if mo: if not ol: lines.insert(i,'<ol>') i += 1 lines[i] = '<li>'+lines[i][len(mo.groups()[0]):] ol = 1 elif ol and not lines.strip(): lines.insert(i,'</ol>') i += 1 ol = 0 i += 1 if ul: lines.append('</ul>'*ul) if ol: lines.append('</ol>'*ol) if bq: lines.append('</blockquote>'*bq) sections = [] scripts = [] section = Marked() i = 0 while i<len(lines): line = lines[i] if line.strip() and line.startswith(' '): if isinstance(section,Marked) and section.line: sections.append(section) section = CodeBlock(line[4:]) j = i+1 while j<len(lines) and lines[j].startswith(' '): section.lines.append(lines[j][4:]) j += 1 sections.append(section) section = Marked() i = j continue elif line.lower().startswith('<script'): if isinstance(section,Marked) and section.line: sections.append(section) section = Marked() j = i+1 while j<len(lines): if lines[j].lower().startswith('</script>'): scripts.append('\n'.join(lines[i+1:j])) for k in range(i,j+1): lines[k] = '' break j += 1 i = j continue # atext header elif line.startswith('#'): level = 1 line = lines[i] while level<len(line) and line[level]=='#' and level<=6: level += 1 if not line[level+1:].strip(): if level==1: i += 1 continue else: lines[i] = '<H%s>%s</H%s>\n' %(level-1,'#',level-1) else: lines[i] = '<H%s>%s</H%s>\n' %(level,line[level+1:],level) else: mo = re.search(ref_pattern,line) if mo is not None: if isinstance(section,Marked) and section.line: sections.append(section) section = Marked() key = mo.groups()[0] value = URL(mo.groups()[1]) refs[key.lower()] = value else: if not line.strip(): line = '<p></p>' if section.line: section.line += ' ' section.line += line i += 1 if isinstance(section,Marked) and section.line: sections.append(section) res = '' for section in sections: mk,_scripts = section.to_html() res += mk scripts += _scripts return res,scripts def escape(czone): czone = czone.replace('&','&amp;') czone = czone.replace('<','&lt;') czone = czone.replace('>','&gt;') czone = czone.replace('_','&#95;') czone = czone.replace('*','&#42;') return czone def s_escape(mo): # used in re.sub czone = mo.string[mo.start():mo.end()] return escape(czone) def unmark(code_zone): # convert _ to &#95; inside inline code code_zone = code_zone.replace('_','&#95;') return code_zone def s_unmark(mo): # convert _ to &#95; inside inline code code_zone = mo.string[mo.start():mo.end()] code_zone = code_zone.replace('_','&#95;') return code_zone def apply_markdown(src): scripts = [] i = 0 while i<len(src): if src[i]=='[': start_a = i+1 while True: end_a = src.find(']',i) if end_a == -1: break if src[end_a-1]=='\\': i = end_a+1 else: break if end_a>-1 and src[start_a:end_a].find('\n')==-1: link = src[start_a:end_a] rest = src[end_a+1:].lstrip() if rest and rest[0]=='(': j = 0 while True: end_href = rest.find(')',j) if end_href == -1: break if rest[end_href-1]=='\\': j = end_href+1 else: break if end_href>-1 and rest[:end_href].find('\n')==-1: tag = '<a href="'+rest[1:end_href]+'">'+link+'</a>' src = src[:start_a-1]+tag+rest[end_href+1:] i = start_a+len(tag) elif rest and rest[0]=='[': j = 0 while True: end_key = rest.find(']',j) if end_key == -1: break if rest[end_key-1]=='\\': j = end_key+1 else: break if end_key>-1 and rest[:end_key].find('\n')==-1: if not key: key = link if key.lower() not in refs: raise KeyError('unknown reference %s' %key) url = refs[key.lower()] tag = '<a href="'+url+'">'+link+'</a>' src = src[:start_a-1]+tag+rest[end_key+1:] i = start_a+len(tag) i += 1 # before apply the markup with _ and *, isolate HTML tags because they can # contain these characters # We replace them temporarily by a random string rstr = ''.join(random.choice(letters) for i in range(16)) i = 0 state = None start = -1 data = '' tags = [] while i<len(src): if src[i]=='<': j = i+1 while j<len(src): if src[j]=='"' or src[j]=="'": if state==src[j] and src[j-1]!='\\': state = None src = src[:start+1]+data+src[j:] j = start+len(data)+1 data = '' elif state==None: state = src[j] start = j else: data += src[j] elif src[j]=='>' and state is None: tags.append(src[i:j+1]) src = src[:i]+rstr+src[j+1:] i += len(rstr) break elif state=='"' or state=="'": data += src[j] j += 1 #i = j elif src[i]=='`' and i>0 and src[i-1]!='\\': # ignore the content of inline code j = i+1 while j<len(src): if src[j]=='`' and src[j-1]!='\\': break j += 1 i = j i += 1 # escape "<", ">", "&" and "_" in inline code code_pattern = r'\`(.*?)\`' src = re.sub(code_pattern,s_escape,src) # replace escaped ` _ * by HTML characters src = src.replace(r'\\\`','&#96;') src = src.replace(r'\\_','&#95;') src = src.replace(r'\\*','&#42;') # emphasis strong_patterns = [('STRONG',r'\*\*(.*?)\*\*'),('B',r'__(.*?)__')] for tag,strong_pattern in strong_patterns: src = re.sub(strong_pattern,r'<%s>\1</%s>' %(tag,tag),src) em_patterns = [('EM',r'\*(.*?)\*'),('I',r'\_(.*?)\_')] for tag,em_pattern in em_patterns: src = re.sub(em_pattern,r'<%s>\1</%s>' %(tag,tag),src) # inline code code_pattern = r'\`(.*?)\`' src = re.sub(code_pattern,r'<code>\1</code>',src) # restore tags while True: pos = src.rfind(rstr) if pos==-1: break repl = tags.pop() src = src[:pos]+repl+src[pos+len(rstr):] src = '<p>'+src+'</p>' return src,scripts
gpl-2.0
srottem/indy-sdk
docs/how-tos/write-did-and-query-verkey/python/step3.py
4
1720
# First, put a steward DID and its keypair in the wallet. This doesn't write anything to the ledger, # but it gives us a key that we can use to sign a ledger transaction that we're going to submit later. print_log('\n5. Generate and store steward DID and verkey\n') # The DID and public verkey for this steward key are already in the ledger; they were part of the genesis # transactions we told the SDK to start with in the previous step. But we have to also put the DID, verkey, # and private signing key into our wallet, so we can use the signing key to submit an acceptably signed # transaction to the ledger, creating our *next* DID (which is truly new). This is why we use a hard-coded seed # when creating this DID--it guarantees that the same DID and key material are created that the genesis txns # expect. steward_seed = '000000000000000000000000Steward1' did_json = json.dumps({'seed': steward_seed}) steward_did, steward_verkey = await did.create_and_store_my_did(wallet_handle, did_json) print_log('Steward DID: ', steward_did) print_log('Steward Verkey: ', steward_verkey) # Now, create a new DID and verkey for a trust anchor, and store it in our wallet as well. Don't use a seed; # this DID and its keyas are secure and random. Again, we're not writing to the ledger yet. print_log('\n6. Generating and storing trust anchor DID and verkey\n') trust_anchor_did, trust_anchor_verkey = await did.create_and_store_my_did(wallet_handle, "{}") print_log('Trust anchor DID: ', trust_anchor_did) print_log('Trust anchor Verkey: ', trust_anchor_verkey)
apache-2.0
mkaluza/external_chromium_org
third_party/tlslite/tlslite/utils/rijndael.py
359
11341
""" A pure python (slow) implementation of rijndael with a decent interface To include - from rijndael import rijndael To do a key setup - r = rijndael(key, block_size = 16) key must be a string of length 16, 24, or 32 blocksize must be 16, 24, or 32. Default is 16 To use - ciphertext = r.encrypt(plaintext) plaintext = r.decrypt(ciphertext) If any strings are of the wrong length a ValueError is thrown """ # ported from the Java reference code by Bram Cohen, bram@gawth.com, April 2001 # this code is public domain, unless someone makes # an intellectual property claim against the reference # code, in which case it can be made public domain by # deleting all the comments and renaming all the variables import copy import string #----------------------- #TREV - ADDED BECAUSE THERE'S WARNINGS ABOUT INT OVERFLOW BEHAVIOR CHANGING IN #2.4..... import os if os.name != "java": import exceptions if hasattr(exceptions, "FutureWarning"): import warnings warnings.filterwarnings("ignore", category=FutureWarning, append=1) #----------------------- shifts = [[[0, 0], [1, 3], [2, 2], [3, 1]], [[0, 0], [1, 5], [2, 4], [3, 3]], [[0, 0], [1, 7], [3, 5], [4, 4]]] # [keysize][block_size] num_rounds = {16: {16: 10, 24: 12, 32: 14}, 24: {16: 12, 24: 12, 32: 14}, 32: {16: 14, 24: 14, 32: 14}} A = [[1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1], [1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1]] # produce log and alog tables, needed for multiplying in the # field GF(2^m) (generator = 3) alog = [1] for i in xrange(255): j = (alog[-1] << 1) ^ alog[-1] if j & 0x100 != 0: j ^= 0x11B alog.append(j) log = [0] * 256 for i in xrange(1, 255): log[alog[i]] = i # multiply two elements of GF(2^m) def mul(a, b): if a == 0 or b == 0: return 0 return alog[(log[a & 0xFF] + log[b & 0xFF]) % 255] # substitution box based on F^{-1}(x) box = [[0] * 8 for i in xrange(256)] box[1][7] = 1 for i in xrange(2, 256): j = alog[255 - log[i]] for t in xrange(8): box[i][t] = (j >> (7 - t)) & 0x01 B = [0, 1, 1, 0, 0, 0, 1, 1] # affine transform: box[i] <- B + A*box[i] cox = [[0] * 8 for i in xrange(256)] for i in xrange(256): for t in xrange(8): cox[i][t] = B[t] for j in xrange(8): cox[i][t] ^= A[t][j] * box[i][j] # S-boxes and inverse S-boxes S = [0] * 256 Si = [0] * 256 for i in xrange(256): S[i] = cox[i][0] << 7 for t in xrange(1, 8): S[i] ^= cox[i][t] << (7-t) Si[S[i] & 0xFF] = i # T-boxes G = [[2, 1, 1, 3], [3, 2, 1, 1], [1, 3, 2, 1], [1, 1, 3, 2]] AA = [[0] * 8 for i in xrange(4)] for i in xrange(4): for j in xrange(4): AA[i][j] = G[i][j] AA[i][i+4] = 1 for i in xrange(4): pivot = AA[i][i] if pivot == 0: t = i + 1 while AA[t][i] == 0 and t < 4: t += 1 assert t != 4, 'G matrix must be invertible' for j in xrange(8): AA[i][j], AA[t][j] = AA[t][j], AA[i][j] pivot = AA[i][i] for j in xrange(8): if AA[i][j] != 0: AA[i][j] = alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF]) % 255] for t in xrange(4): if i != t: for j in xrange(i+1, 8): AA[t][j] ^= mul(AA[i][j], AA[t][i]) AA[t][i] = 0 iG = [[0] * 4 for i in xrange(4)] for i in xrange(4): for j in xrange(4): iG[i][j] = AA[i][j + 4] def mul4(a, bs): if a == 0: return 0 r = 0 for b in bs: r <<= 8 if b != 0: r = r | mul(a, b) return r T1 = [] T2 = [] T3 = [] T4 = [] T5 = [] T6 = [] T7 = [] T8 = [] U1 = [] U2 = [] U3 = [] U4 = [] for t in xrange(256): s = S[t] T1.append(mul4(s, G[0])) T2.append(mul4(s, G[1])) T3.append(mul4(s, G[2])) T4.append(mul4(s, G[3])) s = Si[t] T5.append(mul4(s, iG[0])) T6.append(mul4(s, iG[1])) T7.append(mul4(s, iG[2])) T8.append(mul4(s, iG[3])) U1.append(mul4(t, iG[0])) U2.append(mul4(t, iG[1])) U3.append(mul4(t, iG[2])) U4.append(mul4(t, iG[3])) # round constants rcon = [1] r = 1 for t in xrange(1, 30): r = mul(2, r) rcon.append(r) del A del AA del pivot del B del G del box del log del alog del i del j del r del s del t del mul del mul4 del cox del iG class rijndael: def __init__(self, key, block_size = 16): if block_size != 16 and block_size != 24 and block_size != 32: raise ValueError('Invalid block size: ' + str(block_size)) if len(key) != 16 and len(key) != 24 and len(key) != 32: raise ValueError('Invalid key size: ' + str(len(key))) self.block_size = block_size ROUNDS = num_rounds[len(key)][block_size] BC = block_size / 4 # encryption round keys Ke = [[0] * BC for i in xrange(ROUNDS + 1)] # decryption round keys Kd = [[0] * BC for i in xrange(ROUNDS + 1)] ROUND_KEY_COUNT = (ROUNDS + 1) * BC KC = len(key) / 4 # copy user material bytes into temporary ints tk = [] for i in xrange(0, KC): tk.append((ord(key[i * 4]) << 24) | (ord(key[i * 4 + 1]) << 16) | (ord(key[i * 4 + 2]) << 8) | ord(key[i * 4 + 3])) # copy values into round key arrays t = 0 j = 0 while j < KC and t < ROUND_KEY_COUNT: Ke[t / BC][t % BC] = tk[j] Kd[ROUNDS - (t / BC)][t % BC] = tk[j] j += 1 t += 1 tt = 0 rconpointer = 0 while t < ROUND_KEY_COUNT: # extrapolate using phi (the round key evolution function) tt = tk[KC - 1] tk[0] ^= (S[(tt >> 16) & 0xFF] & 0xFF) << 24 ^ \ (S[(tt >> 8) & 0xFF] & 0xFF) << 16 ^ \ (S[ tt & 0xFF] & 0xFF) << 8 ^ \ (S[(tt >> 24) & 0xFF] & 0xFF) ^ \ (rcon[rconpointer] & 0xFF) << 24 rconpointer += 1 if KC != 8: for i in xrange(1, KC): tk[i] ^= tk[i-1] else: for i in xrange(1, KC / 2): tk[i] ^= tk[i-1] tt = tk[KC / 2 - 1] tk[KC / 2] ^= (S[ tt & 0xFF] & 0xFF) ^ \ (S[(tt >> 8) & 0xFF] & 0xFF) << 8 ^ \ (S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ \ (S[(tt >> 24) & 0xFF] & 0xFF) << 24 for i in xrange(KC / 2 + 1, KC): tk[i] ^= tk[i-1] # copy values into round key arrays j = 0 while j < KC and t < ROUND_KEY_COUNT: Ke[t / BC][t % BC] = tk[j] Kd[ROUNDS - (t / BC)][t % BC] = tk[j] j += 1 t += 1 # inverse MixColumn where needed for r in xrange(1, ROUNDS): for j in xrange(BC): tt = Kd[r][j] Kd[r][j] = U1[(tt >> 24) & 0xFF] ^ \ U2[(tt >> 16) & 0xFF] ^ \ U3[(tt >> 8) & 0xFF] ^ \ U4[ tt & 0xFF] self.Ke = Ke self.Kd = Kd def encrypt(self, plaintext): if len(plaintext) != self.block_size: raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext))) Ke = self.Ke BC = self.block_size / 4 ROUNDS = len(Ke) - 1 if BC == 4: SC = 0 elif BC == 6: SC = 1 else: SC = 2 s1 = shifts[SC][1][0] s2 = shifts[SC][2][0] s3 = shifts[SC][3][0] a = [0] * BC # temporary work array t = [] # plaintext to ints + key for i in xrange(BC): t.append((ord(plaintext[i * 4 ]) << 24 | ord(plaintext[i * 4 + 1]) << 16 | ord(plaintext[i * 4 + 2]) << 8 | ord(plaintext[i * 4 + 3]) ) ^ Ke[0][i]) # apply round transforms for r in xrange(1, ROUNDS): for i in xrange(BC): a[i] = (T1[(t[ i ] >> 24) & 0xFF] ^ T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^ T3[(t[(i + s2) % BC] >> 8) & 0xFF] ^ T4[ t[(i + s3) % BC] & 0xFF] ) ^ Ke[r][i] t = copy.copy(a) # last round is special result = [] for i in xrange(BC): tt = Ke[ROUNDS][i] result.append((S[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF) result.append((S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF) result.append((S[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF) result.append((S[ t[(i + s3) % BC] & 0xFF] ^ tt ) & 0xFF) return string.join(map(chr, result), '') def decrypt(self, ciphertext): if len(ciphertext) != self.block_size: raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext))) Kd = self.Kd BC = self.block_size / 4 ROUNDS = len(Kd) - 1 if BC == 4: SC = 0 elif BC == 6: SC = 1 else: SC = 2 s1 = shifts[SC][1][1] s2 = shifts[SC][2][1] s3 = shifts[SC][3][1] a = [0] * BC # temporary work array t = [0] * BC # ciphertext to ints + key for i in xrange(BC): t[i] = (ord(ciphertext[i * 4 ]) << 24 | ord(ciphertext[i * 4 + 1]) << 16 | ord(ciphertext[i * 4 + 2]) << 8 | ord(ciphertext[i * 4 + 3]) ) ^ Kd[0][i] # apply round transforms for r in xrange(1, ROUNDS): for i in xrange(BC): a[i] = (T5[(t[ i ] >> 24) & 0xFF] ^ T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^ T7[(t[(i + s2) % BC] >> 8) & 0xFF] ^ T8[ t[(i + s3) % BC] & 0xFF] ) ^ Kd[r][i] t = copy.copy(a) # last round is special result = [] for i in xrange(BC): tt = Kd[ROUNDS][i] result.append((Si[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF) result.append((Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF) result.append((Si[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF) result.append((Si[ t[(i + s3) % BC] & 0xFF] ^ tt ) & 0xFF) return string.join(map(chr, result), '') def encrypt(key, block): return rijndael(key, len(block)).encrypt(block) def decrypt(key, block): return rijndael(key, len(block)).decrypt(block) def test(): def t(kl, bl): b = 'b' * bl r = rijndael('a' * kl, bl) assert r.decrypt(r.encrypt(b)) == b t(16, 16) t(16, 24) t(16, 32) t(24, 16) t(24, 24) t(24, 32) t(32, 16) t(32, 24) t(32, 32)
bsd-3-clause
mozilla/addons-server
tests/performance/tasks/user.py
4
8985
import logging import urlparse import random from django.conf import settings from locust import TaskSet, task import lxml.html from fxa import oauth as fxa_oauth import helpers log = logging.getLogger(__name__) MAX_UPLOAD_POLL_ATTEMPTS = 200 FXA_CONFIG = settings.FXA_CONFIG[settings.DEFAULT_FXA_CONFIG_NAME] class BaseUserTaskSet(TaskSet): def on_start(self): self.fxa_account, self.email_account = helpers.get_fxa_account() log.info('Created {account} for load-tests'.format(account=self.fxa_account)) def is_legacy_page(self, app): return app in ('thunderbird', 'seamonkey') def get_app(self): # Slightly weighted app = random.choice(['firefox'] * 20 + ['thunderbird'] * 5 + ['seamonkey'] * 1) return app def get_url(self, url, app): # Only take a sub-set of languages, doesn't really matter only # increases variance and may circumvent some caches here and there user_language = random.choice( ('af', 'de', 'dsb', 'en-US', 'hsb', 'ru', 'tr', 'zh-CN', 'zh-TW') ) return url.format(app=app, language=user_language) def on_stop(self): log.info( 'Cleaning up and destroying {account}'.format(account=self.fxa_account) ) helpers.destroy_fxa_account(self.fxa_account, self.email_account) def login(self, fxa_account): log.info('calling login/start to generate fxa_state') response = self.client.get( '/api/v3/accounts/login/start/', allow_redirects=True ) params = dict(urlparse.parse_qsl(response.url)) fxa_state = params['state'] log.info('Get browser id session token') fxa_session = helpers.get_fxa_client().login( email=fxa_account.email, password=fxa_account.password ) oauth_client = fxa_oauth.Client( client_id=FXA_CONFIG['client_id'], client_secret=FXA_CONFIG['client_secret'], server_url=FXA_CONFIG['oauth_host'], ) log.info('convert browser id session token into oauth code') oauth_code = oauth_client.authorize_code(fxa_session, scope='profile') # Now authenticate the user, this will verify the user on the server response = self.client.get( '/api/v3/accounts/authenticate/', params={ 'state': fxa_state, 'code': oauth_code, }, name='/api/v3/accounts/authenticate/?state=:state', ) def logout(self, account): log.info('Logging out {}'.format(account)) self.client.get('/en-US/firefox/users/logout/') class UserTaskSet(BaseUserTaskSet): def _browse_listing_and_click_detail( self, listing_url, app, detail_selector, legacy_selector=None, name=None, force_legacy=False, ): # TODO: This should hit pagination automatically if there is any response = self.client.get( self.get_url(listing_url, app), allow_redirects=False, catch_response=True ) if (self.is_legacy_page(app) or force_legacy) and not legacy_selector: log.warning( 'Received legacy url without legacy selector. {} :: {}'.format( listing_url, detail_selector ) ) return if response.status_code == 200: html = lxml.html.fromstring(response.content) selector = ( detail_selector if not (self.is_legacy_page(app) or force_legacy) else legacy_selector ) collection_links = html.cssselect(selector) if not collection_links: log.warning( 'No selectable links on page. {} :: {}'.format( listing_url, selector ) ) url = random.choice(collection_links).get('href') kwargs = {} if name is not None: if self.is_legacy_page(app) or force_legacy: name = name.replace(':app', ':legacy_app') kwargs['name'] = name self.client.get(url, **kwargs) response.success() else: response.failure('Unexpected status code {}'.format(response.status_code)) @task(8) def browse(self): app = self.get_app() self.client.get(self.get_url('/{language}/{app}/', app)) self._browse_listing_and_click_detail( listing_url='/{language}/{app}/extensions/', app=app, detail_selector='a.SearchResult-link', legacy_selector='.items .item.addon a', ) @task(10) def search(self): app = self.get_app() term_choices = ('Spam', 'Privacy', 'Download') term = random.choice(term_choices) self.client.get( self.get_url('/{language}/{app}/search/?platform=linux&q=' + term, app) ) @task(6) def browse_and_download_addon(self): app = self.get_app() self._browse_listing_and_click_detail( listing_url='/{language}/{app}/extensions/', app=app, detail_selector='a.SearchResult-link', legacy_selector='.items .item.addon a', ) @task(5) def browse_collections(self): app = self.get_app() # detail and legacy selector match both, themes and regular add-ons self._browse_listing_and_click_detail( listing_url='/{language}/{app}/', app=app, detail_selector='a.Home-SubjectShelf-link', legacy_selector='.listing-grid .hovercard .summary>a', ) @task(4) def browse_categories(self): app = self.get_app() self._browse_listing_and_click_detail( listing_url='/{language}/{app}/extensions/', app=app, detail_selector='a.Categories-link', legacy_selector='ul#side-categories li a', ) @task(4) def browse_reviews(self): app = self.get_app() # TODO: Get add-ons more generalized by looking at collections # pages but for now that'll suffice. addons = ( 'grammarly-spell-checker', 'clip-to-onenote', 'evernote-web-clipper', 'reader', 'fractal-summer-colors', 'abstract-splash', 'colorful-fractal', 'tab-mix-plus', ) for addon in addons: self.client.get( self.get_url('/{language}/{app}/addon/%s/reviews/' % addon, app) ) @task(4) def browse_theme_categories(self): app = self.get_app() self._browse_listing_and_click_detail( listing_url='/{language}/{app}/complete-themes/', app=app, detail_selector=None, legacy_selector='.listing-grid .hovercard>a', name='/:lang/:app/complete-themes/:slug/', force_legacy=True, ) self._browse_listing_and_click_detail( listing_url='/{language}/{app}/themes/', app=app, detail_selector='a.SearchResult-link', legacy_selector='ul#side-categories li a', name='/:lang/:app/themes/:slug/', ) @task(3) def test_user_profile(self): app = self.get_app() # TODO: Generalize by actually creating a user-profile and uploading # some data. usernames = ( 'giorgio-maone', 'wot-services', 'onemen', 'gary-reyes', 'mozilla-labs5133025', 'gregglind', # Has many ratings 'daveg', ) for user in usernames: self.client.get(self.get_url('/{language}/{app}/user/%s/' % user, app)) @task(2) def test_rss_feeds(self): app = self.get_app() urls = ( # Add-on Category RSS Feed '/{language}/firefox/extensions/alerts-updates/format:rss', '/{language}/firefox/extensions/appearance/format:rss', '/{language}/firefox/extensions/bookmarks/format:rss', '/{language}/firefox/extensions/language-support/format:rss', # App Version RSS Feed '/{language}/{app}/pages/appversions/format:rss', # Collection RSS Feed '/{language}/firefox/collections/Vivre/ploaia/format:rss', # Featured Add-ons '/{language}/{app}/featured/format:rss', # Search tools RSS Feed '/{language}/{app}/search-tools/format:rss', ) self.client.get(self.get_url(random.choice(urls), app)) @task(1) def test_browse_appversions(self): app = self.get_app() self.client.get(self.get_url('/{language}/{app}/pages/appversions/', app))
bsd-3-clause
tanmaykm/edx-platform
common/djangoapps/contentserver/caching.py
16
1658
""" Helper functions for caching course assets. """ from django.core.cache import caches from django.core.cache.backends.base import InvalidCacheBackendError from opaque_keys import InvalidKeyError from xmodule.contentstore.content import STATIC_CONTENT_VERSION # See if there's a "course_assets" cache configured, and if not, fallback to the default cache. CONTENT_CACHE = caches['default'] try: CONTENT_CACHE = caches['course_assets'] except InvalidCacheBackendError: pass def set_cached_content(content): """ Stores the given piece of content in the cache, using its location as the key. """ CONTENT_CACHE.set(unicode(content.location).encode("utf-8"), content, version=STATIC_CONTENT_VERSION) def get_cached_content(location): """ Retrieves the given piece of content by its location if cached. """ return CONTENT_CACHE.get(unicode(location).encode("utf-8"), version=STATIC_CONTENT_VERSION) def del_cached_content(location): """ Delete content for the given location, as well versions of the content without a run. It's possible that the content could have been cached without knowing the course_key, and so without having the run. """ def location_str(loc): """Force the location to a Unicode string.""" return unicode(loc).encode("utf-8") locations = [location_str(location)] try: locations.append(location_str(location.replace(run=None))) except InvalidKeyError: # although deprecated keys allowed run=None, new keys don't if there is no version. pass CONTENT_CACHE.delete_many(locations, version=STATIC_CONTENT_VERSION)
agpl-3.0
redcoinproject/redcoin
contrib/pyminer/pyminer.py
1257
6438
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file license.txt or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import sys from multiprocessing import Process ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} pp = pprint.PrettyPrinter(indent=4) class BitcoinRPC: OBJID = 1 def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) def rpc(self, method, params=None): self.OBJID += 1 obj = { 'version' : '1.1', 'method' : method, 'id' : self.OBJID } if params is None: obj['params'] = [] else: obj['params'] = params self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) resp = self.conn.getresponse() if resp is None: print "JSON-RPC: no response" return None body = resp.read() resp_obj = json.loads(body) if resp_obj is None: print "JSON-RPC: cannot JSON-decode body" return None if 'error' in resp_obj and resp_obj['error'] != None: return resp_obj['error'] if 'result' not in resp_obj: print "JSON-RPC: no result in object" return None return resp_obj['result'] def getblockcount(self): return self.rpc('getblockcount') def getwork(self, data=None): return self.rpc('getwork', data) def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word))) return ''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return ''.join(out_words) class Miner: def __init__(self, id): self.id = id self.max_nonce = MAX_NONCE def work(self, datastr, targetstr): # decode work data hex string to binary static_data = datastr.decode('hex') static_data = bufreverse(static_data) # the first 76b of 80b do not change blk_hdr = static_data[:76] # decode 256-bit target value targetbin = targetstr.decode('hex') targetbin = targetbin[::-1] # byte-swap and dword-swap targetbin_str = targetbin.encode('hex') target = long(targetbin_str, 16) # pre-hash first 76b of block header static_hash = hashlib.sha256() static_hash.update(blk_hdr) for nonce in xrange(self.max_nonce): # encode 32-bit nonce value nonce_bin = struct.pack("<I", nonce) # hash final 4b, the nonce value hash1_o = static_hash.copy() hash1_o.update(nonce_bin) hash1 = hash1_o.digest() # sha256 hash of sha256 hash hash_o = hashlib.sha256() hash_o.update(hash1) hash = hash_o.digest() # quick test for winning solution: high 32 bits zero? if hash[-4:] != '\0\0\0\0': continue # convert binary hash to 256-bit Python long hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hash.encode('hex') l = long(hash_str, 16) # proof-of-work test: hash < target if l < target: print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,) return (nonce + 1, nonce_bin) else: print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,) # return (nonce + 1, nonce_bin) return (nonce + 1, None) def submit_work(self, rpc, original_data, nonce_bin): nonce_bin = bufreverse(nonce_bin) nonce = nonce_bin.encode('hex') solution = original_data[:152] + nonce + original_data[160:256] param_arr = [ solution ] result = rpc.getwork(param_arr) print time.asctime(), "--> Upstream RPC result:", result def iterate(self, rpc): work = rpc.getwork() if work is None: time.sleep(ERR_SLEEP) return if 'data' not in work or 'target' not in work: time.sleep(ERR_SLEEP) return time_start = time.time() (hashes_done, nonce_bin) = self.work(work['data'], work['target']) time_end = time.time() time_diff = time_end - time_start self.max_nonce = long( (hashes_done * settings['scantime']) / time_diff) if self.max_nonce > 0xfffffffaL: self.max_nonce = 0xfffffffaL if settings['hashmeter']: print "HashMeter(%d): %d hashes, %.2f Khash/sec" % ( self.id, hashes_done, (hashes_done / 1000.0) / time_diff) if nonce_bin is not None: self.submit_work(rpc, work['data'], nonce_bin) def loop(self): rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpass']) if rpc is None: return while True: self.iterate(rpc) def miner_thread(id): miner = Miner(id) miner.loop() if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: pyminer.py CONFIG-FILE" sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'host' not in settings: settings['host'] = '127.0.0.1' if 'port' not in settings: settings['port'] = 8332 if 'threads' not in settings: settings['threads'] = 1 if 'hashmeter' not in settings: settings['hashmeter'] = 0 if 'scantime' not in settings: settings['scantime'] = 30L if 'rpcuser' not in settings or 'rpcpass' not in settings: print "Missing username and/or password in cfg file" sys.exit(1) settings['port'] = int(settings['port']) settings['threads'] = int(settings['threads']) settings['hashmeter'] = int(settings['hashmeter']) settings['scantime'] = long(settings['scantime']) thr_list = [] for thr_id in range(settings['threads']): p = Process(target=miner_thread, args=(thr_id,)) p.start() thr_list.append(p) time.sleep(1) # stagger threads print settings['threads'], "mining threads started" print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port']) try: for thr_proc in thr_list: thr_proc.join() except KeyboardInterrupt: pass print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
mit
rizar/attention-lvcsr
libs/Theano/theano/tensor/blas.py
1
91536
"""Ops and optimizations for using BLAS calls BLAS = Basic Linear Algebra Subroutines Learn more about BLAS here: http://www.netlib.org/blas/blast-forum/ The standard BLAS libraries implement what is called "legacy BLAS" in that document. This documentation describes Theano's BLAS optimization pipeline. Where there is a discrepancy between how things do work and how they *should* work, both aspects should be documented. There are four kinds of BLAS Ops in Theano: - Python implementations (this file) - SciPy-based (blas_scipy) - C-based (blas_c) - CUDA-based (theano.sandbox.cuda.blas) Notes ----- Unfortunately (because it's confusing) this file currently contains Ops that contain both Python and C versions. I think it would be better to move the C implementations to blas_c so that this file is pure Python. -JB Ops === GEMM: Dot22, Dot22Scalar, GemmRelated, Gemm ------------------------------------------- The BLAS GEMM operation implements Z <- a X Y + b Z, where Z, X and Y are matrices, and a and b are scalars. Dot22 is a GEMM where a=1, b=0, and Z is allocated every time. Dot22Scalar is a GEMM where b=0 and Z is allocated every time. Gemm is a GEMM in all its generality. In the future we can refactor the GemmRelated, Gemm, Dot22 and Dot22Scalar Ops into a single Op. That new Op (Gemm2) is basically a normal Gemm, but with an additional configuration variable that says to ignore the input Z. Setting that configuration variable to True would make Gemm2 equivalent to the current Dot22 and Dot22Scalar. This would make the file a lot easier to read, and save a few hundred lines of library, to say nothing of testing and documentation. GEMV: Gemv ---------- The BLAS GEMV operation implements Z <- a X Y + b Z, where X is a matrix, Y, and Z are vectors, and a and b are scalars. GER: Ger -------- The BLAS GER operation implements Z <- a X' Y + Z, where X and Y are vectors, and matrix Z gets a rank-1 update. Other Notable BLAS-related Ops ------------------------------ SYRK is another useful special case of GEMM. Particularly SYRK preserves symmetry in the matrix that it updates. See how the linear-algebra module uses symmetry hints before implementing this Op, so that this Op is compatible with that system. Optimizations ============= The optimization pipeline works something like this: 1. identify dot22 from dot 2. identify gemm from dot22 3. identify dot22scalar from dot22 that are not gemm 4. specialize gemm to gemv where applicable 5. specialize gemm to ger where applicable 6. specialize dot22 -> gemv or ger where applicable :note: GEMM is the most canonical BLAS signature that we deal with so far, it would be good to turn most things into GEMM (dot, inner, outer, dot22, dot22scalar), and then to specialize from gemm to the various other L2 and L3 operations. Identify Dot22 -------------- Numpy's dot supports arguments that are of any rank, and we should support that too (just for compatibility). The BLAS optimizations work with Dot Ops whose inputs are each either vector or matrix. So the first part of the optimization pipeline is to transform qualifying Dot Ops to Dot22 Ops. Dot22 Ops may be transformed further, but they will get implemented by a BLAS call. More precisely, Dot nodes whose inputs are all vectors or matrices and whose inputs both have the same dtype, and whose dtype is float or complex, become Dot22. This is implemented in `local_dot_to_dot22`. Identify Gemm from Dot22 ------------------------ This is complicated, done in GemmOptimizer. Identify Dot22Scalar from Dot22 ------------------------------- Dot22 Ops that remain after the GemmOptimizer is done have not qualified as GEMM Ops. Still they might be scaled by a factor, in which case we use Dot22Scalar which is like Gemm, but without the b and the Z. In the future it would be good to merge this into the GemmOptimizer. Specialize Gemm to Gemv ----------------------- If arguments to GEMM are dimshuffled vectors, then we can use GEMV instead. This optimization is `local_gemm_to_gemv`. """ from __future__ import print_function import copy import logging import os import time import numpy import numpy.distutils try: import numpy.distutils.__config__ except ImportError: pass from six import iteritems from six.moves import reduce, xrange from theano import config from theano.gof import (utils, Op, view_roots, local_optimizer, Optimizer, InconsistencyError, toolbox, SequenceDB, EquilibriumOptimizer, Apply, ReplacementDidntRemovedError) from theano.printing import pprint, FunctionPrinter, debugprint from theano.compile.mode import optdb import theano.scalar from theano.tensor import basic as T from theano.tensor.blas_headers import blas_header_text from theano.tensor.blas_headers import blas_header_version from theano.tensor.opt import in2out, local_dimshuffle_lift _logger = logging.getLogger('theano.tensor.blas') try: import scipy.linalg.blas have_fblas = True try: fblas = scipy.linalg.blas.fblas except AttributeError: # A change merged in Scipy development version on 2012-12-02 replaced # `scipy.linalg.blas.fblas` with `scipy.linalg.blas`. # See http://github.com/scipy/scipy/pull/358 fblas = scipy.linalg.blas _blas_gemv_fns = {numpy.dtype('float32'): fblas.sgemv, numpy.dtype('float64'): fblas.dgemv, numpy.dtype('complex64'): fblas.cgemv, numpy.dtype('complex128'): fblas.zgemv} except ImportError as e: have_fblas = False # This is used in Gemv and ScipyGer. We use CGemv and CGer # when theano.config.blas.ldflags is defined. So we don't need a # warning in that case. if not config.blas.ldflags: _logger.warning('Failed to import scipy.linalg.blas, and ' 'Theano flag blas.ldflags is empty. ' 'Falling back on slower implementations for ' 'dot(matrix, vector), dot(vector, matrix) and ' 'dot(vector, vector) (%s)', str(e)) class Gemv(Op): """ expression is beta * y + alpha * A x A is matrix x, y are vectors alpha, beta are scalars output is a vector that can be inplace on y """ __props__ = ("inplace",) def __init__(self, inplace): self.inplace = inplace if inplace: self.destroy_map = {0: [0]} def __str__(self): if self.inplace: return '%s{inplace}' % self.__class__.__name__ else: return '%s{no_inplace}' % self.__class__.__name__ def make_node(self, y, alpha, A, x, beta): y = T.as_tensor_variable(y) x = T.as_tensor_variable(x) A = T.as_tensor_variable(A) alpha = T.as_tensor_variable(alpha) beta = T.as_tensor_variable(beta) if y.dtype != A.dtype or y.dtype != x.dtype: raise TypeError('Gemv requires matching dtypes', (y.dtype, A.dtype, x.dtype)) if A.ndim != 2: raise TypeError('gemv requires matrix for A', A.type) if x.ndim != 1: raise TypeError('gemv requires vector for x', x.type) if y.ndim != 1: raise TypeError('gemv requires vector for y', y.type) return Apply(self, [y, alpha, A, x, beta], [y.type()]) def perform(self, node, inputs, out_storage): y, alpha, A, x, beta = inputs if (have_fblas and y.shape[0] != 0 and x.shape[0] != 0 and y.dtype in _blas_gemv_fns): gemv = _blas_gemv_fns[y.dtype] if (A.shape[0] != y.shape[0] or A.shape[1] != x.shape[0]): raise ValueError( 'Incompatible shapes for gemv ' '(beta * y + alpha * dot(A, x)). y: %s, A: %s, x: %s ' % (y.shape, A.shape, x.shape)) # Here I suppose that A is in c order. If we don't make it # explicitly as fortran order, scipy 0.7.2 seam to create # a copy in fortran order instead of just reshaping it # and using the trans flag. # If A is already in fortran order, make it in c order and using the # trans flag don't seam to cause slowdown. # out_storage[0][0] = gemv(alpha, A, x, beta, y, # overwrite_y=self.inplace) out_storage[0][0] = gemv(alpha, A.T, x, beta, y, overwrite_y=self.inplace, trans=True) else: out = numpy.dot(A, x) if alpha != 1: out *= alpha if beta != 1: out += beta * y else: out += y out_storage[0][0] = numpy.asarray(out, dtype=y.dtype) def infer_shape(self, node, input_shapes): return [input_shapes[0]] gemv_no_inplace = Gemv(inplace=False) gemv_inplace = Gemv(inplace=True) # For the user interface. Opt will make them inplace later gemv = gemv_no_inplace class Ger(Op): """ BLAS defines general rank-1 update GER as A <- A + alpha x y' for matrix A, scalar alpha, vectors x and y. This interface to GER allows non-destructive operation on A via the `destructive` argument to the constructor. :TODO: Create better classes ScipyGer and CGer that inherit from this class and override the make_thunk() method to use Scipy and C respectively. """ __props__ = ("destructive",) def __init__(self, destructive): self.destructive = destructive if destructive: self.destroy_map = {0: [0]} def __str__(self): if self.destructive: return '%s{destructive}' % self.__class__.__name__ else: return '%s{non-destructive}' % self.__class__.__name__ def make_node(self, A, alpha, x, y): A = T.as_tensor_variable(A) y = T.as_tensor_variable(y) x = T.as_tensor_variable(x) alpha = T.as_tensor_variable(alpha) if len(set([A.dtype, alpha.dtype, x.dtype, y.dtype])) != 1: raise TypeError('ger requires matching dtypes', (A.dtype, alpha.dtype, x.dtype, y.dtype)) if alpha.ndim != 0: raise TypeError('ger requires scalar alpha', alpha.type) if A.ndim != 2: raise TypeError('ger requires matrix for A', A.type) if x.ndim != 1: raise TypeError('ger requires vector for x', x.type) if y.ndim != 1: raise TypeError('ger requires vector for y', y.type) if x.dtype not in ('float32', 'float64', 'complex64', 'complex128'): raise TypeError('only float and complex types supported', x.dtype) return Apply(self, [A, alpha, x, y], [A.type()]) def perform(self, node, inp, out): cA, calpha, cx, cy = inp cZ, = out if self.destructive: A = cA else: A = cA.copy() if calpha != 1: A += calpha * numpy.outer(cx, cy) else: A += numpy.outer(cx, cy) cZ[0] = A def infer_shape(self, node, input_shapes): return [input_shapes[0]] ger = Ger(destructive=False) ger_destructive = Ger(destructive=True) def ldflags(libs=True, flags=False, libs_dir=False, include_dir=False): """Extract a list of compilation flags from config.blas.ldflags. Depending on the options, different type of flags will be kept. It returns a list of libraries against which an Op's object file should be linked to benefit from a BLAS implementation. Parameters ---------- libs : bool, optional Extract flags starting with "-l" (the default is True). libs_dir : bool, optional Extract flags starting with "-L" (the default is False). include_dir : bool, optional Extract flags starting with "-I" (the default is False). flags: bool, optional Extract all the other flags (the default is False). Returns ------- list of strings Extracted flags. """ ldflags_str = theano.config.blas.ldflags return _ldflags(ldflags_str=ldflags_str, libs=libs, flags=flags, libs_dir=libs_dir, include_dir=include_dir) @utils.memoize def _ldflags(ldflags_str, libs, flags, libs_dir, include_dir): """Extract list of compilation flags from a string. Depending on the options, different type of flags will be kept. Parameters ---------- ldflags_str : string The string to process. Typically, this will be the content of `theano.config.blas.ldflags`. libs : bool Extract flags starting with "-l". flags: bool Extract all the other flags. libs_dir: bool Extract flags starting with "-L". include_dir: bool Extract flags starting with "-I". Returns ------- list of strings Extracted flags. """ rval = [] if libs_dir: found_dyn = False dirs = [x[2:] for x in ldflags_str.split() if x.startswith('-L')] l = _ldflags(ldflags_str=ldflags_str, libs=True, flags=False, libs_dir=False, include_dir=False) for d in dirs: for f in os.listdir(d): if (f.endswith('.so') or f.endswith('.dylib') or f.endswith('.dll')): if any([f.find(ll) >= 0 for ll in l]): found_dyn = True if not found_dyn and dirs: _logger.warning( "We did not found a dynamic library into the " "library_dir of the library we use for blas. If you use " "ATLAS, make sure to compile it with dynamics library.") for t in ldflags_str.split(): # Remove extra quote. if t.startswith("'") or t.startswith('"'): t = t[1:] if t.endswith("'") or t.endswith('"'): t = t[:-1] try: t0, t1, t2 = t[0:3] assert t0 == '-' except Exception: raise ValueError('invalid token "%s" in ldflags_str: "%s"' % (t, ldflags_str)) if libs_dir and t1 == 'L': rval.append(t[2:]) elif include_dir and t1 == 'I': raise ValueError('Include dirs are not used for blas. We disable' ' this as this can hide other headers and this' ' is not wanted.', t) rval.append(t[2:]) elif libs and t1 == 'l': # example -lmkl rval.append(t[2:]) elif flags and t1 not in ['L', 'I', 'l']: # example -openmp rval.append(t) elif flags and t1 == 'L': # to find it when we load the compiled op if the env of the # used is not well configured. rval.append('-Wl,-rpath,' + t[2:]) return rval class GemmRelated(Op): """Base class for Gemm and Dot22. This class provides a kind of templated gemm Op. """ __props__ = () def c_support_code(self): # return cblas_header_text() mod_str = """ #ifndef MOD #define MOD % #endif static double time_time() // a time function like time.time() { struct timeval tv; gettimeofday(&tv, 0); return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0; } """ return blas_header_text() + mod_str def c_headers(self): # std.cout doesn't require the '%' symbol to print stuff... # so it works much better with python's string-substitution stuff. return ['<iostream>', '<time.h>', '<sys/time.h>'] def c_libraries(self): return ldflags() # code_cache_version is built by subclasses from # build_gemm_version def c_compile_args(self): return ldflags(libs=False, flags=True) def c_lib_dirs(self): return ldflags(libs=False, libs_dir=True) def c_header_dirs(self): return ldflags(libs=False, include_dir=True) declare_NS = """ int unit = 0; int type_num = PyArray_DESCR(%(_x)s)->type_num; int type_size = PyArray_DESCR(%(_x)s)->elsize; // in bytes npy_intp* Nx = PyArray_DIMS(%(_x)s); npy_intp* Ny = PyArray_DIMS(%(_y)s); npy_intp* Nz = 0; //PyArray_DIMS(%(_zout)s); npy_intp* Sx = PyArray_STRIDES(%(_x)s); npy_intp* Sy = PyArray_STRIDES(%(_y)s); npy_intp* Sz = 0; //PyArray_STRIDES(%(_zout)s); //strides for x, y, z in dimensions 0, 1 int sx_0, sx_1, sy_0, sy_1, sz_0, sz_1; """ # setup_z_Nz_Sz = None check_xyz_rank2 = """ if (PyArray_NDIM(%(_x)s) != 2) { PyErr_Format(PyExc_NotImplementedError, "rank(x) != 2. rank(x) is %%d.", PyArray_NDIM(%(_x)s)); %(fail)s; } if (PyArray_NDIM(%(_y)s) != 2) { PyErr_Format(PyExc_NotImplementedError, "rank(y) != 2. rank(y) is %%d.", PyArray_NDIM(%(_y)s)); %(fail)s; } if (%(_zout)s && PyArray_NDIM(%(_zout)s) != 2) { PyErr_Format(PyExc_NotImplementedError, "rank(z) != 2. rank(z) is %%d.", PyArray_NDIM(%(_zout)s)); %(fail)s; } """ check_xyz_double_or_float = """ if ((PyArray_DESCR(%(_x)s)->type_num != NPY_DOUBLE) && (PyArray_DESCR(%(_x)s)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(x) is not double or float"); %(fail)s;} if ((PyArray_DESCR(%(_y)s)->type_num != NPY_DOUBLE) && (PyArray_DESCR(%(_y)s)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(y) is not double or float"); %(fail)s;} if ((PyArray_DESCR(%(_zout)s)->type_num != NPY_DOUBLE) && (PyArray_DESCR(%(_zout)s)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(z) is not double or float"); %(fail)s;} if ((PyArray_DESCR(%(_x)s)->type_num != PyArray_DESCR(%(_y)s)->type_num) ||(PyArray_DESCR(%(_x)s)->type_num != PyArray_DESCR(%(_zout)s)->type_num)) { PyErr_SetString(PyExc_NotImplementedError, "type(x), type(y), type(z) are not all the same"); %(fail)s; } """ # it is not necessary that a or b have the same type as x,y,z check_ab_double_or_float = """ if ((PyArray_DESCR(%(_a)s)->type_num != NPY_DOUBLE) && (PyArray_DESCR(%(_a)s)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(a) is not double or float"); %(fail)s;} if ((PyArray_DESCR(%(_b)s)->type_num != NPY_DOUBLE) && (PyArray_DESCR(%(_b)s)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(b) is not double or float"); %(fail)s;} """ check_dims = """ if (Nx[0] != Nz[0]) { PyErr_Format(PyExc_ValueError, "Shape mismatch: x has %%ld rows but z has %%ld rows", (long int)Nx[0], (long int)Nz[0]); %(fail)s; } if (Nx[1] != Ny[0]) { PyErr_Format(PyExc_ValueError, "Shape mismatch: x has %%ld cols (and %%ld rows) but y has %%ld rows (and %%ld cols)", (long int)Nx[1], (long int)Nx[0], (long int)Ny[0], (long int)Ny[1]); %(fail)s; } if (Ny[1] != Nz[1]) { PyErr_Format(PyExc_ValueError, "Shape mismatch: y has %%ld cols but z has %%ld cols", (long int)Ny[1], (long int)Nz[1]); %(fail)s; } // We must not raise an error when Nx[1] == 0. This would disable cases // that numpy.dot accept. """ check_strides = """ /* If some matrices are not contiguous on either dimensions, or have invalid strides, copy their content into a contiguous one */ if ((Sx[0] < 1) || (Sx[1] < 1) || (Sx[0] MOD type_size) || (Sx[1] MOD type_size) || ((Sx[0] != type_size) && (Sx[1] != type_size))) { PyArrayObject * _x_copy = (PyArrayObject *) PyArray_Copy(%(_x)s); if (!_x_copy) %(fail)s Py_XDECREF(%(_x)s); %(_x)s = _x_copy; Sx = PyArray_STRIDES(%(_x)s); } if ((Sy[0] < 1) || (Sy[1] < 1) || (Sy[0] MOD type_size) || (Sy[1] MOD type_size) || ((Sy[0] != type_size) && (Sy[1] != type_size))) { PyArrayObject * _y_copy = (PyArrayObject *) PyArray_Copy(%(_y)s); if (!_y_copy) %(fail)s Py_XDECREF(%(_y)s); %(_y)s = _y_copy; Sy = PyArray_STRIDES(%(_y)s); } if ((Sz[0] < 1) || (Sz[1] < 1) || (Sz[0] MOD type_size) || (Sz[1] MOD type_size) || ((Sz[0] != type_size) && (Sz[1] != type_size))) { PyArrayObject * _z_copy = (PyArrayObject *) PyArray_Copy(%(_zout)s); if (!_z_copy) %(fail)s Py_XDECREF(%(_zout)s); %(_zout)s = _z_copy; Sz = PyArray_STRIDES(%(_zout)s); } """ encode_strides_in_unit = """ /* encode the stride structure of _x,_y,_zout into a single integer */ unit |= ((Sx[1] == type_size || Nx[1]==1) ? 0x0 : (Sx[0] == type_size || Nx[0]==1) ? 0x1 : 0x2) << 8; unit |= ((Sy[1] == type_size || Ny[1]==1) ? 0x0 : (Sy[0] == type_size || Ny[0]==1) ? 0x1 : 0x2) << 4; unit |= ((Sz[1] == type_size || Nz[1]==1) ? 0x0 : (Sz[0] == type_size || Nz[0]==1) ? 0x1 : 0x2) << 0; """ compute_strides = """ /* create appropriate strides for malformed matrices that are row or column * vectors, or empty matrices. * In that case, the value of the stride does not really matter, but * some versions of BLAS insist that: * - they are not smaller than the number of elements in the array, * - they are not 0. */ sx_0 = (Nx[0] > 1) ? Sx[0]/type_size : (Nx[1] + 1); sx_1 = (Nx[1] > 1) ? Sx[1]/type_size : (Nx[0] + 1); sy_0 = (Ny[0] > 1) ? Sy[0]/type_size : (Ny[1] + 1); sy_1 = (Ny[1] > 1) ? Sy[1]/type_size : (Ny[0] + 1); sz_0 = (Nz[0] > 1) ? Sz[0]/type_size : (Nz[1] + 1); sz_1 = (Nz[1] > 1) ? Sz[1]/type_size : (Nz[0] + 1); """ begin_switch_typenum = """ switch (type_num) { """ case_float = """ case NPY_FLOAT: { """ # case_float_ab_constants = None case_float_gemm = """ float* x = (float*)PyArray_DATA(%(_x)s); float* y = (float*)PyArray_DATA(%(_y)s); float* z = (float*)PyArray_DATA(%(_zout)s); char N = 'N'; char T = 'T'; int Nz0 = Nz[0], Nz1 = Nz[1], Nx1 = Nx[1]; //std::cerr << (unit/256) MOD 16 << (unit / 16) MOD 16 << unit MOD 16<< '\\n'; //double t0 = time_time(); switch(unit) { case 0x000: sgemm_(&N, &N, &Nz1, &Nz0, &Nx1, &a, y, &sy_0, x, &sx_0, &b, z, &sz_0); break; case 0x100: sgemm_(&N, &T, &Nz1, &Nz0, &Nx1, &a, y, &sy_0, x, &sx_1, &b, z, &sz_0); break; case 0x010: sgemm_(&T, &N, &Nz1, &Nz0, &Nx1, &a, y, &sy_1, x, &sx_0, &b, z, &sz_0); break; case 0x110: sgemm_(&T, &T, &Nz1, &Nz0, &Nx1, &a, y, &sy_1, x, &sx_1, &b, z, &sz_0); break; case 0x001: sgemm_(&T, &T, &Nz0, &Nz1, &Nx1, &a, x, &sx_0, y, &sy_0, &b, z, &sz_1); break; case 0x101: sgemm_(&N, &T, &Nz0, &Nz1, &Nx1, &a, x, &sx_1, y, &sy_0, &b, z, &sz_1); break; case 0x011: sgemm_(&T, &N, &Nz0, &Nz1, &Nx1, &a, x, &sx_0, y, &sy_1, &b, z, &sz_1); break; case 0x111: sgemm_(&N, &N, &Nz0, &Nz1, &Nx1, &a, x, &sx_1, y, &sy_1, &b, z, &sz_1); break; default: PyErr_SetString(PyExc_ValueError, "some matrix has no unit stride"); %(fail)s; }; //fprintf(stderr, "Calling sgemm %%i %%i %%i %%i took %%f\\n", unit, Nz1, Nz0, Nx1, time_time() - t0); """ case_double = """ } break; case NPY_DOUBLE: { """ # case_double_ab_constants = None case_double_gemm = """ double* x = (double*)PyArray_DATA(%(_x)s); double* y = (double*)PyArray_DATA(%(_y)s); double* z = (double*)PyArray_DATA(%(_zout)s); char N = 'N'; char T = 'T'; int Nz0 = Nz[0], Nz1 = Nz[1], Nx1 = Nx[1]; //std::cerr << (unit/256) MOD 16 << (unit / 16) MOD 16 << unit MOD 16<< '\\n'; //double t0 = time_time(); //fprintf(stderr, "unit=%%x N= %%i %%i %%i S = %%i %%i %%i %%i %%i %%i\\n", unit, //Nz1, Nz0, Nx1, //sy_0, sy_1, //sx_0, sx_1, //sz_0, sz_1 //); switch(unit) { case 0x000: dgemm_(&N, &N, &Nz1, &Nz0, &Nx1, &a, y, &sy_0, x, &sx_0, &b, z, &sz_0); break; case 0x100: dgemm_(&N, &T, &Nz1, &Nz0, &Nx1, &a, y, &sy_0, x, &sx_1, &b, z, &sz_0); break; case 0x010: dgemm_(&T, &N, &Nz1, &Nz0, &Nx1, &a, y, &sy_1, x, &sx_0, &b, z, &sz_0); break; case 0x110: dgemm_(&T, &T, &Nz1, &Nz0, &Nx1, &a, y, &sy_1, x, &sx_1, &b, z, &sz_0); break; case 0x001: dgemm_(&T, &T, &Nz0, &Nz1, &Nx1, &a, x, &sx_0, y, &sy_0, &b, z, &sz_1); break; case 0x101: dgemm_(&N, &T, &Nz0, &Nz1, &Nx1, &a, x, &sx_1, y, &sy_0, &b, z, &sz_1); break; case 0x011: dgemm_(&T, &N, &Nz0, &Nz1, &Nx1, &a, x, &sx_0, y, &sy_1, &b, z, &sz_1); break; case 0x111: dgemm_(&N, &N, &Nz0, &Nz1, &Nx1, &a, x, &sx_1, y, &sy_1, &b, z, &sz_1); break; default: PyErr_SetString(PyExc_ValueError, "some matrix has no unit stride"); %(fail)s; }; //fprintf(stderr, "Calling dgemm %%i %%i %%i %%i took %%f\\n", // unit, Nz1, Nz0, Nx1, time_time()- t0); """ end_switch_typenum = """ } break; } """ def build_gemm_call(self): return reduce(str.__add__, ( self.declare_NS, self.check_xyz_rank2, self.setup_z_Nz_Sz, self.check_xyz_double_or_float, self.check_ab_double_or_float, self.check_dims, self.check_strides, self.encode_strides_in_unit, self.compute_strides, self.begin_switch_typenum, self.case_float, self.case_float_ab_constants, self.case_float_gemm, self.case_double, self.case_double_ab_constants, self.case_double_gemm, self.end_switch_typenum), '') def build_gemm_version(self): return (13, blas_header_version()) class Gemm(GemmRelated): """In-place version of matrix-matrix multiplication (with accumulation). When a and b are scalars and x, y, and z are matrices, then gemm(z,a,x,y,b) is similar to b*z + a*dot(x,y) The difference between the two is that the top form is destructive on z, whereas the bottom form is not. Gemm works in-place on the storage associated with z, and the L{Variable} returned by Gemm has a storage that will be aliased to the storage of the z argument. Because of this in-place computation, an L{Apply} of this op will destroy the L{Variable} z on which it operates. (See L{DestructiveOps} for an explanation of what destroying means in the context of theano graphs. See L{BlasLapackSupport} for more optimized linear algebra operations.) """ E_rank = 'gemm only works for rank 2' E_scalar = 'gemm requires scalar argument' E_z_uniq = 'argument z aliased to x or y' # TODO: justify / delete this E_mixed = 'gemm requires matching dtypes' E_float = 'gemm requires floating-point dtypes' __props__ = ('inplace',) def __init__(self, inplace): self.inplace = inplace if self.inplace: self.destroy_map = {0: [0]} self.setup_z_Nz_Sz = self.setup_z_Nz_Sz_inplace else: self.setup_z_Nz_Sz = self.setup_z_Nz_Sz_outplace def __str__(self): if self.inplace: inplace_str = 'inplace' else: inplace_str = 'no_inplace' return '%s{%s}' % (self.__class__.__name__, inplace_str) def __setstate__(self, dct): self.__dict__.update(dct) if self.inplace: self.setup_z_Nz_Sz = self.setup_z_Nz_Sz_inplace else: self.setup_z_Nz_Sz = self.setup_z_Nz_Sz_outplace # Correctly reload older pickles where _op_use_c_code and # destroy_map were not saved if '_op_use_c_code' not in self.__dict__: self._op_use_c_code = theano.config.cxx if 'destroy_map' not in self.__dict__ and self.inplace: self.destroy_map = {0: [0]} def __getstate__(self): rval = self.__dict__.copy() # Do not serialize the setup code, it will be restored in __setstate__ # depending on the value of 'inplace' rval.pop('setup_z_Nz_Sz') return rval def make_node(self, *inputs): inputs = list(map(T.as_tensor_variable, inputs)) if len(inputs) != 5: raise TypeError( "Wrong number of inputs for %s (expected 5, got %s)" % (self, len(inputs))) z, a, x, y, b = inputs # For the consistency check we don't want z to be a cached constant. if getattr(z, 'cached', False): z = copy.copy(z) zr, xr, yr = [set(view_roots(i)) for i in (z, x, y)] # We want the gemm to be inplace. When this op is inplace, it # declare to be inplace only on z. So to make it safe, we # raise an error if z can be a view on x or y. # I don't know if Theano currently can support that case. As # this case don't happen in our code, I won't spent time # investigating this. So the assert is for safety. I also # think there is another mechanism that would prevent this, # but I don't what to modify old code and have chance to break # something. if zr.intersection(xr): raise InconsistencyError(Gemm.E_z_uniq, (z, x)) if zr.intersection(yr): raise InconsistencyError(Gemm.E_z_uniq, (z, y)) if z.ndim != 2: raise TypeError(Gemm.E_rank, z) if a.ndim != 0: raise TypeError(Gemm.E_scalar, a) if x.ndim != 2: raise TypeError(Gemm.E_rank, x) if y.ndim != 2: raise TypeError(Gemm.E_rank, y) if b.ndim != 0: raise TypeError(Gemm.E_scalar, b) if not (z.dtype == a.dtype == x.dtype == y.dtype == b.dtype): raise TypeError(Gemm.E_mixed, (z.dtype, a.dtype, x.dtype, y.dtype, b.dtype)) if (not z.dtype.startswith('float') and not z.dtype.startswith('complex')): raise TypeError(Gemm.E_float, (z.dtype)) output = z.type() return Apply(self, inputs, [output]) def perform(self, node, inp, out): z, a, x, y, b = inp zout, = out assert a.shape == () assert b.shape == () if not self.inplace: z = z.copy() # the original z will not be changed if z.shape == (): z.itemset(z * a + b * numpy.dot(x, y)) zout[0] = z else: if b == 0.0: if a == 1.0: z[:] = numpy.dot(x, y) elif a == -1.0: z[:] = -numpy.dot(x, y) else: z[:] = a * numpy.dot(x, y) elif b == 1.0: if a == 1.0: z += numpy.dot(x, y) elif a == -1.0: z -= numpy.dot(x, y) else: z += a * numpy.dot(x, y) else: z *= b z += a * numpy.dot(x, y) zout[0] = z def infer_shape(self, node, input_shapes): return [input_shapes[0]] setup_z_Nz_Sz_inplace = """ if (%(_zout)s != %(_z)s) { if (%(_zout)s) { Py_DECREF(%(_zout)s); } %(_zout)s = %(_z)s; Py_INCREF(%(_zout)s); } Nz = PyArray_DIMS(%(_z)s); Sz = PyArray_STRIDES(%(_z)s); """ setup_z_Nz_Sz_outplace = """ if ((NULL == %(_zout)s) || (PyArray_DIMS(%(_zout)s)[0] != PyArray_DIMS(%(_z)s)[0]) || (PyArray_DIMS(%(_zout)s)[1] != PyArray_DIMS(%(_z)s)[1]) || (PyArray_STRIDES(%(_zout)s)[0] <= 0) || (PyArray_STRIDES(%(_zout)s)[1] <= 0) || (PyArray_STRIDES(%(_zout)s)[0] MOD type_size) || (PyArray_STRIDES(%(_zout)s)[1] MOD type_size) || ((PyArray_STRIDES(%(_zout)s)[0] != type_size) && (PyArray_STRIDES(%(_zout)s)[1] != type_size))) { Py_XDECREF(%(_zout)s); npy_intp dims[2]; dims[0] = PyArray_DIMS(%(_z)s)[0]; dims[1] = PyArray_DIMS(%(_z)s)[1]; %(_zout)s = (PyArrayObject*)PyArray_SimpleNew(2, dims, PyArray_TYPE(%(_z)s)); //fprintf(stderr, "Gemm Allocating %%i %%i\\n", dims[0], dims[1]); if(!%(_zout)s) { PyErr_SetString(PyExc_MemoryError, "failed to alloc gemm_no_inplace output"); %(fail)s } } Nz = PyArray_DIMS(%(_zout)s); Sz = PyArray_STRIDES(%(_zout)s); if (PyArray_DESCR(%(_zout)s)->type_num == NPY_FLOAT) { float * zoutdata = (float*)PyArray_DATA(%(_zout)s); int zoi = Sz[0] / sizeof(float); int zoj = Sz[1] / sizeof(float); const float * zdata = (float*)PyArray_DATA(%(_z)s); int zi = PyArray_STRIDES(%(_z)s)[0]/sizeof(float); int zj = PyArray_STRIDES(%(_z)s)[1]/sizeof(float); for (int i = 0; i < Nz[0]; ++i) { for (int j = 0; j < Nz[1]; ++j) { zoutdata[zoi*i + zoj*j] = zdata[zi*i + zj*j]; } } } else if (PyArray_DESCR(%(_zout)s)->type_num == NPY_DOUBLE) { double * zoutdata = (double*) PyArray_DATA(%(_zout)s); int zoi = Sz[0] / sizeof(double); int zoj = Sz[1] / sizeof(double); const double * zdata = (double*)PyArray_DATA(%(_z)s); int zi = PyArray_STRIDES(%(_z)s)[0]/sizeof(double); int zj = PyArray_STRIDES(%(_z)s)[1]/sizeof(double); for (int i = 0; i < Nz[0]; ++i) { for (int j = 0; j < Nz[1]; ++j) { zoutdata[zoi*i + zoj*j] = zdata[zi*i + zj*j]; } } } else { PyErr_SetString(PyExc_AssertionError, "neither float nor double dtype"); %(fail)s } """ case_float_ab_constants = """ #define REAL float float a = (PyArray_DESCR(%(_a)s)->type_num == NPY_FLOAT) ? (REAL)(((float*)PyArray_DATA(%(_a)s))[0]) : (REAL)(((double*)PyArray_DATA(%(_a)s))[0]); float b = (PyArray_DESCR(%(_b)s)->type_num == NPY_FLOAT) ? (REAL)(((float*)PyArray_DATA(%(_b)s))[0]) : (REAL)(((double*)PyArray_DATA(%(_b)s))[0]); #undef REAL """ case_double_ab_constants = """ #define REAL double double a = (PyArray_DESCR(%(_a)s)->type_num == NPY_FLOAT) ? (REAL)(((float*)PyArray_DATA(%(_a)s))[0]) : (REAL)(((double*)PyArray_DATA(%(_a)s))[0]); double b = (PyArray_DESCR(%(_b)s)->type_num == NPY_FLOAT) ? (REAL)(((float*)PyArray_DATA(%(_b)s))[0]) : (REAL)(((double*)PyArray_DATA(%(_b)s))[0]); #undef REAL """ def c_code(self, node, name, inp, out, sub): _z, _a, _x, _y, _b = inp _zout, = out if node.inputs[0].type.dtype.startswith('complex'): raise utils.MethodNotDefined('%s.c_code' % self.__class__.__name__) if not config.blas.ldflags: return super(Gemm, self).c_code(node, name, (_z, _a, _x, _y, _b), (_zout, ), sub) full_code = self.build_gemm_call() % dict(locals(), **sub) return full_code def c_code_cache_version(self): gv = self.build_gemm_version() if gv: return (5,) + gv else: return gv gemm_inplace = Gemm(inplace=True) gemm_no_inplace = Gemm(inplace=False) # For the user interface. Theano optimization will make them inplace gemm = gemm_no_inplace pprint.assign(gemm_inplace, FunctionPrinter('gemm_inplace')) pprint.assign(gemm_no_inplace, FunctionPrinter('gemm_no_inplace')) def res_is_a(node, op, maxclients=None): if maxclients is not None: retval = (len(node.clients) <= maxclients) else: retval = True return (node.owner and node.owner.op == op and retval) def _as_scalar(res, dtype=None): """Return None or a TensorVariable whose type is in T.float_scalar_types""" if dtype is None: dtype = config.floatX if numpy.all(res.type.broadcastable): while res.owner and isinstance(res.owner.op, T.DimShuffle): res = res.owner.inputs[0] # may still have some number of True's if res.type.broadcastable: rval = res.dimshuffle() else: rval = res if rval.type.dtype[:3] in ('int', 'uin'): # We check that the upcast of res and dtype won't change dtype. # If dtype is float64, we will cast int64 to float64. # This is valid when res is a scalar used as input to a dot22 # as the cast of the scalar can be done before or after the dot22 # and this will give the same result. if theano.scalar.upcast(res.dtype, dtype) == dtype: return T.cast(rval, dtype) else: return None return rval def _is_real_matrix(res): return (res.type.dtype in ('float32', 'float64') and res.type.ndim == 2 and res.type.broadcastable[0] is False and res.type.broadcastable[1] is False) # cope with tuple vs. list def _is_real_vector(res): return (res.type.dtype in ('float32', 'float64') and res.type.ndim == 1 and res.type.broadcastable[0] is False) def _beta_L_plus_alpha_M(beta, L, alpha, M, recurse_flip=True): # print 'BETA L + ALPHA M', beta, L, alpha, M, recurse_flip # EXPRESSION: (beta * L) + (alpha * M) # we've already checked the client counts, now just make the type check. # if res_is_a(M, _dot22, 1): if M.owner and M.owner.op == _dot22: Ml, Mr = M.owner.inputs rval = [gemm_no_inplace(L, alpha, Ml, Mr, beta)] # print 'GEMM 0', rval, beta, L, alpha, M return rval, M # it also might be the case that there is a dimshuffle between the + # and the dot22. local_dot_to_dot22 in particular will put in such things. if (M.owner and isinstance(M.owner.op, T.DimShuffle) and M.owner.inputs[0].owner and isinstance(M.owner.inputs[0].owner.op, Dot22)): MM = M.owner.inputs[0] if M.owner.op.new_order == (0,): # it is making a column MM into a vector MMl, MMr = MM.owner.inputs g = gemm_no_inplace(L.dimshuffle(0, 'x'), alpha, MMl, MMr, beta) rval = [g.dimshuffle(0)] return rval, MM if M.owner.op.new_order == (1,): # it is making a row MM into a vector MMl, MMr = MM.owner.inputs g = gemm_no_inplace(L.dimshuffle('x', 0), alpha, MMl, MMr, beta) rval = [g.dimshuffle(1)] return rval, MM if len(M.owner.op.new_order) == 0: # it is making a row MM into a vector MMl, MMr = MM.owner.inputs g = gemm_no_inplace(L.dimshuffle('x', 'x'), alpha, MMl, MMr, beta) rval = [g.dimshuffle()] return rval, MM # this is False'd out because of inadequate testing. # TODO see ticket #237 if False and res_is_a(M, gemm_no_inplace, 1): # EXPRESSION: (beta * L) + (alpha * (gemm_no_inplace(G, a, u, v, b))) # EXPRESSION: (beta * L) + alpha * (b * G) + alpha * a * dot(u, v) G, a, u, v, b = M.owner.inputs # print 'GEMM', G, L if res_is_a(G, _dot22, 1): # EXPRESSION: (beta * L) + # (alpha * (gemm_no_inplace(dot(x,y), a, u, v, b))) x, y = G.owner.inputs # EXPRESSION: (beta * L) + (alpha * ((b*dot(x,y) + # (a * dot(u, v))))) # EXPRESSION: (beta * L) + (alpha*b*dot(x,y)) + # (alpha * a * dot(u, v)) rval = [gemm_no_inplace(gemm_no_inplace(L, alpha * b, x, y, beta), alpha * a, u, v, 1.0)] return rval if (G is L): # EXPRESSION: (beta * L) + (alpha*b*L) + (alpha * a * dot(u, v)) rval = [gemm_no_inplace(L, alpha * a, u, v, alpha * b + beta)] return rval if (1.0 != alpha): # at the very least, move the alpha inside the gemm_no_inplace rval = [beta * L + gemm_no_inplace(G, alpha * a, u, v, alpha * b)] return rval if recurse_flip: return _beta_L_plus_alpha_M(alpha, M, beta, L, recurse_flip=False) else: return False, False def _gemm_canonicalize(r, scale, rval, maxclients): # Tries to interpret node as a sum of scalars * (vectors or matrices) def scaled(thing): if scale == 1: return thing if scale == -1: return -thing else: return scale * thing try: r.type.broadcastable except Exception: return None if ((r.type.ndim not in (1, 2)) or r.type.dtype not in ('float32', 'float64', 'complex64', 'complex128')): rval.append(scaled(r)) return rval if maxclients and len(getattr(r, 'clients', [])) > maxclients: rval.append((scale, r)) return rval if r.owner and r.owner.op == T.sub: _gemm_canonicalize(r.owner.inputs[0], scale, rval, 1) _gemm_canonicalize(r.owner.inputs[1], -scale, rval, 1) elif r.owner and r.owner.op == T.add: for i in r.owner.inputs: _gemm_canonicalize(i, scale, rval, 1) elif r.owner and r.owner.op == T.neg: _gemm_canonicalize(r.owner.inputs[0], -scale, rval, 1) elif r.owner and r.owner.op == T.mul: scalars = [] vectors = [] matrices = [] for i in r.owner.inputs: if numpy.all(i.type.broadcastable): while i.owner and isinstance(i.owner.op, T.DimShuffle): i = i.owner.inputs[0] if i.type.broadcastable: scalars.append(i.dimshuffle()) else: scalars.append(i) elif _is_real_vector(i): vectors.append(i) elif _is_real_matrix(i): matrices.append(i) else: # just put the original arguments as in the base case rval.append((scale, r)) return rval if len(matrices) == 1: assert len(vectors) == 0 m = matrices[0] if len(scalars) == 0: _gemm_canonicalize(m, scale, rval, 1) elif len(scalars) == 1: _gemm_canonicalize(m, scaled(scalars[0]), rval, 1) else: _gemm_canonicalize(m, T.mul(scaled(scalars[0]), *scalars[1:]), rval, 1) elif len(vectors) == 1: assert len(matrices) == 0 v = vectors[0] if len(scalars) == 0: _gemm_canonicalize(v, scale, rval, 1) elif len(scalars) == 1: _gemm_canonicalize(v, scaled(scalars[0]), rval, 1) else: _gemm_canonicalize(v, T.mul(scaled(scalars[0]), *scalars[1:]), rval, 1) else: # lets not open this up rval.append((scale, r)) else: rval.append((scale, r)) return rval def _factor_canonicalized(lst): # remove duplicates from canonicalized list # we only delete out of the right end of the list, # once i has touched a list element, it is permantent lst = list(lst) # print 'FACTOR', lst # for t in lst: # if not isinstance(t, (list, tuple)): # t = (t,) # for e in t: # try: # theano.printing.debugprint(e) # except TypeError: # print e, type(e) i = 0 while i < len(lst) - 1: try: s_i, M_i = lst[i] except Exception: i += 1 continue j = i + 1 while j < len(lst): try: s_j, M_j = lst[j] except Exception: j += 1 continue if M_i is M_j: s_i = s_i + s_j lst[i] = (s_i, M_i) del lst[j] else: j += 1 i += 1 return lst def _gemm_from_factored_list(lst): """ Returns None, or a list to replace node.outputs. """ lst2 = [] # Remove the tuple that can't be cast correctly. # This can happen when we try to cast a complex to a real for sM in lst: # Make every pair in list have matching dtypes # sM can be a tuple of 2 elements or a theano variable. if isinstance(sM, tuple): sm0, sm1 = sM sm0 = T.as_tensor_variable(sm0) if theano.scalar.upcast(sm0.dtype, sm1.dtype) == sm1.dtype: lst2.append((T.cast(sm0, sm1.dtype), sM[1])) lst = lst2 def item_to_var(t): try: s, M = t except Exception: return t if s == 1: return M if s == -1: return -M return s * M # Try every pair in the sM_list, trying to turn it into a gemm operation for i in xrange(len(lst) - 1): s_i, M_i = lst[i] for j in xrange(i + 1, len(lst)): s_j, M_j = lst[j] if M_i.type != M_j.type: continue # print 'TRYING', (s_i, M_i, s_j, M_j) gemm_of_sM_list, old_dot22 = _beta_L_plus_alpha_M(s_i, M_i, s_j, M_j) # print 'GOT IT', gemm_of_sM_list if gemm_of_sM_list: assert len(gemm_of_sM_list) == 1 add_inputs = [item_to_var(input) for k, input in enumerate(lst) if k not in (i, j)] add_inputs.extend(gemm_of_sM_list) if len(add_inputs) > 1: rval = [T.add(*add_inputs)] else: rval = add_inputs # print "RETURNING GEMM THIGN", rval return rval, old_dot22 def _gemm_from_node2(node): """ :todo: In many expressions, there are many ways to turn it into a gemm. For example dot(a,b) + c + d. This function should return all of them, so that if one version of gemm causes a cycle in the graph, then another application of gemm can be tried. """ lst = [] t0 = time.time() _gemm_canonicalize(node.outputs[0], 1.0, lst, 0) t1 = time.time() # print "GEMM CANON", lst if len(lst) > 1: lst = _factor_canonicalized(lst) t2 = time.time() rval = _gemm_from_factored_list(lst) t3 = time.time() # It can happen that _factor_canonicalized and # _gemm_from_factored_list return a node with an incorrect # type. This happens in particular when one of the scalar # factors forces the upcast of the whole expression. In that # case, we simply skip that candidate for Gemm. This was # discussed in # http://groups.google.com/group/theano-dev/browse_thread/thread/a3096c82856e3ad5, # but never made it into a trac ticket. if rval and (rval[0][0].type == node.outputs[0].type): return rval, t1 - t0, t2 - t1, t3 - t2 return None, t1 - t0, 0, 0 class GemmOptimizer(Optimizer): """Graph optimizer for inserting Gemm operations.""" def __init__(self): Optimizer.__init__(self) self.warned = False def add_requirements(self, fgraph): fgraph.attach_feature(toolbox.ReplaceValidate()) def apply(self, fgraph): did_something = True nb_iter = 0 nb_replacement = 0 nb_replacement_didn_t_remove = 0 nb_inconsistency_make = 0 nb_inconsistency_replace = 0 time_canonicalize = 0 time_factor_can = 0 time_factor_list = 0 time_toposort = 0 if fgraph.profile: validate_before = fgraph.profile.validate_time callbacks_before = fgraph.execute_callbacks_times.copy() callback_before = fgraph.execute_callbacks_time def on_import(new_node): if new_node is not node: nodelist.append(new_node) u = theano.gof.opt.Updater(on_import, None, None) fgraph.attach_feature(u) while did_something: nb_iter += 1 t0 = time.time() nodelist = theano.gof.graph.io_toposort(fgraph.inputs, fgraph.outputs) time_toposort += time.time() - t0 did_something = False nodelist.reverse() for node in nodelist: if not (isinstance(node.op, T.Elemwise) and isinstance(node.op.scalar_op, (theano.scalar.Add, theano.scalar.Sub, theano.scalar.Neg, theano.scalar.Mul))): continue if node not in fgraph.apply_nodes: # This mean that we already removed this node from # the graph continue try: new_outputs, time1, time2, time3 = _gemm_from_node2(node) time_canonicalize += time1 time_factor_can += time2 time_factor_list += time3 except InconsistencyError: nb_inconsistency_make += 1 continue if new_outputs: new_outputs, old_dot22 = new_outputs assert len(new_outputs) == len(node.outputs) try: fgraph.replace_all_validate_remove( list(zip(node.outputs, new_outputs)), [old_dot22], reason='GemmOptimizer', # For now we disable the warning as we know case # that we need to fix. warn=False, # warn=not self.warned ) did_something = True nb_replacement += 1 except InconsistencyError: # TODO: retry other applications of gemm (see comment # in _gemm_from_node) nb_inconsistency_replace += 1 except ReplacementDidntRemovedError: nb_replacement_didn_t_remove += 1 self.warned = True fgraph.remove_feature(u) if fgraph.profile: validate_time = fgraph.profile.validate_time - validate_before callback_time = fgraph.execute_callbacks_time - callback_before callbacks_time = {} for k, v in iteritems(fgraph.execute_callbacks_times): if k in callbacks_before: callbacks_time[k] = v - callbacks_before[k] else: callbacks_time[k] = v else: validate_time = None callback_time = None callbacks_time = {} return (self, nb_iter, nb_replacement, nb_replacement_didn_t_remove, nb_inconsistency_make, nb_inconsistency_replace, time_canonicalize, time_factor_can, time_factor_list, time_toposort, validate_time, callback_time, callbacks_time,) @staticmethod def print_profile(stream, prof, level=0): blanc = (' ' * level) print(blanc, "GemmOptimizer", file=stream) print(blanc, " nb_iter", prof[1], file=stream) print(blanc, " nb_replacement", prof[2], file=stream) print(blanc, " nb_replacement_didn_t_remove", prof[3], file=stream) print(blanc, " nb_inconsistency_make", prof[4], file=stream) print(blanc, " nb_inconsistency_replace", prof[5], file=stream) print(blanc, " time_canonicalize", prof[6], file=stream) print(blanc, " time_factor_can", prof[7], file=stream) print(blanc, " time_factor_list", prof[8], file=stream) print(blanc, " time_toposort", prof[9], file=stream) print(blanc, " validate_time", prof[10], file=stream) print(blanc, " callback_time", prof[11], file=stream) if prof[11] > 1: print(blanc, " callbacks_time", file=stream) for i in sorted(iteritems(prof[12]), key=lambda a: a[1]): if i[1] > 0: print(i) class Dot22(GemmRelated): """Compute a matrix-matrix product. This is a specialization of the more general Dot(). """ def make_node(self, x, y): dtypes = ('float32', 'float64', 'complex64', 'complex128') if x.type.ndim != 2 or x.type.dtype not in dtypes: raise TypeError(x) if y.type.ndim != 2 or y.type.dtype not in dtypes: raise TypeError(y) if y.type.dtype != x.type.dtype: raise TypeError('dtype mismatch to Dot22') bz = (x.type.broadcastable[0], y.type.broadcastable[1]) outputs = [T.tensor(x.type.dtype, bz)] return Apply(self, [x, y], outputs) def perform(self, node, inp, out): x, y = inp z, = out try: z[0] = numpy.asarray(numpy.dot(x, y)) except ValueError as e: # The error raised by numpy has no shape information, we mean to # add that e.args = e.args + (x.shape, y.shape) raise def infer_shape(self, node, input_shapes): return [[input_shapes[0][0], input_shapes[1][1]]] setup_z_Nz_Sz = """ if ((NULL == %(_zout)s) || (PyArray_DIMS(%(_zout)s)[0] != PyArray_DIMS(%(_x)s)[0]) || (PyArray_DIMS(%(_zout)s)[1] != PyArray_DIMS(%(_y)s)[1])) { if (NULL != %(_zout)s) Py_XDECREF(%(_zout)s); npy_intp dims[2]; dims[0] = PyArray_DIMS(%(_x)s)[0]; dims[1] = PyArray_DIMS(%(_y)s)[1]; %(_zout)s = (PyArrayObject*)PyArray_SimpleNew(2, dims, PyArray_TYPE(%(_x)s)); //fprintf(stderr, "Dot Allocating %%i %%i\\n", dims[0], dims[1]); if(!%(_zout)s) { PyErr_SetString(PyExc_MemoryError, "failed to alloc dot22 output"); %(fail)s } } Nz = PyArray_DIMS(%(_zout)s); Sz = PyArray_STRIDES(%(_zout)s); """ check_ab_double_or_float = "" case_float_ab_constants = """ float a = 1.0; float b = 0.0; """ case_double_ab_constants = """ double a = 1.0; double b = 0.0; """ def c_code(self, node, name, inp, out, sub): # DEBUG _x, _y = inp _zout, = out if node.inputs[0].type.dtype.startswith('complex'): raise utils.MethodNotDefined('%s.c_code' % self.__class__.__name__) if len(self.c_libraries()) <= 0: return super(Dot22, self).c_code(node, name, (_x, _y), (_zout, ), sub) full_code = self.build_gemm_call() % dict(locals(), **sub) return full_code def c_code_cache_version(self): gv = self.build_gemm_version() if gv: return (2,) + gv else: return gv _dot22 = Dot22() @local_optimizer([T.Dot]) def local_dot_to_dot22(node): # This works for tensor.outer too because basic.outer is a macro that # produces a dot(dimshuffle,dimshuffle) of form 4 below if not isinstance(node.op, T.Dot): return x, y = node.inputs if y.type.dtype != x.type.dtype: # TODO: upcast one so the types match _logger.info('Not optimizing dot with inputs %s %s %s %s', x, y, x.type, y.type) return if y.type.dtype in ['float32', 'float64', 'complex64', 'complex128']: if x.ndim == 2 and y.ndim == 2: # print "local_dot_to_dot22: MM" return [_dot22(*node.inputs)] if x.ndim == 2 and y.ndim == 1: # print "local_dot_to_dot22: MV" return [_dot22(x, y.dimshuffle(0, 'x')).dimshuffle(0)] if x.ndim == 1 and y.ndim == 2: # print "local_dot_to_dot22: VM" return [_dot22(x.dimshuffle('x', 0), y).dimshuffle(1)] if x.ndim == 1 and y.ndim == 1: # print "local_dot_to_dot22: VV" return [_dot22(x.dimshuffle('x', 0), y.dimshuffle(0, 'x')).dimshuffle()] _logger.info('Not optimizing dot with inputs %s %s %s %s', x, y, x.type, y.type) @local_optimizer([gemm_no_inplace], inplace=True) def local_inplace_gemm(node): if node.op == gemm_no_inplace: return [gemm_inplace(*node.inputs)] @local_optimizer([gemv_no_inplace], inplace=True) def local_inplace_gemv(node): if node.op == gemv_no_inplace: return [gemv_inplace(*node.inputs)] @local_optimizer([ger], inplace=True) def local_inplace_ger(node): if node.op == ger: return [ger_destructive(*node.inputs)] @local_optimizer([gemm_no_inplace]) def local_gemm_to_gemv(node): """GEMM acting on row or column matrices -> GEMV.""" if node.op == gemm_no_inplace: z, a, x, y, b = node.inputs if z.broadcastable == x.broadcastable == (True, False): r = gemv_no_inplace(z.dimshuffle(1), a, y.T, x.dimshuffle(1), b) return [r.dimshuffle('x', 0)] if z.broadcastable == y.broadcastable == (False, True): r = gemv_no_inplace(z.dimshuffle(0), a, x, y.dimshuffle(0), b) return [r.dimshuffle(0, 'x')] @local_optimizer([gemm_no_inplace]) def local_gemm_to_ger(node): """GEMM computing an outer-product -> GER.""" if node.op == gemm_no_inplace: z, a, x, y, b = node.inputs if x.broadcastable[1] and y.broadcastable[0]: # x and y are both vectors so this might qualifies for a GER xv = x.dimshuffle(0) yv = y.dimshuffle(1) try: bval = T.get_scalar_constant_value(b) except T.NotScalarConstantError: # b isn't a constant, GEMM is doing useful pre-scaling return if bval == 1: # best case a natural GER rval = ger(z, a, xv, yv) return [rval] elif bval == 0: # GER on zeros_like should be faster than GEMM zeros = T.zeros([x.shape[0], y.shape[1]], x.dtype) rval = ger(zeros, a, xv, yv) return [rval] else: # if bval is another constant, then z is being usefully # pre-scaled and GER isn't really the right tool for the job. return # TODO: delete this optimization when we have the proper dot->gemm->ger pipeline # working @local_optimizer([_dot22]) def local_dot22_to_ger_or_gemv(node): """dot22 computing an outer-product -> GER.""" if node.op == _dot22: x, y = node.inputs xb = x.broadcastable yb = y.broadcastable one = T.as_tensor_variable(numpy.asarray(1, dtype=x.dtype)) zero = T.as_tensor_variable(numpy.asarray(0, dtype=x.dtype)) if xb[1] and yb[0]: # x and y are both vectors so this might qualifies for a GER xv = x.dimshuffle(0) yv = y.dimshuffle(1) zeros = T.zeros([x.shape[0], y.shape[1]], dtype=x.dtype) rval = ger(zeros, one, xv, yv) return [rval] if xb[0] and yb[1]: # x and y are both vectors so this qualifies for a sdot / ddot # TODO: Theano doesn't have a sdot, but gemv is better than _dot22 xv = x.dimshuffle(1) zeros = T.AllocEmpty(x.dtype)(1) rval = gemv_no_inplace(zeros, one, y.T, xv, zero) return [rval.dimshuffle('x', 0)] if xb[0] and not yb[0] and not yb[1]: # x is vector, y is matrix so try gemv xv = x.dimshuffle(1) zeros = T.AllocEmpty(x.dtype)(y.shape[1]) rval = gemv_no_inplace(zeros, one, y.T, xv, zero) return [rval.dimshuffle('x', 0)] if not xb[0] and not xb[1] and yb[1]: # x is matrix, y is vector, try gemv yv = y.dimshuffle(0) zeros = T.AllocEmpty(x.dtype)(x.shape[0]) rval = gemv_no_inplace(zeros, one, x, yv, zero) return [rval.dimshuffle(0, 'x')] ################################# # # Set up the BlasOpt optimizer # ################################# blas_optdb = SequenceDB() # run after numerical stability optimizations (1.5) optdb.register('BlasOpt', blas_optdb, 1.7, 'fast_run', 'fast_compile') # run before specialize (2.0) because specialize is basically a # free-for-all that makes the graph crazy. # fast_compile is needed to have GpuDot22 created. blas_optdb.register('local_dot_to_dot22', in2out(local_dot_to_dot22), 0, 'fast_run', 'fast_compile') blas_optdb.register('gemm_optimizer', GemmOptimizer(), 10, 'fast_run') blas_optdb.register('local_gemm_to_gemv', EquilibriumOptimizer([local_gemm_to_gemv, local_gemm_to_ger, local_dot22_to_ger_or_gemv, local_dimshuffle_lift], max_use_ratio=5, ignore_newtrees=False), 15, 'fast_run') # After destroyhandler(49.5) but before we try to make elemwise things # inplace (75) blas_opt_inplace = in2out(local_inplace_gemm, local_inplace_gemv, local_inplace_ger, name="blas_opt_inplace") optdb.register('InplaceBlasOpt', blas_opt_inplace, 70.0, 'fast_run', 'inplace', 'blas_opt_inplace') class Dot22Scalar(GemmRelated): """Compute a matrix-matrix product. This is a specialization of the more general Dot() Used to call optimized gemm implementation. Also used to generate a gemm later. compute scalar*dot(x,y). """ def make_node(self, x, y, a): if a.ndim != 0: raise TypeError(Gemm.E_scalar, a) if x.ndim != 2: raise TypeError(Gemm.E_rank, x) if y.ndim != 2: raise TypeError(Gemm.E_rank, y) if not (a.dtype == x.dtype == y.dtype): raise TypeError('Dot22Scalar requires matching dtypes', (a.dtype, x.dtype, y.dtype)) if (not a.dtype.startswith('float') and not a.dtype.startswith('complex')): raise TypeError('Dot22Scalar requires float or complex args', a.dtype) bz = [x.type.broadcastable[0], y.type.broadcastable[1]] outputs = [T.tensor(x.type.dtype, bz)] return Apply(self, [x, y, a], outputs) def perform(self, node, inp, out): x, y, scalar = inp z, = out try: z[0] = numpy.asarray(scalar * numpy.dot(x, y)) except ValueError as e: # The error raised by numpy has no shape information, we # mean to add that e.args = e.args + (x.shape, y.shape) raise def infer_shape(self, node, input_shapes): return [[input_shapes[0][0], input_shapes[1][1]]] setup_z_Nz_Sz = Dot22.setup_z_Nz_Sz check_ab_double_or_float = """ if ((PyArray_DESCR(%(_a)s)->type_num != NPY_DOUBLE) && (PyArray_DESCR(%(_a)s)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(a) is not double or float"); %(fail)s;} """ case_float_ab_constants = """ #define REAL float float a = (PyArray_DESCR(%(_a)s)->type_num == NPY_FLOAT) ? (REAL)(((float*)PyArray_DATA(%(_a)s))[0]) : (REAL)(((double*)PyArray_DATA(%(_a)s))[0]); #undef REAL float b = 0.0; """ case_double_ab_constants = """ #define REAL double double a = (PyArray_DESCR(%(_a)s)->type_num == NPY_FLOAT) ? (REAL)(((float*)PyArray_DATA(%(_a)s))[0]) : (REAL)(((double*)PyArray_DATA(%(_a)s))[0]); #undef REAL double b = 0.0; """ def c_code(self, node, name, inp, out, sub): _x, _y, _a = inp _zout, = out if node.inputs[0].type.dtype.startswith('complex'): raise utils.MethodNotDefined('%s.c_code' % self.__class__.__name__) if len(self.c_libraries()) <= 0: return super(Dot22Scalar, self).c_code(node, name, (_x, _y), (_zout, ), sub) full_code = self.build_gemm_call() % dict(locals(), **sub) return full_code def c_code_cache_version(self): gv = self.build_gemm_version() if gv: return (2,) + gv else: return gv _dot22scalar = Dot22Scalar() @local_optimizer([T.mul]) def local_dot22_to_dot22scalar(node): """ Notes ----- Previous attempts to alter this optimization to replace dot22 with gemm instead of dot22scalar resulted in some Scan nodes being duplicated and the ScanSaveMem optimization never running on them, resulting in highly increased memory usage. Until this issue is resolved, this optimization should keep using dot22scalar instead of gemm. We upcast the scalar if after the multiplication with the dot this give the same type. We execute this optimizer after the gemm optimizer. This allow to give more priority to gemm that give more speed up then this optimizer, but allow the gemm optimizer to ignore this op. TODO: support when we can reorder the mul to generate a dot22scalar or fix the canonizer to merge them(1 mul with multiple inputs) """ if node.op != T.mul: return False i_dot22 = [x.owner and x.owner.op == _dot22 for x in node.inputs] if not any(i_dot22): return False # no dot22 if i_dot22.count(True) > 1: # TODO: try each of them. pass # return False #TODO fix dot22_idx = i_dot22.index(True) d = node.inputs[dot22_idx] i_scalar = [_as_scalar(x, dtype=d.dtype) for x in node.inputs] if not any(i_scalar): # Check if we can reorder the graph as this mul have a mul in inputs. # We support only 1 additional level of mul. # The canonizer should have merged those mul together. i_mul = [x.owner and x.owner.op == T.mul and any([_as_scalar(x_i, dtype=d.dtype) for x_i in x.owner.inputs]) for x in node.inputs] if not any(i_mul): # no scalar in input and no multiplication # if their was a multiplication we couls reorder the graph # by the associativity of the graph. return False mul_idx = i_mul.index(True) # The first one should always work m = node.inputs[mul_idx] scalar_idx = -1 for i, x in enumerate(m.owner.inputs): if _as_scalar(x, dtype=d.dtype) and (theano.scalar.upcast( x.type.dtype, d.type.dtype) == d.type.dtype): scalar_idx = i break if scalar_idx < 0: _logger.info('Not optimizing dot22 with inputs %s %s, as the' ' type of the scalar cannot be upcasted to the' ' matrix type', node.inputs, [x.type for x in node.inputs]) return False a = T.cast(_as_scalar(m.owner.inputs[scalar_idx], dtype=d.dtype), d.type.dtype) assert not a.type.ndim dot = _dot22scalar(d.owner.inputs[0], d.owner.inputs[1], a) # The other inputs to the original node that were # neither part of the dot22 or this mul should be # factors in the returned "mul" node. assert dot22_idx != mul_idx other_factors = [inpt for i, inpt in enumerate(node.inputs) if i not in (dot22_idx, mul_idx)] other_m_inputs = [inpt for i, inpt in enumerate(m.owner.inputs) if i != scalar_idx] return [T.mul(dot, *(other_factors + other_m_inputs))] scalar_idx = -1 for i, x in enumerate(node.inputs): if (i != dot22_idx and i_scalar[i] is not None and (theano.scalar.upcast(x.type.dtype, d.type.dtype) == d.type.dtype)): scalar_idx = i break if scalar_idx < 0: _logger.info('Not optimizing dot22 with inputs %s %s, as the type ' 'of the scalar cannot be upcasted to the matrix type', node.inputs, [x.type for x in node.inputs]) return False assert scalar_idx < len(node.inputs) s = node.inputs[scalar_idx] o = copy.copy(node.inputs) o.remove(d) o.remove(s) a = T.cast(i_scalar[scalar_idx], d.type.dtype) assert not a.type.ndim if len(o) == 0: return [_dot22scalar(d.owner.inputs[0], d.owner.inputs[1], a)] else: return [T.mul(_dot22scalar(d.owner.inputs[0], d.owner.inputs[1], a), *o)] # must happen after gemm as the gemm optimizer don't understant # dot22scalar and gemm give more speed up then dot22scalar blas_optdb.register('local_dot22_to_dot22scalar', in2out(local_dot22_to_dot22scalar), 11, 'fast_run') class BatchedDot(Op): """ Computes the batched dot product of two variables: batched_dot(a, b)[i] = dot(a[i], b[i]) """ __props__ = () def make_node(self, *inputs): inputs = list(map(T.as_tensor_variable, inputs)) if len(inputs) != 2: raise TypeError("theano.tensor.blas.BatchedDot: 2 arguments" " required, %d given " % len(inputs)) if inputs[0].ndim not in (2, 3): raise TypeError("theano.tensor.blas.BatchedDot: input 0 (0-indexed)" " must have ndim of 2 or 3, %d given. Consider" " calling theano.tensor.batched_dot instead." % inputs[0].ndim) if inputs[1].ndim not in (2, 3): raise TypeError("theano.tensor.blas.BatchedDot: input 1 (0-indexed)" " must have ndim of 2 or 3, %d given. Consider" " calling theano.tensor.batched_dot instead." % inputs[1].ndim) dtype = theano.scalar.upcast(*[input.type.dtype for input in inputs]) # upcast inputs to common dtype if needed upcasted_inputs = [T.cast(input, dtype) for input in inputs] broadcastable = ((inputs[0].type.broadcastable[0] or inputs[1].type.broadcastable[0],) + inputs[0].type.broadcastable[1:-1] + inputs[1].type.broadcastable[2:]) return Apply(self, upcasted_inputs, [T.tensor(dtype, broadcastable)]) def perform(self, node, inp, out): x, y = inp z, = out if x.shape[0] != y.shape[0]: raise TypeError( "theano.tensor.blas.BatchedDot: inputs [%s] must have the" " same size in axis 0, but have sizes [%s]." % (", ".join(map(str, inp)), ", ".join([str(i.shape[0]) for i in inp]))) shape = self.infer_shape(node, [i.shape for i in inp])[0] dtype = node.outputs[0].dtype z0 = z[0] = numpy.empty(shape, dtype=dtype) for i in xrange(z0.shape[0]): z0[i] = numpy.dot(x[i], y[i]) def c_support_code(self): batch_gemm_defn = """ template<typename dtype, typename function> bool batch_gemm(function gemm, int type_size, PyArrayObject* xs, PyArrayObject* ys, PyArrayObject* zs) { npy_intp *Nx = PyArray_DIMS(xs), *Sx = PyArray_STRIDES(xs); npy_intp *Ny = PyArray_DIMS(ys), *Sy = PyArray_STRIDES(ys); npy_intp *Nz = PyArray_DIMS(zs), *Sz = PyArray_STRIDES(zs); if (Nx[0] != Ny[0]) { PyErr_Format(PyExc_ValueError, "Shape mismatch: batch sizes unequal." " x.shape is (%d, %d, %d)," " y.shape is (%d, %d, %d).", Nx[0], Nx[1], Nx[2], Ny[0], Ny[1], Ny[2]); return 1; } if (Nx[2] != Ny[1]) { PyErr_Format(PyExc_ValueError, "Shape mismatch: summation axis sizes unequal." " x.shape is (%d, %d, %d)," " y.shape is (%d, %d, %d).", Nx[0], Nx[1], Nx[2], Ny[0], Ny[1], Ny[2]); return 1; } /* encode the stride structure of _x,_y,_z into a single integer. */ int unit = 0; unit |= ((Sx[2] == type_size || Nx[2] == 1) ? 0x0 : (Sx[1] == type_size || Nx[1]==1) ? 0x1 : 0x2) << 8; unit |= ((Sy[2] == type_size || Ny[2] == 1) ? 0x0 : (Sy[1] == type_size || Ny[1]==1) ? 0x1 : 0x2) << 4; unit |= ((Sz[2] == type_size || Nz[2] == 1) ? 0x0 : (Sz[1] == type_size || Nz[1]==1) ? 0x1 : 0x2) << 0; /* create appropriate strides for malformed matrices that are row or column * vectors, or empty matrices. * In that case, the value of the stride does not really matter, but * some versions of BLAS insist that: * - they are not smaller than the number of elements in the array, * - they are not 0. */ int sx_1 = (Nx[1] > 1) ? Sx[1]/type_size : (Nx[2] + 1); int sx_2 = (Nx[2] > 1) ? Sx[2]/type_size : (Nx[1] + 1); int sy_1 = (Ny[1] > 1) ? Sy[1]/type_size : (Ny[2] + 1); int sy_2 = (Ny[2] > 1) ? Sy[2]/type_size : (Ny[1] + 1); int sz_1 = (Nz[1] > 1) ? Sz[1]/type_size : (Nz[2] + 1); int sz_2 = (Nz[2] > 1) ? Sz[2]/type_size : (Nz[1] + 1); dtype* x = (dtype*)PyArray_DATA(xs); dtype* y = (dtype*)PyArray_DATA(ys); dtype* z = (dtype*)PyArray_DATA(zs); dtype a = 1.0; dtype b = 0.0; char N = 'N'; char T = 'T'; int Nz1 = Nz[1], Nz2 = Nz[2], Nx2 = Nx[2]; // loop over batch axis for (int i = 0; i < Nz[0]; i++) { switch(unit) { case 0x000: gemm(&N, &N, &Nz2, &Nz1, &Nx2, &a, y, &sy_1, x, &sx_1, &b, z, &sz_1); break; case 0x100: gemm(&N, &T, &Nz2, &Nz1, &Nx2, &a, y, &sy_1, x, &sx_2, &b, z, &sz_1); break; case 0x010: gemm(&T, &N, &Nz2, &Nz1, &Nx2, &a, y, &sy_2, x, &sx_1, &b, z, &sz_1); break; case 0x110: gemm(&T, &T, &Nz2, &Nz1, &Nx2, &a, y, &sy_2, x, &sx_2, &b, z, &sz_1); break; case 0x001: gemm(&T, &T, &Nz1, &Nz2, &Nx2, &a, x, &sx_1, y, &sy_1, &b, z, &sz_2); break; case 0x101: gemm(&N, &T, &Nz1, &Nz2, &Nx2, &a, x, &sx_2, y, &sy_1, &b, z, &sz_2); break; case 0x011: gemm(&T, &N, &Nz1, &Nz2, &Nx2, &a, x, &sx_1, y, &sy_2, &b, z, &sz_2); break; case 0x111: gemm(&N, &N, &Nz1, &Nz2, &Nx2, &a, x, &sx_2, y, &sy_2, &b, z, &sz_2); break; default: PyErr_SetString(PyExc_ValueError, "some matrix has no unit stride"); return 1; }; x += Sx[0] / type_size; y += Sy[0] / type_size; z += Sz[0] / type_size; } return 0; } """ return blas_header_text() + batch_gemm_defn def c_libraries(self): return ldflags() def c_compile_args(self): return ldflags(libs=False, flags=True) def c_lib_dirs(self): return ldflags(libs=False, libs_dir=True) def c_header_dirs(self): return ldflags(libs=False, include_dir=True) def c_code_cleanup(self, node, name, inputs, outputs, sub): return """ // clean up views Py_XDECREF(xs); xs = 0; Py_XDECREF(ys); ys = 0; Py_XDECREF(zs); zs = 0; """ def c_code(self, node, name, inp, out, sub): _x, _y = inp _z, = out fail = sub["fail"] # generate contiguity condition def contiguous(var, ndim): strides = "PyArray_STRIDES(%s)" % var return " && ".join([ " && ".join("{strides}[{i}] > 0 && {strides}[{i}] % type_size == 0" .format(strides=strides, i=i) for i in range(ndim)), "(%s)" % " || ".join("{strides}[{i}] == type_size" .format(strides=strides, i=i) for i in range(ndim)), ]) x_ndim, y_ndim, z_ndim = node.inputs[0].ndim, node.inputs[1].ndim, node.outputs[0].ndim # generate code to allocate output based on runtime input shapes z_dims = ["PyArray_DIMS(%s)[0]" % _x] if x_ndim == 3: z_dims.append("PyArray_DIMS(%s)[1]" % _x) if y_ndim == 3: z_dims.append("PyArray_DIMS(%s)[2]" % _y) assert len(z_dims) == z_ndim z_shape_correct = " && ".join("PyArray_DIMS(%s)[%i] == %s" % (_z, i, dim) for i, dim in enumerate(z_dims)) z_shape = ", ".join(z_dims) z_contiguous = contiguous(_z, z_ndim) allocate = """ if (NULL == %(_z)s || !(%(z_shape_correct)s) || !(%(z_contiguous)s)) { npy_intp dims[%(z_ndim)s] = {%(z_shape)s}; Py_XDECREF(%(_z)s); %(_z)s = (PyArrayObject*)PyArray_SimpleNew( %(z_ndim)s, dims, PyArray_TYPE(%(_x)s)); if(!%(_z)s) { PyErr_SetString(PyExc_MemoryError, "failed to alloc BatchedDot output"); %(fail)s } } """ % locals() # code to reallocate inputs contiguously if necessary contiguate = [] for var, ndim in [(_x, x_ndim), (_y, y_ndim)]: _contiguous = contiguous(var, ndim) contiguate.append(""" if (!(%(_contiguous)s)) { PyArrayObject * _copy = (PyArrayObject *) PyArray_Copy(%(var)s); if (!_copy) %(fail)s Py_XDECREF(%(var)s); %(var)s = _copy; } """ % locals()) contiguate = "\n".join(contiguate) def c_dimshuffle(newname, oldname, shape): _fail = fail _shape = ", ".join("1" if axis is None else "PyArray_DIMS(%s)[%i]" % (oldname, axis) for axis in shape) return """{ npy_intp dims[3] = {%(_shape)s}; PyArray_Dims newshape = {dims, 3}; %(newname)s = (PyArrayObject*)PyArray_Newshape(%(oldname)s, &newshape, NPY_ANYORDER); if (!%(newname)s) %(_fail)s // make sure we didn't accidentally copy assert(PyArray_DATA(%(oldname)s) == PyArray_DATA(%(newname)s)); }""" % locals() # create tensor3 views for any of x, y, z that are not tensor3, so that # we only need to implement the tensor3-tensor3 batched dot product. # xs, ys and zs will point to these views, or to the original array if # it was already tensor3. # in the latter case, we artificially increase the reference count of # the original array so that the c_code_cleanup method can decref them # all indiscriminately. upcast = [] if x_ndim == 3: upcast.append("xs = %(_x)s; Py_XINCREF(xs);") elif x_ndim == 2: upcast.append(c_dimshuffle("xs", _x, (0, None, 1))) if y_ndim == 3: upcast.append("ys = %(_y)s; Py_XINCREF(ys);") elif y_ndim == 2: upcast.append(c_dimshuffle("ys", _y, (0, 1, None))) if z_ndim == 3: upcast.append("zs = %(_z)s; Py_XINCREF(zs);") else: upcast.append(c_dimshuffle( "zs", _z, (0, None if x_ndim == 2 else 1, None if y_ndim == 2 else 1))) upcast = "\n".join(upcast) % locals() return """ int type_num = PyArray_DESCR(%(_x)s)->type_num; int type_size = PyArray_DESCR(%(_x)s)->elsize; // in bytes // xs, ys, zs will point to views onto %(_x)s, %(_y)s, %(_z)s PyArrayObject *xs = 0, *ys = 0, *zs = 0; if (PyArray_NDIM(%(_x)s) != %(x_ndim)s) { PyErr_Format(PyExc_NotImplementedError, "rank(x) != %(x_ndim)s. rank(x) is %%d.", PyArray_NDIM(%(_x)s)); %(fail)s; } if (PyArray_NDIM(%(_y)s) != %(y_ndim)s) { PyErr_Format(PyExc_NotImplementedError, "rank(y) != %(y_ndim)s. rank(y) is %%d.", PyArray_NDIM(%(_y)s)); %(fail)s; } if (%(_z)s && PyArray_NDIM(%(_z)s) != %(z_ndim)s) { PyErr_Format(PyExc_NotImplementedError, "rank(z) != %(z_ndim)s. rank(z) is %%d.", PyArray_NDIM(%(_z)s)); %(fail)s; } // allocate output %(allocate)s // reallocate any noncontiguous arrays or arrays with invalid strides %(contiguate)s // add dims to make sure everything is tensor3 %(upcast)s // from here on, use xs, ys and zs as they are tensor3 and share memory // with the original %(_x)s, %(_y)s and %(_z)s arrays. if ((PyArray_DESCR(xs)->type_num != NPY_DOUBLE) && (PyArray_DESCR(xs)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(x) is not double or float"); %(fail)s;} if ((PyArray_DESCR(ys)->type_num != NPY_DOUBLE) && (PyArray_DESCR(ys)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(y) is not double or float"); %(fail)s;} if ((PyArray_DESCR(zs)->type_num != NPY_DOUBLE) && (PyArray_DESCR(zs)->type_num != NPY_FLOAT)) {PyErr_SetString(PyExc_NotImplementedError, "type(z) is not double or float"); %(fail)s;} if ((PyArray_DESCR(xs)->type_num != PyArray_DESCR(ys)->type_num) ||(PyArray_DESCR(xs)->type_num != PyArray_DESCR(zs)->type_num)) { PyErr_SetString(PyExc_NotImplementedError, "type(x), type(y), type(z) are not all the same"); %(fail)s; } switch (type_num) { case NPY_FLOAT: if (batch_gemm<float>(sgemm_, type_size, xs, ys, zs)) { %(fail)s; } break; case NPY_DOUBLE: if (batch_gemm<double>(dgemm_, type_size, xs, ys, zs)) { %(fail)s; } break; } """ % locals() def c_code_cache_version(self): from theano.tensor.blas_headers import blas_header_version return (1, blas_header_version()) def grad(self, inp, grads): x, y = inp gz, = grads xdim, ydim, gdim = x.type.ndim, y.type.ndim, gz.type.ndim # grad is a vector, so x is a matrix and y is a matrix if gdim == 1: xgrad = gz.dimshuffle(0, 'x') * y ygrad = gz.dimshuffle(0, 'x') * x # x is a matrix, y is a tensor3, grad is a matrix elif xdim == 2 and ydim == 3: xgrad = T.batched_dot(gz, y.dimshuffle(0, 2, 1)) ygrad = x.dimshuffle(0, 1, 'x') * gz.dimshuffle(0, 'x', 1) # x is a tensor3, y is a matrix, grad is a matrix elif xdim == 3 and ydim == 2: xgrad = gz.dimshuffle(0, 1, 'x') * y.dimshuffle(0, 'x', 1) ygrad = T.batched_dot(x.dimshuffle(0, 2, 1), gz) # x is a tensor3, y is a tensor3, grad is a tensor3 elif xdim == ydim == 3: xgrad = T.batched_dot(gz, y.dimshuffle(0, 2, 1)) ygrad = T.batched_dot(x.dimshuffle(0, 2, 1), gz) # If x or y contain broadcastable dimensions but only one of # them know that a matching dimensions is broadcastable, the # above code don't always return the right broadcast pattern. # This cause problem down the road. See gh-1461. if xgrad.broadcastable != x.broadcastable: xgrad = T.patternbroadcast(xgrad, x.broadcastable) if ygrad.broadcastable != y.broadcastable: ygrad = T.patternbroadcast(ygrad, y.broadcastable) return xgrad, ygrad def R_op(self, inputs, eval_points): # R_op for batched_dot(a, b) evaluted at c for a and d for b is # simply batched_dot(c, b) + batched_dot(a, d) assert len(inputs) == 2 assert len(eval_points) == 2 if eval_points[0] is None and eval_points[1] is None: return [None] debugger_available = config.compute_test_value != 'off' if debugger_available: try: iv0 = theano.gof.op.get_test_value(inputs[0]) except AttributeError: theano.gof.op.missing_test_message( 'first input passed to BatchedDot.R_op has no test value') debugger_available = False try: iv1 = theano.gof.op.get_test_value(inputs[1]) except AttributeError: theano.gof.op.missing_test_message( 'second input passed to BatchedDot.R_op has no test value') debugger_available = False if eval_points[0]: try: ev0 = theano.gof.op.get_test_value(eval_points[0]) except AttributeError: theano.gof.op.missing_test_message( 'first eval point passed to BatchedDot.R_op ' 'has no test value') debugger_available = False if eval_points[1]: try: ev1 = theano.gof.op.get_test_value(eval_points[1]) except AttributeError: theano.gof.op.missing_test_message( 'second eval point passed to BatchedDot.R_op ' 'has no test value') debugger_available = False if debugger_available: input_values = [iv0, iv1] eval_point_values = [ev0, ev1] for i in xrange(2): if eval_point_values[i] is not None and \ input_values[i].shape != eval_point_values[i].shape: raise ValueError( 'input ' + str(i) + ' and eval_point ' + str(i) + ' to BatchedDot.R_op should have the same shape, but ' 'their shapes are %s and %s, respectively' % ( str(input_values[i].shape), str(eval_point_values[i].shape))) if eval_points[0]: t1 = self(eval_points[0], inputs[1]) if eval_points[1]: t2 = self(inputs[0], eval_points[1]) if eval_points[0] and eval_points[1]: return [t1 + t2] elif eval_points[0]: return [t1] else: return [t2] def infer_shape(self, node, shapes): for shape_ in shapes: if len(shape_) not in (2, 3): raise NotImplementedError() xshp, yshp = shapes return [xshp[:-1] + yshp[2:]] # from opt import register_specialize, register_canonicalize # @register_specialize @local_optimizer([T.sub, T.add]) def local_print_as_we_go_along(node): if node.op in (T.sub, T.add): debugprint(node)
mit
Logitech/logiPy
logipy/logi_led.py
1
22401
""" logi_led.py : Defines the exported functions for the API Logitech Gaming LED SDK Copyright (C) 2011-2015 Logitech. All rights reserved. Author: Tom Lambert Email: devtechsupport@logitech.com """ import ctypes import os import platform import struct # Helpers # class Color: """ an RGBA color object that can be created using RGB, RGBA, color name, or a hex_code. """ def __init__(self, *args, **kwargs): red, green, blue, alpha = 0, 0, 0, 255 hex_code = None if len(args) > 0: if isinstance(args[0], int): red, green, blue = args[0], args[1], args[2] if len(args) > 3: alpha = args[3] elif isinstance(args[0], str): if len(args) > 1: alpha = args[1] if args[0] == 'red': red, green, blue = 255, 0, 0 elif args[0] == 'orange': red, green, blue = 255, 165, 0 elif args[0] == 'yellow': red, green, blue = 255, 255, 0 elif args[0] == 'green': red, green, blue = 0, 255, 0 elif args[0] == 'blue': red, green, blue = 0, 0, 255 elif args[0] == 'indigo': red, green, blue = 75, 0, 130 elif args[0] == 'violet': red, green, blue = 238, 130, 238 elif args[0] == 'cyan': red, green, blue = 0, 220, 255 elif args[0] == 'pink': red, green, blue = 255, 0, 255 elif args[0] == 'purple': red, green, blue = 128, 0, 255 elif args[0] == 'white': red, green, blue = 255, 255, 255 elif args[0] == 'black': red, green, blue = 0, 0, 0 else: hex_code = args[0] hex_code = kwargs.pop('hex', hex_code) if hex_code: hex_code = hex_code.replace('#', '') self.red, self.green, self.blue = struct.unpack('BBB', hex_code.decode('hex')) self.alpha = alpha elif any(x in ['red', 'blue', 'green', 'alpha'] for x in kwargs): self.red = kwargs.pop('red', red) self.green = kwargs.pop('green', green) self.blue = kwargs.pop('blue', blue) self.alpha = kwargs.pop('alpha', alpha) else: self.red = red self.green = green self.blue = blue self.alpha = alpha self.hex_code = '#{h}'.format(h=struct.pack('BBB', *(self.red, self.green, self.blue)).encode('hex')) def rgb_percent(self): return int((self.red / 255.0) * 100), int((self.green / 255.0) * 100), int((self.blue / 255.0) * 100) # DLL Definitions # ESC = 0x01 F1 = 0x3b F2 = 0x3c F3 = 0x3d F4 = 0x3e F5 = 0x3f F6 = 0x40 F7 = 0x41 F8 = 0x42 F9 = 0x43 F10 = 0x44 F11 = 0x57 F12 = 0x58 PRINT_SCREEN = 0x137 SCROLL_LOCK = 0x46 PAUSE_BREAK = 0x145 TILDE = 0x29 ONE = 0x02 TWO = 0x03 THREE = 0x04 FOUR = 0x05 FIVE = 0x06 SIX = 0x07 SEVEN = 0x08 EIGHT = 0x09 NINE = 0x0a ZERO = 0x0b MINUS = 0x0c EQUALS = 0x0d BACKSPACE = 0x0e INSERT = 0x152 HOME = 0x147 PAGE_UP = 0x149 NUM_LOCK = 0x45 NUM_SLASH = 0x135 NUM_ASTERISK = 0x37 NUM_MINUS = 0x4a TAB = 0x0f Q = 0x10 W = 0x11 E = 0x12 R = 0x13 T = 0x14 Y = 0x15 U = 0x16 I = 0x17 O = 0x18 P = 0x19 OPEN_BRACKET = 0x1a CLOSE_BRACKET = 0x1b BACKSLASH = 0x2b KEYBOARD_DELETE = 0x153 END = 0x14f PAGE_DOWN = 0x151 NUM_SEVEN = 0x47 NUM_EIGHT = 0x48 NUM_NINE = 0x49 NUM_PLUS = 0x4e CAPS_LOCK = 0x3a A = 0x1e S = 0x1f D = 0x20 F = 0x21 G = 0x22 H = 0x23 J = 0x24 K = 0x25 L = 0x26 SEMICOLON = 0x27 APOSTROPHE = 0x28 ENTER = 0x1c NUM_FOUR = 0x4b NUM_FIVE = 0x4c NUM_SIX = 0x4d LEFT_SHIFT = 0x2a Z = 0x2c X = 0x2d C = 0x2e V = 0x2f B = 0x30 N = 0x31 M = 0x32 COMMA = 0x33 PERIOD = 0x34 FORWARD_SLASH = 0x35 RIGHT_SHIFT = 0x36 ARROW_UP = 0x148 NUM_ONE = 0x4f NUM_TWO = 0x50 NUM_THREE = 0x51 NUM_ENTER = 0x11c LEFT_CONTROL = 0x1d LEFT_WINDOWS = 0x15b LEFT_ALT = 0x38 SPACE = 0x39 RIGHT_ALT = 0x138 RIGHT_WINDOWS = 0x15c APPLICATION_SELECT = 0x15d RIGHT_CONTROL = 0x11d ARROW_LEFT = 0x14b ARROW_DOWN = 0x150 ARROW_RIGHT = 0x14d NUM_ZERO = 0x52 NUM_PERIOD = 0x53 G_1 = 0xFFF1 G_2 = 0xFFF2 G_3 = 0xFFF3 G_4 = 0xFFF4 G_5 = 0xFFF5 G_6 = 0xFFF6 G_7 = 0xFFF7 G_8 = 0xFFF8 G_9 = 0xFFF9 G_LOGO = 0xFFFF1 G_BADGE = 0xFFFF2 LOGI_LED_BITMAP_WIDTH = 21 LOGI_LED_BITMAP_HEIGHT = 6 LOGI_LED_BITMAP_BYTES_PER_KEY = 4 LOGI_LED_BITMAP_SIZE = LOGI_LED_BITMAP_WIDTH * LOGI_LED_BITMAP_HEIGHT * LOGI_LED_BITMAP_BYTES_PER_KEY LOGI_LED_DURATION_INFINITE = 0 LOGI_DEVICETYPE_MONOCHROME_ORD = 0 LOGI_DEVICETYPE_RGB_ORD = 1 LOGI_DEVICETYPE_PERKEY_RGB_ORD = 2 LOGI_DEVICETYPE_MONOCHROME = 1 << LOGI_DEVICETYPE_MONOCHROME_ORD LOGI_DEVICETYPE_RGB = 1 << LOGI_DEVICETYPE_RGB_ORD LOGI_DEVICETYPE_PERKEY_RGB = 1 << LOGI_DEVICETYPE_PERKEY_RGB_ORD LOGI_DEVICETYPE_ALL = LOGI_DEVICETYPE_MONOCHROME | LOGI_DEVICETYPE_RGB | LOGI_DEVICETYPE_PERKEY_RGB # Required Globals # _LOGI_SHARED_SDK_LED = ctypes.c_int(1) class SDKNotFoundException: pass def load_dll(path_dll = None): if not path_dll: bitness = 'x86' if platform.architecture()[0] == '32bit' else 'x64' subpath_dll = r'/Logitech Gaming Software/SDK/LED/{}/LogitechLed.dll'.format(bitness) try: subpath_lgs = os.environ['ProgramW6432'] except KeyError: subpath_lgs = os.environ['ProgramFiles'] path_dll = subpath_lgs + subpath_dll if os.path.exists(path_dll): return ctypes.cdll.LoadLibrary(path_dll) else: raise SDKNotFoundException('The SDK DLL was not found.') try: led_dll = load_dll() except SDKNotFoundException as exception_sdk: led_dll = None # Wrapped SDK Functions # def logi_led_init(): """ initializes the sdk for the current thread. """ if led_dll: return bool(led_dll.LogiLedInit()) else: return False def logi_led_set_target_device(target_device): """ sets the target device or device group that is affected by the subsequent lighting calls. """ if led_dll: target_device = ctypes.c_int(target_device) return bool(led_dll.LogiLedSetTargetDevice(target_device)) else: return False def logi_led_save_current_lighting(): """ saves the current lighting that can be restored later. """ if led_dll: return bool(led_dll.LogiLedSaveCurrentLighting()) else: return False def logi_led_restore_lighting(): """ restores the last saved lighting. """ if led_dll: return bool(led_dll.LogiLedRestoreLighting()) else: return False def logi_led_set_lighting(red_percentage, green_percentage, blue_percentage): """ sets the lighting to the color of the combined RGB percentages. note that RGB ranges from 0-255, but this function ranges from 0-100. """ if led_dll: red_percentage = ctypes.c_int(red_percentage) green_percentage = ctypes.c_int(green_percentage) blue_percentage = ctypes.c_int(blue_percentage) return bool(led_dll.LogiLedSetLighting(red_percentage, green_percentage, blue_percentage)) else: return False def logi_led_flash_lighting(red_percentage, green_percentage, blue_percentage, ms_duration, ms_interval): """ flashes the lighting color of the combined RGB percentages over the specified millisecond duration and millisecond interval. specifying a duration of 0 will cause the effect to be infinite until reset. note that RGB ranges from 0-255, but this function ranges from 0-100. """ if led_dll: red_percentage = ctypes.c_int(red_percentage) green_percentage = ctypes.c_int(green_percentage) blue_percentage = ctypes.c_int(blue_percentage) ms_duration = ctypes.c_int(ms_duration) ms_interval = ctypes.c_int(ms_interval) return bool(led_dll.LogiLedFlashLighting(red_percentage, green_percentage, blue_percentage, ms_duration, ms_interval)) else: return False def logi_led_pulse_lighting(red_percentage, green_percentage, blue_percentage, ms_duration, ms_interval): """ pulses the lighting color of the combined RGB percentages over the specified millisecond duration and millisecond interval. specifying a duration of 0 will cause the effect to be infinite until reset. note that RGB ranges from 0-255, but this function ranges from 0-100. """ if led_dll: red_percentage = ctypes.c_int(red_percentage) green_percentage = ctypes.c_int(green_percentage) blue_percentage = ctypes.c_int(blue_percentage) ms_duration = ctypes.c_int(ms_duration) ms_interval = ctypes.c_int(ms_interval) return bool(led_dll.LogiLedPulseLighting(red_percentage, green_percentage, blue_percentage, ms_duration, ms_interval)) else: return False def logi_led_stop_effects(): """ stops the pulse and flash effects. """ if led_dll: return bool(led_dll.LogiLedStopEffects()) else: return False def logi_led_set_lighting_from_bitmap(bitmap): """ sets the color of each key in a 21x6 rectangular area specified by the BGRA byte array bitmap. each element corresponds to the physical location of each key. note that the color bit order is BGRA rather than standard RGBA bit order. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: bitmap = ctypes.c_char_p(bitmap) return bool(led_dll.LogiLedSetLightingFromBitmap(bitmap)) else: return False def logi_led_set_lighting_for_key_with_scan_code(key_code, red_percentage, green_percentage, blue_percentage): """ sets the lighting to the color of the combined RGB percentages for the specified key code. note that RGB ranges from 0-255, but this function ranges from 0-100. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: key_code = ctypes.c_int(key_code) red_percentage = ctypes.c_int(red_percentage) green_percentage = ctypes.c_int(green_percentage) blue_percentage = ctypes.c_int(blue_percentage) return bool(led_dll.LogiLedSetLightingForKeyWithScanCode(key_code, red_percentage, green_percentage, blue_percentage)) else: return False def logi_led_set_lighting_for_key_with_hid_code(key_code, red_percentage, green_percentage, blue_percentage): """ sets the lighting to the color of the combined RGB percentages for the specified key code. note that RGB ranges from 0-255, but this function ranges from 0-100. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: key_code = ctypes.c_int(key_code) red_percentage = ctypes.c_int(red_percentage) green_percentage = ctypes.c_int(green_percentage) blue_percentage = ctypes.c_int(blue_percentage) return bool(led_dll.LogiLedSetLightingForKeyWithHidCode(key_code, red_percentage, green_percentage, blue_percentage)) else: return False def logi_led_set_lighting_for_key_with_quartz_code(key_code, red_percentage, green_percentage, blue_percentage): """ sets the lighting to the color of the combined RGB percentages for the specified key code. note that RGB ranges from 0-255, but this function ranges from 0-100. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: key_code = ctypes.c_int(key_code) red_percentage = ctypes.c_int(red_percentage) green_percentage = ctypes.c_int(green_percentage) blue_percentage = ctypes.c_int(blue_percentage) return bool(led_dll.LogiLedSetLightingForKeyWithQuartzCode(key_code, red_percentage, green_percentage, blue_percentage)) else: return False def logi_led_set_lighting_for_key_with_key_name(key_name, red_percentage, green_percentage, blue_percentage): """ sets the lighting to the color of the combined RGB percentages for the specified key name. note that RGB ranges from 0-255, but this function ranges from 0-100. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: key_name = ctypes.c_int(key_name) red_percentage = ctypes.c_int(red_percentage) green_percentage = ctypes.c_int(green_percentage) blue_percentage = ctypes.c_int(blue_percentage) return bool(led_dll.LogiLedSetLightingForKeyWithKeyName(key_name, red_percentage, green_percentage, blue_percentage)) else: return False def logi_led_save_lighting_for_key(key_name): """ saves the current lighting for the specified key name that can be restored later. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: key_name = ctypes.c_int(key_name) return bool(led_dll.LogiLedSaveLightingForKey(key_name)) else: return False def logi_led_restore_lighting_for_key(key_name): """ restores the last saved lighting for the specified key name. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: key_name = ctypes.c_int(key_name) return bool(led_dll.LogiLedRestoreLightingForKey(key_name)) else: return False def logi_led_flash_single_key(key_name, red_percentage, green_percentage, blue_percentage, ms_duration, ms_interval): """ flashes the lighting color of the combined RGB percentages over the specified millisecond duration and millisecond interval for the specified key name. specifying a duration of 0 will cause the effect to be infinite until reset. note that RGB ranges from 0-255, but this function ranges from 0-100. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: key_name = ctypes.c_int(key_name) red_percentage = ctypes.c_int(red_percentage) green_percentage = ctypes.c_int(green_percentage) blue_percentage = ctypes.c_int(blue_percentage) ms_duration = ctypes.c_int(ms_duration) ms_interval = ctypes.c_int(ms_interval) return bool(led_dll.LogiLedFlashSingleKey(key_name, red_percentage, green_percentage, blue_percentage, ms_duration, ms_interval)) else: return False def logi_led_pulse_single_key(key_name, red_percentage_start, green_percentage_start, blue_percentage_start, ms_duration, is_infinite = False, red_percentage_end = 0, green_percentage_end = 0, blue_percentage_end = 0): """ pulses the lighting color of the combined RGB percentages over the specified millisecond duration for the specified key name. the color will gradually change from the starting color to the ending color. if no ending color is specified, the ending color will be black. the effect will stop after one interval unless is_infinite is set to True. note that RGB ranges from 0-255, but this function ranges from 0-100. this function only applies to LOGI_DEVICETYPE_PERKEY_RGB devices. """ if led_dll: key_name = ctypes.c_int(key_name) red_percentage_start = ctypes.c_int(red_percentage_start) green_percentage_start = ctypes.c_int(green_percentage_start) blue_percentage_start = ctypes.c_int(blue_percentage_start) red_percentage_end = ctypes.c_int(red_percentage_end) green_percentage_end = ctypes.c_int(green_percentage_end) blue_percentage_end = ctypes.c_int(blue_percentage_end) ms_duration = ctypes.c_int(ms_duration) is_infinite = ctypes.c_bool(is_infinite) return bool(led_dll.LogiLedPulseSingleKey(key_name, red_percentage_start, green_percentage_start, blue_percentage_start, red_percentage_end, green_percentage_end, blue_percentage_end, ms_duration, is_infinite)) else: return False def logi_led_stop_effects_on_key(key_name): """ stops the pulse and flash effects on a single key. """ if led_dll: key_name = ctypes.c_int(key_name) return bool(led_dll.LogiLedStopEffectsOnKey(key_name)) else: return False def logi_led_shutdown(): """ shutdowns the SDK for the thread. """ if led_dll: return bool(led_dll.LogiLedShutdown()) else: return False def logi_led_get_config_option_number(key, default=0): """ get the default value for the key as a number. if the call fails, the return value is None. for example, get the low health threshold: logi_led_get_config_option_number('health/low_health_threshold', 20.0) """ if led_dll: key = ctypes.c_wchar_p(key) default = ctypes.c_double(default) if led_dll.LogiGetConfigOptionNumber(key, ctypes.pointer(default), _LOGI_SHARED_SDK_LED): return default.value return None def logi_led_get_config_option_bool(key, default=False): """ get the default value for the key as a bool. if the call fails, the return value is None. for example, check if the effect is enabled: logi_led_get_config_option_bool('health/pulse_on_low', True) """ if led_dll: key = ctypes.c_wchar_p(key) default = ctypes.c_bool(default) if led_dll.LogiGetConfigOptionBool(key, ctypes.pointer(default), _LOGI_SHARED_SDK_LED): return default.value return None def logi_led_get_config_option_color(key, *args): """ get the default value for the key as a color. if the call fails, the return value is None. note this function can either be called with red_percentage, green_percentage, and blue_percentage or with the logi_led Color object. for example, get the low health color: logi_led_get_config_option_color('health/pulse_color', 100, 0, 0) logi_led_get_config_option_color('health/pulse_color', Color('red')) logi_led_get_config_option_color('health/pulse_color', Color('#ff0000')) logi_led_get_config_option_color('health/pulse_color', Color(255, 0, 0)) """ if led_dll: key = ctypes.c_wchar_p(key) default = None red_percentage = 0 green_percentage = 0 blue_percentage = 0 if isinstance(args[0], Color): default = args[0] else: red_percentage = args[0] green_percentage = args[1] blue_percentage = args[2] if default: red = ctypes.c_int(default.red) green = ctypes.c_int(default.green) blue = ctypes.c_int(default.blue) else: red = ctypes.c_int(int((red_percentage / 100.0) * 255)) green = ctypes.c_int(int((green_percentage / 100.0) * 255)) blue = ctypes.c_int(int((blue_percentage / 100.0) * 255)) if led_dll.LogiGetConfigOptionColor(key, ctypes.pointer(red), ctypes.pointer(green), ctypes.pointer(blue), _LOGI_SHARED_SDK_LED): return Color(red.value, green.value, blue.value) return None def logi_led_get_config_option_key_input(key, default=''): """ get the default value for the key as a key input. if the call fails, the return value is None. for example, get the primary ability key input: logi_led_get_config_option_key_input('abilities/primary', 'A') """ if led_dll: key = ctypes.c_wchar_p(key) default_key = ctypes.create_string_buffer(256) default_key.value = default if led_dll.LogiGetConfigOptionKeyInput(key, default_key, _LOGI_SHARED_SDK_LED): return str(default_key.value) return None def logi_led_set_config_option_label(key, label): """ set the label for a key. for example, label 'health/pulse_on_low' as 'Health - Pulse on Low': logi_led_set_config_option_label('health', 'Health') logi_led_set_config_option_label('health/pulse_on_low', 'Pulse on Low') """ if led_dll: key = ctypes.c_wchar_p(key) label = ctypes.c_wchar_p(label) return bool(led_dll.LogiSetConfigOptionLabel(key, label, _LOGI_SHARED_SDK_LED)) else: return False
mit
overtherain/scriptfile
software/googleAppEngine/lib/django_1_2/tests/modeltests/test_client/urls.py
99
1592
from django.conf.urls.defaults import * from django.views.generic.simple import redirect_to import views urlpatterns = patterns('', (r'^get_view/$', views.get_view), (r'^post_view/$', views.post_view), (r'^header_view/$', views.view_with_header), (r'^raw_post_view/$', views.raw_post_view), (r'^redirect_view/$', views.redirect_view), (r'^secure_view/$', views.view_with_secure), (r'^permanent_redirect_view/$', redirect_to, {'url': '/test_client/get_view/'}), (r'^temporary_redirect_view/$', redirect_to, {'url': '/test_client/get_view/', 'permanent': False}), (r'^http_redirect_view/$', redirect_to, {'url': '/test_client/secure_view/'}), (r'^https_redirect_view/$', redirect_to, {'url': 'https://testserver/test_client/secure_view/'}), (r'^double_redirect_view/$', views.double_redirect_view), (r'^bad_view/$', views.bad_view), (r'^form_view/$', views.form_view), (r'^form_view_with_template/$', views.form_view_with_template), (r'^login_protected_view/$', views.login_protected_view), (r'^login_protected_method_view/$', views.login_protected_method_view), (r'^login_protected_view_custom_redirect/$', views.login_protected_view_changed_redirect), (r'^permission_protected_view/$', views.permission_protected_view), (r'^permission_protected_method_view/$', views.permission_protected_method_view), (r'^session_view/$', views.session_view), (r'^broken_view/$', views.broken_view), (r'^mail_sending_view/$', views.mail_sending_view), (r'^mass_mail_sending_view/$', views.mass_mail_sending_view) )
mit
riemarc/pyinduct
pyinduct/tests/test_eigenfunctions.py
3
22740
import unittest import numpy as np import pyinduct as pi import pyinduct.parabolic as parabolic from pyinduct.tests import show_plots import matplotlib.pyplot as plt class TestAddMulFunction(unittest.TestCase): def test_it(self): a_mat = np.diag(np.ones(3)) b = np.array( [pi.AddMulFunction(lambda z: z), pi.AddMulFunction(lambda z: 2 * z), pi.AddMulFunction(lambda z: 3 * z)]) x = np.dot(b, a_mat) self.assertAlmostEqual([4, 40, 300], [x[0](4), x[1](20), x[2](100)]) class TestSecondOrderEigenfunction(unittest.TestCase): def test_error_raiser(self): param = [1, 1, 1, 1, 1] l = 1 z = pi.Domain((0, l), 2) n = 10 eig_val, eig_funcs = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, scale=np.ones(n)) eig_freq = pi.SecondOrderDirichletEigenfunction.eigval_tf_eigfreq( param, eig_val=eig_val) _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, n=n) _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, n=n, scale=np.ones(n)) _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, eig_val=eig_val, scale=np.ones(n)) _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, eig_freq=eig_freq, scale=np.ones(n)) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, n=n, scale=np.ones(n + 1)) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, eig_val=eig_val, scale=np.ones(n + 1)) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, n=n, eig_freq=eig_freq) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, eig_val=eig_val, eig_freq=eig_freq) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( z, param=param, n=n, eig_val=eig_val, eig_freq=eig_freq) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( pi.Domain((1, 2), 2), param=param, n=n) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( pi.Domain((0, -2), 2), param=param, n=n) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( pi.Domain((0, 0), 2), param=param, n=n) with self.assertRaises(ValueError): _, _ = pi.SecondOrderDirichletEigenfunction.cure_interval( (0, 1), param=param, n=n) class FiniteTransformTest(unittest.TestCase): def test_trivial(self): l = 5 k = 5 k1, k2, b = parabolic.control.split_domain(k, 0, l, mode='coprime')[0:3] a_mat = parabolic.general.get_in_domain_transformation_matrix( k1, k2, mode="2n") self.assertAlmostEqual(b, 0) self.assertTrue(all(np.isclose(a_mat, np.linalg.inv(a_mat)).all(1))) k1, k2, b = parabolic.control.split_domain(k, l, l, mode='coprime')[0:3] b_mat = parabolic.general.get_in_domain_transformation_matrix( k1, k2, mode="2n") self.assertAlmostEqual(b, l) self.assertTrue( all(np.isclose(b_mat, np.diag(np.ones(b_mat.shape[0]))).all(1))) def test_paper_example(self): l = 5 k = 5 b_desired = 2 k1, k2, b = parabolic.control.split_domain(k, b_desired, l, mode='coprime')[0:3] m_mat = np.linalg.inv( parabolic.general.get_in_domain_transformation_matrix(k1, k2, mode="2n")) shifted_func = pi.FiniteTransformFunction( np.cos, m_mat, l, nested_lambda=False) shifted_func_nl = pi.FiniteTransformFunction( np.cos, m_mat, l, nested_lambda=True) z = np.linspace(0, l, 1000) np.testing.assert_array_almost_equal( shifted_func(z), shifted_func_nl(z)) if show_plots: plt.figure() plt.plot(z, shifted_func(z)) plt.plot(z, np.cos(z)) plt.show() def test_const(self): n = 5 k = 5 b_desired = 2 l = 5 z = pi.Domain((0, l), 2) params = [2, 1.5, -3, 1, .5] k1, k2, b = parabolic.control.split_domain(k, b_desired, l, mode='coprime')[0:3] M = np.linalg.inv( parabolic.general.get_in_domain_transformation_matrix(k1, k2, mode="2n")) eig_val, eig_base = pi.SecondOrderRobinEigenfunction.cure_interval( z, param=params, n=n) shifted_eig_base = pi.Base(np.array( [pi.FiniteTransformFunction( func, M, l, nested_lambda=False) for func in eig_base])) shifted_eig_base_nl = pi.Base(np.array( [pi.FiniteTransformFunction( func, M, l, nested_lambda=True) for func in eig_base])) zz = np.linspace(0, l, 1000) for f1, f2 in zip(shifted_eig_base, shifted_eig_base_nl): np.testing.assert_array_almost_equal(f1(zz), f2(zz)) if show_plots: pi.visualize_functions(eig_base.fractions, 1000) pi.visualize_functions(shifted_eig_base.fractions, 1000) def calc_dirichlet_eigenvalues(params): """ Estimate the eigenvalues of a 2nd order dirichlet problem . by approximating it using polynomial shapefunctions. """ spat_dom, lag_base = pi.cure_interval(pi.LagrangeNthOrder, interval=params.domain, order=3, node_count=31) pi.register_base("fem_base", lag_base) old_params = [params.a2, params.a1, params.a0, -params.alpha0, params.beta0] weak_form = pi.parabolic.get_parabolic_dirichlet_weak_form("fem_base", "fem_base", None, old_params, params.domain) can_form = pi.parse_weak_formulation(weak_form, finalize=True) ss_form = pi.create_state_space(can_form) sys_mat = ss_form.A[1] eig_vals, eig_vecs = np.linalg.eig(sys_mat) real_idx = np.where(np.imag(eig_vals) == 0) abs_idx = np.argsort(np.abs(eig_vals[real_idx])) filtered_vals = eig_vals[real_idx][abs_idx] print(filtered_vals) return filtered_vals class TestSecondOrderEigenVector(unittest.TestCase): def setUp(self): self.domain = pi.Domain(bounds=(0, 1), num=100) self.cnt = 10 self.params_dirichlet = pi.SecondOrderOperator(a2=1, a1=0, a0=1, alpha1=0, alpha0=1, beta1=0, beta0=1, domain=(0, 1)) if 1: self.eig_dirichlet = None self.p_dirichlet = [(1j*n * np.pi, -1j * n * np.pi) for n in range(1, self.cnt + 1)] else: # TODO make computation by approximation work to check to other two self.eig_dirichlet = \ calc_dirichlet_eigenvalues(self.params_dirichlet)[:self.cnt] self.p_dirichlet = \ pi.SecondOrderEigenVector.convert_to_characteristic_root( self.params_dirichlet, self.eig_dirichlet ) self.params_neumann = pi.SecondOrderOperator(a2=1, a1=0, a0=1, alpha1=1, alpha0=0, beta1=1, beta0=0) self.eig_neumann = None self.p_neumann = None # self.p_neumann = np.array([0, np.pi, 2 * np.pi, 3 * np.pi], # dtype=complex) self.params_robin = pi.Parameters(a2=1, a1=0, a0=1, alpha1=1, alpha0=2, beta1=1, beta0=-2) self.eig_robin = None self.p_robin = None # self.p_robin = np.array([(2.39935728j, -2.39935728j,), # (5.59677209j, -5.59677209j), # (8.98681892j, -8.98681892j)]) def test_dirichlet(self): print("dirichlet case") self._test_helper(self.params_dirichlet, self.eig_dirichlet, self.p_dirichlet) def test_neumann(self): print("neumann case") self._test_helper(self.params_neumann, self.eig_neumann, self.p_neumann) def test_robin(self): print("robin case") self._test_helper(self.params_robin, self.eig_robin, self.p_robin) def _test_helper(self, params, l_ref, p_ref): eig_base = pi.SecondOrderEigenVector.cure_interval(self.domain, params=params, count=self.cnt, derivative_order=2, debug=False) char_roots = eig_base.get_attribute("char_pair") eig_values = pi.SecondOrderEigenVector.convert_to_eigenvalue(params, char_roots) # if show_plots: # pi.visualize_functions(eig_base.fractions) # test eigenvalues self.assertEqual(len(eig_values), self.cnt) if l_ref is not None: np.testing.assert_array_equal(eig_values, l_ref, verbose=True) if p_ref is not None: print(char_roots) print(p_ref) np.testing.assert_array_almost_equal(char_roots, p_ref, decimal=5, verbose=True) # test eigenvectors for fraction, lam in zip(eig_base.fractions, eig_values): # test whether the operator is satisfied left = (params.a2 * fraction.derive(2)(self.domain.points) + params.a1 * fraction.derive(1)(self.domain.points) + params.a0 * fraction(self.domain.points)) right = lam * fraction(self.domain.points) np.testing.assert_array_almost_equal(left, right, verbose=True) # test whether the bcs are fulfilled bc1 = (params.alpha0 * fraction(self.domain.bounds[0]) + params.alpha1 * fraction.derive(1)(self.domain.bounds[0])) bc2 = (params.beta0 * fraction(self.domain.bounds[1]) + params.beta1 * fraction.derive(1)(self.domain.bounds[1])) np.testing.assert_array_almost_equal(bc1, 0, decimal=5) np.testing.assert_array_almost_equal(bc2, 0, decimal=5) # check if they are orthonormal product_mat = pi.calculate_scalar_product_matrix(eig_base, eig_base) np.testing.assert_array_almost_equal(product_mat, np.eye(self.cnt)) return eig_base class TestEigenvalues(unittest.TestCase): def test_dirichlet(self): desired_eig_freq = [(i + 1) * np.pi for i in range(4)] eig_freq, _ = pi.SecondOrderDirichletEigenfunction.eigfreq_eigval_hint( [1, 2, 3, None, None], 1, 4) self.assertTrue(all(np.isclose(eig_freq, desired_eig_freq))) def test_robin(self): param_desired_ef_pairs = [ ([.5, 0, 6, -1, -1], [1.543405j, 2.331122, 5.950173, 9.208434]), ([1, 0, 1, -2, -2], [2.39935728j, 0, 5.59677209, 8.98681892]), ([1, 0, 1, 0, 0], [0j, 3.14159265, 6.28318531, 9.42477796]), ([1, 2, 1, 3, 4], [2.06301691, 4.46395118, 7.18653501, 10.09113552]), ([1, -6, 0, -5, -5], [8.000003j, 1.84683426j, 4.86945051, 8.43284888])] for param, desired_eig_freq in param_desired_ef_pairs: eig_freq, _ = pi.SecondOrderRobinEigenfunction.eigfreq_eigval_hint( param, 1, 4, show_plot=False) np.testing.assert_array_almost_equal(eig_freq, desired_eig_freq) class TestSecondOrderEigenvalueProblemFunctions(unittest.TestCase): def setUp(self): self.param = [2, 1.5, -3, -5, -.5] self.z = pi.Domain((0, 1), num=100) self.n = 10 def evp_eq(self, a2, a1, a0, boundary_check): for eig_v, eig_f in zip(self.eig_val, self.eig_funcs): np.testing.assert_array_almost_equal( (a2 * eig_f.derive(2)(self.z) + a1 * eig_f.derive(1)(self.z) + a0 * eig_f(self.z)) / eig_v, eig_v.real * eig_f(self.z) / eig_v, decimal=4) boundary_check(eig_v, eig_f, self.z[-1]) @unittest.skip("not implemented") def test_dirichlet_robin_constant_coefficient(self): def boundary_check(eig_v, eig_f, l): np.testing.assert_array_almost_equal(eig_f(0) / eig_v, 0) np.testing.assert_array_almost_equal(eig_f.derive(1)(l) / eig_v, -beta * eig_f(l) / eig_v) a2, a1, a0, _, beta = self.param param = [a2, a1, a0, None, beta] eig_freq, self.eig_val \ = pi.SecondOrderDiriRobEigenfunction.eigfreq_eigval_hint( self.z, param=param, n=self.n, show_plot=True) _, self.eig_funcs = pi.SecondOrderDiriRobEigenfunction.cure_interval( self.z, param=param, eig_freq=eig_freq) [plt.plot(self.z, func(self.z)) for func in self.eig_funcs] plt.show() self.evp_eq(a2, a1, a0, boundary_check) self.spatially_varying_coefficient(boundary_check) @unittest.skip("not implemented") def test_robin_dirichlet_constant_coefficient(self): def boundary_check(eig_v, eig_f, l): np.testing.assert_array_almost_equal(eig_f.derive(1)(0) / eig_v, alpha * eig_f(0) / eig_v) np.testing.assert_array_almost_equal(eig_f(l) / eig_v, 0) a2, a1, a0, alpha, _ = self.param param = [a2, a1, a0, alpha, None] eig_freq, self.eig_val \ = pi.SecondOrderRobDiriEigenfunction.eigfreq_eigval_hint( self.z, param=param, n=self.n, show_plot=True) _, self.eig_funcs = pi.SecondOrderRobDiriEigenfunction.cure_interval( self.z, param=param, eig_freq=eig_freq) [plt.plot(self.z, func(self.z)) for func in self.eig_funcs] plt.show() self.evp_eq(a2, a1, a0, boundary_check) self.spatially_varying_coefficient(boundary_check) def test_dirichlet_constant_coefficient(self): def boundary_check(eig_v, eig_f, l): np.testing.assert_array_almost_equal(eig_f(0) / eig_v, 0) np.testing.assert_array_almost_equal(eig_f(l) / eig_v, 0) a2, a1, a0, _, _ = self.param param = [a2, a1, a0, None, None] eig_freq, self.eig_val \ = pi.SecondOrderDirichletEigenfunction.eigfreq_eigval_hint( param, self.z[-1], self.n) _, self.eig_funcs = pi.SecondOrderDirichletEigenfunction.cure_interval( self.z, param=param, eig_freq=eig_freq) self.evp_eq(a2, a1, a0, boundary_check) self.spatially_varying_coefficient(boundary_check) def test_robin_constant_coefficient(self): def boundary_check(eig_v, eig_f, l): np.testing.assert_array_almost_equal(eig_f.derive(1)(0) / eig_v, alpha * eig_f(0) / eig_v) np.testing.assert_array_almost_equal(eig_f.derive(1)(l) / eig_v, - beta * eig_f(l) / eig_v) a2, a1, a0, alpha, beta = self.param eig_freq, self.eig_val \ = pi.SecondOrderRobinEigenfunction.eigfreq_eigval_hint( self.param, self.z[-1], self.n, show_plot=show_plots) _, self.eig_funcs = pi.SecondOrderRobinEigenfunction.cure_interval( self.z, param=self.param, eig_freq=eig_freq) self.evp_eq(a2, a1, a0, boundary_check) self.spatially_varying_coefficient(boundary_check) if show_plots: plt.show() def spatially_varying_coefficient(self, boundary_check): a2, a1, a0, _, _ = self.param a2_z = pi.ConstantFunction(a2) a1_z = pi.ConstantFunction(a1) a0_z = pi.ConstantFunction(a0) transformed_eig_funcs = [pi.TransformedSecondOrderEigenfunction( self.eig_val[i], [self.eig_funcs[i](0), self.eig_funcs[i].derive(1)(0), 0, 0], [a2_z, a1_z, a0_z], self.z) for i in range(len(self.eig_funcs))] # TODO: provide second derivative of transformed eigenfunctions for i in range(len(self.eig_funcs)): eig_f = transformed_eig_funcs[i] eig_v = self.eig_val[i] # interval np.testing.assert_array_almost_equal( a2_z(self.z) * self.eig_funcs[i].derive(2)(self.z) + a1_z(self.z) * eig_f.derive(1)(self.z) + a0_z(self.z) * eig_f(self.z), eig_v.real * eig_f(self.z), decimal=2) boundary_check(eig_v, eig_f, self.z[-1]) class IntermediateTransformationTest(unittest.TestCase): def test_it(self): # system/simulation parameters self.l = 1 self.spatial_domain = (0, self.l) self.spatial_disc = 30 self.n = 10 # original system parameters a2 = 1.5 a1 = 2.5 a0 = 28 alpha = -2 beta = -3 self.param = [a2, a1, a0, alpha, beta] adjoint_param = pi.SecondOrderEigenfunction.get_adjoint_problem(self.param) # target system parameters (controller parameters) a1_t = -5 a0_t = -25 alpha_t = 3 beta_t = 2 # a1_t = a1; a0_t = a0; alpha_t = alpha; beta_t = beta self.param_t = [a2, a1_t, a0_t, alpha_t, beta_t] # original intermediate ("_i") and target intermediate ("_ti") system parameters _, _, a0_i, self.alpha_i, self.beta_i = \ parabolic.general.eliminate_advection_term(self.param, self.l) self.param_i = a2, 0, a0_i, self.alpha_i, self.beta_i _, _, a0_ti, self.alpha_ti, self.beta_ti = \ parabolic.general.eliminate_advection_term(self.param_t, self.l) self.param_ti = a2, 0, a0_ti, self.alpha_ti, self.beta_ti # create (not normalized) eigenfunctions self.eig_freq, self.eig_val = \ pi.SecondOrderRobinEigenfunction.eigfreq_eigval_hint(self.param, self.l, self.n) init_eig_base = pi.Base([pi.SecondOrderRobinEigenfunction(om, self.param, self.spatial_domain[-1]) for om in self.eig_freq]) init_adjoint_eig_funcs = pi.Base([pi.SecondOrderRobinEigenfunction(om, adjoint_param, self.spatial_domain[-1]) for om in self.eig_freq]) # normalize eigenfunctions and adjoint eigenfunctions self.eig_base, self.adjoint_eig_funcs = pi.normalize_base(init_eig_base, init_adjoint_eig_funcs) # eigenvalues and -frequencies test eig_freq_i, eig_val_i = pi.SecondOrderRobinEigenfunction.eigfreq_eigval_hint(self.param_i, self.l, self.n) self.assertTrue(all(np.isclose(self.eig_val, eig_val_i))) calc_eig_freq = np.sqrt((a0_i - eig_val_i) / a2) self.assertTrue(all(np.isclose(calc_eig_freq, eig_freq_i))) # intermediate (_i) eigenfunction test eig_funcs_i = np.array([pi.SecondOrderRobinEigenfunction(eig_freq_i[i], self.param_i, self.spatial_domain[-1], self.eig_base.fractions[i](0)) for i in range(self.n)]) self.assertTrue(all(np.isclose([func(0) for func in eig_funcs_i], [func(0) for func in self.eig_base.fractions]))) test_vec = np.linspace(0, self.l, 100) for i in range(self.n): self.assertTrue(all(np.isclose(self.eig_base.fractions[i](test_vec), eig_funcs_i[i](test_vec) * np.exp(-a1 / 2 / a2 * test_vec))))
gpl-3.0
groschovskiy/personfinder
app/unidecode/x073.py
252
4646
data = ( 'Sha ', # 0x00 'Li ', # 0x01 'Han ', # 0x02 'Xian ', # 0x03 'Jing ', # 0x04 'Pai ', # 0x05 'Fei ', # 0x06 'Yao ', # 0x07 'Ba ', # 0x08 'Qi ', # 0x09 'Ni ', # 0x0a 'Biao ', # 0x0b 'Yin ', # 0x0c 'Lai ', # 0x0d 'Xi ', # 0x0e 'Jian ', # 0x0f 'Qiang ', # 0x10 'Kun ', # 0x11 'Yan ', # 0x12 'Guo ', # 0x13 'Zong ', # 0x14 'Mi ', # 0x15 'Chang ', # 0x16 'Yi ', # 0x17 'Zhi ', # 0x18 'Zheng ', # 0x19 'Ya ', # 0x1a 'Meng ', # 0x1b 'Cai ', # 0x1c 'Cu ', # 0x1d 'She ', # 0x1e 'Kari ', # 0x1f 'Cen ', # 0x20 'Luo ', # 0x21 'Hu ', # 0x22 'Zong ', # 0x23 'Ji ', # 0x24 'Wei ', # 0x25 'Feng ', # 0x26 'Wo ', # 0x27 'Yuan ', # 0x28 'Xing ', # 0x29 'Zhu ', # 0x2a 'Mao ', # 0x2b 'Wei ', # 0x2c 'Yuan ', # 0x2d 'Xian ', # 0x2e 'Tuan ', # 0x2f 'Ya ', # 0x30 'Nao ', # 0x31 'Xie ', # 0x32 'Jia ', # 0x33 'Hou ', # 0x34 'Bian ', # 0x35 'You ', # 0x36 'You ', # 0x37 'Mei ', # 0x38 'Zha ', # 0x39 'Yao ', # 0x3a 'Sun ', # 0x3b 'Bo ', # 0x3c 'Ming ', # 0x3d 'Hua ', # 0x3e 'Yuan ', # 0x3f 'Sou ', # 0x40 'Ma ', # 0x41 'Yuan ', # 0x42 'Dai ', # 0x43 'Yu ', # 0x44 'Shi ', # 0x45 'Hao ', # 0x46 '[?] ', # 0x47 'Yi ', # 0x48 'Zhen ', # 0x49 'Chuang ', # 0x4a 'Hao ', # 0x4b 'Man ', # 0x4c 'Jing ', # 0x4d 'Jiang ', # 0x4e 'Mu ', # 0x4f 'Zhang ', # 0x50 'Chan ', # 0x51 'Ao ', # 0x52 'Ao ', # 0x53 'Hao ', # 0x54 'Cui ', # 0x55 'Fen ', # 0x56 'Jue ', # 0x57 'Bi ', # 0x58 'Bi ', # 0x59 'Huang ', # 0x5a 'Pu ', # 0x5b 'Lin ', # 0x5c 'Yu ', # 0x5d 'Tong ', # 0x5e 'Yao ', # 0x5f 'Liao ', # 0x60 'Shuo ', # 0x61 'Xiao ', # 0x62 'Swu ', # 0x63 'Ton ', # 0x64 'Xi ', # 0x65 'Ge ', # 0x66 'Juan ', # 0x67 'Du ', # 0x68 'Hui ', # 0x69 'Kuai ', # 0x6a 'Xian ', # 0x6b 'Xie ', # 0x6c 'Ta ', # 0x6d 'Xian ', # 0x6e 'Xun ', # 0x6f 'Ning ', # 0x70 'Pin ', # 0x71 'Huo ', # 0x72 'Nou ', # 0x73 'Meng ', # 0x74 'Lie ', # 0x75 'Nao ', # 0x76 'Guang ', # 0x77 'Shou ', # 0x78 'Lu ', # 0x79 'Ta ', # 0x7a 'Xian ', # 0x7b 'Mi ', # 0x7c 'Rang ', # 0x7d 'Huan ', # 0x7e 'Nao ', # 0x7f 'Luo ', # 0x80 'Xian ', # 0x81 'Qi ', # 0x82 'Jue ', # 0x83 'Xuan ', # 0x84 'Miao ', # 0x85 'Zi ', # 0x86 'Lu ', # 0x87 'Lu ', # 0x88 'Yu ', # 0x89 'Su ', # 0x8a 'Wang ', # 0x8b 'Qiu ', # 0x8c 'Ga ', # 0x8d 'Ding ', # 0x8e 'Le ', # 0x8f 'Ba ', # 0x90 'Ji ', # 0x91 'Hong ', # 0x92 'Di ', # 0x93 'Quan ', # 0x94 'Gan ', # 0x95 'Jiu ', # 0x96 'Yu ', # 0x97 'Ji ', # 0x98 'Yu ', # 0x99 'Yang ', # 0x9a 'Ma ', # 0x9b 'Gong ', # 0x9c 'Wu ', # 0x9d 'Fu ', # 0x9e 'Wen ', # 0x9f 'Jie ', # 0xa0 'Ya ', # 0xa1 'Fen ', # 0xa2 'Bian ', # 0xa3 'Beng ', # 0xa4 'Yue ', # 0xa5 'Jue ', # 0xa6 'Yun ', # 0xa7 'Jue ', # 0xa8 'Wan ', # 0xa9 'Jian ', # 0xaa 'Mei ', # 0xab 'Dan ', # 0xac 'Pi ', # 0xad 'Wei ', # 0xae 'Huan ', # 0xaf 'Xian ', # 0xb0 'Qiang ', # 0xb1 'Ling ', # 0xb2 'Dai ', # 0xb3 'Yi ', # 0xb4 'An ', # 0xb5 'Ping ', # 0xb6 'Dian ', # 0xb7 'Fu ', # 0xb8 'Xuan ', # 0xb9 'Xi ', # 0xba 'Bo ', # 0xbb 'Ci ', # 0xbc 'Gou ', # 0xbd 'Jia ', # 0xbe 'Shao ', # 0xbf 'Po ', # 0xc0 'Ci ', # 0xc1 'Ke ', # 0xc2 'Ran ', # 0xc3 'Sheng ', # 0xc4 'Shen ', # 0xc5 'Yi ', # 0xc6 'Zu ', # 0xc7 'Jia ', # 0xc8 'Min ', # 0xc9 'Shan ', # 0xca 'Liu ', # 0xcb 'Bi ', # 0xcc 'Zhen ', # 0xcd 'Zhen ', # 0xce 'Jue ', # 0xcf 'Fa ', # 0xd0 'Long ', # 0xd1 'Jin ', # 0xd2 'Jiao ', # 0xd3 'Jian ', # 0xd4 'Li ', # 0xd5 'Guang ', # 0xd6 'Xian ', # 0xd7 'Zhou ', # 0xd8 'Gong ', # 0xd9 'Yan ', # 0xda 'Xiu ', # 0xdb 'Yang ', # 0xdc 'Xu ', # 0xdd 'Luo ', # 0xde 'Su ', # 0xdf 'Zhu ', # 0xe0 'Qin ', # 0xe1 'Ken ', # 0xe2 'Xun ', # 0xe3 'Bao ', # 0xe4 'Er ', # 0xe5 'Xiang ', # 0xe6 'Yao ', # 0xe7 'Xia ', # 0xe8 'Heng ', # 0xe9 'Gui ', # 0xea 'Chong ', # 0xeb 'Xu ', # 0xec 'Ban ', # 0xed 'Pei ', # 0xee '[?] ', # 0xef 'Dang ', # 0xf0 'Ei ', # 0xf1 'Hun ', # 0xf2 'Wen ', # 0xf3 'E ', # 0xf4 'Cheng ', # 0xf5 'Ti ', # 0xf6 'Wu ', # 0xf7 'Wu ', # 0xf8 'Cheng ', # 0xf9 'Jun ', # 0xfa 'Mei ', # 0xfb 'Bei ', # 0xfc 'Ting ', # 0xfd 'Xian ', # 0xfe 'Chuo ', # 0xff )
apache-2.0
apacha/MusicSymbolClassifier
ModelTrainer/models/ResNet1Configuration.py
1
4585
from tensorflow.keras import Input from tensorflow.keras import Model from tensorflow.keras.layers import Layer, Activation, BatchNormalization, Convolution2D, Dense, Flatten, MaxPooling2D, AveragePooling2D, \ add from tensorflow.keras.models import Sequential from tensorflow.keras.regularizers import l2 from tensorflow.keras.utils import plot_model from models.TrainingConfiguration import TrainingConfiguration class ResNet1Configuration(TrainingConfiguration): """ A network with residual modules """ def __init__(self, optimizer: str, width: int, height: int, training_minibatch_size: int, number_of_classes: int): super().__init__(optimizer=optimizer, data_shape=(height, width, 3), training_minibatch_size=training_minibatch_size, number_of_classes=number_of_classes) def classifier(self) -> Sequential: """ Returns the model of this configuration """ input = Input(shape=self.data_shape) layer = self.add_convolution_block_with_batch_normalization(input, 64, 7, (2, 2), 1) layer = MaxPooling2D()(layer) for i in range(1, 4): layer = self.add_res_net_block(layer, 64, 3, False, 2, i) for i in range(1, 4): is_first_convolution = i == 1 layer = self.add_res_net_block(layer, 128, 3, is_first_convolution, 3, i) for i in range(1, 4): is_first_convolution = i == 1 layer = self.add_res_net_block(layer, 256, 3, is_first_convolution, 4, i) for i in range(1, 4): is_first_convolution = i == 1 layer = self.add_res_net_block(layer, 512, 3, is_first_convolution, 5, i) layer = AveragePooling2D()(layer) feature_vector = Flatten()(layer) number_of_output_classes = self.number_of_classes classification_head = Dense(units=number_of_output_classes, kernel_regularizer=l2(self.weight_decay), activation='softmax', name='output_class')(feature_vector) model = Model(inputs=[input], outputs=[classification_head]) model.compile(self.get_optimizer(), loss={'output_class': 'categorical_crossentropy'}, metrics=["accuracy"]) return model def add_convolution_block_with_batch_normalization(self, previous_layer: Layer, filters, kernel_size, strides, layer_number: int) -> Layer: layer = Convolution2D(filters, kernel_size, strides=strides, padding='same', kernel_regularizer=l2(self.weight_decay), name='conv' + str(layer_number))(previous_layer) layer = BatchNormalization()(layer) layer = Activation('relu')(layer) return layer def add_res_net_block(self, previous_layer: Layer, filters, kernel_size, is_first_convolution, layer_number: int, block_number: int): first_strides = (1, 1) if is_first_convolution: first_strides = (2, 2) # use strides instead of max-pooling to downsample image layer = Convolution2D(filters, kernel_size, strides=first_strides, padding='same', kernel_regularizer=l2(self.weight_decay), name="conv{0}_{1}_a".format(layer_number, block_number))( previous_layer) layer = BatchNormalization()(layer) layer = Activation('relu')(layer) layer = Convolution2D(filters, kernel_size, padding='same', kernel_regularizer=l2(self.weight_decay), name="conv{0}_{1}_b".format(layer_number, block_number))(layer) layer = BatchNormalization()(layer) layer = Activation('relu')(layer) shortcut = previous_layer if is_first_convolution: shortcut = Convolution2D(filters, 1, strides=first_strides, padding='same', kernel_regularizer=l2(self.weight_decay), name="conv{0}_{1}_shortcut".format(layer_number, block_number))(previous_layer) return add([layer, shortcut]) def name(self) -> str: """ Returns the name of this configuration """ return "res_net_1" def performs_localization(self) -> bool: return False if __name__ == "__main__": configuration = ResNet1Configuration("Adadelta", 96, 96, 16, 32) configuration.classifier().summary() plot_model(configuration.classifier(), to_file="res_net_1.png") print(configuration.summary())
mit
rockaboxmedia/pexpect
examples/script.py
17
3028
#!/usr/bin/env python """This spawns a sub-shell (bash) and gives the user interactive control. The entire shell session is logged to a file called script.log. This behaves much like the classic BSD command 'script'. ./script.py [-a] [-c command] {logfilename} logfilename : This is the name of the log file. Default is script.log. -a : Append to log file. Default is to overwrite log file. -c : spawn command. Default is to spawn the sh shell. Example: This will start a bash shell and append to the log named my_session.log: ./script.py -a -c bash my_session.log """ import os, sys, time, getopt import signal, fcntl, termios, struct import traceback import pexpect global_pexpect_instance = None # Used by signal handler def exit_with_usage(): print globals()['__doc__'] os._exit(1) def main(): ###################################################################### # Parse the options, arguments, get ready, etc. ###################################################################### try: optlist, args = getopt.getopt(sys.argv[1:], 'h?ac:', ['help','h','?']) except Exception, e: print str(e) exit_with_usage() options = dict(optlist) if len(args) > 1: exit_with_usage() if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]: print "Help:" exit_with_usage() if len(args) == 1: script_filename = args[0] else: script_filename = "script.log" if '-a' in options: fout = file (script_filename, "ab") else: fout = file (script_filename, "wb") if '-c' in options: command = options['-c'] else: command = "sh" # Begin log with date/time in the form CCCCyymm.hhmmss fout.write ('# %4d%02d%02d.%02d%02d%02d \n' % time.localtime()[:-3]) ###################################################################### # Start the interactive session ###################################################################### p = pexpect.spawn(command) p.logfile = fout global global_pexpect_instance global_pexpect_instance = p signal.signal(signal.SIGWINCH, sigwinch_passthrough) print "Script recording started. Type ^] (ASCII 29) to escape from the script shell." p.interact(chr(29)) fout.close() return 0 def sigwinch_passthrough (sig, data): # Check for buggy platforms (see pexpect.setwinsize()). if 'TIOCGWINSZ' in dir(termios): TIOCGWINSZ = termios.TIOCGWINSZ else: TIOCGWINSZ = 1074295912 # assume s = struct.pack ("HHHH", 0, 0, 0, 0) a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s)) global global_pexpect_instance global_pexpect_instance.setwinsize(a[0],a[1]) if __name__ == "__main__": try: main() except SystemExit, e: raise e except Exception, e: print "ERROR" print str(e) traceback.print_exc() os._exit(1)
mit