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
Azulinho/ansible
lib/ansible/playbook/base.py
3
24147
# Copyright: (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # Copyright: (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 itertools import operator from copy import copy as shallowcopy from functools import partial from jinja2.exceptions import UndefinedError from ansible import constants as C from ansible.module_utils.six import iteritems, string_types, with_metaclass from ansible.module_utils.parsing.convert_bool import boolean from ansible.errors import AnsibleParserError, AnsibleUndefinedVariable, AnsibleAssertionError from ansible.module_utils._text import to_text, to_native from ansible.playbook.attribute import Attribute, FieldAttribute from ansible.parsing.dataloader import DataLoader from ansible.utils.vars import combine_vars, isidentifier, get_unique_id try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() def _generic_g(prop_name, self): try: return self._attributes[prop_name] except KeyError: raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, prop_name)) def _generic_g_method(prop_name, self): try: if self._squashed: return self._attributes[prop_name] method = "_get_attr_%s" % prop_name return getattr(self, method)() except KeyError: raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, prop_name)) def _generic_g_parent(prop_name, self): try: value = self._attributes[prop_name] if value is None and not self._squashed and not self._finalized: try: value = self._get_parent_attribute(prop_name) except AttributeError: pass except KeyError: raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, prop_name)) return value def _generic_s(prop_name, self, value): self._attributes[prop_name] = value def _generic_d(prop_name, self): del self._attributes[prop_name] class BaseMeta(type): """ Metaclass for the Base object, which is used to construct the class attributes based on the FieldAttributes available. """ def __new__(cls, name, parents, dct): def _create_attrs(src_dict, dst_dict): ''' Helper method which creates the attributes based on those in the source dictionary of attributes. This also populates the other attributes used to keep track of these attributes and via the getter/setter/deleter methods. ''' keys = list(src_dict.keys()) for attr_name in keys: value = src_dict[attr_name] if isinstance(value, Attribute): if attr_name.startswith('_'): attr_name = attr_name[1:] # here we selectively assign the getter based on a few # things, such as whether we have a _get_attr_<name> # method, or if the attribute is marked as not inheriting # its value from a parent object method = "_get_attr_%s" % attr_name if method in src_dict or method in dst_dict: getter = partial(_generic_g_method, attr_name) elif ('_get_parent_attribute' in dst_dict or '_get_parent_attribute' in src_dict) and value.inherit: getter = partial(_generic_g_parent, attr_name) else: getter = partial(_generic_g, attr_name) setter = partial(_generic_s, attr_name) deleter = partial(_generic_d, attr_name) dst_dict[attr_name] = property(getter, setter, deleter) dst_dict['_valid_attrs'][attr_name] = value dst_dict['_attributes'][attr_name] = value.default if value.alias is not None: dst_dict[value.alias] = property(getter, setter, deleter) dst_dict['_valid_attrs'][value.alias] = value dst_dict['_alias_attrs'][value.alias] = attr_name def _process_parents(parents, dst_dict): ''' Helper method which creates attributes from all parent objects recursively on through grandparent objects ''' for parent in parents: if hasattr(parent, '__dict__'): _create_attrs(parent.__dict__, dst_dict) new_dst_dict = parent.__dict__.copy() new_dst_dict.update(dst_dict) _process_parents(parent.__bases__, new_dst_dict) # create some additional class attributes dct['_attributes'] = dict() dct['_valid_attrs'] = dict() dct['_alias_attrs'] = dict() # now create the attributes based on the FieldAttributes # available, including from parent (and grandparent) objects _create_attrs(dct, dct) _process_parents(parents, dct) return super(BaseMeta, cls).__new__(cls, name, parents, dct) class Base(with_metaclass(BaseMeta, object)): _name = FieldAttribute(isa='string', default='', always_post_validate=True, inherit=False) # connection/transport _connection = FieldAttribute(isa='string') _port = FieldAttribute(isa='int') _remote_user = FieldAttribute(isa='string') # variables _vars = FieldAttribute(isa='dict', priority=100, inherit=False) # flags and misc. settings _environment = FieldAttribute(isa='list') _no_log = FieldAttribute(isa='bool') _always_run = FieldAttribute(isa='bool') _run_once = FieldAttribute(isa='bool') _ignore_errors = FieldAttribute(isa='bool') _check_mode = FieldAttribute(isa='bool') _diff = FieldAttribute(isa='bool') _any_errors_fatal = FieldAttribute(isa='bool') # param names which have been deprecated/removed DEPRECATED_ATTRIBUTES = [ 'sudo', 'sudo_user', 'sudo_pass', 'sudo_exe', 'sudo_flags', 'su', 'su_user', 'su_pass', 'su_exe', 'su_flags', ] _inheritable = True def __init__(self): # initialize the data loader and variable manager, which will be provided # later when the object is actually loaded self._loader = None self._variable_manager = None # other internal params self._validated = False self._squashed = False self._finalized = False # every object gets a random uuid: self._uuid = get_unique_id() # we create a copy of the attributes here due to the fact that # it was initialized as a class param in the meta class, so we # need a unique object here (all members contained within are # unique already). self._attributes = self._attributes.copy() # and init vars, avoid using defaults in field declaration as it lives across plays self.vars = dict() def dump_me(self, depth=0): ''' this is never called from production code, it is here to be used when debugging as a 'complex print' ''' if depth == 0: display.debug("DUMPING OBJECT ------------------------------------------------------") display.debug("%s- %s (%s, id=%s)" % (" " * depth, self.__class__.__name__, self, id(self))) if hasattr(self, '_parent') and self._parent: self._parent.dump_me(depth + 2) dep_chain = self._parent.get_dep_chain() if dep_chain: for dep in dep_chain: dep.dump_me(depth + 2) if hasattr(self, '_play') and self._play: self._play.dump_me(depth + 2) def preprocess_data(self, ds): ''' infrequently used method to do some pre-processing of legacy terms ''' for base_class in self.__class__.mro(): method = getattr(self, "_preprocess_data_%s" % base_class.__name__.lower(), None) if method: return method(ds) return ds def load_data(self, ds, variable_manager=None, loader=None): ''' walk the input datastructure and assign any values ''' if ds is None: raise AnsibleAssertionError('ds (%s) should not be None but it is.' % ds) # cache the datastructure internally setattr(self, '_ds', ds) # the variable manager class is used to manage and merge variables # down to a single dictionary for reference in templating, etc. self._variable_manager = variable_manager # the data loader class is used to parse data from strings and files if loader is not None: self._loader = loader else: self._loader = DataLoader() # call the preprocess_data() function to massage the data into # something we can more easily parse, and then call the validation # function on it to ensure there are no incorrect key values ds = self.preprocess_data(ds) self._validate_attributes(ds) # Walk all attributes in the class. We sort them based on their priority # so that certain fields can be loaded before others, if they are dependent. for name, attr in sorted(iteritems(self._valid_attrs), key=operator.itemgetter(1)): # copy the value over unless a _load_field method is defined target_name = name if name in self._alias_attrs: target_name = self._alias_attrs[name] if name in ds: method = getattr(self, '_load_%s' % name, None) if method: self._attributes[target_name] = method(name, ds[name]) else: self._attributes[target_name] = ds[name] # run early, non-critical validation self.validate() # return the constructed object return self def get_ds(self): try: return getattr(self, '_ds') except AttributeError: return None def get_loader(self): return self._loader def get_variable_manager(self): return self._variable_manager def _validate_attributes(self, ds): ''' Ensures that there are no keys in the datastructure which do not map to attributes for this object. ''' valid_attrs = frozenset(self._valid_attrs.keys()) for key in ds: if key not in valid_attrs: raise AnsibleParserError("'%s' is not a valid attribute for a %s" % (key, self.__class__.__name__), obj=ds) def validate(self, all_vars=None): ''' validation that is done at parse time, not load time ''' all_vars = {} if all_vars is None else all_vars if not self._validated: # walk all fields in the object for (name, attribute) in iteritems(self._valid_attrs): if name in self._alias_attrs: name = self._alias_attrs[name] # run validator only if present method = getattr(self, '_validate_%s' % name, None) if method: method(attribute, name, getattr(self, name)) else: # and make sure the attribute is of the type it should be value = self._attributes[name] if value is not None: if attribute.isa == 'string' and isinstance(value, (list, dict)): raise AnsibleParserError( "The field '%s' is supposed to be a string type," " however the incoming data structure is a %s" % (name, type(value)), obj=self.get_ds() ) self._validated = True def squash(self): ''' Evaluates all attributes and sets them to the evaluated version, so that all future accesses of attributes do not need to evaluate parent attributes. ''' if not self._squashed: for name in self._valid_attrs.keys(): self._attributes[name] = getattr(self, name) self._squashed = True def copy(self): ''' Create a copy of this object and return it. ''' new_me = self.__class__() for name in self._valid_attrs.keys(): if name in self._alias_attrs: continue new_me._attributes[name] = shallowcopy(self._attributes[name]) new_me._loader = self._loader new_me._variable_manager = self._variable_manager new_me._validated = self._validated new_me._finalized = self._finalized new_me._uuid = self._uuid # if the ds value was set on the object, copy it to the new copy too if hasattr(self, '_ds'): new_me._ds = self._ds return new_me def post_validate(self, templar): ''' we can't tell that everything is of the right type until we have all the variables. Run basic types (from isa) as well as any _post_validate_<foo> functions. ''' # save the omit value for later checking omit_value = templar._available_variables.get('omit') for (name, attribute) in iteritems(self._valid_attrs): if getattr(self, name) is None: if not attribute.required: continue else: raise AnsibleParserError("the field '%s' is required but was not set" % name) elif not attribute.always_post_validate and self.__class__.__name__ not in ('Task', 'Handler', 'PlayContext'): # Intermediate objects like Play() won't have their fields validated by # default, as their values are often inherited by other objects and validated # later, so we don't want them to fail out early continue try: # Run the post-validator if present. These methods are responsible for # using the given templar to template the values, if required. method = getattr(self, '_post_validate_%s' % name, None) if method: value = method(attribute, getattr(self, name), templar) elif attribute.isa == 'class': value = getattr(self, name) else: # if the attribute contains a variable, template it now value = templar.template(getattr(self, name)) # if this evaluated to the omit value, set the value back to # the default specified in the FieldAttribute and move on if omit_value is not None and value == omit_value: setattr(self, name, attribute.default) continue # and make sure the attribute is of the type it should be if value is not None: if attribute.isa == 'string': value = to_text(value) elif attribute.isa == 'int': value = int(value) elif attribute.isa == 'float': value = float(value) elif attribute.isa == 'bool': value = boolean(value, strict=False) elif attribute.isa == 'percent': # special value, which may be an integer or float # with an optional '%' at the end if isinstance(value, string_types) and '%' in value: value = value.replace('%', '') value = float(value) elif attribute.isa in ('list', 'barelist'): if value is None: value = [] elif not isinstance(value, list): if isinstance(value, string_types) and attribute.isa == 'barelist': display.deprecated( "Using comma separated values for a list has been deprecated. " "You should instead use the correct YAML syntax for lists. " ) value = value.split(',') else: value = [value] if attribute.listof is not None: for item in value: if not isinstance(item, attribute.listof): raise AnsibleParserError("the field '%s' should be a list of %s, " "but the item '%s' is a %s" % (name, attribute.listof, item, type(item)), obj=self.get_ds()) elif attribute.required and attribute.listof == string_types: if item is None or item.strip() == "": raise AnsibleParserError("the field '%s' is required, and cannot have empty values" % (name,), obj=self.get_ds()) elif attribute.isa == 'set': if value is None: value = set() elif not isinstance(value, (list, set)): if isinstance(value, string_types): value = value.split(',') else: # Making a list like this handles strings of # text and bytes properly value = [value] if not isinstance(value, set): value = set(value) elif attribute.isa == 'dict': if value is None: value = dict() elif not isinstance(value, dict): raise TypeError("%s is not a dictionary" % value) elif attribute.isa == 'class': if not isinstance(value, attribute.class_type): raise TypeError("%s is not a valid %s (got a %s instead)" % (name, attribute.class_type, type(value))) value.post_validate(templar=templar) # and assign the massaged value back to the attribute field setattr(self, name, value) except (TypeError, ValueError) as e: raise AnsibleParserError("the field '%s' has an invalid value (%s), and could not be converted to an %s." "The error was: %s" % (name, value, attribute.isa, e), obj=self.get_ds(), orig_exc=e) except (AnsibleUndefinedVariable, UndefinedError) as e: if templar._fail_on_undefined_errors and name != 'name': if name == 'args': msg = "The task includes an option with an undefined variable. The error was: %s" % (to_native(e)) else: msg = "The field '%s' has an invalid value, which includes an undefined variable. The error was: %s" % (name, to_native(e)) raise AnsibleParserError(msg, obj=self.get_ds(), orig_exc=e) self._finalized = True def _load_vars(self, attr, ds): ''' Vars in a play can be specified either as a dictionary directly, or as a list of dictionaries. If the later, this method will turn the list into a single dictionary. ''' def _validate_variable_keys(ds): for key in ds: if not isidentifier(key): raise TypeError("'%s' is not a valid variable name" % key) try: if isinstance(ds, dict): _validate_variable_keys(ds) return ds elif isinstance(ds, list): all_vars = dict() for item in ds: if not isinstance(item, dict): raise ValueError _validate_variable_keys(item) all_vars = combine_vars(all_vars, item) return all_vars elif ds is None: return {} else: raise ValueError except ValueError as e: raise AnsibleParserError("Vars in a %s must be specified as a dictionary, or a list of dictionaries" % self.__class__.__name__, obj=ds, orig_exc=e) except TypeError as e: raise AnsibleParserError("Invalid variable name in vars specified for %s: %s" % (self.__class__.__name__, e), obj=ds, orig_exc=e) def _extend_value(self, value, new_value, prepend=False): ''' Will extend the value given with new_value (and will turn both into lists if they are not so already). The values are run through a set to remove duplicate values. ''' if not isinstance(value, list): value = [value] if not isinstance(new_value, list): new_value = [new_value] if prepend: combined = new_value + value else: combined = value + new_value return [i for i, _ in itertools.groupby(combined) if i is not None] def dump_attrs(self): ''' Dumps all attributes to a dictionary ''' attrs = dict() for (name, attribute) in iteritems(self._valid_attrs): attr = getattr(self, name) if attribute.isa == 'class' and attr is not None and hasattr(attr, 'serialize'): attrs[name] = attr.serialize() else: attrs[name] = attr return attrs def from_attrs(self, attrs): ''' Loads attributes from a dictionary ''' for (attr, value) in iteritems(attrs): if attr in self._valid_attrs: attribute = self._valid_attrs[attr] if attribute.isa == 'class' and isinstance(value, dict): obj = attribute.class_type() obj.deserialize(value) setattr(self, attr, obj) else: setattr(self, attr, value) def serialize(self): ''' Serializes the object derived from the base object into a dictionary of values. This only serializes the field attributes for the object, so this may need to be overridden for any classes which wish to add additional items not stored as field attributes. ''' repr = self.dump_attrs() # serialize the uuid field repr['uuid'] = self._uuid repr['finalized'] = self._finalized repr['squashed'] = self._squashed return repr def deserialize(self, data): ''' Given a dictionary of values, load up the field attributes for this object. As with serialize(), if there are any non-field attribute data members, this method will need to be overridden and extended. ''' if not isinstance(data, dict): raise AnsibleAssertionError('data (%s) should be a dict but is a %s' % (data, type(data))) for (name, attribute) in iteritems(self._valid_attrs): if name in data: setattr(self, name, data[name]) else: setattr(self, name, attribute.default) # restore the UUID field setattr(self, '_uuid', data.get('uuid')) self._finalized = data.get('finalized', False) self._squashed = data.get('squashed', False)
gpl-3.0
strint/tensorflow
tensorflow/contrib/slim/python/slim/nets/resnet_v2.py
34
13843
# Copyright 2016 The TensorFlow Authors. 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. # ============================================================================== """Contains definitions for the preactivation form of Residual Networks. Residual networks (ResNets) were originally proposed in: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 The full preactivation 'v2' ResNet variant implemented in this module was introduced by: [2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Identity Mappings in Deep Residual Networks. arXiv: 1603.05027 The key difference of the full preactivation 'v2' variant compared to the 'v1' variant in [1] is the use of batch normalization before every weight layer. Another difference is that 'v2' ResNets do not include an activation function in the main pathway. Also see [2; Fig. 4e]. Typical use: from tensorflow.contrib.slim.python.slim.nets import resnet_v2 ResNet-101 for image classification into 1000 classes: # inputs has shape [batch, 224, 224, 3] with slim.arg_scope(resnet_v2.resnet_arg_scope(is_training)): net, end_points = resnet_v2.resnet_v2_101(inputs, 1000) ResNet-101 for semantic segmentation into 21 classes: # inputs has shape [batch, 513, 513, 3] with slim.arg_scope(resnet_v2.resnet_arg_scope(is_training)): net, end_points = resnet_v2.resnet_v2_101(inputs, 21, global_pool=False, output_stride=16) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib import layers as layers_lib from tensorflow.contrib.framework.python.ops import add_arg_scope from tensorflow.contrib.framework.python.ops import arg_scope from tensorflow.contrib.layers.python.layers import layers from tensorflow.contrib.layers.python.layers import utils from tensorflow.contrib.slim.python.slim.nets import resnet_utils from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import variable_scope @add_arg_scope def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None): """Bottleneck residual unit variant with BN before convolutions. This is the full preactivation residual unit variant proposed in [2]. See Fig. 1(b) of [2] for its definition. Note that we use here the bottleneck variant which has an extra bottleneck layer. When putting together two consecutive ResNet blocks that use this unit, one should use stride = 2 in the last unit of the first block. Args: inputs: A tensor of size [batch, height, width, channels]. depth: The depth of the ResNet unit output. depth_bottleneck: The depth of the bottleneck layers. stride: The ResNet unit's stride. Determines the amount of downsampling of the units output compared to its input. rate: An integer, rate for atrous convolution. outputs_collections: Collection to add the ResNet unit output. scope: Optional variable_scope. Returns: The ResNet unit's output. """ with variable_scope.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc: depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4) preact = layers.batch_norm( inputs, activation_fn=nn_ops.relu, scope='preact') if depth == depth_in: shortcut = resnet_utils.subsample(inputs, stride, 'shortcut') else: shortcut = layers_lib.conv2d( preact, depth, [1, 1], stride=stride, normalizer_fn=None, activation_fn=None, scope='shortcut') residual = layers_lib.conv2d( preact, depth_bottleneck, [1, 1], stride=1, scope='conv1') residual = resnet_utils.conv2d_same( residual, depth_bottleneck, 3, stride, rate=rate, scope='conv2') residual = layers_lib.conv2d( residual, depth, [1, 1], stride=1, normalizer_fn=None, activation_fn=None, scope='conv3') output = shortcut + residual return utils.collect_named_outputs(outputs_collections, sc.name, output) def resnet_v2(inputs, blocks, num_classes=None, global_pool=True, output_stride=None, include_root_block=True, reuse=None, scope=None): """Generator for v2 (preactivation) ResNet models. This function generates a family of ResNet v2 models. See the resnet_v2_*() methods for specific model instantiations, obtained by selecting different block instantiations that produce ResNets of various depths. Training for image classification on Imagenet is usually done with [224, 224] inputs, resulting in [7, 7] feature maps at the output of the last ResNet block for the ResNets defined in [1] that have nominal stride equal to 32. However, for dense prediction tasks we advise that one uses inputs with spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In this case the feature maps at the ResNet output will have spatial shape [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1] and corners exactly aligned with the input image corners, which greatly facilitates alignment of the features to the image. Using as input [225, 225] images results in [8, 8] feature maps at the output of the last ResNet block. For dense prediction tasks, the ResNet needs to run in fully-convolutional (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all have nominal stride equal to 32 and a good choice in FCN mode is to use output_stride=16 in order to increase the density of the computed features at small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. blocks: A list of length equal to the number of ResNet blocks. Each element is a resnet_utils.Block object describing the units in the block. num_classes: Number of predicted classes for classification tasks. If None we return the features before the logit layer. global_pool: If True, we perform global average pooling before computing the logits. Set to True for image classification, False for dense prediction. output_stride: If None, then the output will be computed at the nominal network stride. If output_stride is not None, it specifies the requested ratio of input to output spatial resolution. include_root_block: If True, include the initial convolution followed by max-pooling, if False excludes it. If excluded, `inputs` should be the results of an activation-less convolution. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: net: A rank-4 tensor of size [batch, height_out, width_out, channels_out]. If global_pool is False, then height_out and width_out are reduced by a factor of output_stride compared to the respective height_in and width_in, else both height_out and width_out equal one. If num_classes is None, then net is the output of the last ResNet block, potentially after global average pooling. If num_classes is not None, net contains the pre-softmax activations. end_points: A dictionary from components of the network to the corresponding activation. Raises: ValueError: If the target output_stride is not valid. """ with variable_scope.variable_scope( scope, 'resnet_v2', [inputs], reuse=reuse) as sc: end_points_collection = sc.original_name_scope + '_end_points' with arg_scope( [layers_lib.conv2d, bottleneck, resnet_utils.stack_blocks_dense], outputs_collections=end_points_collection): net = inputs if include_root_block: if output_stride is not None: if output_stride % 4 != 0: raise ValueError('The output_stride needs to be a multiple of 4.') output_stride /= 4 # We do not include batch normalization or activation functions in conv1 # because the first ResNet unit will perform these. Cf. Appendix of [2]. with arg_scope( [layers_lib.conv2d], activation_fn=None, normalizer_fn=None): net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1') net = layers.max_pool2d(net, [3, 3], stride=2, scope='pool1') net = resnet_utils.stack_blocks_dense(net, blocks, output_stride) # This is needed because the pre-activation variant does not have batch # normalization or activation functions in the residual unit output. See # Appendix of [2]. net = layers.batch_norm(net, activation_fn=nn_ops.relu, scope='postnorm') if global_pool: # Global average pooling. net = math_ops.reduce_mean(net, [1, 2], name='pool5', keep_dims=True) if num_classes is not None: net = layers_lib.conv2d( net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='logits') # Convert end_points_collection into a dictionary of end_points. end_points = utils.convert_collection_to_dict(end_points_collection) if num_classes is not None: end_points['predictions'] = layers.softmax(net, scope='predictions') return net, end_points resnet_v2.default_image_size = 224 def resnet_v2_50(inputs, num_classes=None, global_pool=True, output_stride=None, reuse=None, scope='resnet_v2_50'): """ResNet-50 model of [1]. See resnet_v2() for arg and return description.""" blocks = [ resnet_utils.Block('block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]), resnet_utils.Block('block2', bottleneck, [(512, 128, 1)] * 3 + [(512, 128, 2)]), resnet_utils.Block('block3', bottleneck, [(1024, 256, 1)] * 5 + [(1024, 256, 2)]), resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3) ] return resnet_v2( inputs, blocks, num_classes, global_pool, output_stride, include_root_block=True, reuse=reuse, scope=scope) def resnet_v2_101(inputs, num_classes=None, global_pool=True, output_stride=None, reuse=None, scope='resnet_v2_101'): """ResNet-101 model of [1]. See resnet_v2() for arg and return description.""" blocks = [ resnet_utils.Block('block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]), resnet_utils.Block('block2', bottleneck, [(512, 128, 1)] * 3 + [(512, 128, 2)]), resnet_utils.Block('block3', bottleneck, [(1024, 256, 1)] * 22 + [(1024, 256, 2)]), resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3) ] return resnet_v2( inputs, blocks, num_classes, global_pool, output_stride, include_root_block=True, reuse=reuse, scope=scope) def resnet_v2_152(inputs, num_classes=None, global_pool=True, output_stride=None, reuse=None, scope='resnet_v2_152'): """ResNet-152 model of [1]. See resnet_v2() for arg and return description.""" blocks = [ resnet_utils.Block('block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]), resnet_utils.Block('block2', bottleneck, [(512, 128, 1)] * 7 + [(512, 128, 2)]), resnet_utils.Block('block3', bottleneck, [(1024, 256, 1)] * 35 + [(1024, 256, 2)]), resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3) ] return resnet_v2( inputs, blocks, num_classes, global_pool, output_stride, include_root_block=True, reuse=reuse, scope=scope) def resnet_v2_200(inputs, num_classes=None, global_pool=True, output_stride=None, reuse=None, scope='resnet_v2_200'): """ResNet-200 model of [2]. See resnet_v2() for arg and return description.""" blocks = [ resnet_utils.Block('block1', bottleneck, [(256, 64, 1)] * 2 + [(256, 64, 2)]), resnet_utils.Block('block2', bottleneck, [(512, 128, 1)] * 23 + [(512, 128, 2)]), resnet_utils.Block('block3', bottleneck, [(1024, 256, 1)] * 35 + [(1024, 256, 2)]), resnet_utils.Block('block4', bottleneck, [(2048, 512, 1)] * 3) ] return resnet_v2( inputs, blocks, num_classes, global_pool, output_stride, include_root_block=True, reuse=reuse, scope=scope)
apache-2.0
splbio/openobject-server
openerp/report/pyPdf/generic.py
136
29129
# vim: sw=4:expandtab:foldmethod=marker # # Copyright (c) 2006, Mathieu Fenniak # 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. # * The name of the author may not 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. """ Implementation of generic PDF objects (dictionary, number, string, and so on) """ __author__ = "Mathieu Fenniak" __author_email__ = "biziqe@mathieu.fenniak.net" import re from utils import readNonWhitespace, RC4_encrypt import filters import utils import decimal import codecs def readObject(stream, pdf): tok = stream.read(1) stream.seek(-1, 1) # reset to start if tok == 't' or tok == 'f': # boolean object return BooleanObject.readFromStream(stream) elif tok == '(': # string object return readStringFromStream(stream) elif tok == '/': # name object return NameObject.readFromStream(stream) elif tok == '[': # array object return ArrayObject.readFromStream(stream, pdf) elif tok == 'n': # null object return NullObject.readFromStream(stream) elif tok == '<': # hexadecimal string OR dictionary peek = stream.read(2) stream.seek(-2, 1) # reset to start if peek == '<<': return DictionaryObject.readFromStream(stream, pdf) else: return readHexStringFromStream(stream) elif tok == '%': # comment while tok not in ('\r', '\n'): tok = stream.read(1) tok = readNonWhitespace(stream) stream.seek(-1, 1) return readObject(stream, pdf) else: # number object OR indirect reference if tok == '+' or tok == '-': # number return NumberObject.readFromStream(stream) peek = stream.read(20) stream.seek(-len(peek), 1) # reset to start if re.match(r"(\d+)\s(\d+)\sR[^a-zA-Z]", peek) is not None: return IndirectObject.readFromStream(stream, pdf) else: return NumberObject.readFromStream(stream) class PdfObject(object): def getObject(self): """Resolves indirect references.""" return self class NullObject(PdfObject): def writeToStream(self, stream, encryption_key): stream.write("null") def readFromStream(stream): nulltxt = stream.read(4) if nulltxt != "null": raise utils.PdfReadError, "error reading null object" return NullObject() readFromStream = staticmethod(readFromStream) class BooleanObject(PdfObject): def __init__(self, value): self.value = value def writeToStream(self, stream, encryption_key): if self.value: stream.write("true") else: stream.write("false") def readFromStream(stream): word = stream.read(4) if word == "true": return BooleanObject(True) elif word == "fals": stream.read(1) return BooleanObject(False) assert False readFromStream = staticmethod(readFromStream) class ArrayObject(list, PdfObject): def writeToStream(self, stream, encryption_key): stream.write("[") for data in self: stream.write(" ") data.writeToStream(stream, encryption_key) stream.write(" ]") def readFromStream(stream, pdf): arr = ArrayObject() tmp = stream.read(1) if tmp != "[": raise utils.PdfReadError, "error reading array" while True: # skip leading whitespace tok = stream.read(1) while tok.isspace(): tok = stream.read(1) stream.seek(-1, 1) # check for array ending peekahead = stream.read(1) if peekahead == "]": break stream.seek(-1, 1) # read and append obj arr.append(readObject(stream, pdf)) return arr readFromStream = staticmethod(readFromStream) class IndirectObject(PdfObject): def __init__(self, idnum, generation, pdf): self.idnum = idnum self.generation = generation self.pdf = pdf def getObject(self): return self.pdf.getObject(self).getObject() def __repr__(self): return "IndirectObject(%r, %r)" % (self.idnum, self.generation) def __eq__(self, other): return ( other is not None and isinstance(other, IndirectObject) and self.idnum == other.idnum and self.generation == other.generation and self.pdf is other.pdf ) def __ne__(self, other): return not self.__eq__(other) def writeToStream(self, stream, encryption_key): stream.write("%s %s R" % (self.idnum, self.generation)) def readFromStream(stream, pdf): idnum = "" while True: tok = stream.read(1) if tok.isspace(): break idnum += tok generation = "" while True: tok = stream.read(1) if tok.isspace(): break generation += tok r = stream.read(1) if r != "R": raise utils.PdfReadError("error reading indirect object reference") return IndirectObject(int(idnum), int(generation), pdf) readFromStream = staticmethod(readFromStream) class FloatObject(decimal.Decimal, PdfObject): def __new__(cls, value="0", context=None): return decimal.Decimal.__new__(cls, str(value), context) def __repr__(self): if self == self.to_integral(): return str(self.quantize(decimal.Decimal(1))) else: # XXX: this adds useless extraneous zeros. return "%.5f" % self def writeToStream(self, stream, encryption_key): stream.write(repr(self)) class NumberObject(int, PdfObject): def __init__(self, value): int.__init__(value) def writeToStream(self, stream, encryption_key): stream.write(repr(self)) def readFromStream(stream): name = "" while True: tok = stream.read(1) if tok != '+' and tok != '-' and tok != '.' and not tok.isdigit(): stream.seek(-1, 1) break name += tok if name.find(".") != -1: return FloatObject(name) else: return NumberObject(name) readFromStream = staticmethod(readFromStream) ## # Given a string (either a "str" or "unicode"), create a ByteStringObject or a # TextStringObject to represent the string. def createStringObject(string): if isinstance(string, unicode): return TextStringObject(string) elif isinstance(string, str): if string.startswith(codecs.BOM_UTF16_BE): retval = TextStringObject(string.decode("utf-16")) retval.autodetect_utf16 = True return retval else: # This is probably a big performance hit here, but we need to # convert string objects into the text/unicode-aware version if # possible... and the only way to check if that's possible is # to try. Some strings are strings, some are just byte arrays. try: retval = TextStringObject(decode_pdfdocencoding(string)) retval.autodetect_pdfdocencoding = True return retval except UnicodeDecodeError: return ByteStringObject(string) else: raise TypeError("createStringObject should have str or unicode arg") def readHexStringFromStream(stream): stream.read(1) txt = "" x = "" while True: tok = readNonWhitespace(stream) if tok == ">": break x += tok if len(x) == 2: txt += chr(int(x, base=16)) x = "" if len(x) == 1: x += "0" if len(x) == 2: txt += chr(int(x, base=16)) return createStringObject(txt) def readStringFromStream(stream): tok = stream.read(1) parens = 1 txt = "" while True: tok = stream.read(1) if tok == "(": parens += 1 elif tok == ")": parens -= 1 if parens == 0: break elif tok == "\\": tok = stream.read(1) if tok == "n": tok = "\n" elif tok == "r": tok = "\r" elif tok == "t": tok = "\t" elif tok == "b": tok = "\b" elif tok == "f": tok = "\f" elif tok == "(": tok = "(" elif tok == ")": tok = ")" elif tok == "\\": tok = "\\" elif tok.isdigit(): # "The number ddd may consist of one, two, or three # octal digits; high-order overflow shall be ignored. # Three octal digits shall be used, with leading zeros # as needed, if the next character of the string is also # a digit." (PDF reference 7.3.4.2, p 16) for i in range(2): ntok = stream.read(1) if ntok.isdigit(): tok += ntok else: break tok = chr(int(tok, base=8)) elif tok in "\n\r": # This case is hit when a backslash followed by a line # break occurs. If it's a multi-char EOL, consume the # second character: tok = stream.read(1) if not tok in "\n\r": stream.seek(-1, 1) # Then don't add anything to the actual string, since this # line break was escaped: tok = '' else: raise utils.PdfReadError("Unexpected escaped string") txt += tok return createStringObject(txt) ## # Represents a string object where the text encoding could not be determined. # This occurs quite often, as the PDF spec doesn't provide an alternate way to # represent strings -- for example, the encryption data stored in files (like # /O) is clearly not text, but is still stored in a "String" object. class ByteStringObject(str, PdfObject): ## # For compatibility with TextStringObject.original_bytes. This method # returns self. original_bytes = property(lambda self: self) def writeToStream(self, stream, encryption_key): bytearr = self if encryption_key: bytearr = RC4_encrypt(encryption_key, bytearr) stream.write("<") stream.write(bytearr.encode("hex")) stream.write(">") ## # Represents a string object that has been decoded into a real unicode string. # If read from a PDF document, this string appeared to match the # PDFDocEncoding, or contained a UTF-16BE BOM mark to cause UTF-16 decoding to # occur. class TextStringObject(unicode, PdfObject): autodetect_pdfdocencoding = False autodetect_utf16 = False ## # It is occasionally possible that a text string object gets created where # a byte string object was expected due to the autodetection mechanism -- # if that occurs, this "original_bytes" property can be used to # back-calculate what the original encoded bytes were. original_bytes = property(lambda self: self.get_original_bytes()) def get_original_bytes(self): # We're a text string object, but the library is trying to get our raw # bytes. This can happen if we auto-detected this string as text, but # we were wrong. It's pretty common. Return the original bytes that # would have been used to create this object, based upon the autodetect # method. if self.autodetect_utf16: return codecs.BOM_UTF16_BE + self.encode("utf-16be") elif self.autodetect_pdfdocencoding: return encode_pdfdocencoding(self) else: raise Exception("no information about original bytes") def writeToStream(self, stream, encryption_key): # Try to write the string out as a PDFDocEncoding encoded string. It's # nicer to look at in the PDF file. Sadly, we take a performance hit # here for trying... try: bytearr = encode_pdfdocencoding(self) except UnicodeEncodeError: bytearr = codecs.BOM_UTF16_BE + self.encode("utf-16be") if encryption_key: bytearr = RC4_encrypt(encryption_key, bytearr) obj = ByteStringObject(bytearr) obj.writeToStream(stream, None) else: stream.write("(") for c in bytearr: if not c.isalnum() and c != ' ': stream.write("\\%03o" % ord(c)) else: stream.write(c) stream.write(")") class NameObject(str, PdfObject): delimiterCharacters = "(", ")", "<", ">", "[", "]", "{", "}", "/", "%" def __init__(self, data): str.__init__(data) def writeToStream(self, stream, encryption_key): stream.write(self) def readFromStream(stream): name = stream.read(1) if name != "/": raise utils.PdfReadError, "name read error" while True: tok = stream.read(1) if tok.isspace() or tok in NameObject.delimiterCharacters: stream.seek(-1, 1) break name += tok return NameObject(name) readFromStream = staticmethod(readFromStream) class DictionaryObject(dict, PdfObject): def __init__(self, *args, **kwargs): if len(args) == 0: self.update(kwargs) elif len(args) == 1: arr = args[0] # If we're passed a list/tuple, make a dict out of it if not hasattr(arr, "iteritems"): newarr = {} for k, v in arr: newarr[k] = v arr = newarr self.update(arr) else: raise TypeError("dict expected at most 1 argument, got 3") def update(self, arr): # note, a ValueError halfway through copying values # will leave half the values in this dict. for k, v in arr.iteritems(): self.__setitem__(k, v) def raw_get(self, key): return dict.__getitem__(self, key) def __setitem__(self, key, value): if not isinstance(key, PdfObject): raise ValueError("key must be PdfObject") if not isinstance(value, PdfObject): raise ValueError("value must be PdfObject") return dict.__setitem__(self, key, value) def setdefault(self, key, value=None): if not isinstance(key, PdfObject): raise ValueError("key must be PdfObject") if not isinstance(value, PdfObject): raise ValueError("value must be PdfObject") return dict.setdefault(self, key, value) def __getitem__(self, key): return dict.__getitem__(self, key).getObject() ## # Retrieves XMP (Extensible Metadata Platform) data relevant to the # this object, if available. # <p> # Stability: Added in v1.12, will exist for all future v1.x releases. # @return Returns a {@link #xmp.XmpInformation XmlInformation} instance # that can be used to access XMP metadata from the document. Can also # return None if no metadata was found on the document root. def getXmpMetadata(self): metadata = self.get("/Metadata", None) if metadata is None: return None metadata = metadata.getObject() import xmp if not isinstance(metadata, xmp.XmpInformation): metadata = xmp.XmpInformation(metadata) self[NameObject("/Metadata")] = metadata return metadata ## # Read-only property that accesses the {@link # #DictionaryObject.getXmpData getXmpData} function. # <p> # Stability: Added in v1.12, will exist for all future v1.x releases. xmpMetadata = property(lambda self: self.getXmpMetadata(), None, None) def writeToStream(self, stream, encryption_key): stream.write("<<\n") for key, value in self.items(): key.writeToStream(stream, encryption_key) stream.write(" ") value.writeToStream(stream, encryption_key) stream.write("\n") stream.write(">>") def readFromStream(stream, pdf): tmp = stream.read(2) if tmp != "<<": raise utils.PdfReadError, "dictionary read error" data = {} while True: tok = readNonWhitespace(stream) if tok == ">": stream.read(1) break stream.seek(-1, 1) key = readObject(stream, pdf) tok = readNonWhitespace(stream) stream.seek(-1, 1) value = readObject(stream, pdf) if data.has_key(key): # multiple definitions of key not permitted raise utils.PdfReadError, "multiple definitions in dictionary" data[key] = value pos = stream.tell() s = readNonWhitespace(stream) if s == 's' and stream.read(5) == 'tream': eol = stream.read(1) # odd PDF file output has spaces after 'stream' keyword but before EOL. # patch provided by Danial Sandler while eol == ' ': eol = stream.read(1) assert eol in ("\n", "\r") if eol == "\r": # read \n after stream.read(1) # this is a stream object, not a dictionary assert data.has_key("/Length") length = data["/Length"] if isinstance(length, IndirectObject): t = stream.tell() length = pdf.getObject(length) stream.seek(t, 0) data["__streamdata__"] = stream.read(length) e = readNonWhitespace(stream) ndstream = stream.read(8) if (e + ndstream) != "endstream": # (sigh) - the odd PDF file has a length that is too long, so # we need to read backwards to find the "endstream" ending. # ReportLab (unknown version) generates files with this bug, # and Python users into PDF files tend to be our audience. # we need to do this to correct the streamdata and chop off # an extra character. pos = stream.tell() stream.seek(-10, 1) end = stream.read(9) if end == "endstream": # we found it by looking back one character further. data["__streamdata__"] = data["__streamdata__"][:-1] else: stream.seek(pos, 0) raise utils.PdfReadError, "Unable to find 'endstream' marker after stream." else: stream.seek(pos, 0) if data.has_key("__streamdata__"): return StreamObject.initializeFromDictionary(data) else: retval = DictionaryObject() retval.update(data) return retval readFromStream = staticmethod(readFromStream) class StreamObject(DictionaryObject): def __init__(self): self._data = None self.decodedSelf = None def writeToStream(self, stream, encryption_key): self[NameObject("/Length")] = NumberObject(len(self._data)) DictionaryObject.writeToStream(self, stream, encryption_key) del self["/Length"] stream.write("\nstream\n") data = self._data if encryption_key: data = RC4_encrypt(encryption_key, data) stream.write(data) stream.write("\nendstream") def initializeFromDictionary(data): if data.has_key("/Filter"): retval = EncodedStreamObject() else: retval = DecodedStreamObject() retval._data = data["__streamdata__"] del data["__streamdata__"] del data["/Length"] retval.update(data) return retval initializeFromDictionary = staticmethod(initializeFromDictionary) def flateEncode(self): if self.has_key("/Filter"): f = self["/Filter"] if isinstance(f, ArrayObject): f.insert(0, NameObject("/FlateDecode")) else: newf = ArrayObject() newf.append(NameObject("/FlateDecode")) newf.append(f) f = newf else: f = NameObject("/FlateDecode") retval = EncodedStreamObject() retval[NameObject("/Filter")] = f retval._data = filters.FlateDecode.encode(self._data) return retval class DecodedStreamObject(StreamObject): def getData(self): return self._data def setData(self, data): self._data = data class EncodedStreamObject(StreamObject): def __init__(self): self.decodedSelf = None def getData(self): if self.decodedSelf: # cached version of decoded object return self.decodedSelf.getData() else: # create decoded object decoded = DecodedStreamObject() decoded._data = filters.decodeStreamData(self) for key, value in self.items(): if not key in ("/Length", "/Filter", "/DecodeParms"): decoded[key] = value self.decodedSelf = decoded return decoded._data def setData(self, data): raise utils.PdfReadError, "Creating EncodedStreamObject is not currently supported" class RectangleObject(ArrayObject): def __init__(self, arr): # must have four points assert len(arr) == 4 # automatically convert arr[x] into NumberObject(arr[x]) if necessary ArrayObject.__init__(self, [self.ensureIsNumber(x) for x in arr]) def ensureIsNumber(self, value): if not isinstance(value, (NumberObject, FloatObject)): value = FloatObject(value) return value def __repr__(self): return "RectangleObject(%s)" % repr(list(self)) def getLowerLeft_x(self): return self[0] def getLowerLeft_y(self): return self[1] def getUpperRight_x(self): return self[2] def getUpperRight_y(self): return self[3] def getUpperLeft_x(self): return self.getLowerLeft_x() def getUpperLeft_y(self): return self.getUpperRight_y() def getLowerRight_x(self): return self.getUpperRight_x() def getLowerRight_y(self): return self.getLowerLeft_y() def getLowerLeft(self): return self.getLowerLeft_x(), self.getLowerLeft_y() def getLowerRight(self): return self.getLowerRight_x(), self.getLowerRight_y() def getUpperLeft(self): return self.getUpperLeft_x(), self.getUpperLeft_y() def getUpperRight(self): return self.getUpperRight_x(), self.getUpperRight_y() def setLowerLeft(self, value): self[0], self[1] = [self.ensureIsNumber(x) for x in value] def setLowerRight(self, value): self[2], self[1] = [self.ensureIsNumber(x) for x in value] def setUpperLeft(self, value): self[0], self[3] = [self.ensureIsNumber(x) for x in value] def setUpperRight(self, value): self[2], self[3] = [self.ensureIsNumber(x) for x in value] def getWidth(self): return self.getUpperRight_x() - self.getLowerLeft_x() def getHeight(self): return self.getUpperRight_y() - self.getLowerLeft_x() lowerLeft = property(getLowerLeft, setLowerLeft, None, None) lowerRight = property(getLowerRight, setLowerRight, None, None) upperLeft = property(getUpperLeft, setUpperLeft, None, None) upperRight = property(getUpperRight, setUpperRight, None, None) def encode_pdfdocencoding(unicode_string): retval = '' for c in unicode_string: try: retval += chr(_pdfDocEncoding_rev[c]) except KeyError: raise UnicodeEncodeError("pdfdocencoding", c, -1, -1, "does not exist in translation table") return retval def decode_pdfdocencoding(byte_array): retval = u'' for b in byte_array: c = _pdfDocEncoding[ord(b)] if c == u'\u0000': raise UnicodeDecodeError("pdfdocencoding", b, -1, -1, "does not exist in translation table") retval += c return retval _pdfDocEncoding = ( u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u0000', u'\u02d8', u'\u02c7', u'\u02c6', u'\u02d9', u'\u02dd', u'\u02db', u'\u02da', u'\u02dc', u'\u0020', u'\u0021', u'\u0022', u'\u0023', u'\u0024', u'\u0025', u'\u0026', u'\u0027', u'\u0028', u'\u0029', u'\u002a', u'\u002b', u'\u002c', u'\u002d', u'\u002e', u'\u002f', u'\u0030', u'\u0031', u'\u0032', u'\u0033', u'\u0034', u'\u0035', u'\u0036', u'\u0037', u'\u0038', u'\u0039', u'\u003a', u'\u003b', u'\u003c', u'\u003d', u'\u003e', u'\u003f', u'\u0040', u'\u0041', u'\u0042', u'\u0043', u'\u0044', u'\u0045', u'\u0046', u'\u0047', u'\u0048', u'\u0049', u'\u004a', u'\u004b', u'\u004c', u'\u004d', u'\u004e', u'\u004f', u'\u0050', u'\u0051', u'\u0052', u'\u0053', u'\u0054', u'\u0055', u'\u0056', u'\u0057', u'\u0058', u'\u0059', u'\u005a', u'\u005b', u'\u005c', u'\u005d', u'\u005e', u'\u005f', u'\u0060', u'\u0061', u'\u0062', u'\u0063', u'\u0064', u'\u0065', u'\u0066', u'\u0067', u'\u0068', u'\u0069', u'\u006a', u'\u006b', u'\u006c', u'\u006d', u'\u006e', u'\u006f', u'\u0070', u'\u0071', u'\u0072', u'\u0073', u'\u0074', u'\u0075', u'\u0076', u'\u0077', u'\u0078', u'\u0079', u'\u007a', u'\u007b', u'\u007c', u'\u007d', u'\u007e', u'\u0000', u'\u2022', u'\u2020', u'\u2021', u'\u2026', u'\u2014', u'\u2013', u'\u0192', u'\u2044', u'\u2039', u'\u203a', u'\u2212', u'\u2030', u'\u201e', u'\u201c', u'\u201d', u'\u2018', u'\u2019', u'\u201a', u'\u2122', u'\ufb01', u'\ufb02', u'\u0141', u'\u0152', u'\u0160', u'\u0178', u'\u017d', u'\u0131', u'\u0142', u'\u0153', u'\u0161', u'\u017e', u'\u0000', u'\u20ac', u'\u00a1', u'\u00a2', u'\u00a3', u'\u00a4', u'\u00a5', u'\u00a6', u'\u00a7', u'\u00a8', u'\u00a9', u'\u00aa', u'\u00ab', u'\u00ac', u'\u0000', u'\u00ae', u'\u00af', u'\u00b0', u'\u00b1', u'\u00b2', u'\u00b3', u'\u00b4', u'\u00b5', u'\u00b6', u'\u00b7', u'\u00b8', u'\u00b9', u'\u00ba', u'\u00bb', u'\u00bc', u'\u00bd', u'\u00be', u'\u00bf', u'\u00c0', u'\u00c1', u'\u00c2', u'\u00c3', u'\u00c4', u'\u00c5', u'\u00c6', u'\u00c7', u'\u00c8', u'\u00c9', u'\u00ca', u'\u00cb', u'\u00cc', u'\u00cd', u'\u00ce', u'\u00cf', u'\u00d0', u'\u00d1', u'\u00d2', u'\u00d3', u'\u00d4', u'\u00d5', u'\u00d6', u'\u00d7', u'\u00d8', u'\u00d9', u'\u00da', u'\u00db', u'\u00dc', u'\u00dd', u'\u00de', u'\u00df', u'\u00e0', u'\u00e1', u'\u00e2', u'\u00e3', u'\u00e4', u'\u00e5', u'\u00e6', u'\u00e7', u'\u00e8', u'\u00e9', u'\u00ea', u'\u00eb', u'\u00ec', u'\u00ed', u'\u00ee', u'\u00ef', u'\u00f0', u'\u00f1', u'\u00f2', u'\u00f3', u'\u00f4', u'\u00f5', u'\u00f6', u'\u00f7', u'\u00f8', u'\u00f9', u'\u00fa', u'\u00fb', u'\u00fc', u'\u00fd', u'\u00fe', u'\u00ff' ) assert len(_pdfDocEncoding) == 256 _pdfDocEncoding_rev = {} for i in xrange(256): char = _pdfDocEncoding[i] if char == u"\u0000": continue assert char not in _pdfDocEncoding_rev _pdfDocEncoding_rev[char] = i
agpl-3.0
aral/isvat
django/utils/unittest/suite.py
219
9301
"""TestSuite""" import sys import unittest from django.utils.unittest import case, util __unittest = True class BaseTestSuite(unittest.TestSuite): """A simple test suite that doesn't provide class or module shared fixtures. """ def __init__(self, tests=()): self._tests = [] self.addTests(tests) def __repr__(self): return "<%s tests=%s>" % (util.strclass(self.__class__), list(self)) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return list(self) == list(other) def __ne__(self, other): return not self == other # Can't guarantee hash invariant, so flag as unhashable __hash__ = None def __iter__(self): return iter(self._tests) def countTestCases(self): cases = 0 for test in self: cases += test.countTestCases() return cases def addTest(self, test): # sanity checks if not hasattr(test, '__call__'): raise TypeError("%r is not callable" % (repr(test),)) if isinstance(test, type) and issubclass(test, (case.TestCase, TestSuite)): raise TypeError("TestCases and TestSuites must be instantiated " "before passing them to addTest()") self._tests.append(test) def addTests(self, tests): if isinstance(tests, basestring): raise TypeError("tests must be an iterable of tests, not a string") for test in tests: self.addTest(test) def run(self, result): for test in self: if result.shouldStop: break test(result) return result def __call__(self, *args, **kwds): return self.run(*args, **kwds) def debug(self): """Run the tests without collecting errors in a TestResult""" for test in self: test.debug() class TestSuite(BaseTestSuite): """A test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test runner, such as TextTestRunner. It will run the individual test cases in the order in which they were added, aggregating the results. When subclassing, do not forget to call the base class constructor. """ def run(self, result): self._wrapped_run(result) self._tearDownPreviousClass(None, result) self._handleModuleTearDown(result) return result def debug(self): """Run the tests without collecting errors in a TestResult""" debug = _DebugResult() self._wrapped_run(debug, True) self._tearDownPreviousClass(None, debug) self._handleModuleTearDown(debug) ################################ # private methods def _wrapped_run(self, result, debug=False): for test in self: if result.shouldStop: break if _isnotsuite(test): self._tearDownPreviousClass(test, result) self._handleModuleFixture(test, result) self._handleClassSetUp(test, result) result._previousTestClass = test.__class__ if (getattr(test.__class__, '_classSetupFailed', False) or getattr(result, '_moduleSetUpFailed', False)): continue if hasattr(test, '_wrapped_run'): test._wrapped_run(result, debug) elif not debug: test(result) else: test.debug() def _handleClassSetUp(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if result._moduleSetUpFailed: return if getattr(currentClass, "__unittest_skip__", False): return try: currentClass._classSetupFailed = False except TypeError: # test may actually be a function # so its class will be a builtin-type pass setUpClass = getattr(currentClass, 'setUpClass', None) if setUpClass is not None: try: setUpClass() except Exception as e: if isinstance(result, _DebugResult): raise currentClass._classSetupFailed = True className = util.strclass(currentClass) errorName = 'setUpClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) def _get_previous_module(self, result): previousModule = None previousClass = getattr(result, '_previousTestClass', None) if previousClass is not None: previousModule = previousClass.__module__ return previousModule def _handleModuleFixture(self, test, result): previousModule = self._get_previous_module(result) currentModule = test.__class__.__module__ if currentModule == previousModule: return self._handleModuleTearDown(result) result._moduleSetUpFailed = False try: module = sys.modules[currentModule] except KeyError: return setUpModule = getattr(module, 'setUpModule', None) if setUpModule is not None: try: setUpModule() except Exception as e: if isinstance(result, _DebugResult): raise result._moduleSetUpFailed = True errorName = 'setUpModule (%s)' % currentModule self._addClassOrModuleLevelException(result, e, errorName) def _addClassOrModuleLevelException(self, result, exception, errorName): error = _ErrorHolder(errorName) addSkip = getattr(result, 'addSkip', None) if addSkip is not None and isinstance(exception, case.SkipTest): addSkip(error, str(exception)) else: result.addError(error, sys.exc_info()) def _handleModuleTearDown(self, result): previousModule = self._get_previous_module(result) if previousModule is None: return if result._moduleSetUpFailed: return try: module = sys.modules[previousModule] except KeyError: return tearDownModule = getattr(module, 'tearDownModule', None) if tearDownModule is not None: try: tearDownModule() except Exception as e: if isinstance(result, _DebugResult): raise errorName = 'tearDownModule (%s)' % previousModule self._addClassOrModuleLevelException(result, e, errorName) def _tearDownPreviousClass(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if getattr(previousClass, '_classSetupFailed', False): return if getattr(result, '_moduleSetUpFailed', False): return if getattr(previousClass, "__unittest_skip__", False): return tearDownClass = getattr(previousClass, 'tearDownClass', None) if tearDownClass is not None: try: tearDownClass() except Exception as e: if isinstance(result, _DebugResult): raise className = util.strclass(previousClass) errorName = 'tearDownClass (%s)' % className self._addClassOrModuleLevelException(result, e, errorName) class _ErrorHolder(object): """ Placeholder for a TestCase inside a result. As far as a TestResult is concerned, this looks exactly like a unit test. Used to insert arbitrary errors into a test suite run. """ # Inspired by the ErrorHolder from Twisted: # http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py # attribute used by TestResult._exc_info_to_string failureException = None def __init__(self, description): self.description = description def id(self): return self.description def shortDescription(self): return None def __repr__(self): return "<ErrorHolder description=%r>" % (self.description,) def __str__(self): return self.id() def run(self, result): # could call result.addError(...) - but this test-like object # shouldn't be run anyway pass def __call__(self, result): return self.run(result) def countTestCases(self): return 0 def _isnotsuite(test): "A crude way to tell apart testcases and suites with duck-typing" try: iter(test) except TypeError: return True return False class _DebugResult(object): "Used by the TestSuite to hold previous class when running in debug." _previousTestClass = None _moduleSetUpFailed = False shouldStop = False
mit
jerryz1982/neutron
neutron/plugins/ml2/drivers/cisco/apic/mechanism_apic.py
20
12887
# Copyright (c) 2014 Cisco Systems 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. from apicapi import apic_manager from keystoneclient.v2_0 import client as keyclient import netaddr from oslo_concurrency import lockutils from oslo_config import cfg from oslo_log import log from neutron.common import constants as n_constants from neutron.plugins.common import constants from neutron.plugins.ml2 import driver_api as api from neutron.plugins.ml2.drivers.cisco.apic import apic_model from neutron.plugins.ml2.drivers.cisco.apic import apic_sync from neutron.plugins.ml2.drivers.cisco.apic import config from neutron.plugins.ml2 import models LOG = log.getLogger(__name__) class APICMechanismDriver(api.MechanismDriver): @staticmethod def get_apic_manager(client=True): apic_config = cfg.CONF.ml2_cisco_apic network_config = { 'vlan_ranges': cfg.CONF.ml2_type_vlan.network_vlan_ranges, 'switch_dict': config.create_switch_dictionary(), 'vpc_dict': config.create_vpc_dictionary(), 'external_network_dict': config.create_external_network_dictionary(), } apic_system_id = cfg.CONF.apic_system_id keyclient_param = keyclient if client else None keystone_authtoken = cfg.CONF.keystone_authtoken if client else None return apic_manager.APICManager(apic_model.ApicDbModel(), log, network_config, apic_config, keyclient_param, keystone_authtoken, apic_system_id) @staticmethod def get_base_synchronizer(inst): apic_config = cfg.CONF.ml2_cisco_apic return apic_sync.ApicBaseSynchronizer(inst, apic_config.apic_sync_interval) @staticmethod def get_router_synchronizer(inst): apic_config = cfg.CONF.ml2_cisco_apic return apic_sync.ApicRouterSynchronizer(inst, apic_config.apic_sync_interval) def initialize(self): # initialize apic self.apic_manager = APICMechanismDriver.get_apic_manager() self.name_mapper = self.apic_manager.apic_mapper self.synchronizer = None self.apic_manager.ensure_infra_created_on_apic() self.apic_manager.ensure_bgp_pod_policy_created_on_apic() def sync_init(f): def inner(inst, *args, **kwargs): if not inst.synchronizer: inst.synchronizer = ( APICMechanismDriver.get_base_synchronizer(inst)) inst.synchronizer.sync_base() # pylint: disable=not-callable return f(inst, *args, **kwargs) return inner @lockutils.synchronized('apic-portlock') def _perform_path_port_operations(self, context, port): # Get network network_id = context.network.current['id'] anetwork_id = self.name_mapper.network(context, network_id) # Get tenant details from port context tenant_id = context.current['tenant_id'] tenant_id = self.name_mapper.tenant(context, tenant_id) # Get segmentation id segment = context.top_bound_segment if not segment: LOG.debug("Port %s is not bound to a segment", port) return seg = None if (segment.get(api.NETWORK_TYPE) in [constants.TYPE_VLAN]): seg = segment.get(api.SEGMENTATION_ID) # hosts on which this vlan is provisioned host = context.host # Create a static path attachment for the host/epg/switchport combo with self.apic_manager.apic.transaction() as trs: self.apic_manager.ensure_path_created_for_port( tenant_id, anetwork_id, host, seg, transaction=trs) def _perform_gw_port_operations(self, context, port): router_id = port.get('device_id') network = context.network.current anetwork_id = self.name_mapper.network(context, network['id']) router_info = self.apic_manager.ext_net_dict.get(network['name']) if router_id and router_info: address = router_info['cidr_exposed'] next_hop = router_info['gateway_ip'] encap = router_info.get('encap') # No encap if None switch = router_info['switch'] module, sport = router_info['port'].split('/') with self.apic_manager.apic.transaction() as trs: # Get/Create contract arouter_id = self.name_mapper.router(context, router_id) cid = self.apic_manager.get_router_contract(arouter_id) # Ensure that the external ctx exists self.apic_manager.ensure_context_enforced() # Create External Routed Network and configure it self.apic_manager.ensure_external_routed_network_created( anetwork_id, transaction=trs) self.apic_manager.ensure_logical_node_profile_created( anetwork_id, switch, module, sport, encap, address, transaction=trs) self.apic_manager.ensure_static_route_created( anetwork_id, switch, next_hop, transaction=trs) self.apic_manager.ensure_external_epg_created( anetwork_id, transaction=trs) self.apic_manager.ensure_external_epg_consumed_contract( anetwork_id, cid, transaction=trs) self.apic_manager.ensure_external_epg_provided_contract( anetwork_id, cid, transaction=trs) def _perform_port_operations(self, context): # Get port port = context.current # Check if a compute port if context.host: self._perform_path_port_operations(context, port) if port.get('device_owner') == n_constants.DEVICE_OWNER_ROUTER_GW: self._perform_gw_port_operations(context, port) def _delete_contract(self, context): port = context.current network_id = self.name_mapper.network( context, context.network.current['id']) arouter_id = self.name_mapper.router(context, port.get('device_id')) self.apic_manager.delete_external_epg_contract(arouter_id, network_id) def _get_active_path_count(self, context): return context._plugin_context.session.query( models.PortBinding).filter_by( host=context.host, segment=context._binding.segment).count() @lockutils.synchronized('apic-portlock') def _delete_port_path(self, context, atenant_id, anetwork_id): if not self._get_active_path_count(context): self.apic_manager.ensure_path_deleted_for_port( atenant_id, anetwork_id, context.host) def _delete_path_if_last(self, context): if not self._get_active_path_count(context): tenant_id = context.current['tenant_id'] atenant_id = self.name_mapper.tenant(context, tenant_id) network_id = context.network.current['id'] anetwork_id = self.name_mapper.network(context, network_id) self._delete_port_path(context, atenant_id, anetwork_id) def _get_subnet_info(self, context, subnet): if subnet['gateway_ip']: tenant_id = subnet['tenant_id'] network_id = subnet['network_id'] network = context._plugin.get_network(context._plugin_context, network_id) if not network.get('router:external'): cidr = netaddr.IPNetwork(subnet['cidr']) gateway_ip = '%s/%s' % (subnet['gateway_ip'], str(cidr.prefixlen)) # Convert to APIC IDs tenant_id = self.name_mapper.tenant(context, tenant_id) network_id = self.name_mapper.network(context, network_id) return tenant_id, network_id, gateway_ip @sync_init def create_port_postcommit(self, context): self._perform_port_operations(context) @sync_init def update_port_postcommit(self, context): self._perform_port_operations(context) def delete_port_postcommit(self, context): port = context.current # Check if a compute port if context.host: self._delete_path_if_last(context) if port.get('device_owner') == n_constants.DEVICE_OWNER_ROUTER_GW: self._delete_contract(context) @sync_init def create_network_postcommit(self, context): if not context.current.get('router:external'): tenant_id = context.current['tenant_id'] network_id = context.current['id'] # Convert to APIC IDs tenant_id = self.name_mapper.tenant(context, tenant_id) network_id = self.name_mapper.network(context, network_id) # Create BD and EPG for this network with self.apic_manager.apic.transaction() as trs: self.apic_manager.ensure_bd_created_on_apic(tenant_id, network_id, transaction=trs) self.apic_manager.ensure_epg_created( tenant_id, network_id, transaction=trs) @sync_init def update_network_postcommit(self, context): super(APICMechanismDriver, self).update_network_postcommit(context) def delete_network_postcommit(self, context): if not context.current.get('router:external'): tenant_id = context.current['tenant_id'] network_id = context.current['id'] # Convert to APIC IDs tenant_id = self.name_mapper.tenant(context, tenant_id) network_id = self.name_mapper.network(context, network_id) # Delete BD and EPG for this network with self.apic_manager.apic.transaction() as trs: self.apic_manager.delete_epg_for_network(tenant_id, network_id, transaction=trs) self.apic_manager.delete_bd_on_apic(tenant_id, network_id, transaction=trs) else: network_name = context.current['name'] if self.apic_manager.ext_net_dict.get(network_name): network_id = self.name_mapper.network(context, context.current['id']) self.apic_manager.delete_external_routed_network(network_id) @sync_init def create_subnet_postcommit(self, context): info = self._get_subnet_info(context, context.current) if info: tenant_id, network_id, gateway_ip = info # Create subnet on BD self.apic_manager.ensure_subnet_created_on_apic( tenant_id, network_id, gateway_ip) @sync_init def update_subnet_postcommit(self, context): if context.current['gateway_ip'] != context.original['gateway_ip']: with self.apic_manager.apic.transaction() as trs: info = self._get_subnet_info(context, context.original) if info: tenant_id, network_id, gateway_ip = info # Delete subnet self.apic_manager.ensure_subnet_deleted_on_apic( tenant_id, network_id, gateway_ip, transaction=trs) info = self._get_subnet_info(context, context.current) if info: tenant_id, network_id, gateway_ip = info # Create subnet self.apic_manager.ensure_subnet_created_on_apic( tenant_id, network_id, gateway_ip, transaction=trs) def delete_subnet_postcommit(self, context): info = self._get_subnet_info(context, context.current) if info: tenant_id, network_id, gateway_ip = info self.apic_manager.ensure_subnet_deleted_on_apic( tenant_id, network_id, gateway_ip)
apache-2.0
carthagecollege/django-djforms
djforms/polisci/iea/proposal/views.py
2
3922
from django.conf import settings from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from djforms.polisci.iea.proposal.forms import ProposalContactForm from djforms.polisci.iea.proposal.forms import ProposalOrderForm from djforms.processors.forms import TrustCommerceForm from djforms.polisci.iea import TO_LIST, BCC from djtools.utils.mail import send_mail def form(request): """ Abstract Proposal form """ if request.POST: form_con =ProposalContactForm(request.POST, request.FILES) form_ord = ProposalOrderForm(request.POST) if form_con.is_valid() and form_ord.is_valid(): contact = form_con.save() order = form_ord.save() order.operator = settings.POLITICAL_SCIENCE_IEA_OPERATOR if contact.payment_method == 'Credit Card': form_proc = TrustCommerceForm( order, contact, request.POST, use_required_attribute=False ) if form_proc.is_valid(): r = form_proc.processor_response order.status = r.msg['status'] order.transid = r.msg['transid'] order.cc_name = form_proc.name order.cc_4_digits = form_proc.card[-4:] order.save() contact.order.add(order) order.reg = contact order.contact = contact sent = send_mail( request, TO_LIST, "[IEA] Abstract Submission", contact.email, 'polisci/iea/proposal/email.html', order, BCC ) order.send_mail = sent order.save() return HttpResponseRedirect( reverse('iea_proposal_success') ) else: r = form_proc.processor_response if r: order.status = r.status else: order.status = 'Form Invalid' order.cc_name = form_proc.name if form_proc.card: order.cc_4_digits = form_proc.card[-4:] order.save() contact.order.add(order) else: order.auth='COD' order.status='Pay later' order.save() contact.order.add(order) order.reg = contact order.contact = contact sent = send_mail( request, TO_LIST, "[IEA] Conference Abstract Proposal", contact.email, 'polisci/iea/proposal/email.html', order, BCC ) order.send_mail = sent order.save() return HttpResponseRedirect( reverse('iea_proposal_success') ) else: if request.POST.get('payment_method') == 'Credit Card': form_proc = TrustCommerceForm( None, request.POST, use_required_attribute=False ) form_proc.is_valid() else: form_proc = TrustCommerceForm(use_required_attribute=False) else: form_con = ProposalContactForm() form_ord = ProposalOrderForm( initial={'total':50, 'avs':False,'auth':'sale'} ) form_proc = TrustCommerceForm(use_required_attribute=False) return render( request, 'polisci/iea/proposal/form.html', { 'form_con': form_con, 'form_ord':form_ord, 'form_proc':form_proc } )
unlicense
yosukesuzuki/kay-template
project/kay/ext/media_compressor/media_compiler.py
9
23159
# -*- coding: utf-8 -*- """ media_compiler ~~~~~~~~~~~~~~ Compile media files(JavaScript/css) :Copyright: (c) 2009 reedom, Inc. All rights reserved. :license: BSD, see LICENSE for more details. """ import copy import logging import md5 import os import re import shutil import sys import tempfile import types import yaml import kay from kay.conf import settings import kay.ext.media_compressor.default_settings as media_conf IS_DEVSERVER = 'SERVER_SOFTWARE' in os.environ and \ os.environ['SERVER_SOFTWARE'].startswith('Dev') IS_APPSERVER = 'SERVER_SOFTWARE' in os.environ and \ os.environ['SERVER_SOFTWARE'].startswith('Google App Engine') #-------------------------------------------------------------- def union_list(a, b): return list(set(a).union(b)) class MediaInfo: path_ = os.path.join(kay.PROJECT_DIR, '_media.yaml') def __init__(self): self.info_ = {} @classmethod def load(cls): instance = cls() if os.path.exists(cls.path_): istream = open(cls.path_, 'rb') try: instance.info_ = yaml.safe_load(istream) except: pass finally: istream.close() return instance def save(self): ostream = open(self.path_, 'wb') try: yaml.safe_dump(self.info_, ostream, indent=2) finally: ostream.close() def get(self, category, name): info = self.info_.get(category) if info is None: return None return info.get(name) def set(self, category, name, new_value): info = self.info_.get(category) if info is None: self.info_[category] = {name: new_value} else: self.info_[category][name] = new_value media_info = None #-------------------------------------------------------------- VERBOSE_SURPRESS = 0 VERBOSE_PRINT = 1 VERBOSE_LOGGING = 2 def surpress_print_status(s): pass print_status_method = surpress_print_status def print_status(s): print_status_method(s) def set_verbose_method(method): global print_status_method if method == VERBOSE_SURPRESS: print_status_method = default_print_status elif method == VERBOSE_PRINT: print_status_method = kay.management.utils.print_status elif method == VERBOSE_LOGGING: print_status_method = logging.info #-------------------------------------------------------------- def _merge_css_config(dst, another): return _merge_config(dst, another, ['csstidy']) def _merge_js_config(dst, another): return _merge_config(dst, another, ['goog_calcdeps', 'goog_compiler']) def _merge_config(dst, another, merge_keys): if another is None: return {} if dst is None else dst if getattr(another, 'iteritems', None): for k, v in another.iteritems(): if k in merge_keys and k in dst: dst[k].update(v) else: dst[k] = copy.deepcopy(v) return dst COMPILE_COMMON = copy.deepcopy(media_conf.COMPILE_MEDIA) COMPILE_COMMON.update(getattr(settings, 'COMPILE_MEDIA_COMMON', {})) COMPILE_CSS = _merge_css_config(copy.deepcopy(COMPILE_COMMON), media_conf.COMPILE_MEDIA_CSS) if IS_DEVSERVER: COMPILE_CSS = _merge_css_config(COMPILE_CSS, media_conf.COMPILE_MEDIA_CSS_DEV) COMPILE_CSS = _merge_css_config( COMPILE_CSS, getattr(settings, 'COMPILE_MEDIA_CSS_COMMON', {})) if IS_DEVSERVER: COMPILE_CSS = _merge_css_config( COMPILE_CSS, getattr(settings, 'COMPILE_MEDIA_CSS_DEV', {})) COMPILE_JS = _merge_js_config(copy.deepcopy(COMPILE_COMMON), media_conf.COMPILE_MEDIA_JS) if IS_DEVSERVER: COMPILE_JS = _merge_js_config(COMPILE_JS, media_conf.COMPILE_MEDIA_JS_DEV) COMPILE_JS = _merge_js_config( COMPILE_JS, getattr(settings, 'COMPILE_MEDIA_JS_COMMON', {})) if IS_DEVSERVER: COMPILE_JS = _merge_js_config( COMPILE_JS, getattr(settings, 'COMPILE_MEDIA_JS_DEV', {})) #-------------------------------------------------------------- def manage_static_files(): if hasattr(settings, 'COMPILE_MEDIA_COMMON') and \ COMPILE_COMMON.has_key('static_dir') and \ COMPILE_COMMON['static_dir']: _create_symlinks() def _create_symlinks(): for from_path, to_path in COMPILE_COMMON['static_dir']: src_path = os.path.join(kay.PROJECT_DIR, from_path) dest_path = make_output_path_(COMPILE_COMMON, to_path) print_status(' %s => %s' % (from_path, dest_path[len(kay.PROJECT_DIR):])) dest_dir = os.path.dirname(dest_path) if dest_dir and not os.path.exists(dest_dir): os.makedirs(dest_dir) if not os.path.lexists(dest_path): os.symlink(os.path.abspath(from_path), dest_path) #-------------------------------------------------------------- def get_css_config(tag_name): if not getattr(settings, 'COMPILE_MEDIA_CSS'): raise Exception('settings.COMPILE_MEDIA_CSS is not defined') if not tag_name in settings.COMPILE_MEDIA_CSS: raise Exception('settings.COMPILE_MEDIA_CSS["%s"] is not defined' % tag_name) return _merge_css_config(copy.deepcopy(COMPILE_CSS), settings.COMPILE_MEDIA_CSS[tag_name]) def get_css_urls(tag_name, auto_compile=False): css_config = get_css_config(tag_name) if not css_config['enabled']: if css_config['source_urls']: return css_config['source_urls'] else: return [path if re.match(ur'https?://', path) else '/%s' % path for path in css_config['source_files']] if auto_compile: compile_css(tag_name) global media_info if media_info is None: media_info = MediaInfo.load() last_info = media_info.get(css_config['subdir'], tag_name) if not last_info: raise Exception('settings.COMPILE_MEDIA_CSS["%s"] has not been compiled' % tag_name) return last_info['result_urls'] def compile_css(tag_name=None, force=False): for name, x in settings.COMPILE_MEDIA_CSS.iteritems(): if tag_name is not None: if tag_name != name: continue print_status('Compiling css media [%s]' % name) css_config = get_css_config(name) compile_css_(name, css_config, force) return True def compile_css_(tag_name, css_config, force): if IS_APPSERVER: return def needs_update(media_info, output_path): if not css_config['enabled']: return False if not os.path.exists(output_path): return True last_info = media_info.get(css_config['subdir'], tag_name) if not last_info: return True last_config = last_info.get('config') if not last_config: return True if not equal_object_(last_config, css_config): return True if 'source_files' not in last_info: return True for path, mtime in last_info['source_files']: if mtime != os.path.getmtime(path): return True def csstidy(css_path): tmp_file = tempfile.NamedTemporaryFile(mode='w+b') ifile = open(css_path) tmp_file.write(ifile.read()) ifile.close() tmp_file.flush() output_file = tempfile.NamedTemporaryFile(mode='w+b') print_status(" %s %s %s ..." % (css_config['csstidy']['path'], css_path, css_config['csstidy']['arguments'])) command = '%s %s %s %s' % (css_config['csstidy']['path'], tmp_file.name, css_config['csstidy']['arguments'], output_file.name) command_output = os.popen(command).read() filtered_css = output_file.read() output_file.close() tmp_file.close() return filtered_css def concat(css_path): print_status(" concat %s" % css_path) ifile = open(css_path) css = ifile.read() ifile.close() return css if css_config['tool'] not in ('csstidy', 'concat'): print_status("COMPILE_MEDIA_CSS['tool'] setting is invalid;" " unknown tool `%s'" % css_config['tool']) sys.exit(1) global media_info if media_info is None: media_info = MediaInfo.load() output_path = make_output_path_(css_config, css_config['subdir'], css_config['output_filename']) if not force and not needs_update(media_info, output_path): print_status(' up to date.') return if css_config['tool'] == 'csstidy': tool_method = csstidy elif css_config['tool'] == 'concat': tool_method = concat source_files = [] for path in css_config['source_files']: path = make_input_path_(path) logging.info(path) source_files.append((path, os.path.getmtime(path))) ofile = create_file_(output_path) try: for path, mtime in source_files: ofile.write(tool_method(path)) finally: ofile.close() result_url = '/' + make_output_path_(css_config, css_config['subdir'], css_config['output_filename'], relative=True) last_info = {'config': copy.deepcopy(css_config), 'source_files': source_files, 'result_urls': [result_url]} media_info.set(css_config['subdir'], tag_name, last_info) media_info.save() #-------------------------------------------------------------- def get_js_config(tag_name): if not getattr(settings, 'COMPILE_MEDIA_JS'): raise Exception('settings.COMPILE_MEDIA_JS is not defined') if not tag_name in settings.COMPILE_MEDIA_JS: raise Exception('settings.COMPILE_MEDIA_JS["%s"] is not defined' % tag_name) return _merge_js_config(copy.deepcopy(COMPILE_JS), settings.COMPILE_MEDIA_JS[tag_name]) def get_js_urls(tag_name, auto_compile=False): js_config = get_js_config(tag_name) if not js_config['enabled']: if js_config['source_urls']: return js_config['source_urls'] else: return [path if re.match(ur'https?://', path) else '/%s' % path for path in js_config['source_files']] if auto_compile: compile_js(tag_name) global media_info if media_info is None: media_info = MediaInfo.load() last_info = media_info.get(js_config['subdir'], tag_name) if not last_info: raise Exception('settings.COMPILE_MEDIA_JS["%s"] is not defined' % tag_name) return last_info['result_urls'] def compile_js(tag_name = None, force=False): for name, x in settings.COMPILE_MEDIA_JS.iteritems(): if tag_name is not None: if tag_name != name: continue print_status('Compiling js media [%s]' % name) js_config = get_js_config(name) compile_js_(name, js_config, force) return True def compile_js_(tag_name, js_config, force): if IS_APPSERVER: return def needs_update(media_info): if js_config['tool'] != 'goog_calcdeps': # update if target file does not exist target_path = make_output_path_(js_config, js_config['subdir'], js_config['output_filename']) if not os.path.exists(target_path): return True # update if it lacks required info in _media.yaml last_info = media_info.get(js_config['subdir'], tag_name) if not last_info: return True last_config = last_info.get('config') if not last_config: return True # update if any configuration setting is changed if not equal_object_(last_config, js_config): return True if 'related_files' not in last_info: return True for path, mtime in last_info['related_files']: if mtime != os.path.getmtime(path): return True def jsminify(js_path): from StringIO import StringIO from kay.ext.media_compressor.jsmin import JavascriptMinify ifile = open(js_path) outs = StringIO() JavascriptMinify().minify(ifile, outs) ret = outs.getvalue() if len(ret) > 0 and ret[0] == '\n': ret = ret[1:] return ret def concat(js_path): print_status(" concat %s" % js_path) ifile = open(js_path) js = ifile.read() ifile.close() return js def goog_calcdeps(): deps_config = copy.deepcopy(js_config['goog_common']) deps_config.update(js_config['goog_calcdeps']) if deps_config.get('method') not in \ ['separate', 'concat', 'concat_refs', 'compile']: print_status("COMPILE_MEDIA_JS['goog_calcdeps']['method'] setting is" " invalid; unknown method `%s'" % deps_config.get('method')) sys.exit(1) output_urls = [] if deps_config['method'] == 'separate': source_files, output_urls = goog_calcdeps_separate(deps_config) elif deps_config['method'] == 'concat': source_files, output_urls = goog_calcdeps_concat(deps_config) elif deps_config['method'] == 'concat_refs': source_files, output_urls = goog_calcdeps_concat_refs(deps_config) elif deps_config['method'] == 'compile': source_files, output_urls = goog_calcdeps_compile(deps_config) source_files = [file[0] for file in source_files] related_files = union_list(source_files, [make_input_path_(path) for path in js_config['source_files']]) related_file_info = [(path, os.path.getmtime(path)) for path in related_files] # create yaml info last_info = {'config': copy.deepcopy(js_config), 'related_files': related_file_info, 'result_urls': output_urls} media_info.set(js_config['subdir'], tag_name, last_info) media_info.save() def goog_calcdeps_separate(deps_config): source_files = goog_calcdeps_list(deps_config) (output_urls, extern_urls) = goog_calcdeps_copy_files(deps_config, source_files) return (source_files, extern_urls + output_urls) def goog_calcdeps_concat(deps_config): source_files = goog_calcdeps_list(deps_config) (output_urls, extern_urls) = goog_calcdeps_concat_files(deps_config, source_files) return (source_files, extern_urls + output_urls) def goog_calcdeps_concat_refs(deps_config): source_files = goog_calcdeps_list(deps_config) original_files = [make_input_path_(path) for path in js_config['source_files']] ref_files = [path for path in source_files if path not in original_files] (output_urls, extern_urls) = goog_calcdeps_concat_files(deps_config, ref_files) original_urls = [path[len(kay.PROJECT_DIR):] for path in original_files] return (source_files, extern_urls + output_urls + original_urls) def goog_calcdeps_compile(deps_config): comp_config = copy.deepcopy(js_config['goog_common']) comp_config.update(js_config['goog_compiler']) source_files = [] extern_urls = [] command = '%s -o compiled -c "%s" ' % (deps_config['path'], comp_config['path']) for path in deps_config.get('search_paths', []): command += '-p %s ' % make_input_path_(path) for path in js_config['source_files']: path = make_input_path_(path) command += '-i %s ' % path source_files.append((path, os.path.getmtime(path))) if comp_config['level'] == 'minify': level = 'WHITESPACE_ONLY' elif comp_config['level'] == 'advanced': level = 'ADVANCED_OPTIMIZATIONS' else: level = 'SIMPLE_OPTIMIZATIONS' flags = '--compilation_level=%s' % level # for path in comp_config.get('externs', []): # flags += '--externs=%s ' % make_input_path_(path) # if comp_config.get('externs'): # flags += ' --externs=%s ' % " ".join(comp_config['externs']) command += '-f "%s" ' % flags print_status(command) command_output = os.popen(command).read() output_path = make_output_path_(js_config, js_config['subdir'], js_config['output_filename']) ofile = create_file_(output_path) try: for path in comp_config.get('externs', []): if re.match(r'^https?://', path): extern_urls.append(path) continue path = make_input_path_(path) ifile = open(path) try: ofile.write(ifile.read()) finally: ifile.close() source_files.append((path, os.path.getmtime(path))) ofile.write(command_output) finally: ofile.close() return (source_files, extern_urls + [output_path[len(kay.PROJECT_DIR):]]) def goog_calcdeps_list(deps_config): source_files = [] command = '%s -o list ' % deps_config['path'] for path in deps_config['search_paths']: command += '-p %s ' % make_input_path_(path) for path in js_config['source_files']: command += '-i %s ' % make_input_path_(path) print_status(command) command_output = os.popen(command).read() for path in command_output.split("\n"): if path == '': continue source_files.append(path) return source_files def goog_calcdeps_copy_files(deps_config, source_files): extern_urls = [] output_urls = [] output_dir_base = make_output_path_(js_config, 'separated_js') if not os.path.exists(output_dir_base): os.makedirs(output_dir_base) if not deps_config.get('use_dependency_file', True): output_path = os.path.join(output_dir_base, '__goog_nodeps.js') ofile = open(output_path, "w") output_urls.append(output_path[len(kay.PROJECT_DIR):]) try: ofile.write('CLOSURE_NO_DEPS = true;') finally: ofile.close() output_dirs = {} search_paths = [make_input_path_(path) for path in deps_config['search_paths']] for path in search_paths: output_dirs[path] = os.path.join(output_dir_base, md5.new(path).hexdigest()) all_paths = [make_input_path_(path) for path in deps_config.get('externs', [])] all_paths.extend(source_files) for path in all_paths: if re.match(r'^https?://', path): extern_urls.append(path) continue path = make_input_path_(path) output_path = os.path.join(output_dir_base, re.sub('^/', '', path)) for dir in search_paths: if path[0:len(dir)] == dir: output_path = os.path.join(output_dirs[dir], re.sub('^/', '', path[len(dir):])) break output_dir = os.path.dirname(output_path) if not os.path.exists(output_dir): os.makedirs(output_dir) shutil.copy2(path, output_path) output_urls.append(output_path[len(kay.PROJECT_DIR):]) return (output_urls, extern_urls) def goog_calcdeps_concat_files(deps_config, source_files): extern_urls = [] output_path = make_output_path_(js_config, js_config['subdir'], js_config['output_filename']) ofile = create_file_(output_path) try: if not deps_config.get('use_dependency_file', True): ofile.write('CLOSURE_NO_DEPS = true;') all_paths = [make_input_path_(path) for path in deps_config.get('externs', [])] all_paths.extend(source_files) for path in all_paths: if re.match(r'^https?://', path): extern_urls.append(path) continue ifile = open(make_input_path_(path)) ofile.write(ifile.read()) ifile.close() finally: ofile.close() return ([output_path[len(kay.PROJECT_DIR):]], extern_urls) selected_tool = js_config['tool'] if selected_tool not in \ (None, 'jsminify', 'concat', 'goog_calcdeps', 'goog_compiler'): print_status("COMPILE_MEDIA_JS['tool'] setting is invalid;" " unknown tool `%s'" % selected_tool) sys.exit(1) global media_info if media_info is None: media_info = MediaInfo.load() if not force and not needs_update(media_info): print_status(' up to date.') return if selected_tool == 'goog_calcdeps': return goog_calcdeps() if selected_tool is None: last_info = {'config': copy.deepcopy(js_config), 'result_urls': ['/'+f for f in js_config['source_files']]} media_info.set(js_config['subdir'], tag_name, last_info) media_info.save() return dest_path = make_output_path_(js_config, js_config['subdir'], js_config['output_filename']) ofile = create_file_(dest_path) try: if selected_tool == 'jsminify': for path in js_config['source_files']: src_path = make_input_path_(path) ofile.write(jsminify(src_path)) elif selected_tool == 'concat': for path in js_config['source_files']: src_path = make_input_path_(path) ofile.write(concat(src_path)) finally: ofile.close() if selected_tool == 'goog_compiler': comp_config = copy.deepcopy(js_config['goog_common']) comp_config.update(js_config['goog_compiler']) if comp_config['level'] == 'minify': level = 'WHITESPACE_ONLY' elif comp_config['level'] == 'advanced': level = 'ADVANCED_OPTIMIZATIONS' else: level = 'SIMPLE_OPTIMIZATIONS' command_args = '--compilation_level=%s' % level for path in js_config['source_files']: command_args += ' --js %s' % make_input_path_(path) command_args += ' --js_output_file %s' % dest_path command = 'java -jar %s %s' % (comp_config['path'], command_args) command_output = os.popen(command).read() info = copy.deepcopy(js_config) info['output_filename'] = make_output_path_(js_config, js_config['subdir'], js_config['output_filename'], relative=True) info['result_urls'] = ['/'+info['output_filename']] media_info.set(js_config['subdir'], tag_name, info) media_info.save() #-------------------------------------------------------------- def make_input_path_(path): return os.path.join(kay.PROJECT_DIR, path) def make_output_path_(config, *path, **kwargs): version = config['version'] if version is not None: result = os.path.join(config['output_base_dir'], str(version), *path) else: result = os.path.join(config['output_base_dir'], *path) if kwargs.get('relative'): return result else: return os.path.join(kay.PROJECT_DIR, result) def create_file_(path): dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) return open(path, 'wb') def equal_object_(a, b): if type(a) == types.DictType and type(b) == types.DictType: if len(a.keys()) != len(b.keys()): return False for k, v in a.iteritems(): if k not in b: return False if not equal_object_(v, b[k]): return False return True elif type(a) in [types.ListType, types.TupleType] and \ type(b) in [types.ListType, types.TupleType]: if len(a) != len(b): return False ia = iter(a) ib = iter(b) try: while True: if not equal_object_(ia.next(), ib.next()): return False except: pass return True else: return a == b
mit
oscarlorentzon/OpenSfM
opensfm/features.py
1
16918
"""Tools to extract features.""" import logging import sys import time import cv2 import numpy as np from opensfm import context, pyfeatures logger = logging.getLogger(__name__) def resized_image(image, max_size): """Resize image to feature_process_size.""" h, w, _ = image.shape size = max(w, h) if 0 < max_size < size: dsize = w * max_size // size, h * max_size // size return cv2.resize(image, dsize=dsize, interpolation=cv2.INTER_AREA) else: return image def root_feature(desc, l2_normalization=False): if l2_normalization: s2 = np.linalg.norm(desc, axis=1) desc = (desc.T / s2).T s = np.sum(desc, 1) desc = np.sqrt(desc.T / s).T return desc def root_feature_surf(desc, l2_normalization=False, partial=False): """ Experimental square root mapping of surf-like feature, only work for 64-dim surf now """ if desc.shape[1] == 64: if l2_normalization: s2 = np.linalg.norm(desc, axis=1) desc = (desc.T / s2).T if partial: ii = np.array([i for i in range(64) if (i % 4 == 2 or i % 4 == 3)]) else: ii = np.arange(64) desc_sub = np.abs(desc[:, ii]) desc_sub_sign = np.sign(desc[:, ii]) # s_sub = np.sum(desc_sub, 1) # This partial normalization gives slightly better results for AKAZE surf s_sub = np.sum(np.abs(desc), 1) desc_sub = np.sqrt(desc_sub.T / s_sub).T desc[:, ii] = desc_sub * desc_sub_sign return desc def normalized_image_coordinates(pixel_coords, width, height): size = max(width, height) p = np.empty((len(pixel_coords), 2)) p[:, 0] = (pixel_coords[:, 0] + 0.5 - width / 2.0) / size p[:, 1] = (pixel_coords[:, 1] + 0.5 - height / 2.0) / size return p def denormalized_image_coordinates(norm_coords, width, height): size = max(width, height) p = np.empty((len(norm_coords), 2)) p[:, 0] = norm_coords[:, 0] * size - 0.5 + width / 2.0 p[:, 1] = norm_coords[:, 1] * size - 0.5 + height / 2.0 return p def normalize_features(points, desc, colors, width, height): """Normalize feature coordinates and size.""" points[:, :2] = normalized_image_coordinates(points[:, :2], width, height) points[:, 2:3] /= max(width, height) return points, desc, colors def _in_mask(point, width, height, mask): """Check if a point is inside a binary mask.""" u = mask.shape[1] * (point[0] + 0.5) / width v = mask.shape[0] * (point[1] + 0.5) / height return mask[int(v), int(u)] != 0 def extract_features_sift(image, config, features_count): sift_edge_threshold = config["sift_edge_threshold"] sift_peak_threshold = float(config["sift_peak_threshold"]) # SIFT support is in cv2 main from version 4.4.0 if context.OPENCV44 or context.OPENCV5: # OpenCV versions concerned /** 3.4.11, >= 4.4.0 **/ ==> Sift became free since March 2020 detector = cv2.SIFT_create( edgeThreshold=sift_edge_threshold, contrastThreshold=sift_peak_threshold ) descriptor = detector elif context.OPENCV3 or context.OPENCV4: try: # OpenCV versions concerned /** 3.2.x, 3.3.x, 3.4.0, 3.4.1, 3.4.2, 3.4.10, 4.3.0, 4.4.0 **/ detector = cv2.xfeatures2d.SIFT_create( edgeThreshold=sift_edge_threshold, contrastThreshold=sift_peak_threshold ) except AttributeError as ae: # OpenCV versions concerned /** 3.4.3, 3.4.4, 3.4.5, 3.4.6, 3.4.7, 3.4.8, 3.4.9, 4.0.x, 4.1.x, 4.2.x **/ if "no attribute 'xfeatures2d'" in str(ae): logger.error( "OpenCV Contrib modules are required to extract SIFT features" ) raise descriptor = detector else: detector = cv2.FeatureDetector_create("SIFT") descriptor = cv2.DescriptorExtractor_create("SIFT") detector.setDouble("edgeThreshold", sift_edge_threshold) while True: logger.debug("Computing sift with threshold {0}".format(sift_peak_threshold)) t = time.time() # SIFT support is in cv2 main from version 4.4.0 if context.OPENCV44 or context.OPENCV5: detector = cv2.SIFT_create( edgeThreshold=sift_edge_threshold, contrastThreshold=sift_peak_threshold ) elif context.OPENCV3: detector = cv2.xfeatures2d.SIFT_create( edgeThreshold=sift_edge_threshold, contrastThreshold=sift_peak_threshold ) else: detector.setDouble("contrastThreshold", sift_peak_threshold) points = detector.detect(image) logger.debug("Found {0} points in {1}s".format(len(points), time.time() - t)) if len(points) < features_count and sift_peak_threshold > 0.0001: sift_peak_threshold = (sift_peak_threshold * 2) / 3 logger.debug("reducing threshold") else: logger.debug("done") break points, desc = descriptor.compute(image, points) if config["feature_root"]: desc = root_feature(desc) points = np.array([(i.pt[0], i.pt[1], i.size, i.angle) for i in points]) return points, desc def extract_features_surf(image, config, features_count): surf_hessian_threshold = config["surf_hessian_threshold"] if context.OPENCV3: try: detector = cv2.xfeatures2d.SURF_create() except AttributeError as ae: if "no attribute 'xfeatures2d'" in str(ae): logger.error( "OpenCV Contrib modules are required to extract SURF features" ) raise descriptor = detector detector.setHessianThreshold(surf_hessian_threshold) detector.setNOctaves(config["surf_n_octaves"]) detector.setNOctaveLayers(config["surf_n_octavelayers"]) detector.setUpright(config["surf_upright"]) else: detector = cv2.FeatureDetector_create("SURF") descriptor = cv2.DescriptorExtractor_create("SURF") detector.setDouble("hessianThreshold", surf_hessian_threshold) detector.setDouble("nOctaves", config["surf_n_octaves"]) detector.setDouble("nOctaveLayers", config["surf_n_octavelayers"]) detector.setInt("upright", config["surf_upright"]) while True: logger.debug("Computing surf with threshold {0}".format(surf_hessian_threshold)) t = time.time() if context.OPENCV3: detector.setHessianThreshold(surf_hessian_threshold) else: detector.setDouble( "hessianThreshold", surf_hessian_threshold ) # default: 0.04 points = detector.detect(image) logger.debug("Found {0} points in {1}s".format(len(points), time.time() - t)) if len(points) < features_count and surf_hessian_threshold > 0.0001: surf_hessian_threshold = (surf_hessian_threshold * 2) / 3 logger.debug("reducing threshold") else: logger.debug("done") break points, desc = descriptor.compute(image, points) if config["feature_root"]: desc = root_feature_surf(desc, partial=True) points = np.array([(i.pt[0], i.pt[1], i.size, i.angle) for i in points]) return points, desc def akaze_descriptor_type(name): d = pyfeatures.AkazeDescriptorType.__dict__ if name in d: return d[name] else: logger.debug("Wrong akaze descriptor type") return d["MSURF"] def extract_features_akaze(image, config, features_count): options = pyfeatures.AKAZEOptions() options.omax = config["akaze_omax"] akaze_descriptor_name = config["akaze_descriptor"] options.descriptor = akaze_descriptor_type(akaze_descriptor_name) options.descriptor_size = config["akaze_descriptor_size"] options.descriptor_channels = config["akaze_descriptor_channels"] options.dthreshold = config["akaze_dthreshold"] options.kcontrast_percentile = config["akaze_kcontrast_percentile"] options.use_isotropic_diffusion = config["akaze_use_isotropic_diffusion"] options.target_num_features = features_count options.use_adaptive_suppression = config["feature_use_adaptive_suppression"] logger.debug("Computing AKAZE with threshold {0}".format(options.dthreshold)) t = time.time() points, desc = pyfeatures.akaze(image, options) logger.debug("Found {0} points in {1}s".format(len(points), time.time() - t)) if config["feature_root"]: if akaze_descriptor_name in ["SURF_UPRIGHT", "MSURF_UPRIGHT"]: desc = root_feature_surf(desc, partial=True) elif akaze_descriptor_name in ["SURF", "MSURF"]: desc = root_feature_surf(desc, partial=False) points = points.astype(float) return points, desc def extract_features_hahog(image, config, features_count): t = time.time() points, desc = pyfeatures.hahog( image.astype(np.float32) / 255, # VlFeat expects pixel values between 0, 1 peak_threshold=config["hahog_peak_threshold"], edge_threshold=config["hahog_edge_threshold"], target_num_features=features_count, use_adaptive_suppression=config["feature_use_adaptive_suppression"], ) if config["feature_root"]: desc = np.sqrt(desc) uchar_scaling = 362 # x * 512 < 256 => sqrt(x) * 362 < 256 else: uchar_scaling = 512 if config["hahog_normalize_to_uchar"]: desc = (uchar_scaling * desc).clip(0, 255).round() logger.debug("Found {0} points in {1}s".format(len(points), time.time() - t)) return points, desc def extract_features_orb(image, config, features_count): if context.OPENCV3: detector = cv2.ORB_create(nfeatures=features_count) descriptor = detector else: detector = cv2.FeatureDetector_create("ORB") descriptor = cv2.DescriptorExtractor_create("ORB") detector.setDouble("nFeatures", features_count) logger.debug("Computing ORB") t = time.time() points = detector.detect(image) points, desc = descriptor.compute(image, points) points = np.array([(i.pt[0], i.pt[1], i.size, i.angle) for i in points]) logger.debug("Found {0} points in {1}s".format(len(points), time.time() - t)) return points, desc def extract_features(image, config, is_panorama): """Detect features in a color or gray-scale image. The type of feature detected is determined by the ``feature_type`` config option. The coordinates of the detected points are returned in normalized image coordinates. Parameters: - image: a color image with shape (h, w, 3) or gray-scale image with (h, w) or (h, w, 1) - config: the configuration structure - is_panorama : if True, alternate settings are used for feature count and extraction size. Returns: tuple: - points: ``x``, ``y``, ``size`` and ``angle`` for each feature - descriptors: the descriptor of each feature - colors: the color of the center of each feature """ extraction_size = ( config["feature_process_size_panorama"] if is_panorama else config["feature_process_size"] ) features_count = ( config["feature_min_frames_panorama"] if is_panorama else config["feature_min_frames"] ) assert len(image.shape) == 3 or len(image.shape) == 2 if len(image.shape) == 2: # convert (h, w) to (h, w, 1) image = np.expand_dims(image, axis=2) image = resized_image(image, extraction_size) # convert color to gray-scale if necessary if image.shape[2] == 3: image_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) else: image_gray = image feature_type = config["feature_type"].upper() if feature_type == "SIFT": points, desc = extract_features_sift(image_gray, config, features_count) elif feature_type == "SURF": points, desc = extract_features_surf(image_gray, config, features_count) elif feature_type == "AKAZE": points, desc = extract_features_akaze(image_gray, config, features_count) elif feature_type == "HAHOG": points, desc = extract_features_hahog(image_gray, config, features_count) elif feature_type == "ORB": points, desc = extract_features_orb(image_gray, config, features_count) else: raise ValueError( "Unknown feature type " "(must be SURF, SIFT, AKAZE, HAHOG or ORB)" ) xs = points[:, 0].round().astype(int) ys = points[:, 1].round().astype(int) colors = image[ys, xs] if image.shape[2] == 1: colors = np.repeat(colors, 3).reshape((-1, 3)) return normalize_features(points, desc, colors, image.shape[1], image.shape[0]) def build_flann_index(features, config): # FLANN_INDEX_LINEAR = 0 FLANN_INDEX_KDTREE = 1 FLANN_INDEX_KMEANS = 2 # FLANN_INDEX_COMPOSITE = 3 # FLANN_INDEX_KDTREE_SINGLE = 4 # FLANN_INDEX_HIERARCHICAL = 5 FLANN_INDEX_LSH = 6 if features.dtype.type is np.float32: algorithm_type = config["flann_algorithm"].upper() if algorithm_type == "KMEANS": FLANN_INDEX_METHOD = FLANN_INDEX_KMEANS elif algorithm_type == "KDTREE": FLANN_INDEX_METHOD = FLANN_INDEX_KDTREE else: raise ValueError("Unknown flann algorithm type " "must be KMEANS, KDTREE") else: FLANN_INDEX_METHOD = FLANN_INDEX_LSH flann_params = { "algorithm": FLANN_INDEX_METHOD, "branching": config["flann_branching"], "iterations": config["flann_iterations"], "tree": config["flann_tree"], } return context.flann_Index(features, flann_params) FEATURES_VERSION = 2 FEATURES_HEADER = "OPENSFM_FEATURES_VERSION" def load_features(filepath, config): """ Load features from filename """ s = np.load(filepath, allow_pickle=True) version = _features_file_version(s) return getattr(sys.modules[__name__], "_load_features_v%d" % version)(s, config) def _features_file_version(obj): """ Retrieve features file version. Return 0 if none """ if FEATURES_HEADER in obj: return obj[FEATURES_HEADER] else: return 0 def _load_features_v0(s, config): """Base version of features file Scale (desc[2]) set to reprojection_error_sd by default (legacy behaviour) """ feature_type = config["feature_type"] if feature_type == "HAHOG" and config["hahog_normalize_to_uchar"]: descriptors = s["descriptors"].astype(np.float32) else: descriptors = s["descriptors"] points = s["points"] points[:, 2:3] = config["reprojection_error_sd"] return points, descriptors, s["colors"].astype(float), None def _load_features_v1(s, config): """Version 1 of features file Scale is not properly set higher in the pipeline, default is gone. """ feature_type = config["feature_type"] if feature_type == "HAHOG" and config["hahog_normalize_to_uchar"]: descriptors = s["descriptors"].astype(np.float32) else: descriptors = s["descriptors"] return s["points"], descriptors, s["colors"].astype(float), None def _load_features_v2(s, config): """Version 2 of features file Added segmentation and segmentation labels. """ feature_type = config["feature_type"] if feature_type == "HAHOG" and config["hahog_normalize_to_uchar"]: descriptors = s["descriptors"].astype(np.float32) else: descriptors = s["descriptors"] has_segmentation = s["segmentations"].any() has_instances = s["instances"].any() return ( s["points"], descriptors, s["colors"].astype(float), { "segmentations": s["segmentations"] if has_segmentation else None, "instances": s["instances"] if has_instances else None, "segmentation_labels": s["segmentation_labels"], }, ) def save_features( filepath, points, desc, colors, segmentations, instances, segmentation_labels, config, ): feature_type = config["feature_type"] if ( ( feature_type == "AKAZE" and config["akaze_descriptor"] in ["MLDB_UPRIGHT", "MLDB"] ) or (feature_type == "HAHOG" and config["hahog_normalize_to_uchar"]) or (feature_type == "ORB") ): feature_data_type = np.uint8 else: feature_data_type = np.float32 np.savez_compressed( filepath, points=points.astype(np.float32), descriptors=desc.astype(feature_data_type), colors=colors, segmentations=segmentations, instances=instances, segmentation_labels=segmentation_labels, OPENSFM_FEATURES_VERSION=FEATURES_VERSION, allow_pickle=True, )
bsd-2-clause
myarjunar/inasafe
safe/messaging/example/error_message_example.py
3
2902
""" InaSAFE Disaster risk assessment tool by AusAid - **Error Message example.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 2 of the License, or (at your option) any later version. """ __author__ = 'tim@kartoza.com' __revision__ = '$Format:%H$' __date__ = '27/05/2013' __copyright__ = ('Copyright 2012, Australia Indonesia Facility for ' 'Disaster Reduction') import traceback from safe.messaging import ( Message, ErrorMessage, ImportantText, Paragraph) DYNAMIC_MESSAGE_SIGNAL = 'ImpactFunctionMessage' class SafeError(Exception): """Base class for all SAFE messages that propogates ErrorMessages.""" def __init__(self, message, error_message=None): # print traceback.format_exc() Exception.__init__(self, message) if error_message is not None: self.error_message = error_message else: self.error_message = ErrorMessage( message.message, traceback=traceback.format_exc()) def error_creator1(): """Simple function that will create an error.""" raise IOError('File could not be read.') def error_creator2(): """Simple function that will extend an error and its traceback.""" try: error_creator1() except IOError, e1: e1.args = (e1.args[0] + '\nCreator 2 error',) # Tuple dont remove , raise def error_creator3(): """Raise a safe style error.""" try: error_creator2() except IOError, e2: # e2.args = (e2.args[0] + '\nCreator 3 error',) # Tuple dont remove , raise SafeError(e2) def error_creator4(): """Raise a safe style error.""" try: error_creator3() except SafeError, e3: e3.error_message.problems.append('Creator 4 error') raise def error_creator5(): """Raise a safe style error and append a full message.""" try: error_creator4() except SafeError, e4: message = ErrorMessage( 'Creator 5 problem', detail=Message( Paragraph('Could not', ImportantText('call'), 'function.'), Paragraph('Try reinstalling your computer with windows.')), suggestion=Message(ImportantText('Important note'))) e4.error_message.append(message) raise if __name__ == '__main__': # best practice non safe style errors # try: # error_creator2() # except IOError, e: # # print e # tb = traceback.format_exc() # print tb # Safe style errors try: error_creator5() except SafeError, e: # print e # tb = traceback.format_exc() # print tb print e.error_message.to_text()
gpl-3.0
bronzehedwick/YouCompleteMe
python/ycm/tests/vimsupport_test.py
6
22440
#!/usr/bin/env python # # Copyright (C) 2015 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe 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. # # YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. from ycm import vimsupport from nose.tools import eq_ def ReplaceChunk_SingleLine_Repl_1_test(): # Replace with longer range # 12345678901234567 result_buffer = [ "This is a string" ] start, end = _BuildLocations( 1, 1, 1, 5 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'How long', 0, 0, result_buffer ) eq_( [ "How long is a string" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 4 ) # and replace again, using delta start, end = _BuildLocations( 1, 10, 1, 11 ) ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( start, end, ' piece of ', line_offset, char_offset, result_buffer ) line_offset += new_line_offset char_offset += new_char_offset eq_( [ 'How long is a piece of string' ], result_buffer ) eq_( new_line_offset, 0 ) eq_( new_char_offset, 9 ) eq_( line_offset, 0 ) eq_( char_offset, 13 ) # and once more, for luck start, end = _BuildLocations( 1, 11, 1, 17 ) ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( start, end, 'pie', line_offset, char_offset, result_buffer ) line_offset += new_line_offset char_offset += new_char_offset eq_( ['How long is a piece of pie' ], result_buffer ) eq_( new_line_offset, 0 ) eq_( new_char_offset, -3 ) eq_( line_offset, 0 ) eq_( char_offset, 10 ) def ReplaceChunk_SingleLine_Repl_2_test(): # Replace with shorter range # 12345678901234567 result_buffer = [ "This is a string" ] start, end = _BuildLocations( 1, 11, 1, 17 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'test', 0, 0, result_buffer ) eq_( [ "This is a test" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, -2 ) def ReplaceChunk_SingleLine_Repl_3_test(): # Replace with equal range # 12345678901234567 result_buffer = [ "This is a string" ] start, end = _BuildLocations( 1, 6, 1, 8 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'be', 0, 0, result_buffer ) eq_( [ "This be a string" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 0 ) def ReplaceChunk_SingleLine_Add_1_test(): # Insert at start result_buffer = [ "is a string" ] start, end = _BuildLocations( 1, 1, 1, 1 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'This ', 0, 0, result_buffer ) eq_( [ "This is a string" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 5 ) def ReplaceChunk_SingleLine_Add_2_test(): # Insert at end result_buffer = [ "This is a " ] start, end = _BuildLocations( 1, 11, 1, 11 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'string', 0, 0, result_buffer ) eq_( [ "This is a string" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 6 ) def ReplaceChunk_SingleLine_Add_3_test(): # Insert in the middle result_buffer = [ "This is a string" ] start, end = _BuildLocations( 1, 8, 1, 8 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, ' not', 0, 0, result_buffer ) eq_( [ "This is not a string" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 4 ) def ReplaceChunk_SingleLine_Del_1_test(): # Delete from start result_buffer = [ "This is a string" ] start, end = _BuildLocations( 1, 1, 1, 6 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, '', 0, 0, result_buffer ) eq_( [ "is a string" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, -5 ) def ReplaceChunk_SingleLine_Del_2_test(): # Delete from end result_buffer = [ "This is a string" ] start, end = _BuildLocations( 1, 10, 1, 18 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, '', 0, 0, result_buffer ) eq_( [ "This is a" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, -8 ) def ReplaceChunk_SingleLine_Del_3_test(): # Delete from middle result_buffer = [ "This is not a string" ] start, end = _BuildLocations( 1, 9, 1, 13 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, '', 0, 0, result_buffer ) eq_( [ "This is a string" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, -4 ) def ReplaceChunk_RemoveSingleLine_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 2, 1, 3, 1 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, '', 0, 0, result_buffer ) expected_buffer = [ "aAa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, -1 ) eq_( char_offset, 0 ) def ReplaceChunk_SingleToMultipleLines_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 2, 2, 2, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbF', 0, 0, result_buffer ) expected_buffer = [ "aAa", "aEb", "bFBa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 1 ) eq_( char_offset, 1 ) # now make another change to the "2nd" line start, end = _BuildLocations( 2, 3, 2, 4 ) ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( start, end, 'cccc', line_offset, char_offset, result_buffer ) line_offset += new_line_offset char_offset += new_char_offset eq_( [ "aAa", "aEb", "bFBcccc", "aCa" ], result_buffer ) eq_( line_offset, 1 ) eq_( char_offset, 4 ) def ReplaceChunk_SingleToMultipleLines2_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 2, 2, 2, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nG', 0, 0, result_buffer ) expected_buffer = [ "aAa", "aEb", "bFb", "GBa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 2 ) eq_( char_offset, 0 ) def ReplaceChunk_SingleToMultipleLines3_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 2, 2, 2, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nbGb', 0, 0, result_buffer ) expected_buffer = [ "aAa", "aEb", "bFb", "bGbBa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 2 ) eq_( char_offset, 2 ) def ReplaceChunk_SingleToMultipleLinesReplace_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 1, 2, 1, 4 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nbGb', 0, 0, result_buffer ) expected_buffer = [ "aEb", "bFb", "bGb", "aBa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 2 ) eq_( char_offset, 0 ) def ReplaceChunk_SingleToMultipleLinesReplace_2_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 1, 2, 1, 4 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nbGb', 0, 0, result_buffer ) expected_buffer = [ "aEb", "bFb", "bGb", "aBa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 2 ) eq_( char_offset, 0 ) # now do a subsequent change (insert at end of line "1") start, end = _BuildLocations( 1, 4, 1, 4 ) ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( start, end, 'cccc', line_offset, char_offset, result_buffer ) line_offset += new_line_offset char_offset += new_char_offset eq_( [ "aEb", "bFb", "bGbcccc", "aBa", "aCa" ], result_buffer ) eq_( line_offset, 2 ) eq_( char_offset, 4 ) def ReplaceChunk_MultipleLinesToSingleLine_test(): result_buffer = [ "aAa", "aBa", "aCaaaa" ] start, end = _BuildLocations( 2, 2, 3, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'E', 0, 0, result_buffer ) expected_buffer = [ "aAa", "aECaaaa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, -1 ) eq_( char_offset, 1 ) # make another modification applying offsets start, end = _BuildLocations( 3, 3, 3, 4 ) ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( start, end, 'cccc', line_offset, char_offset, result_buffer ) line_offset += new_line_offset char_offset += new_char_offset eq_( [ "aAa", "aECccccaaa" ], result_buffer ) eq_( line_offset, -1 ) eq_( char_offset, 4 ) # and another, for luck start, end = _BuildLocations( 3, 4, 3, 5 ) ( new_line_offset, new_char_offset ) = vimsupport.ReplaceChunk( start, end, 'dd\ndd', line_offset, char_offset, result_buffer ) line_offset += new_line_offset char_offset += new_char_offset eq_( [ "aAa", "aECccccdd", "ddaa" ], result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, -2 ) def ReplaceChunk_MultipleLinesToSameMultipleLines_test(): result_buffer = [ "aAa", "aBa", "aCa", "aDe" ] start, end = _BuildLocations( 2, 2, 3, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbF', 0, 0, result_buffer ) expected_buffer = [ "aAa", "aEb", "bFCa", "aDe" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 1 ) def ReplaceChunk_MultipleLinesToMoreMultipleLines_test(): result_buffer = [ "aAa", "aBa", "aCa", "aDe" ] start, end = _BuildLocations( 2, 2, 3, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbFb\nbG', 0, 0, result_buffer ) expected_buffer = [ "aAa", "aEb", "bFb", "bGCa", "aDe" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 1 ) eq_( char_offset, 1 ) def ReplaceChunk_MultipleLinesToLessMultipleLines_test(): result_buffer = [ "aAa", "aBa", "aCa", "aDe" ] start, end = _BuildLocations( 1, 2, 3, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbF', 0, 0, result_buffer ) expected_buffer = [ "aEb", "bFCa", "aDe" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, -1 ) eq_( char_offset, 1 ) def ReplaceChunk_MultipleLinesToEvenLessMultipleLines_test(): result_buffer = [ "aAa", "aBa", "aCa", "aDe" ] start, end = _BuildLocations( 1, 2, 4, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Eb\nbF', 0, 0, result_buffer ) expected_buffer = [ "aEb", "bFDe" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, -2 ) eq_( char_offset, 1 ) def ReplaceChunk_SpanBufferEdge_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 1, 1, 1, 3 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', 0, 0, result_buffer ) expected_buffer = [ "bDba", "aBa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 1 ) def ReplaceChunk_DeleteTextInLine_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 2, 2, 2, 3 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, '', 0, 0, result_buffer ) expected_buffer = [ "aAa", "aa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, -1 ) def ReplaceChunk_AddTextInLine_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 2, 2, 2, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', 0, 0, result_buffer ) expected_buffer = [ "aAa", "abDbBa", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 3 ) def ReplaceChunk_ReplaceTextInLine_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 2, 2, 2, 3 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', 0, 0, result_buffer ) expected_buffer = [ "aAa", "abDba", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 2 ) def ReplaceChunk_SingleLineOffsetWorks_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 1, 1, 1, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', 1, 1, result_buffer ) expected_buffer = [ "aAa", "abDba", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 0 ) eq_( char_offset, 2 ) def ReplaceChunk_SingleLineToMultipleLinesOffsetWorks_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 1, 1, 1, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'Db\nE', 1, 1, result_buffer ) expected_buffer = [ "aAa", "aDb", "Ea", "aCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 1 ) eq_( char_offset, -1 ) def ReplaceChunk_MultipleLinesToSingleLineOffsetWorks_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 1, 1, 2, 2 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb', 1, 1, result_buffer ) expected_buffer = [ "aAa", "abDbCa" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, -1 ) eq_( char_offset, 3 ) def ReplaceChunk_MultipleLineOffsetWorks_test(): result_buffer = [ "aAa", "aBa", "aCa" ] start, end = _BuildLocations( 3, 1, 4, 3 ) ( line_offset, char_offset ) = vimsupport.ReplaceChunk( start, end, 'bDb\nbEb\nbFb', -1, 1, result_buffer ) expected_buffer = [ "aAa", "abDb", "bEb", "bFba" ] eq_( expected_buffer, result_buffer ) eq_( line_offset, 1 ) eq_( char_offset, 1 ) def _BuildLocations( start_line, start_column, end_line, end_column ): return { 'line_num' : start_line, 'column_num': start_column, }, { 'line_num' : end_line, 'column_num': end_column, } def ReplaceChunksList_SortedChunks_test(): chunks = [ _BuildChunk( 1, 4, 1, 4, '('), _BuildChunk( 1, 11, 1, 11, ')' ) ] result_buffer = [ "CT<10 >> 2> ct" ] vimsupport.ReplaceChunksList( chunks, result_buffer ) expected_buffer = [ "CT<(10 >> 2)> ct" ] eq_( expected_buffer, result_buffer ) def ReplaceChunksList_UnsortedChunks_test(): chunks = [ _BuildChunk( 1, 11, 1, 11, ')'), _BuildChunk( 1, 4, 1, 4, '(' ) ] result_buffer = [ "CT<10 >> 2> ct" ] vimsupport.ReplaceChunksList( chunks, result_buffer ) expected_buffer = [ "CT<(10 >> 2)> ct" ] eq_( expected_buffer, result_buffer ) def _BuildChunk( start_line, start_column, end_line, end_column, replacement_text ): return { 'range': { 'start': { 'line_num': start_line, 'column_num': start_column, }, 'end': { 'line_num': end_line, 'column_num': end_column, }, }, 'replacement_text': replacement_text }
gpl-3.0
karllessard/tensorflow
tensorflow/tools/compatibility/ast_edits.py
15
40414
# Lint as: python2, python3 # Copyright 2016 The TensorFlow Authors. 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. # ============================================================================== """Upgrader for Python scripts according to an API change specification.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import ast import collections import os import re import shutil import sys import tempfile import traceback import pasta import six from six.moves import range # Some regular expressions we will need for parsing FIND_OPEN = re.compile(r"^\s*(\[).*$") FIND_STRING_CHARS = re.compile(r"['\"]") INFO = "INFO" WARNING = "WARNING" ERROR = "ERROR" ImportRename = collections.namedtuple( "ImportRename", ["new_name", "excluded_prefixes"]) def full_name_node(name, ctx=ast.Load()): """Make an Attribute or Name node for name. Translate a qualified name into nested Attribute nodes (and a Name node). Args: name: The name to translate to a node. ctx: What context this name is used in. Defaults to Load() Returns: A Name or Attribute node. """ names = six.ensure_str(name).split(".") names.reverse() node = ast.Name(id=names.pop(), ctx=ast.Load()) while names: node = ast.Attribute(value=node, attr=names.pop(), ctx=ast.Load()) # Change outermost ctx to the one given to us (inner ones should be Load). node.ctx = ctx return node def get_arg_value(node, arg_name, arg_pos=None): """Get the value of an argument from a ast.Call node. This function goes through the positional and keyword arguments to check whether a given argument was used, and if so, returns its value (the node representing its value). This cannot introspect *args or **args, but it safely handles *args in Python3.5+. Args: node: The ast.Call node to extract arg values from. arg_name: The name of the argument to extract. arg_pos: The position of the argument (in case it's passed as a positional argument). Returns: A tuple (arg_present, arg_value) containing a boolean indicating whether the argument is present, and its value in case it is. """ # Check keyword args if arg_name is not None: for kw in node.keywords: if kw.arg == arg_name: return (True, kw.value) # Check positional args if arg_pos is not None: idx = 0 for arg in node.args: if sys.version_info[:2] >= (3, 5) and isinstance(arg, ast.Starred): continue # Can't parse Starred if idx == arg_pos: return (True, arg) idx += 1 return (False, None) def uses_star_args_in_call(node): """Check if an ast.Call node uses arbitrary-length positional *args. This function works with the AST call node format of Python3.5+ as well as the different AST format of earlier versions of Python. Args: node: The ast.Call node to check arg values for. Returns: True if the node uses starred variadic positional args or keyword args. False if it does not. """ if sys.version_info[:2] >= (3, 5): # Check for an *args usage in python 3.5+ for arg in node.args: if isinstance(arg, ast.Starred): return True else: if node.starargs: return True return False def uses_star_kwargs_in_call(node): """Check if an ast.Call node uses arbitrary-length **kwargs. This function works with the AST call node format of Python3.5+ as well as the different AST format of earlier versions of Python. Args: node: The ast.Call node to check arg values for. Returns: True if the node uses starred variadic positional args or keyword args. False if it does not. """ if sys.version_info[:2] >= (3, 5): # Check for a **kwarg usage in python 3.5+ for keyword in node.keywords: if keyword.arg is None: return True else: if node.kwargs: return True return False def uses_star_args_or_kwargs_in_call(node): """Check if an ast.Call node uses arbitrary-length *args or **kwargs. This function works with the AST call node format of Python3.5+ as well as the different AST format of earlier versions of Python. Args: node: The ast.Call node to check arg values for. Returns: True if the node uses starred variadic positional args or keyword args. False if it does not. """ return uses_star_args_in_call(node) or uses_star_kwargs_in_call(node) def excluded_from_module_rename(module, import_rename_spec): """Check if this module import should not be renamed. Args: module: (string) module name. import_rename_spec: ImportRename instance. Returns: True if this import should not be renamed according to the import_rename_spec. """ for excluded_prefix in import_rename_spec.excluded_prefixes: if module.startswith(excluded_prefix): return True return False class APIChangeSpec(object): """This class defines the transformations that need to happen. This class must provide the following fields: * `function_keyword_renames`: maps function names to a map of old -> new argument names * `symbol_renames`: maps function names to new function names * `change_to_function`: a set of function names that have changed (for notifications) * `function_reorders`: maps functions whose argument order has changed to the list of arguments in the new order * `function_warnings`: maps full names of functions to warnings that will be printed out if the function is used. (e.g. tf.nn.convolution()) * `function_transformers`: maps function names to custom handlers * `module_deprecations`: maps module names to warnings that will be printed if the module is still used after all other transformations have run * `import_renames`: maps import name (must be a short name without '.') to ImportRename instance. For an example, see `TFAPIChangeSpec`. """ def preprocess(self, root_node): # pylint: disable=unused-argument """Preprocess a parse tree. Return a preprocessed node, logs and errors.""" return root_node, [], [] def clear_preprocessing(self): """Restore this APIChangeSpec to before it preprocessed a file. This is needed if preprocessing a file changed any rewriting rules. """ pass class NoUpdateSpec(APIChangeSpec): """A specification of an API change which doesn't change anything.""" def __init__(self): self.function_handle = {} self.function_reorders = {} self.function_keyword_renames = {} self.symbol_renames = {} self.function_warnings = {} self.change_to_function = {} self.module_deprecations = {} self.function_transformers = {} self.import_renames = {} class _PastaEditVisitor(ast.NodeVisitor): """AST Visitor that processes function calls. Updates function calls from old API version to new API version using a given change spec. """ def __init__(self, api_change_spec): self._api_change_spec = api_change_spec self._log = [] # Holds 4-tuples: severity, line, col, msg. self._stack = [] # Allow easy access to parents. # Overridden to maintain a stack of nodes to allow for parent access def visit(self, node): self._stack.append(node) super(_PastaEditVisitor, self).visit(node) self._stack.pop() @property def errors(self): return [log for log in self._log if log[0] == ERROR] @property def warnings(self): return [log for log in self._log if log[0] == WARNING] @property def warnings_and_errors(self): return [log for log in self._log if log[0] in (WARNING, ERROR)] @property def info(self): return [log for log in self._log if log[0] == INFO] @property def log(self): return self._log def add_log(self, severity, lineno, col, msg): self._log.append((severity, lineno, col, msg)) print("%s line %d:%d: %s" % (severity, lineno, col, msg)) def add_logs(self, logs): """Record a log and print it. The log should be a tuple `(severity, lineno, col_offset, msg)`, which will be printed and recorded. It is part of the log available in the `self.log` property. Args: logs: The logs to add. Must be a list of tuples `(severity, lineno, col_offset, msg)`. """ self._log.extend(logs) for log in logs: print("%s line %d:%d: %s" % log) def _get_applicable_entries(self, transformer_field, full_name, name): """Get all list entries indexed by name that apply to full_name or name.""" # Transformers are indexed to full name, name, or no name # as a performance optimization. function_transformers = getattr(self._api_change_spec, transformer_field, {}) glob_name = "*." + six.ensure_str(name) if name else None transformers = [] if full_name in function_transformers: transformers.append(function_transformers[full_name]) if glob_name in function_transformers: transformers.append(function_transformers[glob_name]) if "*" in function_transformers: transformers.append(function_transformers["*"]) return transformers def _get_applicable_dict(self, transformer_field, full_name, name): """Get all dict entries indexed by name that apply to full_name or name.""" # Transformers are indexed to full name, name, or no name # as a performance optimization. function_transformers = getattr(self._api_change_spec, transformer_field, {}) glob_name = "*." + six.ensure_str(name) if name else None transformers = function_transformers.get("*", {}).copy() transformers.update(function_transformers.get(glob_name, {})) transformers.update(function_transformers.get(full_name, {})) return transformers def _get_full_name(self, node): """Traverse an Attribute node to generate a full name, e.g., "tf.foo.bar". This is the inverse of `full_name_node`. Args: node: A Node of type Attribute. Returns: a '.'-delimited full-name or None if node was not Attribute or Name. i.e. `foo()+b).bar` returns None, while `a.b.c` would return "a.b.c". """ curr = node items = [] while not isinstance(curr, ast.Name): if not isinstance(curr, ast.Attribute): return None items.append(curr.attr) curr = curr.value items.append(curr.id) return ".".join(reversed(items)) def _maybe_add_warning(self, node, full_name): """Adds an error to be printed about full_name at node.""" function_warnings = self._api_change_spec.function_warnings if full_name in function_warnings: level, message = function_warnings[full_name] message = six.ensure_str(message).replace("<function name>", full_name) self.add_log(level, node.lineno, node.col_offset, "%s requires manual check. %s" % (full_name, message)) return True else: return False def _maybe_add_module_deprecation_warning(self, node, full_name, whole_name): """Adds a warning if full_name is a deprecated module.""" warnings = self._api_change_spec.module_deprecations if full_name in warnings: level, message = warnings[full_name] message = six.ensure_str(message).replace("<function name>", six.ensure_str(whole_name)) self.add_log(level, node.lineno, node.col_offset, "Using member %s in deprecated module %s. %s" % (whole_name, full_name, message)) return True else: return False def _maybe_add_call_warning(self, node, full_name, name): """Print a warning when specific functions are called with selected args. The function _print_warning_for_function matches the full name of the called function, e.g., tf.foo.bar(). This function matches the function name that is called, as long as the function is an attribute. For example, `tf.foo.bar()` and `foo.bar()` are matched, but not `bar()`. Args: node: ast.Call object full_name: The precomputed full name of the callable, if one exists, None otherwise. name: The precomputed name of the callable, if one exists, None otherwise. Returns: Whether an error was recorded. """ # Only look for *.-warnings here, the other will be handled by the Attribute # visitor. Also, do not warn for bare functions, only if the call func is # an attribute. warned = False if isinstance(node.func, ast.Attribute): warned = self._maybe_add_warning(node, "*." + six.ensure_str(name)) # All arg warnings are handled here, since only we have the args arg_warnings = self._get_applicable_dict("function_arg_warnings", full_name, name) variadic_args = uses_star_args_or_kwargs_in_call(node) for (kwarg, arg), (level, warning) in sorted(arg_warnings.items()): present, _ = get_arg_value(node, kwarg, arg) or variadic_args if present: warned = True warning_message = six.ensure_str(warning).replace( "<function name>", six.ensure_str(full_name or name)) template = "%s called with %s argument, requires manual check: %s" if variadic_args: template = ("%s called with *args or **kwargs that may include %s, " "requires manual check: %s") self.add_log(level, node.lineno, node.col_offset, template % (full_name or name, kwarg, warning_message)) return warned def _maybe_rename(self, parent, node, full_name): """Replace node (Attribute or Name) with a node representing full_name.""" new_name = self._api_change_spec.symbol_renames.get(full_name, None) if new_name: self.add_log(INFO, node.lineno, node.col_offset, "Renamed %r to %r" % (full_name, new_name)) new_node = full_name_node(new_name, node.ctx) ast.copy_location(new_node, node) pasta.ast_utils.replace_child(parent, node, new_node) return True else: return False def _maybe_change_to_function_call(self, parent, node, full_name): """Wraps node (typically, an Attribute or Expr) in a Call.""" if full_name in self._api_change_spec.change_to_function: if not isinstance(parent, ast.Call): # ast.Call's constructor is really picky about how many arguments it # wants, and also, it changed between Py2 and Py3. if six.PY2: new_node = ast.Call(node, [], [], None, None) else: new_node = ast.Call(node, [], []) pasta.ast_utils.replace_child(parent, node, new_node) ast.copy_location(new_node, node) self.add_log(INFO, node.lineno, node.col_offset, "Changed %r to a function call" % full_name) return True return False def _maybe_add_arg_names(self, node, full_name): """Make args into keyword args if function called full_name requires it.""" function_reorders = self._api_change_spec.function_reorders if full_name in function_reorders: if uses_star_args_in_call(node): self.add_log(WARNING, node.lineno, node.col_offset, "(Manual check required) upgrading %s may require " "re-ordering the call arguments, but it was passed " "variable-length positional *args. The upgrade " "script cannot handle these automatically." % full_name) reordered = function_reorders[full_name] new_keywords = [] idx = 0 for arg in node.args: if sys.version_info[:2] >= (3, 5) and isinstance(arg, ast.Starred): continue # Can't move Starred to keywords keyword_arg = reordered[idx] keyword = ast.keyword(arg=keyword_arg, value=arg) new_keywords.append(keyword) idx += 1 if new_keywords: self.add_log(INFO, node.lineno, node.col_offset, "Added keywords to args of function %r" % full_name) node.args = [] node.keywords = new_keywords + (node.keywords or []) return True return False def _maybe_modify_args(self, node, full_name, name): """Rename keyword args if the function called full_name requires it.""" renamed_keywords = self._get_applicable_dict("function_keyword_renames", full_name, name) if not renamed_keywords: return False if uses_star_kwargs_in_call(node): self.add_log(WARNING, node.lineno, node.col_offset, "(Manual check required) upgrading %s may require " "renaming or removing call arguments, but it was passed " "variable-length *args or **kwargs. The upgrade " "script cannot handle these automatically." % (full_name or name)) modified = False new_keywords = [] for keyword in node.keywords: argkey = keyword.arg if argkey in renamed_keywords: modified = True if renamed_keywords[argkey] is None: lineno = getattr(keyword, "lineno", node.lineno) col_offset = getattr(keyword, "col_offset", node.col_offset) self.add_log(INFO, lineno, col_offset, "Removed argument %s for function %s" % ( argkey, full_name or name)) else: keyword.arg = renamed_keywords[argkey] lineno = getattr(keyword, "lineno", node.lineno) col_offset = getattr(keyword, "col_offset", node.col_offset) self.add_log(INFO, lineno, col_offset, "Renamed keyword argument for %s from %s to %s" % ( full_name, argkey, renamed_keywords[argkey])) new_keywords.append(keyword) else: new_keywords.append(keyword) if modified: node.keywords = new_keywords return modified def visit_Call(self, node): # pylint: disable=invalid-name """Handle visiting a call node in the AST. Args: node: Current Node """ assert self._stack[-1] is node # Get the name for this call, so we can index stuff with it. full_name = self._get_full_name(node.func) if full_name: name = full_name.split(".")[-1] elif isinstance(node.func, ast.Name): name = node.func.id elif isinstance(node.func, ast.Attribute): name = node.func.attr else: name = None # Call standard transformers for this node. # Make sure warnings come first, since args or names triggering warnings # may be removed by the other transformations. self._maybe_add_call_warning(node, full_name, name) # Make all args into kwargs self._maybe_add_arg_names(node, full_name) # Argument name changes or deletions self._maybe_modify_args(node, full_name, name) # Call transformers. These have the ability to modify the node, and if they # do, will return the new node they created (or the same node if they just # changed it). The are given the parent, but we will take care of # integrating their changes into the parent if they return a new node. # # These are matched on the old name, since renaming is performed by the # Attribute visitor, which happens later. transformers = self._get_applicable_entries("function_transformers", full_name, name) parent = self._stack[-2] if transformers: if uses_star_args_or_kwargs_in_call(node): self.add_log(WARNING, node.lineno, node.col_offset, "(Manual check required) upgrading %s may require " "modifying call arguments, but it was passed " "variable-length *args or **kwargs. The upgrade " "script cannot handle these automatically." % (full_name or name)) for transformer in transformers: logs = [] new_node = transformer(parent, node, full_name, name, logs) self.add_logs(logs) if new_node and new_node is not node: pasta.ast_utils.replace_child(parent, node, new_node) node = new_node self._stack[-1] = node self.generic_visit(node) def visit_Attribute(self, node): # pylint: disable=invalid-name """Handle bare Attributes i.e. [tf.foo, tf.bar].""" assert self._stack[-1] is node full_name = self._get_full_name(node) if full_name: parent = self._stack[-2] # Make sure the warning comes first, otherwise the name may have changed self._maybe_add_warning(node, full_name) # Once we did a modification, node is invalid and not worth inspecting # further. Also, we only perform modifications for simple nodes, so # There'd be no point in descending further. if self._maybe_rename(parent, node, full_name): return if self._maybe_change_to_function_call(parent, node, full_name): return # The isinstance check is enough -- a bare Attribute is never root. i = 2 while isinstance(self._stack[-i], ast.Attribute): i += 1 whole_name = pasta.dump(self._stack[-(i-1)]) self._maybe_add_module_deprecation_warning(node, full_name, whole_name) self.generic_visit(node) def visit_Import(self, node): # pylint: disable=invalid-name """Handle visiting an import node in the AST. Args: node: Current Node """ new_aliases = [] import_updated = False import_renames = getattr(self._api_change_spec, "import_renames", {}) max_submodule_depth = getattr(self._api_change_spec, "max_submodule_depth", 1) inserts_after_imports = getattr(self._api_change_spec, "inserts_after_imports", {}) # This loop processes imports in the format # import foo as f, bar as b for import_alias in node.names: all_import_components = six.ensure_str(import_alias.name).split(".") # Look for rename, starting with longest import levels. found_update = False for i in reversed(list(range(1, max_submodule_depth + 1))): import_component = all_import_components[0] for j in range(1, min(i, len(all_import_components))): import_component += "." + six.ensure_str(all_import_components[j]) import_rename_spec = import_renames.get(import_component, None) if not import_rename_spec or excluded_from_module_rename( import_alias.name, import_rename_spec): continue new_name = ( import_rename_spec.new_name + import_alias.name[len(import_component):]) # If current import is # import foo # then new import should preserve imported name: # import new_foo as foo # This happens when module has just one component. new_asname = import_alias.asname if not new_asname and "." not in import_alias.name: new_asname = import_alias.name new_alias = ast.alias(name=new_name, asname=new_asname) new_aliases.append(new_alias) import_updated = True found_update = True # Insert any followup lines that should happen after this import. full_import = (import_alias.name, import_alias.asname) insert_offset = 1 for line_to_insert in inserts_after_imports.get(full_import, []): assert self._stack[-1] is node parent = self._stack[-2] new_line_node = pasta.parse(line_to_insert) ast.copy_location(new_line_node, node) parent.body.insert( parent.body.index(node) + insert_offset, new_line_node) insert_offset += 1 # Insert a newline after the import if necessary old_suffix = pasta.base.formatting.get(node, "suffix") if old_suffix is None: old_suffix = os.linesep if os.linesep not in old_suffix: pasta.base.formatting.set(node, "suffix", six.ensure_str(old_suffix) + os.linesep) # Apply indentation to new node. pasta.base.formatting.set(new_line_node, "prefix", pasta.base.formatting.get(node, "prefix")) pasta.base.formatting.set(new_line_node, "suffix", os.linesep) self.add_log( INFO, node.lineno, node.col_offset, "Adding `%s` after import of %s" % (new_line_node, import_alias.name)) # Find one match, break if found_update: break # No rename is found for all levels if not found_update: new_aliases.append(import_alias) # no change needed # Replace the node if at least one import needs to be updated. if import_updated: assert self._stack[-1] is node parent = self._stack[-2] new_node = ast.Import(new_aliases) ast.copy_location(new_node, node) pasta.ast_utils.replace_child(parent, node, new_node) self.add_log( INFO, node.lineno, node.col_offset, "Changed import from %r to %r." % (pasta.dump(node), pasta.dump(new_node))) self.generic_visit(node) def visit_ImportFrom(self, node): # pylint: disable=invalid-name """Handle visiting an import-from node in the AST. Args: node: Current Node """ if not node.module: self.generic_visit(node) return from_import = node.module # Look for rename based on first component of from-import. # i.e. based on foo in foo.bar. from_import_first_component = six.ensure_str(from_import).split(".")[0] import_renames = getattr(self._api_change_spec, "import_renames", {}) import_rename_spec = import_renames.get(from_import_first_component, None) if not import_rename_spec: self.generic_visit(node) return # Split module aliases into the ones that require import update # and those that don't. For e.g. if we want to rename "a" to "b" # unless we import "a.c" in the following: # from a import c, d # we want to update import for "d" but not for "c". updated_aliases = [] same_aliases = [] for import_alias in node.names: full_module_name = "%s.%s" % (from_import, import_alias.name) if excluded_from_module_rename(full_module_name, import_rename_spec): same_aliases.append(import_alias) else: updated_aliases.append(import_alias) if not updated_aliases: self.generic_visit(node) return assert self._stack[-1] is node parent = self._stack[-2] # Replace first component of from-import with new name. new_from_import = ( import_rename_spec.new_name + from_import[len(from_import_first_component):]) updated_node = ast.ImportFrom(new_from_import, updated_aliases, node.level) ast.copy_location(updated_node, node) pasta.ast_utils.replace_child(parent, node, updated_node) # If some imports had to stay the same, add another import for them. additional_import_log = "" if same_aliases: same_node = ast.ImportFrom(from_import, same_aliases, node.level, col_offset=node.col_offset, lineno=node.lineno) ast.copy_location(same_node, node) parent.body.insert(parent.body.index(updated_node), same_node) # Apply indentation to new node. pasta.base.formatting.set( same_node, "prefix", pasta.base.formatting.get(updated_node, "prefix")) additional_import_log = " and %r" % pasta.dump(same_node) self.add_log( INFO, node.lineno, node.col_offset, "Changed import from %r to %r%s." % (pasta.dump(node), pasta.dump(updated_node), additional_import_log)) self.generic_visit(node) class AnalysisResult(object): """This class represents an analysis result and how it should be logged. This class must provide the following fields: * `log_level`: The log level to which this detection should be logged * `log_message`: The message that should be logged for this detection For an example, see `VersionedTFImport`. """ class APIAnalysisSpec(object): """This class defines how `AnalysisResult`s should be generated. It specifies how to map imports and symbols to `AnalysisResult`s. This class must provide the following fields: * `symbols_to_detect`: maps function names to `AnalysisResult`s * `imports_to_detect`: maps imports represented as (full module name, alias) tuples to `AnalysisResult`s notifications) For an example, see `TFAPIImportAnalysisSpec`. """ class PastaAnalyzeVisitor(_PastaEditVisitor): """AST Visitor that looks for specific API usage without editing anything. This is used before any rewriting is done to detect if any symbols are used that require changing imports or disabling rewriting altogether. """ def __init__(self, api_analysis_spec): super(PastaAnalyzeVisitor, self).__init__(NoUpdateSpec()) self._api_analysis_spec = api_analysis_spec self._results = [] # Holds AnalysisResult objects @property def results(self): return self._results def add_result(self, analysis_result): self._results.append(analysis_result) def visit_Attribute(self, node): # pylint: disable=invalid-name """Handle bare Attributes i.e. [tf.foo, tf.bar].""" full_name = self._get_full_name(node) if full_name: detection = self._api_analysis_spec.symbols_to_detect.get(full_name, None) if detection: self.add_result(detection) self.add_log( detection.log_level, node.lineno, node.col_offset, detection.log_message) self.generic_visit(node) def visit_Import(self, node): # pylint: disable=invalid-name """Handle visiting an import node in the AST. Args: node: Current Node """ for import_alias in node.names: # Detect based on full import name and alias) full_import = (import_alias.name, import_alias.asname) detection = (self._api_analysis_spec .imports_to_detect.get(full_import, None)) if detection: self.add_result(detection) self.add_log( detection.log_level, node.lineno, node.col_offset, detection.log_message) self.generic_visit(node) def visit_ImportFrom(self, node): # pylint: disable=invalid-name """Handle visiting an import-from node in the AST. Args: node: Current Node """ if not node.module: self.generic_visit(node) return from_import = node.module for import_alias in node.names: # Detect based on full import name(to & as) full_module_name = "%s.%s" % (from_import, import_alias.name) full_import = (full_module_name, import_alias.asname) detection = (self._api_analysis_spec .imports_to_detect.get(full_import, None)) if detection: self.add_result(detection) self.add_log( detection.log_level, node.lineno, node.col_offset, detection.log_message) self.generic_visit(node) class ASTCodeUpgrader(object): """Handles upgrading a set of Python files using a given API change spec.""" def __init__(self, api_change_spec): if not isinstance(api_change_spec, APIChangeSpec): raise TypeError("Must pass APIChangeSpec to ASTCodeUpgrader, got %s" % type(api_change_spec)) self._api_change_spec = api_change_spec def process_file(self, in_filename, out_filename, no_change_to_outfile_on_error=False): """Process the given python file for incompatible changes. Args: in_filename: filename to parse out_filename: output file to write to no_change_to_outfile_on_error: not modify the output file on errors Returns: A tuple representing number of files processed, log of actions, errors """ # Write to a temporary file, just in case we are doing an implace modify. # pylint: disable=g-backslash-continuation with open(in_filename, "r") as in_file, \ tempfile.NamedTemporaryFile("w", delete=False) as temp_file: ret = self.process_opened_file(in_filename, in_file, out_filename, temp_file) # pylint: enable=g-backslash-continuation if no_change_to_outfile_on_error and ret[0] == 0: os.remove(temp_file.name) else: shutil.move(temp_file.name, out_filename) return ret def format_log(self, log, in_filename): log_string = "%d:%d: %s: %s" % (log[1], log[2], log[0], log[3]) if in_filename: return six.ensure_str(in_filename) + ":" + log_string else: return log_string def update_string_pasta(self, text, in_filename): """Updates a file using pasta.""" try: t = pasta.parse(text) except (SyntaxError, ValueError, TypeError): log = ["ERROR: Failed to parse.\n" + traceback.format_exc()] return 0, "", log, [] t, preprocess_logs, preprocess_errors = self._api_change_spec.preprocess(t) visitor = _PastaEditVisitor(self._api_change_spec) visitor.visit(t) self._api_change_spec.clear_preprocessing() logs = [self.format_log(log, None) for log in (preprocess_logs + visitor.log)] errors = [self.format_log(error, in_filename) for error in (preprocess_errors + visitor.warnings_and_errors)] return 1, pasta.dump(t), logs, errors def _format_log(self, log, in_filename, out_filename): text = six.ensure_str("-" * 80) + "\n" text += "Processing file %r\n outputting to %r\n" % (in_filename, out_filename) text += six.ensure_str("-" * 80) + "\n\n" text += "\n".join(log) + "\n" text += six.ensure_str("-" * 80) + "\n\n" return text def process_opened_file(self, in_filename, in_file, out_filename, out_file): """Process the given python file for incompatible changes. This function is split out to facilitate StringIO testing from tf_upgrade_test.py. Args: in_filename: filename to parse in_file: opened file (or StringIO) out_filename: output file to write to out_file: opened file (or StringIO) Returns: A tuple representing number of files processed, log of actions, errors """ lines = in_file.readlines() processed_file, new_file_content, log, process_errors = ( self.update_string_pasta("".join(lines), in_filename)) if out_file and processed_file: out_file.write(new_file_content) return (processed_file, self._format_log(log, in_filename, out_filename), process_errors) def process_tree(self, root_directory, output_root_directory, copy_other_files): """Processes upgrades on an entire tree of python files in place. Note that only Python files. If you have custom code in other languages, you will need to manually upgrade those. Args: root_directory: Directory to walk and process. output_root_directory: Directory to use as base. copy_other_files: Copy files that are not touched by this converter. Returns: A tuple of files processed, the report string for all files, and a dict mapping filenames to errors encountered in that file. """ if output_root_directory == root_directory: return self.process_tree_inplace(root_directory) # make sure output directory doesn't exist if output_root_directory and os.path.exists(output_root_directory): print("Output directory %r must not already exist." % (output_root_directory)) sys.exit(1) # make sure output directory does not overlap with root_directory norm_root = os.path.split(os.path.normpath(root_directory)) norm_output = os.path.split(os.path.normpath(output_root_directory)) if norm_root == norm_output: print("Output directory %r same as input directory %r" % (root_directory, output_root_directory)) sys.exit(1) # Collect list of files to process (we do this to correctly handle if the # user puts the output directory in some sub directory of the input dir) files_to_process = [] files_to_copy = [] for dir_name, _, file_list in os.walk(root_directory): py_files = [f for f in file_list if six.ensure_str(f).endswith(".py")] copy_files = [ f for f in file_list if not six.ensure_str(f).endswith(".py") ] for filename in py_files: fullpath = os.path.join(dir_name, filename) fullpath_output = os.path.join(output_root_directory, os.path.relpath(fullpath, root_directory)) files_to_process.append((fullpath, fullpath_output)) if copy_other_files: for filename in copy_files: fullpath = os.path.join(dir_name, filename) fullpath_output = os.path.join(output_root_directory, os.path.relpath( fullpath, root_directory)) files_to_copy.append((fullpath, fullpath_output)) file_count = 0 tree_errors = {} report = "" report += six.ensure_str(("=" * 80)) + "\n" report += "Input tree: %r\n" % root_directory report += six.ensure_str(("=" * 80)) + "\n" for input_path, output_path in files_to_process: output_directory = os.path.dirname(output_path) if not os.path.isdir(output_directory): os.makedirs(output_directory) if os.path.islink(input_path): link_target = os.readlink(input_path) link_target_output = os.path.join( output_root_directory, os.path.relpath(link_target, root_directory)) if (link_target, link_target_output) in files_to_process: # Create a link to the new location of the target file os.symlink(link_target_output, output_path) else: report += "Copying symlink %s without modifying its target %s" % ( input_path, link_target) os.symlink(link_target, output_path) continue file_count += 1 _, l_report, l_errors = self.process_file(input_path, output_path) tree_errors[input_path] = l_errors report += l_report for input_path, output_path in files_to_copy: output_directory = os.path.dirname(output_path) if not os.path.isdir(output_directory): os.makedirs(output_directory) shutil.copy(input_path, output_path) return file_count, report, tree_errors def process_tree_inplace(self, root_directory): """Process a directory of python files in place.""" files_to_process = [] for dir_name, _, file_list in os.walk(root_directory): py_files = [ os.path.join(dir_name, f) for f in file_list if six.ensure_str(f).endswith(".py") ] files_to_process += py_files file_count = 0 tree_errors = {} report = "" report += six.ensure_str(("=" * 80)) + "\n" report += "Input tree: %r\n" % root_directory report += six.ensure_str(("=" * 80)) + "\n" for path in files_to_process: if os.path.islink(path): report += "Skipping symlink %s.\n" % path continue file_count += 1 _, l_report, l_errors = self.process_file(path, path) tree_errors[path] = l_errors report += l_report return file_count, report, tree_errors
apache-2.0
capybaralet/fuel
fuel/bin/fuel_info.py
19
1581
#!/usr/bin/env python """Fuel utility for extracting metadata.""" import argparse import os import h5py message_prefix_template = 'Metadata for {}' message_body_template = """ The command used to generate this file is {} Relevant versions are H5PYDataset {} fuel.converters {} """ def main(args=None): """Entry point for `fuel-info` script. This function can also be imported and used from Python. Parameters ---------- args : iterable, optional (default: None) A list of arguments that will be passed to Fuel's information utility. If this argument is not specified, `sys.argv[1:]` will be used. """ parser = argparse.ArgumentParser( description='Extracts metadata from a Fuel-converted HDF5 file.') parser.add_argument("filename", help="HDF5 file to analyze") args = parser.parse_args() with h5py.File(args.filename, 'r') as h5file: interface_version = h5file.attrs.get('h5py_interface_version', 'N/A') fuel_convert_version = h5file.attrs.get('fuel_convert_version', 'N/A') fuel_convert_command = h5file.attrs.get('fuel_convert_command', 'N/A') message_prefix = message_prefix_template.format( os.path.basename(args.filename)) message_body = message_body_template.format( fuel_convert_command, interface_version, fuel_convert_version) message = ''.join(['\n', message_prefix, '\n', '=' * len(message_prefix), message_body]) print(message) if __name__ == "__main__": main()
mit
laosiaudi/tensorflow
tensorflow/contrib/graph_editor/tests/transform_test.py
8
7728
# Copyright 2015 The TensorFlow Authors. 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. # ============================================================================== """Tests for tensorflow.contrib.graph_editor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np import tensorflow as tf from tensorflow.contrib import graph_editor as ge # Precision tolerance for floating-point value tests. ERROR_TOLERANCE = 1e-3 class TransformTest(tf.test.TestCase): def setUp(self): self.graph = tf.Graph() with self.graph.as_default(): c0 = tf.constant(1.0, shape=[10], name="Const") c1 = tf.constant(1.0, shape=[10], name="Const") c2 = tf.constant(1.0, shape=[10], name="Const") i = tf.constant(1.0, shape=[10], name="Input") self.o = tf.add(c2, tf.add(c1, tf.add(c0, i))) def test_copy(self): graph = tf.Graph() _, info = ge.copy(self.graph, graph) self.assertEqual(set(op.name for op in self.graph.get_operations()), set(op.name for op in graph.get_operations())) src_ops = self.graph.get_operations() dst_ops = graph.get_operations() for op in src_ops: op_ = info.transformed(op) self.assertTrue(op_ in dst_ops) self.assertEqual(op.name, op_.name) self.assertEqual(info.original(op_), op) src_ts = ge.util.get_tensors(self.graph) dst_ts = ge.util.get_tensors(graph) for t in src_ts: t_ = info.transformed(t) self.assertTrue(t_ in dst_ts) self.assertEqual(t.name, t_.name) self.assertEqual(info.original(t_), t) def test_copy_assert(self): tf.reset_default_graph() a = tf.constant(1) b = tf.constant(1) eq = tf.equal(a, b) assert_op = tf.Assert(eq, [a, b]) with tf.control_dependencies([assert_op]): _ = tf.add(a, b) sgv = ge.make_view([assert_op, eq.op, a.op, b.op]) copier = ge.Transformer() copied_sgv, info = copier(sgv, sgv.graph, "", "") new_assert_op = info.transformed(assert_op) self.assertIsNotNone(new_assert_op) def test_transform(self): transformer = ge.Transformer() def my_transform_op_handler(info, op): add_noise = op.name.startswith("Add") op_ = ge.transform.copy_op_handler(info, op) if add_noise: # add some noise to op with info.graph_.as_default(): t_ = tf.add(tf.constant(1.0, shape=[10], name="Noise"), op_.outputs[0], name="AddNoise") # return the "noisy" op return t_.op else: return op_ transformer.transform_op_handler = my_transform_op_handler graph = tf.Graph() transformer(self.graph, graph, "", "") matcher0 = ge.matcher("AddNoise").input_ops( "Noise", ge.matcher("Add").input_ops("Const", "Input")) matcher1 = ge.matcher("AddNoise_1").input_ops( "Noise_1", ge.matcher("Add_1").input_ops("Const_1", matcher0)) matcher2 = ge.matcher("AddNoise_2").input_ops( "Noise_2", ge.matcher("Add_2").input_ops("Const_2", matcher1)) top = ge.select_ops("^AddNoise_2$", graph=graph)[0] self.assertTrue(matcher2(top)) def test_transform_in_place(self): transformer = ge.Transformer() def my_transform_op_handler_in_place(info, op): add_noise = op.name.startswith("Add") op = ge.transform.transform_op_in_place(info, op, detach_outputs=add_noise) if add_noise: # add some noise to op with info.graph_.as_default(): t = tf.add(tf.constant(1.0, shape=[10], name="Noise"), op.outputs[0], name="AddNoise") # return the "noisy" op return t.op else: return op transformer.transform_op_handler = my_transform_op_handler_in_place transformer(self.graph, self.graph, "", "") matcher0 = ge.matcher("AddNoise").input_ops( "Noise", ge.matcher("Add").input_ops("Const", "Input")) matcher1 = ge.matcher("AddNoise_1").input_ops( "Noise_1", ge.matcher("Add_1").input_ops("Const_1", matcher0)) matcher2 = ge.matcher("AddNoise_2").input_ops( "Noise_2", ge.matcher("Add_2").input_ops("Const_2", matcher1)) top = ge.select_ops("^AddNoise_2$", graph=self.graph)[0] self.assertTrue(matcher2(top)) def test_copy_with_input_replacements(self): with self.graph.as_default(): ten = tf.constant(10.0, shape=[10], name="Input") sgv, _ = ge.copy_with_input_replacements(self.o.op, {self.o.op.inputs[1]: ten}) with tf.Session() as sess: val = sess.run(sgv.outputs[0]) self.assertNear(np.linalg.norm(val - np.array([11])), 0.0, ERROR_TOLERANCE) def test_graph_replace(self): tf.reset_default_graph() a = tf.constant(1.0, name="a") b = tf.Variable(1.0, name="b") eps = tf.constant(0.001, name="eps") c = tf.identity(a + b + eps, name="c") a_new = tf.constant(2.0, name="a_new") c_new = ge.graph_replace(c, {a: a_new}) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) c_val, c_new_val = sess.run([c, c_new]) self.assertNear(c_val, 2.001, ERROR_TOLERANCE) self.assertNear(c_new_val, 3.001, ERROR_TOLERANCE) def test_graph_replace_dict(self): tf.reset_default_graph() a = tf.constant(1.0, name="a") b = tf.Variable(1.0, name="b") eps = tf.constant(0.001, name="eps") c = tf.identity(a + b + eps, name="c") a_new = tf.constant(2.0, name="a_new") c_new = ge.graph_replace({"c": c}, {a: a_new}) self.assertTrue(isinstance(c_new, dict)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) c_val, c_new_val = sess.run([c, c_new]) self.assertTrue(isinstance(c_new_val, dict)) self.assertNear(c_val, 2.001, ERROR_TOLERANCE) self.assertNear(c_new_val["c"], 3.001, ERROR_TOLERANCE) def test_graph_replace_ordered_dict(self): tf.reset_default_graph() a = tf.constant(1.0, name="a") b = tf.Variable(1.0, name="b") eps = tf.constant(0.001, name="eps") c = tf.identity(a + b + eps, name="c") a_new = tf.constant(2.0, name="a_new") c_new = ge.graph_replace(collections.OrderedDict({"c": c}), {a: a_new}) self.assertTrue(isinstance(c_new, collections.OrderedDict)) def test_graph_replace_named_tuple(self): tf.reset_default_graph() a = tf.constant(1.0, name="a") b = tf.Variable(1.0, name="b") eps = tf.constant(0.001, name="eps") c = tf.identity(a + b + eps, name="c") a_new = tf.constant(2.0, name="a_new") one_tensor = collections.namedtuple("OneTensor", ["t"]) c_new = ge.graph_replace(one_tensor(c), {a: a_new}) self.assertTrue(isinstance(c_new, one_tensor)) def test_graph_replace_missing(self): tf.reset_default_graph() a = tf.constant(1.0, name="a") b = tf.constant(2.0, name="b") c = a + 2 * b d = tf.constant(2.0, name="d") res = ge.graph_replace([b, c], {a: d}) self.assertEqual(res[0].name, "b:0") self.assertEqual(res[1].name, "add_1:0") if __name__ == "__main__": tf.test.main()
apache-2.0
sergeykolychev/mxnet
benchmark/python/sparse/dot.py
16
19756
# 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. import ctypes import os import time import argparse import subprocess import scipy.sparse as sp import mxnet as mx import numpy as np import numpy.random as rnd from mxnet.test_utils import rand_ndarray, set_default_context, assert_almost_equal, get_bz2_data from mxnet.base import check_call, _LIB from util import estimate_density PARSER = argparse.ArgumentParser(description="Benchmark sparse operators", formatter_class=argparse.ArgumentDefaultsHelpFormatter) PARSER.add_argument('--num-omp-threads', type=int, default=1, help='number of omp threads to set in MXNet') PARSER.add_argument('--gpu', action='store_true', help="to be run on gpu") # TODO: Use logging later PARSER.add_argument('--verbose', action='store_true', help="Verbose output") ARGS = PARSER.parse_args() # some data information KDDA = { 'data_mini': 'kdda.t.mini', 'data_name': 'kdda.t', 'data_origin_name': 'kdda.t.bz2', 'url': "https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/kdda.t.bz2", 'feature_dim': 20216830, 'm': [1, 8, 32], 'batch_size': [64], 'default_index': {'batch_size': 0, 'output_dim': 2}, 'num_batches': 10 } AVAZU = { 'data_mini': 'avazu-app.t.mini', 'data_name': 'avazu-app.t', 'data_origin_name': 'avazu-app.t.bz2', 'url': "https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/avazu-app.t.bz2", 'feature_dim': 1000000, 'm': [1, 1000, 2000], 'batch_size': [128, 256], 'default_index': {'batch_size': 0, 'output_dim': 1}, 'num_batches': 10 } CRITEO = { 'data_mini': 'criteo.t.mini', 'data_name': 'criteo.t', 'data_origin_name': 'criteo.t.bz2', 'url' : "https://s3-us-west-2.amazonaws.com/sparse-dataset/criteo.t.bz2", 'feature_dim': 8388621, 'm': [1, 8, 16, 32, 64], 'batch_size': [64, 128], 'default_index': {'batch_size': 1, 'output_dim': 3}, 'num_batches': 10 } SYNTHETIC1 = { 'feature_dim': [1000000], 'm': [256, 1000], 'density': [0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.65], 'batch_size': [64, 128], 'default_index': {'batch_size': 1, 'density': 2, 'output_dim': 1, 'feature_dim': 0}, 'num_repeat': 10 } SYNTHETIC2 = { 'feature_dim': [8000000, 16000000], 'm': [1, 32], 'density': [0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.65], 'batch_size': [64, 128], 'default_index': {'batch_size': 1, 'density': 2, 'output_dim': 1, 'feature_dim': 0}, 'num_repeat': 10 } def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs): """Measure time cost of running a function """ mx.nd.waitall() args_list = [] for arg in args: args_list.append(arg) start = time.time() if scipy_trans_lhs: args_list[0] = np.transpose(args_list[0]) if scipy_dns_lhs else sp.spmatrix.transpose(args_list[0]) for _ in range(repeat): func_name(*args_list, **kwargs) mx.nd.waitall() end = time.time() diff = end - start return diff / repeat def _get_iter(path, data_shape, batch_size): data_train = mx.io.LibSVMIter(data_libsvm=path, data_shape=data_shape, batch_size=batch_size) data_iter = iter(data_train) return data_iter def _line_count(path): return int(subprocess.check_output('wc -l {}'.format(path), shell=True).split()[0]) def _compare_sparse_dense(data_dir, file_name, mini_file_name, feature_dim, output_dim, density, batch_size, num_batches=3, num_repeat=5, transpose=False, rsp=False): def create_mini_path(mini_path, path, num_batches): """Samples batches of size: batch_size, total number: num_batches from the dataset files for running benchmarks""" if not os.path.exists(mini_path): last = _line_count(path) - num_batches * batch_size last = last if last >= 1 else 1 start = int(rnd.uniform(1, last)) os.system("sed -n '%d,%dp' %r > %r" %(start, start + num_batches * batch_size, path, mini_path)) assert os.path.exists(mini_path) def run_benchmark(mini_path): """Run benchmarks """ data_shape = (feature_dim, ) train_iter = _get_iter(mini_path, data_shape, batch_size) weight_row_dim = batch_size if transpose else feature_dim weight_shape = (weight_row_dim, output_dim) if not rsp: weight = mx.nd.random.uniform(low=0, high=1, shape=weight_shape) else: weight = rand_ndarray(weight_shape, "row_sparse", density=0.05, distribution="uniform") total_cost = {} average_cost = {} count = 0 total_cost["sparse"] = 0. total_cost["dense"] = 0. for _ in train_iter: csr_data = train_iter.getdata() dns_data = csr_data.tostype('default') cost_sparse = measure_cost(num_repeat, False, False, mx.nd.sparse.dot, csr_data, weight, transpose_a=transpose) cost_dense = measure_cost(num_repeat, False, False, mx.nd.dot, dns_data, weight, transpose_a=transpose) total_cost["sparse"] += cost_sparse total_cost["dense"] += cost_dense count = count + 1 average_cost["sparse"] = total_cost["sparse"] / count average_cost["dense"] = total_cost["dense"] / count return (average_cost["sparse"], average_cost["dense"]) def print_result(average_cost_sparse, average_cost_dense): """Print result of comparison between sparse and dense """ ratio = average_cost_dense / average_cost_sparse fmt = '{:15.4f} {:10d} {:10d} {:10d} {:20.2f} {:15.2f} {:15.2f} {:10} {:10}' print(fmt.format(density * 100, batch_size, output_dim, feature_dim, ratio, average_cost_dense*1000, average_cost_sparse*1000, transpose, rsp)) mini_path = os.path.join(data_dir, mini_file_name) path = os.path.join(data_dir, file_name) create_mini_path(mini_path, path, num_batches) average_cost_sparse, average_cost_dense = run_benchmark(mini_path) print_result(average_cost_sparse, average_cost_dense) def test_dot_real(data_dict): """Dot operator testing with real datasets""" data_dir = os.path.join(os.getcwd(), 'data') path = os.path.join(data_dir, data_dict['data_name']) if not os.path.exists(path): get_bz2_data( data_dir, data_dict['data_name'], data_dict['url'], data_dict['data_origin_name'] ) assert os.path.exists(path) k = data_dict['feature_dim'] m = data_dict['m'] batch_size_list = data_dict['batch_size'] default_output_index = data_dict['default_index']['output_dim'] default_batch_size_index = data_dict['default_index']['batch_size'] density = estimate_density(path, data_dict['feature_dim']) num_batches = data_dict['num_batches'] assert default_batch_size_index < len(batch_size_list) assert default_output_index < len(m) if ARGS.verbose: print("Running Benchmarking on %r data") % data_dict['data_mini'] print('{:>15} {:>10} {:>10} {:>10} {:>20} {:>15} {:>15} {:>10} {:>10}'.format('density(%)', 'n', 'm', 'k', 't_dense/t_sparse', 't_dense(ms)', 't_sparse(ms)', 'is_transpose', 'rhs_rsp')) for output_dim in m: _compare_sparse_dense(data_dir, data_dict['data_name'], data_dict['data_mini'], k, output_dim, density, batch_size_list[default_batch_size_index], num_batches) _compare_sparse_dense(data_dir, data_dict['data_name'], data_dict['data_mini'], k, output_dim, density, batch_size_list[default_batch_size_index], num_batches, transpose=True) _compare_sparse_dense(data_dir, data_dict['data_name'], data_dict['data_mini'], k, output_dim, density, batch_size_list[default_batch_size_index], num_batches, rsp=True) for batch_size in batch_size_list: _compare_sparse_dense(data_dir, data_dict['data_name'], data_dict['data_mini'], k, m[default_output_index], density, batch_size, num_batches) _compare_sparse_dense(data_dir, data_dict['data_name'], data_dict['data_mini'], k, m[default_output_index], density, batch_size, num_batches, transpose=True) _compare_sparse_dense(data_dir, data_dict['data_name'], data_dict['data_mini'], k, output_dim, density, batch_size_list[default_batch_size_index], num_batches, rsp=True) def test_dot_synthetic(data_dict): """benchmark sparse mxnet dot and scipy dot operator with matrices of given density. `t_sparse` is the runtime of the invoked sparse dot operator in ms, while `t_dense` is the runtime of dot(dns, dns), with the same matrices except that they are in default storage type. """ # Benchmark MXNet and Scipys dot operator def bench_dot(lhs_shape, rhs_shape, lhs_stype, rhs_stype, lhs_den, rhs_den, trans_lhs, ctx, num_repeat=10, fw="mxnet", distribution="uniform"): set_default_context(ctx) assert fw == "mxnet" or fw == "scipy" # Set funcs dot_func_sparse = mx.nd.sparse.dot if fw == "mxnet" else sp.spmatrix.dot dot_func_dense = mx.nd.dot if fw == "mxnet" else np.dot # Create matrix instances lhs_nd = rand_ndarray(lhs_shape, lhs_stype, density=lhs_den, distribution=distribution) # only uniform distribution supported for rhs rhs_nd = rand_ndarray(rhs_shape, rhs_stype, density=rhs_den, distribution="uniform") lhs_dns = None rhs_dns = None dense_cost = None sparse_cost = None if fw == "mxnet": lhs_dns = lhs_nd if lhs_stype == 'default' else lhs_nd.tostype('default') rhs_dns = rhs_nd if rhs_stype == 'default' else rhs_nd.tostype('default') # One warm up run, verify correctness out = dot_func_sparse(lhs_nd, rhs_dns, trans_lhs) out_expected = dot_func_dense(lhs_dns, rhs_dns, trans_lhs) assert_almost_equal(out.asnumpy(), out_expected.asnumpy(), rtol=1e-1, atol=1e-1) sparse_cost = measure_cost(num_repeat, False, False, dot_func_sparse, lhs_nd, rhs_nd, trans_lhs) dense_cost = measure_cost(num_repeat, False, False, dot_func_dense, lhs_dns, rhs_dns, trans_lhs) else: lhs_dns = lhs_nd.asnumpy() rhs_dns = rhs_nd.asnumpy() lhs_nd = sp.csr_matrix(lhs_nd.asnumpy()) rhs_nd = rhs_nd.asnumpy() # One warm up run, verify correctness lhs_nd_copy = sp.spmatrix.transpose(lhs_nd) if trans_lhs else lhs_nd out = dot_func_sparse(lhs_nd_copy, rhs_dns) sparse_cost = measure_cost(num_repeat, trans_lhs, False, dot_func_sparse, lhs_nd, rhs_nd) dense_cost = measure_cost(num_repeat, trans_lhs, True, dot_func_dense, lhs_dns, rhs_dns) speedup = dense_cost / sparse_cost # Print results m = lhs_shape[0] k = lhs_shape[1] n = rhs_shape[1] result_pattern = '{:15.1f} {:15.1f} {:>10} {:8d} {:8d} {:8d} {:13.2f} {:13.2f} {:8.2f}' results = result_pattern.format(lhs_den*100, rhs_den*100, str(ctx), m, k, n, sparse_cost*1000, dense_cost*1000, speedup) print(results) def print_benchmark_info(lhs, rhs, lhs_trans, fw): trans_str = "^T" if lhs_trans else "" print("========================================================") print(" %s sparse dot benchmark: dot(%s, %s) = %s ") % (fw, lhs, rhs, rhs) print(" (matrix multiplication: (m x k)%s * (k x n) = m x n) ") % (trans_str) print("========================================================") headline_pattern = '{:>15} {:>15} {:>10} {:>8} {:>8} {:>8} {:>13} {:>13} {:>8}' headline = headline_pattern.format('lhs_density(%)', 'rhs_density(%)', 'context', 'm', 'k', 'n', 't_sparse(ms)', 't_dense(ms)', 'speedup') print(headline) def run_benchmark(ctx=None, lhs="csr", lhs_trans=False, rhs="dns", fw="mxnet", rhs_density=1, distribution="uniform"): if lhs != "csr": raise ValueError("Value other than csr for lhs not supported") if rhs_density > 1 or rhs_density < 0: raise ValueError("rhs_density has to be between 0 and 1") print_benchmark_info(lhs, rhs, lhs_trans, fw) lhs_stype = "csr" rhs_stype = "row_sparse" if rhs == "rsp" else "default" feature_dim_list = data_dict['feature_dim'] output_dim_list = data_dict['m'] batch_size_list = data_dict['batch_size'] density_list = data_dict['density'] default_output_index = data_dict['default_index']['output_dim'] default_batch_size_index = data_dict['default_index']['batch_size'] default_feature_index = data_dict['default_index']['feature_dim'] default_density_index = data_dict['default_index']['density'] num_repeat = data_dict['num_repeat'] for output_dim in output_dim_list: if lhs_trans: output_row_dim = batch_size_list[default_batch_size_index] else: output_row_dim = feature_dim_list[default_feature_index] bench_dot((batch_size_list[default_batch_size_index], feature_dim_list[default_feature_index]), (output_row_dim, output_dim), lhs_stype, rhs_stype, density_list[default_density_index], rhs_density, lhs_trans, ctx, num_repeat=num_repeat, fw=fw, distribution=distribution) for feature_dim in feature_dim_list: if lhs_trans: output_row_dim = batch_size_list[default_batch_size_index] else: output_row_dim = feature_dim bench_dot((batch_size_list[default_batch_size_index], feature_dim), (output_row_dim, output_dim_list[default_output_index]), lhs_stype, rhs_stype, density_list[default_density_index], rhs_density, lhs_trans, ctx, num_repeat=num_repeat, fw=fw, distribution=distribution) for batch_size in batch_size_list: if lhs_trans: output_row_dim = batch_size else: output_row_dim = feature_dim_list[default_feature_index] bench_dot((batch_size, feature_dim_list[default_feature_index]), (output_row_dim, output_dim_list[default_output_index]), lhs_stype, rhs_stype, density_list[default_density_index], rhs_density, lhs_trans, ctx, num_repeat=num_repeat, fw=fw, distribution=distribution) for density in density_list: if lhs_trans: output_row_dim = batch_size_list[default_batch_size_index] else: output_row_dim = feature_dim_list[default_feature_index] bench_dot((batch_size_list[default_batch_size_index], feature_dim_list[default_feature_index]), (output_row_dim, output_dim_list[default_output_index]), lhs_stype, rhs_stype, density, rhs_density, lhs_trans, ctx, num_repeat=num_repeat, fw=fw, distribution=distribution) check_call(_LIB.MXSetNumOMPThreads(ctypes.c_int(ARGS.num_omp_threads))) context = mx.gpu() if ARGS.gpu else mx.cpu() # TODO(anirudh): make the data dicts to config which can be passed at runtime distributions = ["uniform", "powerlaw"] for distribution in distributions: run_benchmark(context, lhs="csr", rhs="default", lhs_trans=False, fw="mxnet", rhs_density=1, distribution=distribution) run_benchmark(context, lhs="csr", rhs="default", lhs_trans=True, fw="mxnet", rhs_density=1, distribution=distribution) run_benchmark(context, lhs="csr", rhs="rsp", lhs_trans=False, fw="mxnet", rhs_density=0.05, distribution=distribution) if not ARGS.gpu: run_benchmark(context, lhs="csr", rhs="default", lhs_trans=False, fw="scipy", rhs_density=1, distribution=distribution) run_benchmark(context, lhs="csr", rhs="default", lhs_trans=True, fw="scipy", rhs_density=1, distribution=distribution) if __name__ == "__main__": begin_time = time.time() test_dot_real(KDDA) test_dot_real(AVAZU) test_dot_real(CRITEO) test_dot_synthetic(SYNTHETIC1) test_dot_synthetic(SYNTHETIC2) total_time = time.time() - begin_time print("total time is %f") % total_time
apache-2.0
idea4bsd/idea4bsd
python/lib/Lib/pdb.py
90
42362
#! /usr/bin/env python """A Python debugger.""" # (See pdb.doc for documentation.) import sys import linecache import cmd import bdb from repr import Repr import os import re import pprint import traceback # Create a custom safe Repr instance and increase its maxstring. # The default of 30 truncates error messages too easily. _repr = Repr() _repr.maxstring = 200 _saferepr = _repr.repr __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", "post_mortem", "help"] def find_function(funcname, filename): cre = re.compile(r'def\s+%s\s*[(]' % funcname) try: fp = open(filename) except IOError: return None # consumer of this info expects the first line to be 1 lineno = 1 answer = None while 1: line = fp.readline() if line == '': break if cre.match(line): answer = funcname, filename, lineno break lineno = lineno + 1 fp.close() return answer # Interaction prompt line will separate file and call info from code # text using value of line_prefix string. A newline and arrow may # be to your liking. You can set it once pdb is imported using the # command "pdb.line_prefix = '\n% '". # line_prefix = ': ' # Use this to get the old situation back line_prefix = '\n-> ' # Probably a better default class Pdb(bdb.Bdb, cmd.Cmd): def __init__(self, completekey='tab', stdin=None, stdout=None): bdb.Bdb.__init__(self) cmd.Cmd.__init__(self, completekey, stdin, stdout) if stdout: self.use_rawinput = 0 self.prompt = '(Pdb) ' self.aliases = {} self.mainpyfile = '' self._wait_for_mainpyfile = 0 # Try to load readline if it exists try: import readline except ImportError: pass # Read $HOME/.pdbrc and ./.pdbrc self.rcLines = [] if 'HOME' in os.environ: envHome = os.environ['HOME'] try: rcFile = open(os.path.join(envHome, ".pdbrc")) except IOError: pass else: for line in rcFile.readlines(): self.rcLines.append(line) rcFile.close() try: rcFile = open(".pdbrc") except IOError: pass else: for line in rcFile.readlines(): self.rcLines.append(line) rcFile.close() self.commands = {} # associates a command list to breakpoint numbers self.commands_doprompt = {} # for each bp num, tells if the prompt must be disp. after execing the cmd list self.commands_silent = {} # for each bp num, tells if the stack trace must be disp. after execing the cmd list self.commands_defining = False # True while in the process of defining a command list self.commands_bnum = None # The breakpoint number for which we are defining a list def reset(self): bdb.Bdb.reset(self) self.forget() def forget(self): self.lineno = None self.stack = [] self.curindex = 0 self.curframe = None def setup(self, f, t): self.forget() self.stack, self.curindex = self.get_stack(f, t) self.curframe = self.stack[self.curindex][0] self.execRcLines() # Can be executed earlier than 'setup' if desired def execRcLines(self): if self.rcLines: # Make local copy because of recursion rcLines = self.rcLines # executed only once self.rcLines = [] for line in rcLines: line = line[:-1] if len(line) > 0 and line[0] != '#': self.onecmd(line) # Override Bdb methods def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" if self._wait_for_mainpyfile: return if self.stop_here(frame): print >>self.stdout, '--Call--' self.interaction(frame, None) def user_line(self, frame): """This function is called when we stop or break at this line.""" if self._wait_for_mainpyfile: if (self.mainpyfile != self.canonic(frame.f_code.co_filename) or frame.f_lineno<= 0): return self._wait_for_mainpyfile = 0 if self.bp_commands(frame): self.interaction(frame, None) def bp_commands(self,frame): """ Call every command that was set for the current active breakpoint (if there is one) Returns True if the normal interaction function must be called, False otherwise """ #self.currentbp is set in bdb.py in bdb.break_here if a breakpoint was hit if getattr(self,"currentbp",False) and self.currentbp in self.commands: currentbp = self.currentbp self.currentbp = 0 lastcmd_back = self.lastcmd self.setup(frame, None) for line in self.commands[currentbp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[currentbp]: self.print_stack_entry(self.stack[self.curindex]) if self.commands_doprompt[currentbp]: self.cmdloop() self.forget() return return 1 def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" frame.f_locals['__return__'] = return_value print >>self.stdout, '--Return--' self.interaction(frame, None) def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" frame.f_locals['__exception__'] = exc_type, exc_value if type(exc_type) == type(''): exc_type_name = exc_type else: exc_type_name = exc_type.__name__ print >>self.stdout, exc_type_name + ':', _saferepr(exc_value) self.interaction(frame, exc_traceback) # General interaction function def interaction(self, frame, traceback): self.setup(frame, traceback) self.print_stack_entry(self.stack[self.curindex]) self.cmdloop() self.forget() def default(self, line): if line[:1] == '!': line = line[1:] locals = self.curframe.f_locals globals = self.curframe.f_globals try: code = compile(line + '\n', '<stdin>', 'single') exec code in globals, locals except: t, v = sys.exc_info()[:2] if type(t) == type(''): exc_type_name = t else: exc_type_name = t.__name__ print >>self.stdout, '***', exc_type_name + ':', v def precmd(self, line): """Handle alias expansion and ';;' separator.""" if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = line.replace("%" + str(ii), tmpArg) ii = ii + 1 line = line.replace("%*", ' '.join(args[1:])) args = line.split() # split into ';;' separated commands # unless it's an alias command if args[0] != 'alias': marker = line.find(';;') if marker >= 0: # queue up everything after marker next = line[marker+2:].lstrip() self.cmdqueue.append(next) line = line[:marker].rstrip() return line def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition. """ if not self.commands_defining: return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line) def handle_command_def(self,line): """ Handles one command line during command list definition. """ cmd, arg, line = self.parseline(line) if cmd == 'silent': self.commands_silent[self.commands_bnum] = True return # continue to handle other cmd def in the cmd list elif cmd == 'end': self.cmdqueue = [] return 1 # end of cmd list cmdlist = self.commands[self.commands_bnum] if (arg): cmdlist.append(cmd+' '+arg) else: cmdlist.append(cmd) # Determine if we must stop try: func = getattr(self, 'do_' + cmd) except AttributeError: func = self.default if func.func_name in self.commands_resuming : # one of the resuming commands. self.commands_doprompt[self.commands_bnum] = False self.cmdqueue = [] return 1 return # Command definitions, called by cmdloop() # The argument is the remaining string on the command line # Return true to exit from the command loop do_h = cmd.Cmd.do_help def do_commands(self, arg): """Defines a list of commands associated to a breakpoint Those commands will be executed whenever the breakpoint causes the program to stop execution.""" if not arg: bnum = len(bdb.Breakpoint.bpbynumber)-1 else: try: bnum = int(arg) except: print >>self.stdout, "Usage : commands [bnum]\n ...\n end" return self.commands_bnum = bnum self.commands[bnum] = [] self.commands_doprompt[bnum] = True self.commands_silent[bnum] = False prompt_back = self.prompt self.prompt = '(com) ' self.commands_defining = True self.cmdloop() self.commands_defining = False self.prompt = prompt_back def do_break(self, arg, temporary = 0): # break [ ([filename:]lineno | function) [, "condition"] ] if not arg: if self.breaks: # There's at least one print >>self.stdout, "Num Type Disp Enb Where" for bp in bdb.Breakpoint.bpbynumber: if bp: bp.bpprint(self.stdout) return # parse arguments; comma has lowest precedence # and cannot occur in filename filename = None lineno = None cond = None comma = arg.find(',') if comma > 0: # parse stuff after comma: "condition" cond = arg[comma+1:].lstrip() arg = arg[:comma].rstrip() # parse stuff before comma: [filename:]lineno | function colon = arg.rfind(':') funcname = None if colon >= 0: filename = arg[:colon].rstrip() f = self.lookupmodule(filename) if not f: print >>self.stdout, '*** ', repr(filename), print >>self.stdout, 'not found from sys.path' return else: filename = f arg = arg[colon+1:].lstrip() try: lineno = int(arg) except ValueError, msg: print >>self.stdout, '*** Bad lineno:', arg return else: # no colon; can be lineno or function try: lineno = int(arg) except ValueError: try: func = eval(arg, self.curframe.f_globals, self.curframe.f_locals) except: func = arg try: if hasattr(func, 'im_func'): func = func.im_func code = func.func_code #use co_name to identify the bkpt (function names #could be aliased, but co_name is invariant) funcname = code.co_name lineno = code.co_firstlineno filename = code.co_filename except: # last thing to try (ok, filename, ln) = self.lineinfo(arg) if not ok: print >>self.stdout, '*** The specified object', print >>self.stdout, repr(arg), print >>self.stdout, 'is not a function' print >>self.stdout, 'or was not found along sys.path.' return funcname = ok # ok contains a function name lineno = int(ln) if not filename: filename = self.defaultFile() # Check for reasonable breakpoint line = self.checkline(filename, lineno) if line: # now set the break point err = self.set_break(filename, line, temporary, cond, funcname) if err: print >>self.stdout, '***', err else: bp = self.get_breaks(filename, line)[-1] print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number, bp.file, bp.line) # To be overridden in derived debuggers def defaultFile(self): """Produce a reasonable default.""" filename = self.curframe.f_code.co_filename if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile return filename do_b = do_break def do_tbreak(self, arg): self.do_break(arg, 1) def lineinfo(self, identifier): failed = (None, None, None) # Input is identifier, may be in single quotes idstring = identifier.split("'") if len(idstring) == 1: # not in single quotes id = idstring[0].strip() elif len(idstring) == 3: # quoted id = idstring[1].strip() else: return failed if id == '': return failed parts = id.split('.') # Protection for derived debuggers if parts[0] == 'self': del parts[0] if len(parts) == 0: return failed # Best first guess at file to look at fname = self.defaultFile() if len(parts) == 1: item = parts[0] else: # More than one part. # First is module, second is method/class f = self.lookupmodule(parts[0]) if f: fname = f item = parts[1] answer = find_function(item, fname) return answer or failed def checkline(self, filename, lineno): """Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive. """ line = linecache.getline(filename, lineno) if not line: print >>self.stdout, 'End of file' return 0 line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): print >>self.stdout, '*** Blank or comment' return 0 return lineno def do_enable(self, arg): args = arg.split() for i in args: try: i = int(i) except ValueError: print >>self.stdout, 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print >>self.stdout, 'No breakpoint numbered', i continue bp = bdb.Breakpoint.bpbynumber[i] if bp: bp.enable() def do_disable(self, arg): args = arg.split() for i in args: try: i = int(i) except ValueError: print >>self.stdout, 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print >>self.stdout, 'No breakpoint numbered', i continue bp = bdb.Breakpoint.bpbynumber[i] if bp: bp.disable() def do_condition(self, arg): # arg is breakpoint number and condition args = arg.split(' ', 1) try: bpnum = int(args[0].strip()) except ValueError: # something went wrong print >>self.stdout, \ 'Breakpoint index %r is not a number' % args[0] return try: cond = args[1] except: cond = None try: bp = bdb.Breakpoint.bpbynumber[bpnum] except IndexError: print >>self.stdout, 'Breakpoint index %r is not valid' % args[0] return if bp: bp.cond = cond if not cond: print >>self.stdout, 'Breakpoint', bpnum, print >>self.stdout, 'is now unconditional.' def do_ignore(self,arg): """arg is bp number followed by ignore count.""" args = arg.split() try: bpnum = int(args[0].strip()) except ValueError: # something went wrong print >>self.stdout, \ 'Breakpoint index %r is not a number' % args[0] return try: count = int(args[1].strip()) except: count = 0 try: bp = bdb.Breakpoint.bpbynumber[bpnum] except IndexError: print >>self.stdout, 'Breakpoint index %r is not valid' % args[0] return if bp: bp.ignore = count if count > 0: reply = 'Will ignore next ' if count > 1: reply = reply + '%d crossings' % count else: reply = reply + '1 crossing' print >>self.stdout, reply + ' of breakpoint %d.' % bpnum else: print >>self.stdout, 'Will stop next time breakpoint', print >>self.stdout, bpnum, 'is reached.' def do_clear(self, arg): """Three possibilities, tried in this order: clear -> clear all breaks, ask for confirmation clear file:lineno -> clear all breaks at file:lineno clear bpno bpno ... -> clear breakpoints by number""" if not arg: try: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = reply.strip().lower() if reply in ('y', 'yes'): self.clear_all_breaks() return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" i = arg.rfind(':') filename = arg[:i] arg = arg[i+1:] try: lineno = int(arg) except ValueError: err = "Invalid line number (%s)" % arg else: err = self.clear_break(filename, lineno) if err: print >>self.stdout, '***', err return numberlist = arg.split() for i in numberlist: try: i = int(i) except ValueError: print >>self.stdout, 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print >>self.stdout, 'No breakpoint numbered', i continue err = self.clear_bpbynumber(i) if err: print >>self.stdout, '***', err else: print >>self.stdout, 'Deleted breakpoint', i do_cl = do_clear # 'c' is already an abbreviation for 'continue' def do_where(self, arg): self.print_stack_trace() do_w = do_where do_bt = do_where def do_up(self, arg): if self.curindex == 0: print >>self.stdout, '*** Oldest frame' else: self.curindex = self.curindex - 1 self.curframe = self.stack[self.curindex][0] self.print_stack_entry(self.stack[self.curindex]) self.lineno = None do_u = do_up def do_down(self, arg): if self.curindex + 1 == len(self.stack): print >>self.stdout, '*** Newest frame' else: self.curindex = self.curindex + 1 self.curframe = self.stack[self.curindex][0] self.print_stack_entry(self.stack[self.curindex]) self.lineno = None do_d = do_down def do_step(self, arg): self.set_step() return 1 do_s = do_step def do_next(self, arg): self.set_next(self.curframe) return 1 do_n = do_next def do_return(self, arg): self.set_return(self.curframe) return 1 do_r = do_return def do_continue(self, arg): self.set_continue() return 1 do_c = do_cont = do_continue def do_jump(self, arg): if self.curindex + 1 != len(self.stack): print >>self.stdout, "*** You can only jump within the bottom frame" return try: arg = int(arg) except ValueError: print >>self.stdout, "*** The 'jump' command requires a line number." else: try: # Do the jump, fix up our copy of the stack, and display the # new position self.curframe.f_lineno = arg self.stack[self.curindex] = self.stack[self.curindex][0], arg self.print_stack_entry(self.stack[self.curindex]) except ValueError, e: print >>self.stdout, '*** Jump failed:', e do_j = do_jump def do_debug(self, arg): sys.settrace(None) globals = self.curframe.f_globals locals = self.curframe.f_locals p = Pdb(self.completekey, self.stdin, self.stdout) p.prompt = "(%s) " % self.prompt.strip() print >>self.stdout, "ENTERING RECURSIVE DEBUGGER" sys.call_tracing(p.run, (arg, globals, locals)) print >>self.stdout, "LEAVING RECURSIVE DEBUGGER" sys.settrace(self.trace_dispatch) self.lastcmd = p.lastcmd def do_quit(self, arg): self._user_requested_quit = 1 self.set_quit() return 1 do_q = do_quit do_exit = do_quit def do_EOF(self, arg): print >>self.stdout self._user_requested_quit = 1 self.set_quit() return 1 def do_args(self, arg): f = self.curframe co = f.f_code dict = f.f_locals n = co.co_argcount if co.co_flags & 4: n = n+1 if co.co_flags & 8: n = n+1 for i in range(n): name = co.co_varnames[i] print >>self.stdout, name, '=', if name in dict: print >>self.stdout, dict[name] else: print >>self.stdout, "*** undefined ***" do_a = do_args def do_retval(self, arg): if '__return__' in self.curframe.f_locals: print >>self.stdout, self.curframe.f_locals['__return__'] else: print >>self.stdout, '*** Not yet returned!' do_rv = do_retval def _getval(self, arg): try: return eval(arg, self.curframe.f_globals, self.curframe.f_locals) except: t, v = sys.exc_info()[:2] if isinstance(t, str): exc_type_name = t else: exc_type_name = t.__name__ print >>self.stdout, '***', exc_type_name + ':', repr(v) raise def do_p(self, arg): try: print >>self.stdout, repr(self._getval(arg)) except: pass def do_pp(self, arg): try: pprint.pprint(self._getval(arg), self.stdout) except: pass def do_list(self, arg): self.lastcmd = 'list' last = None if arg: try: x = eval(arg, {}, {}) if type(x) == type(()): first, last = x first = int(first) last = int(last) if last < first: # Assume it's a count last = first + last else: first = max(1, int(x) - 5) except: print >>self.stdout, '*** Error in argument:', repr(arg) return elif self.lineno is None: first = max(1, self.curframe.f_lineno - 5) else: first = self.lineno + 1 if last is None: last = first + 10 filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: for lineno in range(first, last+1): line = linecache.getline(filename, lineno) if not line: print >>self.stdout, '[EOF]' break else: s = repr(lineno).rjust(3) if len(s) < 4: s = s + ' ' if lineno in breaklist: s = s + 'B' else: s = s + ' ' if lineno == self.curframe.f_lineno: s = s + '->' print >>self.stdout, s + '\t' + line, self.lineno = lineno except KeyboardInterrupt: pass do_l = do_list def do_whatis(self, arg): try: value = eval(arg, self.curframe.f_globals, self.curframe.f_locals) except: t, v = sys.exc_info()[:2] if type(t) == type(''): exc_type_name = t else: exc_type_name = t.__name__ print >>self.stdout, '***', exc_type_name + ':', repr(v) return code = None # Is it a function? try: code = value.func_code except: pass if code: print >>self.stdout, 'Function', code.co_name return # Is it an instance method? try: code = value.im_func.func_code except: pass if code: print >>self.stdout, 'Method', code.co_name return # None of the above... print >>self.stdout, type(value) def do_alias(self, arg): args = arg.split() if len(args) == 0: keys = self.aliases.keys() keys.sort() for alias in keys: print >>self.stdout, "%s = %s" % (alias, self.aliases[alias]) return if args[0] in self.aliases and len(args) == 1: print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]]) else: self.aliases[args[0]] = ' '.join(args[1:]) def do_unalias(self, arg): args = arg.split() if len(args) == 0: return if args[0] in self.aliases: del self.aliases[args[0]] #list of all the commands making the program resume execution. commands_resuming = ['do_continue', 'do_step', 'do_next', 'do_return', 'do_quit', 'do_jump'] # Print a traceback starting at the top stack frame. # The most recently entered frame is printed last; # this is different from dbx and gdb, but consistent with # the Python interpreter's stack trace. # It is also consistent with the up/down commands (which are # compatible with dbx and gdb: up moves towards 'main()' # and down moves towards the most recent stack frame). def print_stack_trace(self): try: for frame_lineno in self.stack: self.print_stack_entry(frame_lineno) except KeyboardInterrupt: pass def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix): frame, lineno = frame_lineno if frame is self.curframe: print >>self.stdout, '>', else: print >>self.stdout, ' ', print >>self.stdout, self.format_stack_entry(frame_lineno, prompt_prefix) # Help methods (derived from pdb.doc) def help_help(self): self.help_h() def help_h(self): print >>self.stdout, """h(elp) Without argument, print the list of available commands. With a command name as argument, print help about that command "help pdb" pipes the full documentation file to the $PAGER "help exec" gives help on the ! command""" def help_where(self): self.help_w() def help_w(self): print >>self.stdout, """w(here) Print a stack trace, with the most recent frame at the bottom. An arrow indicates the "current frame", which determines the context of most commands. 'bt' is an alias for this command.""" help_bt = help_w def help_down(self): self.help_d() def help_d(self): print >>self.stdout, """d(own) Move the current frame one level down in the stack trace (to a newer frame).""" def help_up(self): self.help_u() def help_u(self): print >>self.stdout, """u(p) Move the current frame one level up in the stack trace (to an older frame).""" def help_break(self): self.help_b() def help_b(self): print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition] With a line number argument, set a break there in the current file. With a function name, set a break at first executable line of that function. Without argument, list all breaks. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted.""" def help_clear(self): self.help_cl() def help_cl(self): print >>self.stdout, "cl(ear) filename:lineno" print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file. Note that the argument is different from previous versions of the debugger (in python distributions 1.5.1 and before) where a linenumber was used instead of either filename:lineno or breakpoint numbers.""" def help_tbreak(self): print >>self.stdout, """tbreak same arguments as break, but breakpoint is removed when first hit.""" def help_enable(self): print >>self.stdout, """enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of bp numbers.""" def help_disable(self): print >>self.stdout, """disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of bp numbers.""" def help_ignore(self): print >>self.stdout, """ignore bpnumber count Sets the ignore count for the given breakpoint number. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true.""" def help_condition(self): print >>self.stdout, """condition bpnumber str_condition str_condition is a string specifying an expression which must evaluate to true before the breakpoint is honored. If str_condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional.""" def help_step(self): self.help_s() def help_s(self): print >>self.stdout, """s(tep) Execute the current line, stop at the first possible occasion (either in a function that is called or in the current function).""" def help_next(self): self.help_n() def help_n(self): print >>self.stdout, """n(ext) Continue execution until the next line in the current function is reached or it returns.""" def help_return(self): self.help_r() def help_r(self): print >>self.stdout, """r(eturn) Continue execution until the current function returns.""" def help_continue(self): self.help_c() def help_cont(self): self.help_c() def help_c(self): print >>self.stdout, """c(ont(inue)) Continue execution, only stop when a breakpoint is encountered.""" def help_jump(self): self.help_j() def help_j(self): print >>self.stdout, """j(ump) lineno Set the next line that will be executed.""" def help_debug(self): print >>self.stdout, """debug code Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment).""" def help_list(self): self.help_l() def help_l(self): print >>self.stdout, """l(ist) [first [,last]] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count.""" def help_args(self): self.help_a() def help_a(self): print >>self.stdout, """a(rgs) Print the arguments of the current function.""" def help_p(self): print >>self.stdout, """p expression Print the value of the expression.""" def help_pp(self): print >>self.stdout, """pp expression Pretty-print the value of the expression.""" def help_exec(self): print >>self.stdout, """(!) statement Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command. To assign to a global variable you must always prefix the command with a 'global' command, e.g.: (Pdb) global list_options; list_options = ['-l'] (Pdb)""" def help_quit(self): self.help_q() def help_q(self): print >>self.stdout, """q(uit) or exit - Quit from the debugger. The program being executed is aborted.""" help_exit = help_q def help_whatis(self): print >>self.stdout, """whatis arg Prints the type of the argument.""" def help_EOF(self): print >>self.stdout, """EOF Handles the receipt of EOF as a command.""" def help_alias(self): print >>self.stdout, """alias [name [command [parameter parameter ...] ]] Creates an alias called 'name' the executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters are indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed. Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note! You *can* override internal pdb commands with aliases! Those internal commands are then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone. Some useful aliases (especially when placed in the .pdbrc file) are: #Print instance variables (usage "pi classInst") alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k] #Print instance variables in self alias ps pi self """ def help_unalias(self): print >>self.stdout, """unalias name Deletes the specified alias.""" def help_commands(self): print >>self.stdout, """commands [bpnumber] (com) ... (com) end (Pdb) Specify a list of commands for breakpoint number bpnumber. The commands themselves appear on the following lines. Type a line containing just 'end' to terminate the commands. To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands. With no bpnumber argument, commands refers to the last breakpoint set. You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution. Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint--which could have its own command list, leading to ambiguities about which list to execute. If you use the 'silent' command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you see no sign that the breakpoint was reached. """ def help_pdb(self): help() def lookupmodule(self, filename): """Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. """ if os.path.isabs(filename) and os.path.exists(filename): return filename f = os.path.join(sys.path[0], filename) if os.path.exists(f) and self.canonic(f) == self.mainpyfile: return f root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if os.path.isabs(filename): return filename for dirname in sys.path: while os.path.islink(dirname): dirname = os.readlink(dirname) fullname = os.path.join(dirname, filename) if os.path.exists(fullname): return fullname return None def _runscript(self, filename): # Start with fresh empty copy of globals and locals and tell the script # that it's being run as __main__ to avoid scripts being able to access # the pdb.py namespace. globals_ = {"__name__" : "__main__", "__file__" : filename} locals_ = globals_ # When bdb sets tracing, a number of call and line events happens # BEFORE debugger even reaches user's code (and the exact sequence of # events depends on python version). So we take special measures to # avoid stopping before we reach the main script (see user_line and # user_call for details). self._wait_for_mainpyfile = 1 self.mainpyfile = self.canonic(filename) self._user_requested_quit = 0 statement = 'execfile( "%s")' % filename self.run(statement, globals=globals_, locals=locals_) # Simplified interface def run(statement, globals=None, locals=None): Pdb().run(statement, globals, locals) def runeval(expression, globals=None, locals=None): return Pdb().runeval(expression, globals, locals) def runctx(statement, globals, locals): # B/W compatibility run(statement, globals, locals) def runcall(*args, **kwds): return Pdb().runcall(*args, **kwds) def set_trace(): Pdb().set_trace(sys._getframe().f_back) # Post-Mortem interface def post_mortem(t): p = Pdb() p.reset() while t.tb_next is not None: t = t.tb_next p.interaction(t.tb_frame, t) def pm(): post_mortem(sys.last_traceback) # Main program for testing TESTCMD = 'import x; x.main()' def test(): run(TESTCMD) # print help def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path' def main(): if not sys.argv[1:]: print "usage: pdb.py scriptfile [arg] ..." sys.exit(2) mainpyfile = sys.argv[1] # Get script filename if not os.path.exists(mainpyfile): print 'Error:', mainpyfile, 'does not exist' sys.exit(1) del sys.argv[0] # Hide "pdb.py" from argument list # Replace pdb's dir with script's dir in front of module search path. sys.path[0] = os.path.dirname(mainpyfile) # Note on saving/restoring sys.argv: it's a good idea when sys.argv was # modified by the script being debugged. It's a bad idea when it was # changed by the user from the command line. The best approach would be to # have a "restart" command which would allow explicit specification of # command line arguments. pdb = Pdb() while 1: try: pdb._runscript(mainpyfile) if pdb._user_requested_quit: break print "The program finished and will be restarted" except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. print "The program exited via sys.exit(). Exit status: ", print sys.exc_info()[1] except: traceback.print_exc() print "Uncaught exception. Entering post mortem debugging" print "Running 'cont' or 'step' will restart the program" t = sys.exc_info()[2] while t.tb_next is not None: t = t.tb_next pdb.interaction(t.tb_frame,t) print "Post mortem debugger finished. The "+mainpyfile+" will be restarted" # When invoked as main program, invoke the debugger on a script if __name__=='__main__': main()
apache-2.0
BellScurry/gem5-fault-injection
src/mem/slicc/generate/tex.py
92
2816
# Copyright (c) 1999-2008 Mark D. Hill and David A. Wood # Copyright (c) 2009 The Hewlett-Packard Development Company # 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 holders 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. from m5.util.code_formatter import code_formatter class tex_formatter(code_formatter): braced = "<>" double_braced = "<<>>" def printTexTable(sm, code): tex = tex_formatter() tex(r''' %& latex \documentclass[12pt]{article} \usepackage{graphics} \begin{document} \begin{tabular}{|l||$<<"l" * len(sm.events)>>|} \hline ''') for event in sm.events: code(r" & \rotatebox{90}{$<<event.short>>}") tex(r'\\ \hline \hline') for state in sm.states: state_str = state.short for event in sm.events: state_str += ' & ' trans = sm.get_transition(state, event) if trans: actions = trans.getActionShorthands() # FIXME: should compare index, not the string if trans.getNextStateShorthand() != state.short: nextState = trans.getNextStateShorthand() else: nextState = "" state_str += actions if nextState and actions: state_str += '/' state_str += nextState tex(r'$0 \\', state_str) tex(r''' \hline \end{tabular} \end{document} ''') code.append(tex)
bsd-3-clause
psychobaka/PatchCorral
src/data/synthesizers/rolandfantomxr/UserVoices.py
4
14785
#################################################################################################### # Copyright 2013 John Crawford # # This file is part of PatchCorral. # # PatchCorral 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. # # PatchCorral 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 PatchCorral. If not, see <http://www.gnu.org/licenses/>. #################################################################################################### ## @file # Module Information. # @date 3/10/2013 Created file. -jc # @author John Crawford NAME = 'User' PATCHES = [ ('UltimatGrand', 87, 0, 0, 'AC.PIANO', 'USER 001'), ('Strobot', 87, 0, 1, 'PULSATING', 'USER 002'), ('Full Strings', 87, 0, 2, 'STRINGS', 'USER 003'), ('The VorteX', 87, 0, 3, 'SYNTH FX', 'USER 004'), ('Purple Organ', 87, 0, 4, 'ORGAN', 'USER 005'), ('X Brs Sect 1', 87, 0, 5, 'AC.BRASS', 'USER 006'), ('FlamencoGt X', 87, 0, 6, 'AC.GUITAR', 'USER 007'), ('* EuroPhrSeq', 87, 0, 7, 'BEAT&GROOVE', 'USER 008'), ('SquareSphere', 87, 0, 8, 'PULSATING', 'USER 009'), ('HimalayaThaw', 87, 0, 9, 'BELL', 'USER 010'), ('Nu RnB Bass', 87, 0, 10, 'SYNTH BASS', 'USER 011'), ('Killerbeez', 87, 0, 11, 'TECHNO SYNTH', 'USER 012'), ('Angel Pipes', 87, 0, 12, 'OTHER SYNTH', 'USER 013'), ('GTR Heroes', 87, 0, 13, 'DIST.GUITAR', 'USER 014'), ('Symphonika', 87, 0, 14, 'ORCHESTRA', 'USER 015'), ('Cut Thru Wah', 87, 0, 15, 'EL.GUITAR', 'USER 016'), ('Mr. Nasty', 87, 0, 16, 'SYNTH BASS', 'USER 017'), ('ParisRomance', 87, 0, 17, 'ACCORDION', 'USER 018'), ('Spr SideBand', 87, 0, 18, 'BRIGHT PAD', 'USER 019'), ('Tre EP', 87, 0, 19, 'EL.PIANO', 'USER 020'), ('Epic Lead', 87, 0, 20, 'HARD LEAD', 'USER 021'), ('Motion Pad', 87, 0, 21, 'SOFT PAD', 'USER 022'), ('VKHold4Speed', 87, 0, 22, 'ORGAN', 'USER 023'), ('Double Track', 87, 0, 23, 'EL.GUITAR', 'USER 024'), ('Nylon Gtr VS', 87, 0, 24, 'AC.GUITAR', 'USER 025'), ('AirPluck', 87, 0, 25, 'MALLET', 'USER 026'), ('Nu RnB Saw 1', 87, 0, 26, 'SYNTH BASS', 'USER 027'), ('X Finger Bs2', 87, 0, 27, 'BASS', 'USER 028'), ('SolarPleXus', 87, 0, 28, 'SYNTH FX', 'USER 029'), ('Arie Piano', 87, 0, 29, 'AC.PIANO', 'USER 030'), ('StellarTreck', 87, 0, 30, 'PULSATING', 'USER 031'), ('Larsen /Aft', 87, 0, 31, 'DIST.GUITAR', 'USER 032'), ('Moody Tron', 87, 0, 32, 'STRINGS', 'USER 033'), ('Magic Wave', 87, 0, 33, 'SYNTH FX', 'USER 034'), ('DigimaX', 87, 0, 34, 'OTHER SYNTH', 'USER 035'), ('X Perc Organ', 87, 0, 35, 'ORGAN', 'USER 036'), ('Mini Growl', 87, 0, 36, 'SOFT LEAD', 'USER 037'), ('Snappy Clav', 87, 0, 37, 'KEYBOARDS', 'USER 038'), ('Staccato VS', 87, 0, 38, 'STRINGS', 'USER 039'), ('Life-on', 87, 0, 39, 'BRIGHT PAD', 'USER 040'), ('Powerline', 87, 0, 40, 'SYNTH BASS', 'USER 041'), ('Disto Stab !', 87, 0, 41, 'HIT&STAB', 'USER 042'), ('Piano Oz', 87, 0, 42, 'AC.PIANO', 'USER 043'), ('Space & Time', 87, 0, 43, 'PULSATING', 'USER 044'), ('Cello', 87, 0, 44, 'STRINGS', 'USER 045'), ('CerealKiller', 87, 0, 45, 'SYNTH FX', 'USER 046'), ('EP Belle', 87, 0, 46, 'EL.PIANO', 'USER 047'), ('Trancy X', 87, 0, 47, 'OTHER SYNTH', 'USER 048'), ('HimalayaPipe', 87, 0, 48, 'FLUTE', 'USER 049'), ('JP8000 Brass', 87, 0, 49, 'SYNTH BRASS', 'USER 050'), ('WithALtlHelp', 87, 0, 50, 'AC.GUITAR', 'USER 051'), ('Strobe X', 87, 0, 51, 'PULSATING', 'USER 052'), ('Trancepire', 87, 0, 52, 'TECHNO SYNTH', 'USER 053'), ('TubyRuesday', 87, 0, 53, 'BELL', 'USER 054'), ('Exhale', 87, 0, 54, 'OTHER SYNTH', 'USER 055'), ('Searing COSM', 87, 0, 55, 'DIST.GUITAR', 'USER 056'), ('Follow', 87, 0, 56, 'SOFT PAD', 'USER 057'), ('Grand Pipe', 87, 0, 57, 'ORGAN', 'USER 058'), ('Sad ceremony', 87, 0, 58, 'VOX', 'USER 059'), ('BodyElectric', 87, 0, 59, 'HARD LEAD', 'USER 060'), ('Doubled Bass', 87, 0, 60, 'BASS', 'USER 061'), ('Xtrem Sine', 87, 0, 61, 'SOFT LEAD', 'USER 062'), ('Mod Chord', 87, 0, 62, 'HIT&STAB', 'USER 063'), ('Filament', 87, 0, 63, 'SYNTH BASS', 'USER 064'), ('SuperSawSlow', 87, 0, 64, 'OTHER SYNTH', 'USER 065'), ('FS Wurly', 87, 0, 65, 'EL.PIANO', 'USER 066'), ('Mash Pad', 87, 0, 66, 'BRIGHT PAD', 'USER 067'), ('Vocastic', 87, 0, 67, 'PULSATING', 'USER 068'), ('Bon Voyage', 87, 0, 68, 'HARD LEAD', 'USER 069'), ('Visionary', 87, 0, 69, 'BRIGHT PAD', 'USER 070'), ('So true...', 87, 0, 70, 'AC.PIANO', 'USER 071'), ('Are U ready?', 87, 0, 71, 'PULSATING', 'USER 072'), ('Mellow Tron', 87, 0, 72, 'STRINGS', 'USER 073'), ('Shangri-La', 87, 0, 73, 'SYNTH FX', 'USER 074'), ('BluesHrp V/S', 87, 0, 74, 'HARMONICA', 'USER 075'), ('EuronalSynth', 87, 0, 75, 'SOFT LEAD', 'USER 076'), ('Alto Sax', 87, 0, 76, 'SAX', 'USER 077'), ('SBF Nozer', 87, 0, 77, 'TECHNO SYNTH', 'USER 078'), ('Nu Romance', 87, 0, 78, 'OTHER SYNTH', 'USER 079'), ('Ring Worldz', 87, 0, 79, 'BRIGHT PAD', 'USER 080'), ('Rezo Sync', 87, 0, 80, 'HARD LEAD', 'USER 081'), ('Over-D6', 87, 0, 81, 'KEYBOARDS', 'USER 082'), ('Orange Skin', 87, 0, 82, 'HIT&STAB', 'USER 083'), ('Atk Flute', 87, 0, 83, 'FLUTE', 'USER 084'), ('* FiestaBeat', 87, 0, 84, 'BEAT&GROOVE', 'USER 085'), ('Lounge Kit', 87, 0, 85, 'COMBINATION', 'USER 086'), ('Galaxadin', 87, 0, 86, 'PULSATING', 'USER 087'), ('Tornrubber', 87, 0, 87, 'SYNTH BASS', 'USER 088'), ('Comp Stl Gtr', 87, 0, 88, 'AC.GUITAR', 'USER 089'), ('Pop Brs Stac', 87, 0, 89, 'AC.BRASS', 'USER 090'), ('Sweet House', 87, 0, 90, 'TECHNO SYNTH', 'USER 091'), ('Celebrated', 87, 0, 91, 'SYNTH FX', 'USER 092'), ('Digitvox', 87, 0, 92, 'BRIGHT PAD', 'USER 093'), ('Viola', 87, 0, 93, 'STRINGS', 'USER 094'), ('Optik\'Synth', 87, 0, 94, 'HARD LEAD', 'USER 095'), ('Crystal EP', 87, 0, 95, 'EL.PIANO', 'USER 096'), ('xcultural', 87, 0, 96, 'COMBINATION', 'USER 097'), ('Control Room', 87, 0, 97, 'SYNTH FX', 'USER 098'), ('Pearly Harp', 87, 0, 98, 'PLUCKED', 'USER 099'), ('Machine Str', 87, 0, 99, 'STRINGS', 'USER 100'), ('X Mute Bass', 87, 0, 100, 'BASS', 'USER 101'), ('Bass Drive', 87, 0, 101, 'SYNTH BASS', 'USER 102'), ('Dance Steam', 87, 0, 102, 'HIT&STAB', 'USER 103'), ('Riven Pad', 87, 0, 103, 'SOFT PAD', 'USER 104'), ('Vint Clavier', 87, 0, 104, 'OTHER SYNTH', 'USER 105'), ('Jazz Guitar', 87, 0, 105, 'EL.GUITAR', 'USER 106'), ('When I\'m 64', 87, 0, 106, 'COMBINATION', 'USER 107'), ('SideBandBell', 87, 0, 107, 'BELL', 'USER 108'), ('D n\' Bass', 87, 0, 108, 'SYNTH BASS', 'USER 109'), ('La Seine', 87, 0, 109, 'ACCORDION', 'USER 110'), ('InfinitePhsr', 87, 0, 110, 'BRIGHT PAD', 'USER 111'), ('Wired Synth', 87, 0, 111, 'OTHER SYNTH', 'USER 112'), ('5th Pad X', 87, 0, 112, 'SOFT PAD', 'USER 113'), ('FS SoapOpera', 87, 0, 113, 'ORGAN', 'USER 114'), ('NylonGt /HO', 87, 0, 114, 'AC.GUITAR', 'USER 115'), ('Dark Grand', 87, 0, 115, 'AC.PIANO', 'USER 116'), ('Auto Sync', 87, 0, 116, 'PULSATING', 'USER 117'), ('Film Cue', 87, 0, 117, 'VOX', 'USER 118'), ('Violin', 87, 0, 118, 'STRINGS', 'USER 119'), ('Minty Fresh', 87, 0, 119, 'PULSATING', 'USER 120'), ('StakDraw Org', 87, 0, 120, 'ORGAN', 'USER 121'), ('F.Horns Sect', 87, 0, 121, 'AC.BRASS', 'USER 122'), ('Wind & Str 1', 87, 0, 122, 'ORCHESTRA', 'USER 123'), ('FS 12str Gtr', 87, 0, 123, 'AC.GUITAR', 'USER 124'), ('Comp Picker', 87, 0, 124, 'BASS', 'USER 125'), ('eXisDance', 87, 0, 125, 'PULSATING', 'USER 126'), ('Dreaming Box', 87, 0, 126, 'BELL', 'USER 127'), ('Andes Mood', 87, 0, 127, 'FLUTE', 'USER 128'), ('Dust Bass', 87, 1, 0, 'SYNTH BASS', 'USER 129'), ('Survivoz', 87, 1, 1, 'BRIGHT PAD', 'USER 130'), ('Backing PhEP', 87, 1, 2, 'EL.PIANO', 'USER 131'), ('Tutti', 87, 1, 3, 'HIT&STAB', 'USER 132'), ('ActualAnalog', 87, 1, 4, 'HARD LEAD', 'USER 133'), ('TrnsSweepPad', 87, 1, 5, 'SOFT PAD', 'USER 134'), ('Ivan\'s', 87, 1, 6, 'TECHNO SYNTH', 'USER 135'), ('Triple X', 87, 1, 7, 'OTHER SYNTH', 'USER 136'), ('DelicatePizz', 87, 1, 8, 'STRINGS', 'USER 137'), ('SubOscar', 87, 1, 9, 'SYNTH BASS', 'USER 138'), ('FS Sitar 1', 87, 1, 10, 'PLUCKED', 'USER 139'), ('Punker 1', 87, 1, 11, 'DIST.GUITAR', 'USER 140'), ('Ooh La La', 87, 1, 12, 'BRIGHT PAD', 'USER 141'), ('Solo Tb', 87, 1, 13, 'AC.BRASS', 'USER 142'), ('Psycho EP', 87, 1, 14, 'EL.PIANO', 'USER 143'), ('SBF Lead', 87, 1, 15, 'HARD LEAD', 'USER 144'), ('Flange Dream', 87, 1, 16, 'SOFT PAD', 'USER 145'), ('X Picked Bs', 87, 1, 17, 'BASS', 'USER 146'), ('Classic Lead', 87, 1, 18, 'HARD LEAD', 'USER 147'), ('LongDistance', 87, 1, 19, 'ETHNIC', 'USER 148'), ('X Pure Grand', 87, 1, 20, 'AC.PIANO', 'USER 149'), ('Da Chronic', 87, 1, 21, 'SYNTH BASS', 'USER 150'), ('Tenor Sax', 87, 1, 22, 'SAX', 'USER 151'), ('Dancefloor', 87, 1, 23, 'PULSATING', 'USER 152'), ('Shroomy', 87, 1, 24, 'TECHNO SYNTH', 'USER 153'), ('Ethno Keys', 87, 1, 25, 'MALLET', 'USER 154'), ('Simply Nasty', 87, 1, 26, 'HARD LEAD', 'USER 155'), ('Beat Vox', 87, 1, 27, 'VOX', 'USER 156'), ('AMP EP', 87, 1, 28, 'EL.PIANO', 'USER 157'), ('Contrabass', 87, 1, 29, 'STRINGS', 'USER 158'), ('Bend SynBrs', 87, 1, 30, 'SYNTH BRASS', 'USER 159'), ('Modular', 87, 1, 31, 'OTHER SYNTH', 'USER 160'), ('Dirty D/A', 87, 1, 32, 'SOFT LEAD', 'USER 161'), ('Tekno Tone', 87, 1, 33, 'PULSATING', 'USER 162'), ('Nu Bace', 87, 1, 34, 'SYNTH BASS', 'USER 163'), ('Mod Scanner', 87, 1, 35, 'SYNTH FX', 'USER 164'), ('Fantomas Pad', 87, 1, 36, 'PULSATING', 'USER 165'), ('FS Fretnot 1', 87, 1, 37, 'BASS', 'USER 166'), ('Solo Tp', 87, 1, 38, 'AC.BRASS', 'USER 167'), ('Farewell', 87, 1, 39, 'ORCHESTRA', 'USER 168'), ('Wezcoast', 87, 1, 40, 'HARD LEAD', 'USER 169'), ('FS Flute', 87, 1, 41, 'FLUTE', 'USER 170'), ('Theramax', 87, 1, 42, 'SOFT LEAD', 'USER 171'), ('Mojo Man', 87, 1, 43, 'HIT&STAB', 'USER 172'), ('Solo Sop Sax', 87, 1, 44, 'SAX', 'USER 173'), ('Timeline', 87, 1, 45, 'BRIGHT PAD', 'USER 174'), ('Wet TC', 87, 1, 46, 'EL.GUITAR', 'USER 175'), ('Underneath', 87, 1, 47, 'SYNTH BASS', 'USER 176'), ('Lazer Points', 87, 1, 48, 'SYNTH FX', 'USER 177'), ('Wire Sync', 87, 1, 49, 'HARD LEAD', 'USER 178'), ('JD-800 Piano', 87, 1, 50, 'AC.PIANO', 'USER 179'), ('Cross Talk', 87, 1, 51, 'PULSATING', 'USER 180'), ('Nu Pad', 87, 1, 52, 'PULSATING', 'USER 181'), ('Phase Clavi', 87, 1, 53, 'KEYBOARDS', 'USER 182'), ('Anadroid', 87, 1, 54, 'TECHNO SYNTH', 'USER 183'), ('Phono Organ', 87, 1, 55, 'ORGAN', 'USER 184'), ('Dirt & Grime', 87, 1, 56, 'SYNTH BASS', 'USER 185'), ('Rockin\' Dly', 87, 1, 57, 'DIST.GUITAR', 'USER 186'), ('Mr. Fourier', 87, 1, 58, 'PULSATING', 'USER 187'), ('NewAge Frtls', 87, 1, 59, 'BASS', 'USER 188'), ('Evolution X', 87, 1, 60, 'SOFT PAD', 'USER 189'), ('Baritone Sax', 87, 1, 61, 'SAX', 'USER 190'), ('Hall Oboe', 87, 1, 62, 'WIND', 'USER 191'), ('TB-Sequence', 87, 1, 63, 'OTHER SYNTH', 'USER 192'), ('GuitaratiuG', 87, 1, 64, 'EL.GUITAR', 'USER 193'), ('Alpha Hoover', 87, 1, 65, 'TECHNO SYNTH', 'USER 194'), ('ChoruSE ONE', 87, 1, 66, 'SYNTH BASS', 'USER 195'), ('Sinetific', 87, 1, 67, 'SOFT LEAD', 'USER 196'), ('Wired Rez', 87, 1, 68, 'TECHNO SYNTH', 'USER 197'), ('FS Marimba', 87, 1, 69, 'MALLET', 'USER 198'), ('SlippingSaws', 87, 1, 70, 'HARD LEAD', 'USER 199'), ('Choral Sweep', 87, 1, 71, 'VOX', 'USER 200'), ('Flugel Horn', 87, 1, 72, 'AC.BRASS', 'USER 201'), ('TDreamTouch', 87, 1, 73, 'OTHER SYNTH', 'USER 202'), ('Polar Morn', 87, 1, 74, 'BRIGHT PAD', 'USER 203'), ('Drop Bass', 87, 1, 75, 'SYNTH BASS', 'USER 204'), ('Pop Orch', 87, 1, 76, 'ORCHESTRA', 'USER 205'), ('Nyl-Intro', 87, 1, 77, 'AC.GUITAR', 'USER 206'), ('Morph Filter', 87, 1, 78, 'SOFT PAD', 'USER 207'), ('Kinda Kurt', 87, 1, 79, 'EL.GUITAR', 'USER 208'), ('Downright Bs', 87, 1, 80, 'BASS', 'USER 209'), ('50`SteelDrms', 87, 1, 81, 'MALLET', 'USER 210'), ('Reso SynBass', 87, 1, 82, 'SYNTH BASS', 'USER 211'), ('South Pole', 87, 1, 83, 'SYNTH FX', 'USER 212'), ('Studio Grand', 87, 1, 84, 'AC.PIANO', 'USER 213'), ('VirtualHuman', 87, 1, 85, 'PULSATING', 'USER 214'), ('Darmstrat X', 87, 1, 86, 'DIST.GUITAR', 'USER 215'), ('Ending Scene', 87, 1, 87, 'ORCHESTRA', 'USER 216'), ('Distro FXM', 87, 1, 88, 'HARD LEAD', 'USER 217'), ('FullDraw Org', 87, 1, 89, 'ORGAN', 'USER 218'), ('Alien Voice', 87, 1, 90, 'SYNTH FX', 'USER 219'), ('Stadium SBF', 87, 1, 91, 'OTHER SYNTH', 'USER 220'), ('Good Old Day', 87, 1, 92, 'WIND', 'USER 221'), ('FS Slap Bass', 87, 1, 93, 'BASS', 'USER 222'), ('Skydiver', 87, 1, 94, 'PLUCKED', 'USER 223'), ('Harmon Mute', 87, 1, 95, 'AC.BRASS', 'USER 224'), ('PeakArpSine', 87, 1, 96, 'SOFT LEAD', 'USER 225'), ('Alien Bubble', 87, 1, 97, 'TECHNO SYNTH', 'USER 226'), ('Twin StratsB', 87, 1, 98, 'EL.GUITAR', 'USER 227'), ('Orbiting', 87, 1, 99, 'PULSATING', 'USER 228'), ('Sahara Str', 87, 1, 100, 'STRINGS', 'USER 229'), ('Fundamental', 87, 1, 101, 'SYNTH BASS', 'USER 230'), ('SA Dance Pno', 87, 1, 102, 'AC.PIANO', 'USER 231'), ('Dirty Saw', 87, 1, 103, 'HARD LEAD', 'USER 232'), ('X-panda', 87, 1, 104, 'OTHER SYNTH', 'USER 233'), ('Saturn Siren', 87, 1, 105, 'BRIGHT PAD', 'USER 234'), ('Orch & Horns', 87, 1, 106, 'ORCHESTRA', 'USER 235'), ('Amore Story', 87, 1, 107, 'AC.GUITAR', 'USER 236'), ('Raven Chord', 87, 1, 108, 'TECHNO SYNTH', 'USER 237'), ('Soulfinger', 87, 1, 109, 'BASS', 'USER 238'), ('Landing Pad', 87, 1, 110, 'SYNTH FX', 'USER 239'), ('Virtual RnBs', 87, 1, 111, 'SYNTH BASS', 'USER 240'), ('Clarence.net', 87, 1, 112, 'WIND', 'USER 241'), ('PanningFrmnt', 87, 1, 113, 'PULSATING', 'USER 242'), ('Quiet River', 87, 1, 114, 'PLUCKED', 'USER 243'), ('OB Slow Str', 87, 1, 115, 'SOFT PAD', 'USER 244'), ('FS Loud Gtr', 87, 1, 116, 'DIST.GUITAR', 'USER 245'), ('X Finger Bs1', 87, 1, 117, 'BASS', 'USER 246'), ('VelPanWurly', 87, 1, 118, 'EL.PIANO', 'USER 247'), ('Syn Opera', 87, 1, 119, 'VOX', 'USER 248'), ('Modular Lead', 87, 1, 120, 'SOFT LEAD', 'USER 249'), ('With Love', 87, 1, 121, 'AC.GUITAR', 'USER 250'), ('JP-8 Phase', 87, 1, 122, 'SOFT PAD', 'USER 251'), ('Pop Brs wAtk', 87, 1, 123, 'AC.BRASS', 'USER 252'), ('Cicada Piano', 87, 1, 124, 'AC.PIANO', 'USER 253'), ('X StrSection', 87, 1, 125, 'STRINGS', 'USER 254'), ('Jupiter-X', 87, 1, 126, 'SOFT PAD', 'USER 255'), ('Bending Logo', 87, 1, 127, 'SYNTH FX', 'USER 256'), ]
gpl-3.0
zstackio/zstack-woodpecker
integrationtest/vm/zstackformation/test_create_stack_template_state_false.py
2
6471
# coding:utf-8 ''' New Integration Test for zstack cloudformation. Create Resource Stack when state of stack template is false (expected result is failed). @author: Lei Liu ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.operations.resource_stack as resource_stack_ops import zstackwoodpecker.operations.stack_template as stack_template_ops import zstackwoodpecker.operations.resource_operations as res_ops def test(): test_util.test_dsc("Test Resource template Apis") cond = res_ops.gen_query_conditions('status', '=', 'Ready') cond = res_ops.gen_query_conditions('state', '=', 'Enabled', cond) cond = res_ops.gen_query_conditions('system', '=', 'false', cond) image_queried = res_ops.query_resource(res_ops.IMAGE, cond) cond = res_ops.gen_query_conditions("category", '=', "Public") l3_queried = res_ops.query_resource(res_ops.L3_NETWORK, cond) if len(l3_queried) == 0: cond = res_ops.gen_query_conditions("category", '=', "Private") l3_queried = res_ops.query_resource(res_ops.L3_NETWORK, cond) cond = res_ops.gen_query_conditions('state', '=', 'Enabled') cond = res_ops.gen_query_conditions('type', '=', 'UserVm', cond) instance_offering_queried = res_ops.query_resource( res_ops.INSTANCE_OFFERING, cond) stack_template_option = test_util.StackTemplateOption() stack_template_option.set_name("template") resource_stack_option = test_util.ResourceStackOption() resource_stack_option.set_name("Stack_test") templateContent = ''' { "ZStackTemplateFormatVersion": "2018-06-18", "Description": "Just create a flat network & VM", "Parameters": { "L3NetworkUuid":{ "Type": "String", "Label": "三层网络" }, "ImageUuid":{ "Type": "String", "Label": "镜像" }, "InstanceOfferingUuid":{ "Type": "String", "Label": "计算规格" } }, "Resources": { "VmInstance": { "Type": "ZStack::Resource::VmInstance", "Properties": { "name": "VM-STACK", "instanceOfferingUuid": {"Ref":"InstanceOfferingUuid"}, "imageUuid":{"Ref":"ImageUuid"}, "l3NetworkUuids":[{"Ref":"L3NetworkUuid"}] } } }, "Outputs": { "VmInstance": { "Value": { "Ref": "VmInstance" } } } } ''' # 1.Add template which state is false stack_template_option.set_templateContent(templateContent) stack_template = stack_template_ops.add_stack_template( stack_template_option) cond = res_ops.gen_query_conditions('uuid', '=', stack_template.uuid) stack_template_queried = res_ops.query_resource( res_ops.STACK_TEMPLATE, cond) if len(stack_template_queried) == 0: test_util.test_fail("Fail to query stack template") stack_template_option.set_state('false') new_stack_template = stack_template_ops.update_stack_template( stack_template.uuid, stack_template_option) # 2.Create a resource stack based on this template parameter = '{"L3NetworkUuid":"%s","ImageUuid":"%s","InstanceOfferingUuid":"%s"}' % (l3_queried[0].uuid, image_queried[0].uuid, instance_offering_queried[0].uuid) resource_stack_option.set_template_uuid(new_stack_template.uuid) resource_stack_option.set_parameters(parameter) try: resource_stack = resource_stack_ops.create_resource_stack( resource_stack_option) test_util.test_fail( 'Cannot create stack when stack template is disabled.') except Exception: pass # 3.Qeury this stack cond = res_ops.gen_query_conditions('name', '=', 'Stack_test') resource_stack_queried = res_ops.query_resource( res_ops.RESOURCE_STACK, cond) if len(resource_stack_queried) != 0: test_util.test_fail('Resource stack should not be existed.') stack_template_option.set_state('true') lastest_stack_template = stack_template_ops.update_stack_template( stack_template.uuid, stack_template_option) test_util.test_logger(lastest_stack_template.uuid) # 4.Set template state true resource_stack_option.set_template_uuid(lastest_stack_template.uuid) resource_stack_option.set_parameters(parameter) resource_stack_option.set_name("Stack_test") resource_stack = resource_stack_ops.create_resource_stack( resource_stack_option) cond = res_ops.gen_query_conditions('name', '=', 'Stack_test') resource_stack_queried = res_ops.query_resource( res_ops.RESOURCE_STACK, cond) if len(resource_stack_queried) == 0: test_util.test_fail('Failed to create resource stack.') cond = res_ops.gen_query_conditions('name', '=', 'VM-STACK') vm_queried = res_ops.query_resource(res_ops.VM_INSTANCE, cond) if resource_stack_queried[0].status == 'Created': if len(vm_queried) == 0: test_util.test_fail( "Fail to create all resource when " "resource stack status is Created") # 5.delete resource stack resource_stack_ops.delete_resource_stack(resource_stack.uuid) cond = res_ops.gen_query_conditions('uuid', '=', resource_stack.uuid) resource_stack_queried = res_ops.query_resource( res_ops.RESOURCE_STACK, cond) cond = res_ops.gen_query_conditions('name', '=', 'VM-STACK') vm_queried = res_ops.query_resource(res_ops.VM_INSTANCE, cond) if len(resource_stack_queried) != 0: test_util.test_fail("Fail to delete resource stack") elif len(vm_queried) != 0: test_util.test_fail( "Fail to delete resource when resource stack is deleted") # 6.delete stack template stack_template_ops.delete_stack_template(lastest_stack_template.uuid) stack_template_queried = res_ops.query_resource( res_ops.STACK_TEMPLATE, cond) if len(stack_template_queried) != 0: test_util.test_fail("Fail to query stack template") test_util.test_pass('Create Resource Stack Test Success') # Will be called only if exception happens in test(). def error_cleanup(): print "Ignore cleanup"
apache-2.0
popgengui/negui
supplementary_scripts/compare.sim.to.genepop.output.py
1
2350
''' Description Check for each generation n, compare the list of individual IDs in the sim file, to the list of individual IDs in the nth pop in the genepop file ''' from __future__ import print_function __filename__ ="" __date__ = "20160825" __author__ = "Ted Cosart<ted.cosart@umontana.edu>" import sys import supp_utils as supu try: import pgutilities as pgut except ImportError as oie: supu.add_main_pg_dir_to_path() import pgutilities as pgut #end try...except SIMCOLINDIV=2 SIMCOLGEN=0 def getsiminfo( s_simfile ): dli_indivbygen={} osimfile=open( s_simfile, 'r' ) i_entrycount=0 for s_line in osimfile: i_entrycount+=1 ls_vals=s_line.strip().split( " " ) gennum=ls_vals[SIMCOLGEN] indivnum=ls_vals[ SIMCOLINDIV ] if gennum in dli_indivbygen: dli_indivbygen[gennum].append( indivnum ) else: dli_indivbygen[gennum]=[ indivnum ] #end if old gennum else new #end for each line osimfile.close() return ( i_entrycount, dli_indivbygen ) #end getgeninfo def compare_genepop_file( s_genfile, s_popfile ): i_entrycount, dli_indivbygen=getsiminfo( s_genfile ) i_genepop_indiv_entries=0 currgen=-1 countindivcorrect=0 countindivwrong=0 countlocicorrect=0 countlociwrong=0 opopfile=open( s_popfile, 'r' ) i_poplinecount=0 i_pop_loci_count=0 for s_line in opopfile: i_poplinecount+=1 ls_vals=s_line.strip().split( "," ) ispopline=( ls_vals[0]=="pop" ) if ispopline: currgen=currgen + 1 elif currgen == -1 and i_poplinecount > 1: i_pop_loci_count+=1 elif currgen >= 0 and not( ispopline ): indiv=ls_vals[0] b_indivisin=( indiv in dli_indivbygen[ str( currgen ) ] ) if b_indivisin: countindivcorrect+=1 #end if indiv in else not #end if in pop sections and not pop line #end for each line in file opopfile.close() print ( "total sim file entries: " + str( i_entrycount ) ) print ( "correct indiv-gen associations: " + str( countindivcorrect ) ) print ( "wrong indiv-gen associations: " + str( countindivwrong ) ) #end compare_genepop_file if __name__=="__main__": lsargs=[ "sim file", "genepop file" ] s_usage=pgut.do_usage_check ( sys.argv, lsargs ) if s_usage: print( s_usage ) sys.exit() #end if usage s_simfile=sys.argv[1] s_popfile=sys.argv[2] compare_genepop_file( s_simfile, s_popfile ) #end if name is "main"
agpl-3.0
zeptonaut/catapult
dashboard/dashboard/models/bug_data.py
5
1524
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """The database models for bug data.""" import logging from google.appengine.ext import ndb BUG_STATUS_OPENED = 'opened' BUG_STATUS_CLOSED = 'closed' BUG_STATUS_RECOVERED = 'recovered' BISECT_STATUS_STARTED = 'started' BISECT_STATUS_COMPLETED = 'completed' BISECT_STATUS_FAILED = 'failed' class Bug(ndb.Model): """Information about a bug created in issue tracker. Keys for Bug entities will be in the form ndb.Key('Bug', <bug_id>). """ status = ndb.StringProperty( default=BUG_STATUS_OPENED, choices=[ BUG_STATUS_OPENED, BUG_STATUS_CLOSED, BUG_STATUS_RECOVERED, ], indexed=True) # Status of the latest bisect run for this bug # (e.g., started, failed, completed). latest_bisect_status = ndb.StringProperty( default=None, choices=[ BISECT_STATUS_STARTED, BISECT_STATUS_COMPLETED, BISECT_STATUS_FAILED, ], indexed=True) # The time that the Bug entity was created. timestamp = ndb.DateTimeProperty(indexed=True, auto_now_add=True) def SetBisectStatus(bug_id, status): """Sets bisect status for bug with bug_id.""" if bug_id is None or bug_id < 0: return bug = ndb.Key('Bug', int(bug_id)).get() if bug: bug.latest_bisect_status = status bug.put() else: logging.error('Bug %s does not exist.', bug_id)
bsd-3-clause
ticosax/opbeat_python
opbeat/contrib/django/middleware/__init__.py
2
6174
""" opbeat.contrib.django.middleware ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011-2012 Opbeat Large portions are :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import logging import threading from django.conf import settings as django_settings try: from importlib import import_module except ImportError: from django.utils.importlib import import_module from opbeat.contrib.django.models import client, get_client from opbeat.utils import disabled_due_to_debug, get_name_from_func from opbeat.utils import wrapt def _is_ignorable_404(uri): """ Returns True if the given request *shouldn't* notify the site managers. """ urls = getattr(django_settings, 'IGNORABLE_404_URLS', ()) return any(pattern.search(uri) for pattern in urls) class Opbeat404CatchMiddleware(object): def process_response(self, request, response): if (response.status_code != 404 or _is_ignorable_404(request.get_full_path())): return response data = client.get_data_from_request(request) data.update({ 'level': logging.INFO, 'logger': 'http404', }) result = client.capture( 'Message', param_message={ 'message': 'Page Not Found: %s', 'params': [request.build_absolute_uri()] }, data=data ) request.opbeat = { 'app_id': data.get('app_id', client.app_id), 'id': client.get_ident(result), } return response def get_name_from_middleware(wrapped, instance): name = [type(instance).__name__, wrapped.__name__] if type(instance).__module__: name = [type(instance).__module__] + name return '.'.join(name) def process_request_wrapper(wrapped, instance, args, kwargs): response = wrapped(*args, **kwargs) try: if response is not None: request = args[0] request._opbeat_transaction_name = get_name_from_middleware( wrapped, instance ) finally: return response def process_response_wrapper(wrapped, instance, args, kwargs): response = wrapped(*args, **kwargs) try: request, original_response = args # if there's no view_func on the request, and this middleware created # a new response object, it's logged as the responsible transaction # name if (not hasattr(request, '_opbeat_view_func') and response is not original_response): request._opbeat_transaction_name = get_name_from_middleware( wrapped, instance ) finally: return response class OpbeatAPMMiddleware(object): _opbeat_instrumented = False _instrumenting_lock = threading.Lock() def __init__(self): self.client = get_client() if not self._opbeat_instrumented: with self._instrumenting_lock: if not self._opbeat_instrumented: if self.client.instrument_django_middleware: self.instrument_middlewares() OpbeatAPMMiddleware._opbeat_instrumented = True def instrument_middlewares(self): for middleware_path in django_settings.MIDDLEWARE_CLASSES: module_path, class_name = middleware_path.rsplit('.', 1) try: module = import_module(module_path) middleware_class = getattr(module, class_name) if middleware_class == type(self): # don't instrument ourselves continue if hasattr(middleware_class, 'process_request'): wrapt.wrap_function_wrapper( middleware_class, 'process_request', process_request_wrapper, ) if hasattr(middleware_class, 'process_response'): wrapt.wrap_function_wrapper( middleware_class, 'process_response', process_response_wrapper, ) except ImportError: client.logger.info( "Can't instrument middleware %s", middleware_path ) def process_request(self, request): if not disabled_due_to_debug( getattr(django_settings, 'OPBEAT', {}), django_settings.DEBUG ): self.client.begin_transaction("web.django") def process_view(self, request, view_func, view_args, view_kwargs): request._opbeat_view_func = view_func def process_response(self, request, response): try: if hasattr(response, 'status_code'): if getattr(request, '_opbeat_view_func', False): view_func = get_name_from_func( request._opbeat_view_func) else: view_func = getattr( request, '_opbeat_transaction_name', '' ) status_code = response.status_code self.client.end_transaction(view_func, status_code) except Exception: self.client.error_logger.error( 'Exception during timing of request', exc_info=True, ) return response class OpbeatResponseErrorIdMiddleware(object): """ Appends the X-Opbeat-ID response header for referencing a message within the Opbeat datastore. """ def process_response(self, request, response): if not getattr(request, 'opbeat', None): return response response['X-Opbeat-ID'] = request.opbeat['id'] return response class OpbeatLogMiddleware(object): # Create a thread local variable to store the session in for logging thread = threading.local() def process_request(self, request): self.thread.request = request
bsd-3-clause
BoPeng/simuPOP
docs/applicableGen.py
1
1818
#!/usr/bin/env python # # $File: applicableGen.py $ # # This file is part of simuPOP, a forward-time population genetics # simulation environment. Please visit http://simupop.sourceforge.net # for details. # # Copyright (C) 2004 - 2010 Bo Peng (bpeng@mdanderson.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/>. # # This script is an example in the simuPOP user's guide. Please refer to # the user's guide (http://simupop.sourceforge.net/manual) for a detailed # description of this example. # import simuPOP as sim pop = sim.Population(1000, loci=[20]) pop.evolve( initOps=[ sim.InitSex(), sim.InitGenotype(freq=[0.8, 0.2]) ], preOps=[ sim.PyEval(r"'At the beginning of gen %d: allele Freq: %.2f\n' % (gen, alleleFreq[0][0])", at = [-10, -1]) ], matingScheme = sim.RandomMating(), postOps=[ sim.Stat(alleleFreq=0, begin=80, step=10), sim.PyEval(r"'At the end of gen %d: allele freq: %.2f\n' % (gen, alleleFreq[0][0])", begin=80, step=10), sim.PyEval(r"'At the end of gen %d: allele Freq: %.2f\n' % (gen, alleleFreq[0][0])", at = [-10, -1]) ], finalOps=sim.SavePopulation(output='sample.pop'), gen=100 )
gpl-2.0
winglink/rectangle
Tools/LogAnalyzer/tests/TestIMUMatch.py
61
3781
from LogAnalyzer import Test,TestResult import DataflashLog from math import sqrt class TestIMUMatch(Test): '''test for empty or near-empty logs''' def __init__(self): Test.__init__(self) self.name = "IMU Mismatch" def run(self, logdata, verbose): #tuning parameters: warn_threshold = .75 fail_threshold = 1.5 filter_tc = 5.0 self.result = TestResult() self.result.status = TestResult.StatusType.GOOD if ("IMU" in logdata.channels) and (not "IMU2" in logdata.channels): self.result.status = TestResult.StatusType.NA self.result.statusMessage = "No IMU2" return if (not "IMU" in logdata.channels) or (not "IMU2" in logdata.channels): self.result.status = TestResult.StatusType.UNKNOWN self.result.statusMessage = "No IMU log data" return imu1 = logdata.channels["IMU"] imu2 = logdata.channels["IMU2"] imu1_timems = imu1["TimeMS"].listData imu1_accx = imu1["AccX"].listData imu1_accy = imu1["AccY"].listData imu1_accz = imu1["AccZ"].listData imu2_timems = imu2["TimeMS"].listData imu2_accx = imu2["AccX"].listData imu2_accy = imu2["AccY"].listData imu2_accz = imu2["AccZ"].listData imu1 = [] imu2 = [] for i in range(len(imu1_timems)): imu1.append({ 't': imu1_timems[i][1]*1.0E-3, 'x': imu1_accx[i][1], 'y': imu1_accy[i][1], 'z': imu1_accz[i][1]}) for i in range(len(imu2_timems)): imu2.append({ 't': imu2_timems[i][1]*1.0E-3, 'x': imu2_accx[i][1], 'y': imu2_accy[i][1], 'z': imu2_accz[i][1]}) imu1.sort(key=lambda x: x['t']) imu2.sort(key=lambda x: x['t']) imu2_index = 0 last_t = None xdiff_filtered = 0 ydiff_filtered = 0 zdiff_filtered = 0 max_diff_filtered = 0 for i in range(len(imu1)): #find closest imu2 value t = imu1[i]['t'] dt = 0 if last_t is None else t-last_t dt=min(dt,.1) next_imu2 = None for i in range(imu2_index,len(imu2)): next_imu2 = imu2[i] imu2_index=i if next_imu2['t'] >= t: break prev_imu2 = imu2[imu2_index-1] closest_imu2 = next_imu2 if abs(next_imu2['t']-t)<abs(prev_imu2['t']-t) else prev_imu2 xdiff = imu1[i]['x']-closest_imu2['x'] ydiff = imu1[i]['y']-closest_imu2['y'] zdiff = imu1[i]['z']-closest_imu2['z'] xdiff_filtered += (xdiff-xdiff_filtered)*dt/filter_tc ydiff_filtered += (ydiff-ydiff_filtered)*dt/filter_tc zdiff_filtered += (zdiff-zdiff_filtered)*dt/filter_tc diff_filtered = sqrt(xdiff_filtered**2+ydiff_filtered**2+zdiff_filtered**2) max_diff_filtered = max(max_diff_filtered,diff_filtered) #print max_diff_filtered last_t = t if max_diff_filtered > fail_threshold: self.result.statusMessage = "Check vibration or accelerometer calibration. (Mismatch: %.2f, WARN: %.2f, FAIL: %.2f)" % (max_diff_filtered,warn_threshold,fail_threshold) self.result.status = TestResult.StatusType.FAIL elif max_diff_filtered > warn_threshold: self.result.statusMessage = "Check vibration or accelerometer calibration. (Mismatch: %.2f, WARN: %.2f, FAIL: %.2f)" % (max_diff_filtered,warn_threshold,fail_threshold) self.result.status = TestResult.StatusType.WARN else: self.result.statusMessage = "(Mismatch: %.2f, WARN: %.2f, FAIL: %.2f)" % (max_diff_filtered,warn_threshold, fail_threshold)
gpl-3.0
D4wN/brickv
src/brickv/plugin_system/plugins/red/program_page_shell.py
1
10104
# -*- coding: utf-8 -*- """ RED Plugin Copyright (C) 2014-2015 Matthias Bolte <matthias@tinkerforge.com> Copyright (C) 2014 Olaf Lüke <olaf@tinkerforge.com> program_page_shell.py: Program Wizard Shell Page 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ from brickv.plugin_system.plugins.red.program_page import ProgramPage from brickv.plugin_system.plugins.red.program_utils import * from brickv.plugin_system.plugins.red.ui_program_page_shell import Ui_ProgramPageShell from brickv.plugin_system.plugins.red.script_manager import check_script_result def get_shell_versions(script_manager, callback): def cb_versions(result): okay, _ = check_script_result(result) if okay: try: version = (' '.join(result.stdout.split('\n')[0].split(' ')[:-1])).replace('version ', '') callback([ExecutableVersion('/bin/bash', version)]) return except: pass # Could not get versions, we assume that some version of bash is installed callback([ExecutableVersion('/bin/bash', 'bash')]) script_manager.execute_script('shell_versions', cb_versions) class ProgramPageShell(ProgramPage, Ui_ProgramPageShell): def __init__(self, title_prefix=''): ProgramPage.__init__(self) self.setupUi(self) self.language = Constants.LANGUAGE_SHELL self.setTitle('{0}{1} Configuration'.format(title_prefix, Constants.language_display_names[self.language])) self.registerField('shell.version', self.combo_version) self.registerField('shell.start_mode', self.combo_start_mode) self.registerField('shell.script_file', self.combo_script_file, 'currentText') self.registerField('shell.command', self.edit_command) self.registerField('shell.working_directory', self.combo_working_directory, 'currentText') self.combo_start_mode.currentIndexChanged.connect(self.update_ui_state) self.combo_start_mode.currentIndexChanged.connect(self.completeChanged.emit) self.check_show_advanced_options.stateChanged.connect(self.update_ui_state) self.label_spacer.setText('') self.combo_script_file_selector = MandatoryTypedFileSelector(self, self.label_script_file, self.combo_script_file, self.label_script_file_type, self.combo_script_file_type, self.label_script_file_help) self.edit_command_checker = MandatoryLineEditChecker(self, self.label_command, self.edit_command) self.combo_working_directory_selector = MandatoryDirectorySelector(self, self.label_working_directory, self.combo_working_directory) self.option_list_editor = ListWidgetEditor(self.label_options, self.list_options, self.label_options_help, self.button_add_option, self.button_remove_option, self.button_up_option, self.button_down_option, '<new Shell option {0}>') # overrides QWizardPage.initializePage def initializePage(self): self.set_formatted_sub_title(u'Specify how the {language} program [{name}] should be executed.') self.update_combo_version('shell', self.combo_version) self.combo_start_mode.setCurrentIndex(Constants.DEFAULT_SHELL_START_MODE) self.combo_script_file_selector.reset() self.check_show_advanced_options.setChecked(False) self.combo_working_directory_selector.reset() self.option_list_editor.reset() # if a program exists then this page is used in an edit wizard program = self.wizard().program if program != None: # start mode start_mode_api_name = program.cast_custom_option_value('shell.start_mode', unicode, '<unknown>') start_mode = Constants.get_shell_start_mode(start_mode_api_name) self.combo_start_mode.setCurrentIndex(start_mode) # script file self.combo_script_file_selector.set_current_text(program.cast_custom_option_value('shell.script_file', unicode, '')) # command self.edit_command.setText(program.cast_custom_option_value('shell.command', unicode, '')) # working directory self.combo_working_directory_selector.set_current_text(program.working_directory) # options self.option_list_editor.clear() for option in program.cast_custom_option_value_list('shell.options', unicode, []): self.option_list_editor.add_item(option) self.update_ui_state() # overrides QWizardPage.isComplete def isComplete(self): executable = self.get_executable() start_mode = self.get_field('shell.start_mode') if len(executable) == 0: return False if start_mode == Constants.SHELL_START_MODE_SCRIPT_FILE and \ not self.combo_script_file_selector.complete: return False if start_mode == Constants.SHELL_START_MODE_COMMAND and \ not self.edit_command_checker.complete: return False return self.combo_working_directory_selector.complete and ProgramPage.isComplete(self) # overrides ProgramPage.update_ui_state def update_ui_state(self): start_mode = self.get_field('shell.start_mode') start_mode_script_file = start_mode == Constants.SHELL_START_MODE_SCRIPT_FILE start_mode_command = start_mode == Constants.SHELL_START_MODE_COMMAND show_advanced_options = self.check_show_advanced_options.isChecked() self.combo_script_file_selector.set_visible(start_mode_script_file) self.label_command.setVisible(start_mode_command) self.edit_command.setVisible(start_mode_command) self.label_command_help.setVisible(start_mode_command) self.combo_working_directory_selector.set_visible(show_advanced_options) self.option_list_editor.set_visible(show_advanced_options) self.label_spacer.setVisible(not show_advanced_options) self.option_list_editor.update_ui_state() def get_executable(self): return self.combo_version.itemData(self.get_field('shell.version')) def get_html_summary(self): version = self.get_field('shell.version') start_mode = self.get_field('shell.start_mode') script_file = self.get_field('shell.script_file') command = self.get_field('shell.command') working_directory = self.get_field('shell.working_directory') options = ' '.join(self.option_list_editor.get_items()) html = u'Shell Version: {0}<br/>'.format(Qt.escape(self.combo_version.itemText(version))) html += u'Start Mode: {0}<br/>'.format(Qt.escape(Constants.shell_start_mode_display_names[start_mode])) if start_mode == Constants.SHELL_START_MODE_SCRIPT_FILE: html += u'Script File: {0}<br/>'.format(Qt.escape(script_file)) elif start_mode == Constants.SHELL_START_MODE_COMMAND: html += u'Command: {0}<br/>'.format(Qt.escape(command)) html += u'Working Directory: {0}<br/>'.format(Qt.escape(working_directory)) html += u'Shell Options: {0}<br/>'.format(Qt.escape(options)) return html def get_custom_options(self): return { 'shell.start_mode': Constants.shell_start_mode_api_names[self.get_field('shell.start_mode')], 'shell.script_file': self.get_field('shell.script_file'), 'shell.command': self.get_field('shell.command'), 'shell.options': self.option_list_editor.get_items() } def get_command(self): executable = self.get_executable() arguments = self.option_list_editor.get_items() environment = [] start_mode = self.get_field('shell.start_mode') if start_mode == Constants.SHELL_START_MODE_SCRIPT_FILE: arguments.append(self.get_field('shell.script_file')) elif start_mode == Constants.SHELL_START_MODE_COMMAND: arguments.append('-c') arguments.append(self.get_field('shell.command')) working_directory = self.get_field('shell.working_directory') return executable, arguments, environment, working_directory def apply_program_changes(self): self.apply_program_custom_options_and_command_changes()
gpl-2.0
gamesbrewer/kegger
kegger/myapp/libs/werkzeug/utils.py
317
22676
# -*- coding: utf-8 -*- """ werkzeug.utils ~~~~~~~~~~~~~~ This module implements various utilities for WSGI applications. Most of them are used by the request and response wrappers but especially for middleware development it makes sense to use them without the wrappers. :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import re import os import sys import pkgutil try: from html.entities import name2codepoint except ImportError: from htmlentitydefs import name2codepoint from werkzeug._compat import unichr, text_type, string_types, iteritems, \ reraise, PY2 from werkzeug._internal import _DictAccessorProperty, \ _parse_signature, _missing _format_re = re.compile(r'\$(?:(%s)|\{(%s)\})' % (('[a-zA-Z_][a-zA-Z0-9_]*',) * 2)) _entity_re = re.compile(r'&([^;]+);') _filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]') _windows_device_files = ('CON', 'AUX', 'COM1', 'COM2', 'COM3', 'COM4', 'LPT1', 'LPT2', 'LPT3', 'PRN', 'NUL') class cached_property(object): """A decorator that converts a function into a lazy property. The function wrapped is called the first time to retrieve the result and then that calculated result is used the next time you access the value:: class Foo(object): @cached_property def foo(self): # calculate something important here return 42 The class has to have a `__dict__` in order for this property to work. """ # implementation detail: this property is implemented as non-data # descriptor. non-data descriptors are only invoked if there is # no entry with the same name in the instance's __dict__. # this allows us to completely get rid of the access function call # overhead. If one choses to invoke __get__ by hand the property # will still work as expected because the lookup logic is replicated # in __get__ for manual invocation. def __init__(self, func, name=None, doc=None): self.__name__ = name or func.__name__ self.__module__ = func.__module__ self.__doc__ = doc or func.__doc__ self.func = func def __get__(self, obj, type=None): if obj is None: return self value = obj.__dict__.get(self.__name__, _missing) if value is _missing: value = self.func(obj) obj.__dict__[self.__name__] = value return value class environ_property(_DictAccessorProperty): """Maps request attributes to environment variables. This works not only for the Werzeug request object, but also any other class with an environ attribute: >>> class Test(object): ... environ = {'key': 'value'} ... test = environ_property('key') >>> var = Test() >>> var.test 'value' If you pass it a second value it's used as default if the key does not exist, the third one can be a converter that takes a value and converts it. If it raises :exc:`ValueError` or :exc:`TypeError` the default value is used. If no default value is provided `None` is used. Per default the property is read only. You have to explicitly enable it by passing ``read_only=False`` to the constructor. """ read_only = True def lookup(self, obj): return obj.environ class header_property(_DictAccessorProperty): """Like `environ_property` but for headers.""" def lookup(self, obj): return obj.headers class HTMLBuilder(object): """Helper object for HTML generation. Per default there are two instances of that class. The `html` one, and the `xhtml` one for those two dialects. The class uses keyword parameters and positional parameters to generate small snippets of HTML. Keyword parameters are converted to XML/SGML attributes, positional arguments are used as children. Because Python accepts positional arguments before keyword arguments it's a good idea to use a list with the star-syntax for some children: >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ', ... html.a('bar', href='bar.html')]) u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>' This class works around some browser limitations and can not be used for arbitrary SGML/XML generation. For that purpose lxml and similar libraries exist. Calling the builder escapes the string passed: >>> html.p(html("<foo>")) u'<p>&lt;foo&gt;</p>' """ _entity_re = re.compile(r'&([^;]+);') _entities = name2codepoint.copy() _entities['apos'] = 39 _empty_elements = set([ 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'keygen', 'isindex', 'link', 'meta', 'param', 'source', 'wbr' ]) _boolean_attributes = set([ 'selected', 'checked', 'compact', 'declare', 'defer', 'disabled', 'ismap', 'multiple', 'nohref', 'noresize', 'noshade', 'nowrap' ]) _plaintext_elements = set(['textarea']) _c_like_cdata = set(['script', 'style']) def __init__(self, dialect): self._dialect = dialect def __call__(self, s): return escape(s) def __getattr__(self, tag): if tag[:2] == '__': raise AttributeError(tag) def proxy(*children, **arguments): buffer = '<' + tag for key, value in iteritems(arguments): if value is None: continue if key[-1] == '_': key = key[:-1] if key in self._boolean_attributes: if not value: continue if self._dialect == 'xhtml': value = '="' + key + '"' else: value = '' else: value = '="' + escape(value) + '"' buffer += ' ' + key + value if not children and tag in self._empty_elements: if self._dialect == 'xhtml': buffer += ' />' else: buffer += '>' return buffer buffer += '>' children_as_string = ''.join([text_type(x) for x in children if x is not None]) if children_as_string: if tag in self._plaintext_elements: children_as_string = escape(children_as_string) elif tag in self._c_like_cdata and self._dialect == 'xhtml': children_as_string = '/*<![CDATA[*/' + \ children_as_string + '/*]]>*/' buffer += children_as_string + '</' + tag + '>' return buffer return proxy def __repr__(self): return '<%s for %r>' % ( self.__class__.__name__, self._dialect ) html = HTMLBuilder('html') xhtml = HTMLBuilder('xhtml') def get_content_type(mimetype, charset): """Return the full content type string with charset for a mimetype. If the mimetype represents text the charset will be appended as charset parameter, otherwise the mimetype is returned unchanged. :param mimetype: the mimetype to be used as content type. :param charset: the charset to be appended in case it was a text mimetype. :return: the content type. """ if mimetype.startswith('text/') or \ mimetype == 'application/xml' or \ (mimetype.startswith('application/') and mimetype.endswith('+xml')): mimetype += '; charset=' + charset return mimetype def format_string(string, context): """String-template format a string: >>> format_string('$foo and ${foo}s', dict(foo=42)) '42 and 42s' This does not do any attribute lookup etc. For more advanced string formattings have a look at the `werkzeug.template` module. :param string: the format string. :param context: a dict with the variables to insert. """ def lookup_arg(match): x = context[match.group(1) or match.group(2)] if not isinstance(x, string_types): x = type(string)(x) return x return _format_re.sub(lookup_arg, string) def secure_filename(filename): r"""Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:`os.path.join`. The filename returned is an ASCII only string for maximum portability. On windows system the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt' The function might return an empty filename. It's your responsibility to ensure that the filename is unique and that you generate random filename if the function returned an empty one. .. versionadded:: 0.5 :param filename: the filename to secure """ if isinstance(filename, text_type): from unicodedata import normalize filename = normalize('NFKD', filename).encode('ascii', 'ignore') if not PY2: filename = filename.decode('ascii') for sep in os.path.sep, os.path.altsep: if sep: filename = filename.replace(sep, ' ') filename = str(_filename_ascii_strip_re.sub('', '_'.join( filename.split()))).strip('._') # on nt a couple of special files are present in each folder. We # have to ensure that the target file is not such a filename. In # this case we prepend an underline if os.name == 'nt' and filename and \ filename.split('.')[0].upper() in _windows_device_files: filename = '_' + filename return filename def escape(s, quote=None): """Replace special characters "&", "<", ">" and (") to HTML-safe sequences. There is a special handling for `None` which escapes to an empty string. .. versionchanged:: 0.9 `quote` is now implicitly on. :param s: the string to escape. :param quote: ignored. """ if s is None: return '' elif hasattr(s, '__html__'): return text_type(s.__html__()) elif not isinstance(s, string_types): s = text_type(s) if quote is not None: from warnings import warn warn(DeprecationWarning('quote parameter is implicit now'), stacklevel=2) s = s.replace('&', '&amp;').replace('<', '&lt;') \ .replace('>', '&gt;').replace('"', "&quot;") return s def unescape(s): """The reverse function of `escape`. This unescapes all the HTML entities, not only the XML entities inserted by `escape`. :param s: the string to unescape. """ def handle_match(m): name = m.group(1) if name in HTMLBuilder._entities: return unichr(HTMLBuilder._entities[name]) try: if name[:2] in ('#x', '#X'): return unichr(int(name[2:], 16)) elif name.startswith('#'): return unichr(int(name[1:])) except ValueError: pass return u'' return _entity_re.sub(handle_match, s) def redirect(location, code=302): """Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. """ from werkzeug.wrappers import Response display_location = escape(location) if isinstance(location, text_type): from werkzeug.urls import iri_to_uri location = iri_to_uri(location) response = Response( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.' % (escape(location), display_location), code, mimetype='text/html') response.headers['Location'] = location return response def append_slash_redirect(environ, code=301): """Redirect to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already. :param environ: the WSGI environment for the request that triggers the redirect. :param code: the status code for the redirect. """ new_path = environ['PATH_INFO'].strip('/') + '/' query_string = environ.get('QUERY_STRING') if query_string: new_path += '?' + query_string return redirect(new_path, code) def import_string(import_name, silent=False): """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `silent` is True the return value will be `None` if the import fails. :param import_name: the dotted name for the object to import. :param silent: if set to `True` import errors are ignored and `None` is returned instead. :return: imported object """ #XXX: py3 review needed assert isinstance(import_name, string_types) # force the import name to automatically convert to strings import_name = str(import_name) try: if ':' in import_name: module, obj = import_name.split(':', 1) elif '.' in import_name: module, obj = import_name.rsplit('.', 1) else: return __import__(import_name) # __import__ is not able to handle unicode strings in the fromlist # if the module is a package if PY2 and isinstance(obj, unicode): obj = obj.encode('utf-8') try: return getattr(__import__(module, None, None, [obj]), obj) except (ImportError, AttributeError): # support importing modules not yet set up by the parent module # (or package for that matter) modname = module + '.' + obj __import__(modname) return sys.modules[modname] except ImportError as e: if not silent: reraise( ImportStringError, ImportStringError(import_name, e), sys.exc_info()[2]) def find_modules(import_path, include_packages=False, recursive=False): """Find all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless `include_packages` is `True`. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module. :param import_name: the dotted name for the package to find child modules. :param include_packages: set to `True` if packages should be returned, too. :param recursive: set to `True` if recursion should happen. :return: generator """ module = import_string(import_path) path = getattr(module, '__path__', None) if path is None: raise ValueError('%r is not a package' % import_path) basename = module.__name__ + '.' for importer, modname, ispkg in pkgutil.iter_modules(path): modname = basename + modname if ispkg: if include_packages: yield modname if recursive: for item in find_modules(modname, include_packages, True): yield item else: yield modname def validate_arguments(func, args, kwargs, drop_extra=True): """Check if the function accepts the arguments and keyword arguments. Returns a new ``(args, kwargs)`` tuple that can safely be passed to the function without causing a `TypeError` because the function signature is incompatible. If `drop_extra` is set to `True` (which is the default) any extra positional or keyword arguments are dropped automatically. The exception raised provides three attributes: `missing` A set of argument names that the function expected but where missing. `extra` A dict of keyword arguments that the function can not handle but where provided. `extra_positional` A list of values that where given by positional argument but the function cannot accept. This can be useful for decorators that forward user submitted data to a view function:: from werkzeug.utils import ArgumentValidationError, validate_arguments def sanitize(f): def proxy(request): data = request.values.to_dict() try: args, kwargs = validate_arguments(f, (request,), data) except ArgumentValidationError: raise BadRequest('The browser failed to transmit all ' 'the data expected.') return f(*args, **kwargs) return proxy :param func: the function the validation is performed against. :param args: a tuple of positional arguments. :param kwargs: a dict of keyword arguments. :param drop_extra: set to `False` if you don't want extra arguments to be silently dropped. :return: tuple in the form ``(args, kwargs)``. """ parser = _parse_signature(func) args, kwargs, missing, extra, extra_positional = parser(args, kwargs)[:5] if missing: raise ArgumentValidationError(tuple(missing)) elif (extra or extra_positional) and not drop_extra: raise ArgumentValidationError(None, extra, extra_positional) return tuple(args), kwargs def bind_arguments(func, args, kwargs): """Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments `bind_arguments` returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments. :param func: the function the arguments should be bound for. :param args: tuple of positional arguments. :param kwargs: a dict of keyword arguments. :return: a :class:`dict` of bound keyword arguments. """ args, kwargs, missing, extra, extra_positional, \ arg_spec, vararg_var, kwarg_var = _parse_signature(func)(args, kwargs) values = {} for (name, has_default, default), value in zip(arg_spec, args): values[name] = value if vararg_var is not None: values[vararg_var] = tuple(extra_positional) elif extra_positional: raise TypeError('too many positional arguments') if kwarg_var is not None: multikw = set(extra) & set([x[0] for x in arg_spec]) if multikw: raise TypeError('got multiple values for keyword argument ' + repr(next(iter(multikw)))) values[kwarg_var] = extra elif extra: raise TypeError('got unexpected keyword argument ' + repr(next(iter(extra)))) return values class ArgumentValidationError(ValueError): """Raised if :func:`validate_arguments` fails to validate""" def __init__(self, missing=None, extra=None, extra_positional=None): self.missing = set(missing or ()) self.extra = extra or {} self.extra_positional = extra_positional or [] ValueError.__init__(self, 'function arguments invalid. (' '%d missing, %d additional)' % ( len(self.missing), len(self.extra) + len(self.extra_positional) )) class ImportStringError(ImportError): """Provides information about a failed :func:`import_string` attempt.""" #: String in dotted notation that failed to be imported. import_name = None #: Wrapped exception. exception = None def __init__(self, import_name, exception): self.import_name = import_name self.exception = exception msg = ( 'import_string() failed for %r. Possible reasons are:\n\n' '- missing __init__.py in a package;\n' '- package or module path not included in sys.path;\n' '- duplicated package or module name taking precedence in ' 'sys.path;\n' '- missing module, class, function or variable;\n\n' 'Debugged import:\n\n%s\n\n' 'Original exception:\n\n%s: %s') name = '' tracked = [] for part in import_name.replace(':', '.').split('.'): name += (name and '.') + part imported = import_string(name, silent=True) if imported: tracked.append((name, getattr(imported, '__file__', None))) else: track = ['- %r found in %r.' % (n, i) for n, i in tracked] track.append('- %r not found.' % name) msg = msg % (import_name, '\n'.join(track), exception.__class__.__name__, str(exception)) break ImportError.__init__(self, msg) def __repr__(self): return '<%s(%r, %r)>' % (self.__class__.__name__, self.import_name, self.exception) # circular dependencies from werkzeug.http import quote_header_value, unquote_header_value, \ cookie_date # DEPRECATED # these objects were previously in this module as well. we import # them here for backwards compatibility with old pickles. from werkzeug.datastructures import MultiDict, CombinedMultiDict, \ Headers, EnvironHeaders from werkzeug.http import parse_cookie, dump_cookie
cc0-1.0
Sweetgrassbuffalo/ReactionSweeGrass-v2
.meteor/local/dev_bundle/python/Lib/test/test_cmd_line_script.py
10
11863
# Tests command line execution of scripts import contextlib import unittest import os import os.path import test.test_support from test.script_helper import (run_python, temp_dir, make_script, compile_script, assert_python_failure, make_pkg, make_zip_script, make_zip_pkg) verbose = test.test_support.verbose example_args = ['test1', 'test2', 'test3'] test_source = """\ # Script may be run with optimisation enabled, so don't rely on assert # statements being executed def assertEqual(lhs, rhs): if lhs != rhs: raise AssertionError('%r != %r' % (lhs, rhs)) def assertIdentical(lhs, rhs): if lhs is not rhs: raise AssertionError('%r is not %r' % (lhs, rhs)) # Check basic code execution result = ['Top level assignment'] def f(): result.append('Lower level reference') f() assertEqual(result, ['Top level assignment', 'Lower level reference']) # Check population of magic variables assertEqual(__name__, '__main__') print '__file__==%r' % __file__ print '__package__==%r' % __package__ # Check the sys module import sys assertIdentical(globals(), sys.modules[__name__].__dict__) print 'sys.argv[0]==%r' % sys.argv[0] """ def _make_test_script(script_dir, script_basename, source=test_source): return make_script(script_dir, script_basename, source) def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source=test_source, depth=1): return make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source, depth) # There's no easy way to pass the script directory in to get # -m to work (avoiding that is the whole point of making # directories and zipfiles executable!) # So we fake it for testing purposes with a custom launch script launch_source = """\ import sys, os.path, runpy sys.path.insert(0, %s) runpy._run_module_as_main(%r) """ def _make_launch_script(script_dir, script_basename, module_name, path=None): if path is None: path = "os.path.dirname(__file__)" else: path = repr(path) source = launch_source % (path, module_name) return make_script(script_dir, script_basename, source) class CmdLineTest(unittest.TestCase): def _check_script(self, script_name, expected_file, expected_argv0, expected_package, *cmd_line_switches): run_args = cmd_line_switches + (script_name,) exit_code, data = run_python(*run_args) if verbose: print 'Output from test script %r:' % script_name print data self.assertEqual(exit_code, 0) printed_file = '__file__==%r' % expected_file printed_argv0 = 'sys.argv[0]==%r' % expected_argv0 printed_package = '__package__==%r' % expected_package if verbose: print 'Expected output:' print printed_file print printed_package print printed_argv0 self.assertIn(printed_file, data) self.assertIn(printed_package, data) self.assertIn(printed_argv0, data) def _check_import_error(self, script_name, expected_msg, *cmd_line_switches): run_args = cmd_line_switches + (script_name,) exit_code, data = run_python(*run_args) if verbose: print 'Output from test script %r:' % script_name print data print 'Expected output: %r' % expected_msg self.assertIn(expected_msg, data) def test_basic_script(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script') self._check_script(script_name, script_name, script_name, None) def test_script_compiled(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script') compiled_name = compile_script(script_name) os.remove(script_name) self._check_script(compiled_name, compiled_name, compiled_name, None) def test_directory(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') self._check_script(script_dir, script_name, script_dir, '') def test_directory_compiled(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') compiled_name = compile_script(script_name) os.remove(script_name) self._check_script(script_dir, compiled_name, script_dir, '') def test_directory_error(self): with temp_dir() as script_dir: msg = "can't find '__main__' module in %r" % script_dir self._check_import_error(script_dir, msg) def test_zipfile(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name) self._check_script(zip_name, run_name, zip_name, '') def test_zipfile_compiled(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') compiled_name = compile_script(script_name) zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, run_name, zip_name, '') def test_zipfile_error(self): with temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'not_main') zip_name, run_name = make_zip_script(script_dir, 'test_zip', script_name) msg = "can't find '__main__' module in %r" % zip_name self._check_import_error(zip_name, msg) def test_module_in_package(self): with temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, 'script') launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script') self._check_script(launch_name, script_name, script_name, 'test_pkg') def test_module_in_package_in_zipfile(self): with temp_dir() as script_dir: zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script') launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name) self._check_script(launch_name, run_name, run_name, 'test_pkg') def test_module_in_subpackage_in_zipfile(self): with temp_dir() as script_dir: zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2) launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name) self._check_script(launch_name, run_name, run_name, 'test_pkg.test_pkg') def test_package(self): with temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, '__main__') launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') self._check_script(launch_name, script_name, script_name, 'test_pkg') def test_package_compiled(self): with temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, '__main__') compiled_name = compile_script(script_name) os.remove(script_name) launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') self._check_script(launch_name, compiled_name, compiled_name, 'test_pkg') def test_package_error(self): with temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) msg = ("'test_pkg' is a package and cannot " "be directly executed") launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') self._check_import_error(launch_name, msg) def test_package_recursion(self): with temp_dir() as script_dir: pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) main_dir = os.path.join(pkg_dir, '__main__') make_pkg(main_dir) msg = ("Cannot use package as __main__ module; " "'test_pkg' is a package and cannot " "be directly executed") launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') self._check_import_error(launch_name, msg) @contextlib.contextmanager def setup_test_pkg(self, *args): with temp_dir() as script_dir, \ test.test_support.change_cwd(script_dir): pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir, *args) yield pkg_dir def check_dash_m_failure(self, *args): rc, out, err = assert_python_failure('-m', *args) if verbose > 1: print(out) self.assertEqual(rc, 1) return err def test_dash_m_error_code_is_one(self): # If a module is invoked with the -m command line flag # and results in an error that the return code to the # shell is '1' with self.setup_test_pkg() as pkg_dir: script_name = _make_test_script(pkg_dir, 'other', "if __name__ == '__main__': raise ValueError") err = self.check_dash_m_failure('test_pkg.other', *example_args) self.assertIn(b'ValueError', err) def test_dash_m_errors(self): # Exercise error reporting for various invalid package executions tests = ( ('__builtin__', br'No code object available'), ('__builtin__.x', br'No module named'), ('__builtin__.x.y', br'No module named'), ('os.path', br'Loader.*cannot handle'), ('importlib', br'No module named.*' br'is a package and cannot be directly executed'), ('importlib.nonexistant', br'No module named'), ) for name, regex in tests: rc, _, err = assert_python_failure('-m', name) self.assertEqual(rc, 1) self.assertRegexpMatches(err, regex) self.assertNotIn(b'Traceback', err) def test_dash_m_init_traceback(self): # These were wrapped in an ImportError and tracebacks were # suppressed; see Issue 14285 exceptions = (ImportError, AttributeError, TypeError, ValueError) for exception in exceptions: exception = exception.__name__ init = "raise {0}('Exception in __init__.py')".format(exception) with self.setup_test_pkg(init) as pkg_dir: err = self.check_dash_m_failure('test_pkg') self.assertIn(exception.encode('ascii'), err) self.assertIn(b'Exception in __init__.py', err) self.assertIn(b'Traceback', err) def test_dash_m_main_traceback(self): # Ensure that an ImportError's traceback is reported with self.setup_test_pkg() as pkg_dir: main = "raise ImportError('Exception in __main__ module')" _make_test_script(pkg_dir, '__main__', main) err = self.check_dash_m_failure('test_pkg') self.assertIn(b'ImportError', err) self.assertIn(b'Exception in __main__ module', err) self.assertIn(b'Traceback', err) def test_main(): test.test_support.run_unittest(CmdLineTest) test.test_support.reap_children() if __name__ == '__main__': test_main()
gpl-3.0
jessstrap/servotk
tests/wpt/css-tests/tools/wptserve/wptserve/wptserve.py
515
1117
#!/usr/bin/env python import argparse import os import server def abs_path(path): return os.path.abspath(path) def parse_args(): parser = argparse.ArgumentParser(description="HTTP server designed for extreme flexibility " "required in testing situations.") parser.add_argument("document_root", action="store", type=abs_path, help="Root directory to serve files from") parser.add_argument("--port", "-p", dest="port", action="store", type=int, default=8000, help="Port number to run server on") parser.add_argument("--host", "-H", dest="host", action="store", type=str, default="127.0.0.1", help="Host to run server on") return parser.parse_args() def main(): args = parse_args() httpd = server.WebTestHttpd(host=args.host, port=args.port, use_ssl=False, certificate=None, doc_root=args.document_root) httpd.start() if __name__ == "__main__": main()
mpl-2.0
onecodex/onecodex
tests/test_upload.py
2
9365
# -*- coding: utf-8 -*- from collections import OrderedDict from io import BytesIO from mock import patch import pytest from requests_toolbelt import MultipartEncoder from requests.exceptions import HTTPError from onecodex.exceptions import OneCodexException, UploadException from onecodex.lib.upload import ( _choose_boto3_chunksize, FilePassthru, upload_document, _upload_document_fileobj, upload_sequence, _upload_sequence_fileobj, ) class FakeAPISession: # TODO: We should migrate this to use responses vs. a faked API session adapters = {} def post(self, url, **kwargs): resp = lambda: None # noqa resp.json = lambda: {"code": 200} resp.status_code = 201 if "auth" in kwargs else 200 resp.raise_for_status = lambda: None # noqa if url.endswith("s3_confirm"): resp.status_code = 200 resp.json = lambda: {"sample_id": "s3_confirm_sample_id"} # noqa return resp def mount(self, url, adapter): self.adapters[url] = adapter class FakeSamplesResource: def __init__(self, what_fails=None): self.what_fails = what_fails @staticmethod def err_resp(): resp = lambda: None # noqa resp.status_code = 400 resp.json = lambda: {} # noqa raise HTTPError(response=resp) def init_multipart_upload(self, obj): if self.what_fails == "init_multipart": self.err_resp() return { "callback_url": "/s3_confirm", "s3_bucket": "some_bucket", "file_id": "hey", "paired_end_file_id": "ho", "upload_aws_access_key_id": "key", "upload_aws_secret_access_key": "secret", } def confirm_upload(self, obj): if self.what_fails == "confirm": self.err_resp() assert "sample_id" in obj assert "upload_type" in obj def cancel_upload(self, obj): if self.what_fails == "cancel": self.err_resp() assert "sample_id" in obj return {"success": True, "message": "Upload cancelled"} class _client(object): _root_url = "http://localhost:3000" session = FakeAPISession() class FakeDocumentsResource: def __init__(self, what_fails=None): self.what_fails = what_fails @staticmethod def err_resp(): resp = lambda: None # noqa resp.status_code = 400 resp.json = lambda: {} # noqa raise HTTPError(response=resp) def init_multipart_upload(self): if self.what_fails == "init_multipart": self.err_resp() return { "callback_url": "/s3_confirm", "s3_bucket": "some_bucket", "file_id": "hey", "upload_aws_access_key_id": "key", "upload_aws_secret_access_key": "secret", } def confirm_upload(self, obj): if self.what_fails == "confirm": self.err_resp() assert "sample_id" in obj assert "upload_type" in obj class _client(object): _root_url = "http://localhost:3000" session = FakeAPISession() @pytest.mark.parametrize( "files,n_uploads,fxi_calls,fxp_calls", [ ("file.1000.fa", 1, 0, 1), ("file.5e10.fa", 1, 0, 1), (("file.3e10.R1.fa", "file.3e10.R2.fa"), 2, 1, 0), # (["file.1000.fa", "file.5e10.fa"], 2, 0, 2, 2), # ([("file.3e10.R1.fa", "file.3e10.R2.fa")], 1, 1, 0, 2), # ([("file.3e5.R1.fa", "file.3e5.R2.fa"), "file.1e5.fa"], 2, 1, 1, 3), ], ) def test_upload_lots_of_files(files, n_uploads, fxi_calls, fxp_calls): with patch("boto3.session.Session"): fake_size = lambda filename: int(float(filename.split(".")[1])) # noqa uso = "onecodex.lib.upload._upload_sequence_fileobj" udo = "onecodex.lib.upload._upload_document_fileobj" fxi = "onecodex.lib.files.PairedEndFiles" fxp = "onecodex.lib.files.FilePassthru" sz = "os.path.getsize" sample_resource = FakeSamplesResource() with patch(uso) as upload_sequence_fileobj, patch(fxi) as paired, patch(fxp) as passthru: with patch(sz, size_effect=fake_size): upload_sequence(files, sample_resource) assert upload_sequence_fileobj.call_count == n_uploads assert paired.call_count == fxi_calls assert passthru.call_count == fxp_calls # Need to patch from `upload.` instead of `files.` for that test with patch(udo) as upload_document_fileobj, patch( "onecodex.lib.upload.FilePassthru" ) as passthru: with patch(sz, size_effect=fake_size): files = files[0] if isinstance(files, tuple) else files upload_document(files, FakeDocumentsResource()) assert ( upload_document_fileobj.call_count == n_uploads - 1 if isinstance(files, tuple) else n_uploads ) assert passthru.call_count == fxp_calls + fxi_calls def test_api_failures(caplog): with patch("boto3.session.Session"): files = ("tests/data/files/test_R1_L001.fq.gz", "tests/data/files/test_R2_L001.fq.gz") with pytest.raises(UploadException) as e: upload_sequence(files, FakeSamplesResource("init_multipart")) assert "Could not initialize upload" in str(e.value) def test_unicode_filenames(caplog): with patch("boto3.session.Session"): file_list = [ (u"tests/data/files/François.fq", "Francois.fq"), (u"tests/data/files/Málaga.fasta", "Malaga.fasta"), (u"tests/data/files/Röö.fastq", "Roo.fastq"), ] # should raise if --coerce-ascii not passed sample_resource = FakeSamplesResource() for before, after in file_list: with pytest.raises(OneCodexException) as e: upload_sequence(before, sample_resource) assert "must be ascii" in str(e.value) # make sure log gets warnings when we rename files for before, _ in file_list: upload_sequence(before, sample_resource, coerce_ascii=True) for _, after in file_list: assert after in caplog.text def test_callback_retry_handling(): with patch("boto3.session.Session") as _: sample_resource = FakeSamplesResource() files = ("tests/data/files/test_R1_L001.fq.gz", "tests/data/files/test_R2_L001.fq.gz") upload_sequence(files, sample_resource) assert ( sample_resource._client.session.adapters[ "http://localhost:3000/s3_confirm" ].max_retries.total == 3 ) assert ( sample_resource._client.session.adapters[ "http://localhost:3000/s3_confirm" ].max_retries.method_whitelist is False ) def test_single_end_files(): with patch("boto3.session.Session") as b3: upload_sequence("tests/data/files/test_R1_L001.fq.gz", FakeSamplesResource()) assert b3.call_count == 1 def test_paired_end_files(): with patch("boto3.session.Session") as b3: upload_sequence( ("tests/data/files/test_R1_L001.fq.gz", "tests/data/files/test_R2_L001.fq.gz"), FakeSamplesResource(), ) assert b3.call_count == 2 def test_upload_sequence_fileobj(): with patch("boto3.session.Session") as b3: # upload succeeds via multipart file_obj = BytesIO(b">test\nACGT\n") _upload_sequence_fileobj( file_obj, "test.fa", FakeSamplesResource().init_multipart_upload({}), FakeSamplesResource(), ) file_obj.close() assert b3.call_count == 1 def test_upload_document_fileobj(): with patch("boto3.session.Session") as b3: file_obj = BytesIO(b"MY_SPOON_IS_TOO_BIG\n") _upload_document_fileobj(file_obj, "spoon.pdf", FakeDocumentsResource()) file_obj.close() assert b3.call_count == 1 with pytest.raises(UploadException) as e: file_obj = BytesIO(b"MY_SPOON_IS_TOO_BIG\n") _upload_document_fileobj(file_obj, "spoon.pdf", FakeDocumentsResource("init_multipart")) file_obj.close() assert "Could not initialize" in str(e.value) def test_multipart_encoder_passthru(): wrapper = FilePassthru("tests/data/files/test_R1_L001.fq.bz2") wrapper_len = len(wrapper.read()) wrapper.seek(0) assert wrapper_len == wrapper._fsize multipart_fields = OrderedDict() multipart_fields["file"] = ("fakefile", wrapper, "application/x-gzip") encoder = MultipartEncoder(multipart_fields) MAGIC_HEADER_LEN = 178 wrapper.seek(0) assert len(encoder.read()) - MAGIC_HEADER_LEN == wrapper_len def test_boto3_chunksize(): # test file that is too large to upload wrapper = FilePassthru("tests/data/files/test_R1_L001.fq.gz") wrapper._fsize = 1024 ** 4 # 1 TB with pytest.raises(OneCodexException) as e: _choose_boto3_chunksize(wrapper) assert "too large to upload" in str(e.value) # test file with no known size assert ( _choose_boto3_chunksize(open("tests/data/files/test_R1_L001.fq.gz", "r")) == 25 * 1024 ** 2 )
mit
owers19856/django-cms
cms/test_utils/project/emailuserapp/migrations/0001_initial.py
43
2459
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [ migrations.CreateModel( name='EmailUser', fields=[ ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(default=django.utils.timezone.now, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(max_length=75, verbose_name='email address', help_text='Required. Standard format email address.', unique=True, blank=True)), ('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)), ('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(related_query_name='user', to='auth.Group', verbose_name='groups', related_name='user_set', help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', blank=True)), ('user_permissions', models.ManyToManyField(related_query_name='user', to='auth.Permission', verbose_name='user permissions', related_name='user_set', help_text='Specific permissions for this user.', blank=True)), ], options={ 'abstract': False, 'verbose_name': 'user', 'verbose_name_plural': 'users', }, bases=(models.Model,), ), ]
bsd-3-clause
Anaethelion/Geotrek
geotrek/common/parsers.py
1
25974
# -*- encoding: utf-8 -*- import os import re import requests from requests.auth import HTTPBasicAuth import xlrd import xml.etree.ElementTree as ET import json import urllib2 from ftplib import FTP from os.path import dirname from urlparse import urlparse from django.db import models from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.gis.gdal import DataSource from django.core.files.base import ContentFile from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext as _ from django.utils.encoding import force_text from modeltranslation.fields import TranslationField from modeltranslation.translator import translator, NotRegistered from paperclip.models import Attachment, attachment_upload from geotrek.common.models import FileType class ImportError(Exception): pass class GlobalImportError(ImportError): pass class RowImportError(ImportError): pass class ValueImportError(ImportError): pass class Parser(object): label = None filename = None url = None simplify_tolerance = 0 # meters update_only = False delete = False duplicate_eid_allowed = False warn_on_missing_fields = False warn_on_missing_objects = False separator = '+' eid = None fields = None m2m_fields = {} constant_fields = {} m2m_constant_fields = {} non_fields = {} natural_keys = {} field_options = {} def __init__(self, progress_cb=None): self.warnings = {} self.line = 0 self.nb_success = 0 self.nb_created = 0 self.nb_updated = 0 self.nb_unmodified = 0 self.progress_cb = progress_cb try: mto = translator.get_options_for_model(self.model) except NotRegistered: self.translated_fields = [] else: self.translated_fields = mto.fields.keys() if self.fields is None: self.fields = { f.name: force_text(f.verbose_name) for f in self.model._meta.fields if not isinstance(f, TranslationField) } self.m2m_fields = { f.name: force_text(f.verbose_name) for f in self.model._meta.many_to_many } def normalize_field_name(self, name): return name.upper() def normalize_src(self, src): if hasattr(src, '__iter__'): return [self.normalize_field_name(subsrc) for subsrc in src] else: return self.normalize_field_name(src) def add_warning(self, msg): key = _(u"Line {line}".format(line=self.line)) warnings = self.warnings.setdefault(key, []) warnings.append(msg) def get_val(self, row, dst, src): if hasattr(src, '__iter__'): val = [] for subsrc in src: try: val.append(self.get_val(row, dst, subsrc)) except ValueImportError as warning: if self.warn_on_missing_fields: self.add_warning(unicode(warning)) val.append(None) else: val = row for part in src.split('.'): try: if part.isdigit(): val = val[int(part)] else: val = val[part] except (KeyError, IndexError): required = u"required " if self.field_options.get(dst, {}).get('required', False) else "" raise ValueImportError(_(u"Missing {required}field '{src}'").format(required=required, src=src)) return val def apply_filter(self, dst, src, val): field = self.model._meta.get_field_by_name(dst)[0] if (isinstance(field, models.ForeignKey) or isinstance(field, models.ManyToManyField)): if dst not in self.natural_keys: raise ValueImportError(_(u"Destination field '{dst}' not in natural keys configuration").format(dst=dst)) to = field.rel.to natural_key = self.natural_keys[dst] kwargs = self.field_options.get(dst, {}) if isinstance(field, models.ForeignKey): val = self.filter_fk(src, val, to, natural_key, **kwargs) else: val = self.filter_m2m(src, val, to, natural_key, **kwargs) return val def parse_non_field(self, dst, src, val): """Returns True if modified""" if hasattr(self, 'save_{0}'.format(dst)): return getattr(self, 'save_{0}'.format(dst))(src, val) def set_value(self, dst, src, val): field = self.model._meta.get_field_by_name(dst)[0] if val is None and not field.null: if field.blank and (isinstance(field, models.CharField) or isinstance(field, models.TextField)): val = u"" else: raise RowImportError(_(u"Null value not allowed for field '{src}'".format(src=src))) if val == u"" and not field.blank: raise RowImportError(_(u"Blank value not allowed for field '{src}'".format(src=src))) setattr(self.obj, dst, val) def parse_field(self, dst, src, val): """Returns True if modified""" if hasattr(self, 'filter_{0}'.format(dst)): try: val = getattr(self, 'filter_{0}'.format(dst))(src, val) except ValueImportError as warning: self.add_warning(unicode(warning)) return False else: try: val = self.apply_filter(dst, src, val) except ValueImportError as warning: self.add_warning(unicode(warning)) return False if hasattr(self.obj, dst): if dst in self.m2m_fields or dst in self.m2m_constant_fields: old = set(getattr(self.obj, dst).all()) val = set(val) else: old = getattr(self.obj, dst) if isinstance(old, float) and isinstance(val, float): old = round(old, 10) val = round(val, 10) if old != val: self.set_value(dst, src, val) return True else: return False else: self.set_value(dst, src, val) return True def parse_fields(self, row, fields, non_field=False): updated = [] for dst, src in fields.items(): if dst in self.constant_fields or dst in self.m2m_constant_fields: val = src else: src = self.normalize_src(src) try: val = self.get_val(row, dst, src) except ValueImportError as warning: if self.field_options.get(dst, {}).get('required', False): raise RowImportError(warning) if self.warn_on_missing_fields: self.add_warning(unicode(warning)) continue if non_field: modified = self.parse_non_field(dst, src, val) else: modified = self.parse_field(dst, src, val) if modified: updated.append(dst) if dst in self.translated_fields: lang = translation.get_language() updated.append('{field}_{lang}'.format(field=dst, lang=lang)) return updated def parse_obj(self, row, operation): try: update_fields = self.parse_fields(row, self.fields) update_fields += self.parse_fields(row, self.constant_fields) except RowImportError as warnings: self.add_warning(unicode(warnings)) return if operation == u"created": self.obj.save() else: self.obj.save(update_fields=update_fields) update_fields += self.parse_fields(row, self.m2m_fields) update_fields += self.parse_fields(row, self.m2m_constant_fields) update_fields += self.parse_fields(row, self.non_fields, non_field=True) if operation == u"created": self.nb_created += 1 elif update_fields: self.nb_updated += 1 else: self.nb_unmodified += 1 def get_eid_kwargs(self, row): try: eid_src = self.fields[self.eid] except KeyError: raise GlobalImportError(_(u"Eid field '{eid_dst}' missing in parser configuration").format(eid_dst=self.eid)) eid_src = self.normalize_field_name(eid_src) try: eid_val = self.get_val(row, self.eid, eid_src) except KeyError: raise GlobalImportError(_(u"Missing id field '{eid_src}'").format(eid_src=eid_src)) if hasattr(self, 'filter_{0}'.format(self.eid)): eid_val = getattr(self, 'filter_{0}'.format(self.eid))(eid_src, eid_val) self.eid_src = eid_src self.eid_val = eid_val return {self.eid: eid_val} def parse_row(self, row): self.eid_val = None self.line += 1 if self.eid is None: eid_kwargs = {} objects = self.model.objects.none() else: try: eid_kwargs = self.get_eid_kwargs(row) except RowImportError as warnings: self.add_warning(unicode(warnings)) return objects = self.model.objects.filter(**eid_kwargs) if len(objects) == 0 and self.update_only: if self.warn_on_missing_objects: self.add_warning(_(u"Bad value '{eid_val}' for field '{eid_src}'. No trek with this identifier").format(eid_val=self.eid_val, eid_src=self.eid_src)) return elif len(objects) == 0: objects = [self.model(**eid_kwargs)] operation = u"created" elif len(objects) >= 2 and not self.duplicate_eid_allowed: self.add_warning(_(u"Bad value '{eid_val}' for field '{eid_src}'. Multiple treks with this identifier").format(eid_val=self.eid_val, eid_src=self.eid_src)) return else: operation = u"updated" for self.obj in objects: self.parse_obj(row, operation) self.to_delete.discard(self.obj.pk) self.nb_success += 1 # FIXME if self.progress_cb: self.progress_cb(float(self.line) / self.nb, self.line, self.eid_val) def report(self, output_format='txt'): context = { 'nb_success': self.nb_success, 'nb_lines': self.line, 'nb_created': self.nb_created, 'nb_updated': self.nb_updated, 'nb_deleted': len(self.to_delete) if self.delete else 0, 'nb_unmodified': self.nb_unmodified, 'warnings': self.warnings, } return render_to_string('common/parser_report.{output_format}'.format(output_format=output_format), context) def get_mapping(self, src, val, mapping, partial): if partial: found = False for i, j in mapping.iteritems(): if i in val: val = j found = True break if not found: self.add_warning(_(u"Bad value '{val}' for field {src}. Should contain {values}").format(val=val, src=src, separator=self.separator, values=', '.join(mapping.keys()))) return None else: if mapping is not None: if val not in mapping.keys(): self.add_warning(_(u"Bad value '{val}' for field {src}. Should be {values}").format(val=val, src=src, separator=self.separator, values=', '.join(mapping.keys()))) return None val = mapping[val] return val def filter_fk(self, src, val, model, field, mapping=None, partial=False, create=False): val = self.get_mapping(src, val, mapping, partial) if val is None: return None if create: val, created = model.objects.get_or_create(**{field: val}) if created: self.add_warning(_(u"{model} '{val}' did not exist in Geotrek-Admin and was automatically created").format(model=model._meta.verbose_name.title(), val=val)) return val try: return model.objects.get(**{field: val}) except model.DoesNotExist: self.add_warning(_(u"{model} '{val}' does not exists in Geotrek-Admin. Please add it").format(model=model._meta.verbose_name.title(), val=val)) return None def filter_m2m(self, src, val, model, field, mapping=None, partial=False, create=False): if not val: return [] val = val.split(self.separator) dst = [] for subval in val: subval = subval.strip() subval = self.get_mapping(src, subval, mapping, partial) if subval is None: continue if create: subval, created = model.objects.get_or_create(**{field: subval}) if created: self.add_warning(_(u"{model} '{val}' did not exist in Geotrek-Admin and was automatically created").format(model=model._meta.verbose_name.title(), val=subval)) dst.append(subval) continue try: dst.append(model.objects.get(**{field: subval})) except model.DoesNotExist: self.add_warning(_(u"{model} '{val}' does not exists in Geotrek-Admin. Please add it").format(model=model._meta.verbose_name.title(), val=subval)) continue return dst def start(self): self.to_delete = set(self.model.objects.values_list('pk', flat=True)) def end(self): if self.delete: self.model.objects.filter(pk__in=self.to_delete).delete() def parse(self, filename=None, limit=None): if filename: self.filename = filename if not self.url and not self.filename: raise GlobalImportError(_(u"Filename is required")) if self.filename and not os.path.exists(self.filename): raise GlobalImportError(_(u"File does not exists at: {filename}").format(filename=self.filename)) self.start() for i, row in enumerate(self.next_row()): if limit and i >= limit: break try: self.parse_row(row) except Exception as e: self.add_warning(unicode(e)) if settings.DEBUG: raise self.end() class ShapeParser(Parser): encoding = 'utf-8' def next_row(self): datasource = DataSource(self.filename, encoding=self.encoding) layer = datasource[0] self.nb = len(layer) for i, feature in enumerate(layer): row = {self.normalize_field_name(field.name): field.value for field in feature} try: ogrgeom = feature.geom except: print _(u"Invalid geometry pointer"), i geom = None else: ogrgeom.coord_dim = 2 # Flatten to 2D geom = ogrgeom.geos if self.simplify_tolerance and geom is not None: geom = geom.simplify(self.simplify_tolerance) row[self.normalize_field_name('geom')] = geom yield row def normalize_field_name(self, name): """Shapefile field names length is 10 char max""" name = super(ShapeParser, self).normalize_field_name(name) return name[:10] class ExcelParser(Parser): def next_row(self): workbook = xlrd.open_workbook(self.filename) sheet = workbook.sheet_by_index(0) header = [self.normalize_field_name(cell.value) for cell in sheet.row(0)] self.nb = sheet.nrows - 1 for i in range(1, sheet.nrows): values = [cell.value for cell in sheet.row(i)] row = dict(zip(header, values)) yield row class AtomParser(Parser): ns = { 'Atom': 'http://www.w3.org/2005/Atom', 'georss': 'http://www.georss.org/georss', } def flatten_fields(self, fields): return reduce(lambda x, y: x + (list(y) if hasattr(y, '__iter__') else [y]), fields.values(), []) def next_row(self): srcs = self.flatten_fields(self.fields) srcs += self.flatten_fields(self.m2m_fields) srcs += self.flatten_fields(self.non_fields) tree = ET.parse(self.filename) entries = tree.getroot().findall('Atom:entry', self.ns) self.nb = len(entries) for entry in entries: row = {self.normalize_field_name(src): entry.find(src, self.ns).text for src in srcs} yield row class AttachmentParserMixin(object): base_url = '' delete_attachments = False filetype_name = u"Photographie" non_fields = { 'attachments': _(u"Attachments"), } def start(self): super(AttachmentParserMixin, self).start() try: self.filetype = FileType.objects.get(type=self.filetype_name) except FileType.DoesNotExist: raise GlobalImportError(_(u"FileType '{name}' does not exists in Geotrek-Admin. Please add it").format(name=self.filetype_name)) self.creator, created = get_user_model().objects.get_or_create(username='import', defaults={'is_active': False}) self.attachments_to_delete = {obj.pk: set(Attachment.objects.attachments_for_object(obj)) for obj in self.model.objects.all()} def end(self): if self.delete_attachments: for atts in self.attachments_to_delete.itervalues(): for att in atts: att.delete() super(AttachmentParserMixin, self).end() def filter_attachments(self, src, val): if not val: return [] return [(subval.strip(), '', '') for subval in val.split(self.separator)] def has_size_changed(self, url, attachment): try: parsed_url = urlparse(url) if parsed_url.scheme == 'ftp': directory = dirname(parsed_url.path) ftp = FTP(parsed_url.hostname) ftp.login(user=parsed_url.username, passwd=parsed_url.password) ftp.cwd(directory) size = ftp.size(parsed_url.path.split('/')[-1:][0]) return size != attachment.attachment_file.size if parsed_url.scheme == 'http' or parsed_url.scheme == 'https': http = urllib2.urlopen(url) size = http.headers.getheader('content-length') return int(size) != attachment.attachment_file.size except: return False return True def save_attachments(self, src, val): updated = False for url, legend, author in self.filter_attachments(src, val): url = self.base_url + url legend = legend or u"" author = author or u"" name = os.path.basename(url) found = False for attachment in self.attachments_to_delete.get(self.obj.pk, set()): upload_name, ext = os.path.splitext(attachment_upload(attachment, name)) existing_name = attachment.attachment_file.name if re.search(ur"^{name}(_\d+)?{ext}$".format(name=upload_name, ext=ext), existing_name) and not self.has_size_changed(url, attachment): found = True self.attachments_to_delete[self.obj.pk].remove(attachment) if author != attachment.author or legend != attachment.legend: attachment.author = author attachment.legend = legend attachment.save() updated = True break if found: continue if url[:6] == 'ftp://': try: response = urllib2.urlopen(url) except: self.add_warning(_(u"Failed to download '{url}'").format(url=url)) continue content = response.read() else: response = requests.get(url) if response.status_code != requests.codes.ok: self.add_warning(_(u"Failed to download '{url}'").format(url=url)) continue content = response.content f = ContentFile(content) attachment = Attachment() attachment.content_object = self.obj attachment.attachment_file.save(name, f, save=False) attachment.filetype = self.filetype attachment.creator = self.creator attachment.author = author attachment.legend = legend attachment.save() updated = True return updated class TourInSoftParser(AttachmentParserMixin, Parser): @property def items(self): return self.root['d']['results'] def next_row(self): skip = 0 while True: params = { '$format': 'json', '$inlinecount': 'allpages', '$top': 1000, '$skip': skip, } response = requests.get(self.url, params=params) if response.status_code != 200: raise GlobalImportError(_(u"Failed to download {url}. HTTP status code {status_code}").format(url=self.url, status_code=response.status_code)) self.root = response.json() self.nb = int(self.root['d']['__count']) for row in self.items: yield {self.normalize_field_name(src): val for src, val in row.iteritems()} skip += 1000 if skip >= self.nb: return def filter_attachments(self, src, val): if not val: return [] return [subval.split('||') for subval in val.split('##') if subval.split('||') != ['', '', '']] class TourismSystemParser(AttachmentParserMixin, Parser): @property def items(self): return self.root['data'] def next_row(self): size = 1000 skip = 0 while True: params = { 'size': size, 'start': skip, } response = requests.get(self.url, params=params, auth=HTTPBasicAuth(self.user, self.password)) if response.status_code != 200: raise GlobalImportError(_(u"Failed to download {url}. HTTP status code {status_code}").format(url=self.url, status_code=response.status_code)) self.root = response.json() self.nb = int(self.root['metadata']['total']) for row in self.items: yield {self.normalize_field_name(src): val for src, val in row.iteritems()} skip += size if skip >= self.nb: return def filter_attachments(self, src, val): result = [] for subval in val or []: try: name = subval['name']['fr'] except KeyError: name = None result.append((subval['URL'], name, None)) return result def normalize_field_name(self, name): return name class SitraParser(AttachmentParserMixin, Parser): url = 'http://api.sitra-tourisme.com/api/v002/recherche/list-objets-touristiques/' @property def items(self): return self.root['objetsTouristiques'] def next_row(self): size = 100 skip = 0 while True: params = { 'apiKey': self.api_key, 'projetId': self.project_id, 'selectionIds': [self.selection_id], 'count': size, 'first': skip, } response = requests.get(self.url, params={'query': json.dumps(params)}) if response.status_code != 200: raise GlobalImportError(_(u"Failed to download {url}. HTTP status code {status_code}").format(url=self.url, status_code=response.status_code)) self.root = response.json() self.nb = int(self.root['numFound']) for row in self.items: yield row skip += size if skip >= self.nb: return def filter_attachments(self, src, val): result = [] for subval in val or []: if 'nom' in subval: name = subval['nom']['libelleFr'] else: name = None result.append((subval['traductionFichiers'][0]['url'], name, None)) return result def normalize_field_name(self, name): return name class OpenSystemParser(Parser): url = 'http://proxy-xml.open-system.fr/rest.aspx' def next_row(self): params = { 'Login': self.login, 'Pass': self.password, 'Action': 'concentrateur_liaisons', } response = requests.get(self.url, params=params) if response.status_code != 200: raise GlobalImportError(_(u"Failed to download {url}. HTTP status code {status_code}").format(url=self.url, status_code=response.status_code)) self.root = ET.fromstring(response.content).find('Resultat').find('Objets') self.nb = len(self.root) for row in self.root: id_sitra = row.find('ObjetCle').find('Cle').text for liaison in row.find('Liaisons'): yield { 'id_sitra': id_sitra, 'id_opensystem': liaison.find('ObjetOS').find('CodeUI').text, } def normalize_field_name(self, name): return name
bsd-2-clause
CodeJuan/sinaweibopy
weibo.py
24
11707
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.1.4' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' ''' Python client SDK for sina weibo API using OAuth 2. ''' try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import gzip, time, json, hmac, base64, hashlib, urllib, urllib2, logging, mimetypes, collections class APIError(StandardError): ''' raise APIError if receiving json message indicating failure. ''' def __init__(self, error_code, error, request): self.error_code = error_code self.error = error self.request = request StandardError.__init__(self, error) def __str__(self): return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request) def _parse_json(s): ' parse str into JsonDict ' def _obj_hook(pairs): ' convert json object to python object ' o = JsonDict() for k, v in pairs.iteritems(): o[str(k)] = v return o return json.loads(s, object_hook=_obj_hook) class JsonDict(dict): ' general json object that allows attributes to be bound to and also behaves like a dict ' def __getattr__(self, attr): try: return self[attr] except KeyError: raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr) def __setattr__(self, attr, value): self[attr] = value def _encode_params(**kw): ''' do url-encode parameters >>> _encode_params(a=1, b='R&D') 'a=1&b=R%26D' >>> _encode_params(a=u'\u4e2d\u6587', b=['A', 'B', 123]) 'a=%E4%B8%AD%E6%96%87&b=A&b=B&b=123' ''' args = [] for k, v in kw.iteritems(): if isinstance(v, basestring): qv = v.encode('utf-8') if isinstance(v, unicode) else v args.append('%s=%s' % (k, urllib.quote(qv))) elif isinstance(v, collections.Iterable): for i in v: qv = i.encode('utf-8') if isinstance(i, unicode) else str(i) args.append('%s=%s' % (k, urllib.quote(qv))) else: qv = str(v) args.append('%s=%s' % (k, urllib.quote(qv))) return '&'.join(args) def _encode_multipart(**kw): ' build a multipart/form-data body with randomly generated boundary ' boundary = '----------%s' % hex(int(time.time() * 1000)) data = [] for k, v in kw.iteritems(): data.append('--%s' % boundary) if hasattr(v, 'read'): # file-like object: filename = getattr(v, 'name', '') content = v.read() data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k) data.append('Content-Length: %d' % len(content)) data.append('Content-Type: %s\r\n' % _guess_content_type(filename)) data.append(content) else: data.append('Content-Disposition: form-data; name="%s"\r\n' % k) data.append(v.encode('utf-8') if isinstance(v, unicode) else v) data.append('--%s--\r\n' % boundary) return '\r\n'.join(data), boundary def _guess_content_type(url): n = url.rfind('.') if n==(-1): return 'application/octet-stream' ext = url[n:] return mimetypes.types_map.get(ext, 'application/octet-stream') _HTTP_GET = 0 _HTTP_POST = 1 _HTTP_UPLOAD = 2 def _http_get(url, authorization=None, **kw): logging.info('GET %s' % url) return _http_call(url, _HTTP_GET, authorization, **kw) def _http_post(url, authorization=None, **kw): logging.info('POST %s' % url) return _http_call(url, _HTTP_POST, authorization, **kw) def _http_upload(url, authorization=None, **kw): logging.info('MULTIPART POST %s' % url) return _http_call(url, _HTTP_UPLOAD, authorization, **kw) def _read_body(obj): using_gzip = obj.headers.get('Content-Encoding', '')=='gzip' body = obj.read() if using_gzip: gzipper = gzip.GzipFile(fileobj=StringIO(body)) fcontent = gzipper.read() gzipper.close() return fcontent return body def _http_call(the_url, method, authorization, **kw): ''' send an http request and return a json object if no error occurred. ''' params = None boundary = None if method==_HTTP_UPLOAD: # fix sina upload url: the_url = the_url.replace('https://api.', 'https://upload.api.') params, boundary = _encode_multipart(**kw) else: params = _encode_params(**kw) if '/remind/' in the_url: # fix sina remind api: the_url = the_url.replace('https://api.', 'https://rm.api.') http_url = '%s?%s' % (the_url, params) if method==_HTTP_GET else the_url http_body = None if method==_HTTP_GET else params req = urllib2.Request(http_url, data=http_body) req.add_header('Accept-Encoding', 'gzip') if authorization: req.add_header('Authorization', 'OAuth2 %s' % authorization) if boundary: req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) try: resp = urllib2.urlopen(req, timeout=5) body = _read_body(resp) r = _parse_json(body) if hasattr(r, 'error_code'): raise APIError(r.error_code, r.get('error', ''), r.get('request', '')) return r except urllib2.HTTPError, e: try: r = _parse_json(_read_body(e)) except: r = None if hasattr(r, 'error_code'): raise APIError(r.error_code, r.get('error', ''), r.get('request', '')) raise e class HttpObject(object): def __init__(self, client, method): self.client = client self.method = method def __getattr__(self, attr): def wrap(**kw): if self.client.is_expires(): raise APIError('21327', 'expired_token', attr) return _http_call('%s%s.json' % (self.client.api_url, attr.replace('__', '/')), self.method, self.client.access_token, **kw) return wrap class APIClient(object): ''' API client using synchronized invocation. ''' def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'): self.client_id = str(app_key) self.client_secret = str(app_secret) self.redirect_uri = redirect_uri self.response_type = response_type self.auth_url = 'https://%s/oauth2/' % domain self.api_url = 'https://%s/%s/' % (domain, version) self.access_token = None self.expires = 0.0 self.get = HttpObject(self, _HTTP_GET) self.post = HttpObject(self, _HTTP_POST) self.upload = HttpObject(self, _HTTP_UPLOAD) def parse_signed_request(self, signed_request): ''' parse signed request when using in-site app. Returns: dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp }, or None if parse failed. ''' def _b64_normalize(s): appendix = '=' * (4 - len(s) % 4) return s.replace('-', '+').replace('_', '/') + appendix sr = str(signed_request) logging.info('parse signed request: %s' % sr) enc_sig, enc_payload = sr.split('.', 1) sig = base64.b64decode(_b64_normalize(enc_sig)) data = _parse_json(base64.b64decode(_b64_normalize(enc_payload))) if data['algorithm'] != u'HMAC-SHA256': return None expected_sig = hmac.new(self.client_secret, enc_payload, hashlib.sha256).digest(); if expected_sig==sig: data.user_id = data.uid = data.get('user_id', None) data.access_token = data.get('oauth_token', None) expires = data.get('expires', None) if expires: data.expires = data.expires_in = time.time() + expires return data return None def set_access_token(self, access_token, expires): self.access_token = str(access_token) self.expires = float(expires) def get_authorize_url(self, redirect_uri=None, **kw): ''' return the authorization url that the user should be redirected to. ''' redirect = redirect_uri if redirect_uri else self.redirect_uri if not redirect: raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request') response_type = kw.pop('response_type', 'code') return '%s%s?%s' % (self.auth_url, 'authorize', \ _encode_params(client_id = self.client_id, \ response_type = response_type, \ redirect_uri = redirect, **kw)) def _parse_access_token(self, r): ''' new:return access token as a JsonDict: {"access_token":"your-access-token","expires_in":12345678,"uid":1234}, expires_in is represented using standard unix-epoch-time ''' current = int(time.time()) expires = r.expires_in + current remind_in = r.get('remind_in', None) if remind_in: rtime = int(remind_in) + current if rtime < expires: expires = rtime return JsonDict(access_token=r.access_token, expires=expires, expires_in=expires, uid=r.get('uid', None)) def request_access_token(self, code, redirect_uri=None): redirect = redirect_uri if redirect_uri else self.redirect_uri if not redirect: raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request') r = _http_post('%s%s' % (self.auth_url, 'access_token'), \ client_id = self.client_id, \ client_secret = self.client_secret, \ redirect_uri = redirect, \ code = code, grant_type = 'authorization_code') return self._parse_access_token(r) def refresh_token(self, refresh_token): req_str = '%s%s' % (self.auth_url, 'access_token') r = _http_post(req_str, \ client_id = self.client_id, \ client_secret = self.client_secret, \ refresh_token = refresh_token, \ grant_type = 'refresh_token') return self._parse_access_token(r) def is_expires(self): return not self.access_token or time.time() > self.expires def __getattr__(self, attr): if '__' in attr: return getattr(self.get, attr) return _Callable(self, attr) _METHOD_MAP = { 'GET': _HTTP_GET, 'POST': _HTTP_POST, 'UPLOAD': _HTTP_UPLOAD } class _Executable(object): def __init__(self, client, method, path): self._client = client self._method = method self._path = path def __call__(self, **kw): method = _METHOD_MAP[self._method] if method==_HTTP_POST and 'pic' in kw: method = _HTTP_UPLOAD return _http_call('%s%s.json' % (self._client.api_url, self._path), method, self._client.access_token, **kw) def __str__(self): return '_Executable (%s %s)' % (self._method, self._path) __repr__ = __str__ class _Callable(object): def __init__(self, client, name): self._client = client self._name = name def __getattr__(self, attr): if attr=='get': return _Executable(self._client, 'GET', self._name) if attr=='post': return _Executable(self._client, 'POST', self._name) name = '%s/%s' % (self._name, attr) return _Callable(self._client, name) def __str__(self): return '_Callable (%s)' % self._name __repr__ = __str__ if __name__=='__main__': import doctest doctest.testmod()
apache-2.0
jseabold/statsmodels
statsmodels/sandbox/nonparametric/dgp_examples.py
4
5992
# -*- coding: utf-8 -*- """Examples of non-linear functions for non-parametric regression Created on Sat Jan 05 20:21:22 2013 Author: Josef Perktold """ import numpy as np ## Functions def fg1(x): '''Fan and Gijbels example function 1 ''' return x + 2 * np.exp(-16 * x**2) def fg1eu(x): '''Eubank similar to Fan and Gijbels example function 1 ''' return x + 0.5 * np.exp(-50 * (x - 0.5)**2) def fg2(x): '''Fan and Gijbels example function 2 ''' return np.sin(2 * x) + 2 * np.exp(-16 * x**2) def func1(x): '''made up example with sin, square ''' return np.sin(x * 5) / x + 2. * x - 1. * x**2 ## Classes with Data Generating Processes doc = {'description': '''Base Class for Univariate non-linear example Does not work on it's own. needs additional at least self.func ''', 'ref': ''} class _UnivariateFunction(object): #Base Class for Univariate non-linear example. #Does not work on it's own. needs additionally at least self.func __doc__ = '''%(description)s Parameters ---------- nobs : int number of observations to simulate x : None or 1d array If x is given then it is used for the exogenous variable instead of creating a random sample distr_x : None or distribution instance Only used if x is None. The rvs method is used to create a random sample of the exogenous (explanatory) variable. distr_noise : None or distribution instance The rvs method is used to create a random sample of the errors. Attributes ---------- x : ndarray, 1-D exogenous or explanatory variable. x is sorted. y : ndarray, 1-D endogenous or response variable y_true : ndarray, 1-D expected values of endogenous or response variable, i.e. values of y without noise func : callable underlying function (defined by subclass) %(ref)s ''' #% doc def __init__(self, nobs=200, x=None, distr_x=None, distr_noise=None): if x is None: if distr_x is None: x = np.random.normal(loc=0, scale=self.s_x, size=nobs) else: x = distr_x.rvs(size=nobs) x.sort() self.x = x if distr_noise is None: noise = np.random.normal(loc=0, scale=self.s_noise, size=nobs) else: noise = distr_noise.rvs(size=nobs) if hasattr(self, 'het_scale'): noise *= self.het_scale(self.x) #self.func = fg1 self.y_true = y_true = self.func(x) self.y = y_true + noise def plot(self, scatter=True, ax=None): '''plot the mean function and optionally the scatter of the sample Parameters ---------- scatter : bool If true, then add scatterpoints of sample to plot. ax : None or matplotlib axis instance If None, then a matplotlib.pyplot figure is created, otherwise the given axis, ax, is used. Returns ------- Figure This is either the created figure instance or the one associated with ax if ax is given. ''' if ax is None: import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1) if scatter: ax.plot(self.x, self.y, 'o', alpha=0.5) xx = np.linspace(self.x.min(), self.x.max(), 100) ax.plot(xx, self.func(xx), lw=2, color='b', label='dgp mean') return ax.figure doc = {'description': '''Fan and Gijbels example function 1 linear trend plus a hump ''', 'ref': ''' References ---------- Fan, Jianqing, and Irene Gijbels. 1992. "Variable Bandwidth and Local Linear Regression Smoothers." The Annals of Statistics 20 (4) (December): 2008-2036. doi:10.2307/2242378. '''} class UnivariateFanGijbels1(_UnivariateFunction): __doc__ = _UnivariateFunction.__doc__ % doc def __init__(self, nobs=200, x=None, distr_x=None, distr_noise=None): self.s_x = 1. self.s_noise = 0.7 self.func = fg1 super(self.__class__, self).__init__(nobs=nobs, x=x, distr_x=distr_x, distr_noise=distr_noise) doc['description'] =\ '''Fan and Gijbels example function 2 sin plus a hump ''' class UnivariateFanGijbels2(_UnivariateFunction): __doc__ = _UnivariateFunction.__doc__ % doc def __init__(self, nobs=200, x=None, distr_x=None, distr_noise=None): self.s_x = 1. self.s_noise = 0.5 self.func = fg2 super(self.__class__, self).__init__(nobs=nobs, x=x, distr_x=distr_x, distr_noise=distr_noise) class UnivariateFanGijbels1EU(_UnivariateFunction): ''' Eubank p.179f ''' def __init__(self, nobs=50, x=None, distr_x=None, distr_noise=None): if distr_x is None: from scipy import stats distr_x = stats.uniform self.s_noise = 0.15 self.func = fg1eu super(self.__class__, self).__init__(nobs=nobs, x=x, distr_x=distr_x, distr_noise=distr_noise) class UnivariateFunc1(_UnivariateFunction): ''' made up, with sin and quadratic trend ''' def __init__(self, nobs=200, x=None, distr_x=None, distr_noise=None): if x is None and distr_x is None: from scipy import stats distr_x = stats.uniform(-2, 4) else: nobs = x.shape[0] self.s_noise = 2. self.func = func1 super(UnivariateFunc1, self).__init__(nobs=nobs, x=x, distr_x=distr_x, distr_noise=distr_noise) def het_scale(self, x): return np.sqrt(np.abs(3+x))
bsd-3-clause
CMSS-BCRDB/RDS
trove/taskmanager/manager.py
1
18943
# Copyright 2011 OpenStack Foundation # 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. from sets import Set from oslo import messaging from trove.common.context import TroveContext from oslo.utils import importutils from trove.backup.models import Backup import trove.common.cfg as cfg from trove.common.i18n import _ import trove.common.rpc.version as rpc_version from trove.common import exception from trove.common.exception import ReplicationSlaveAttachError from trove.common.exception import TroveError from trove.common.strategies.cluster import strategy import trove.extensions.mgmt.instances.models as mgmtmodels from trove.instance.tasks import InstanceTasks from trove.openstack.common import log as logging from trove.openstack.common import periodic_task from trove.taskmanager import models from trove.taskmanager.models import FreshInstanceTasks, BuiltInstanceTasks LOG = logging.getLogger(__name__) CONF = cfg.CONF class Manager(periodic_task.PeriodicTasks): target = messaging.Target(version=rpc_version.RPC_API_VERSION) def __init__(self): super(Manager, self).__init__() self.admin_context = TroveContext( user=CONF.nova_proxy_admin_user, auth_token=CONF.nova_proxy_admin_pass, tenant=CONF.nova_proxy_admin_tenant_name) if CONF.exists_notification_transformer: self.exists_transformer = importutils.import_object( CONF.exists_notification_transformer, context=self.admin_context) def resize_volume(self, context, instance_id, new_size): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.resize_volume(new_size) def resize_flavor(self, context, instance_id, old_flavor, new_flavor): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.resize_flavor(old_flavor, new_flavor) def reboot(self, context, instance_id): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.reboot() #rds-start def restore_instance(self, context, packages, flavor, datastore_manager, instance_id, image_id, backup_id): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) new_tasks = FreshInstanceTasks.load(context, instance_id) files = new_tasks._get_injected_files(datastore_manager) instance_tasks.rebuild(image_id, files) backup_info = None if backup_id is not None: backup = models.bkup_models.Backup.get_by_id(context, backup_id) backup_info = {'id': backup_id, 'location': backup.location, 'type': backup.backup_type, 'checksum': backup.checksum, } volume_info = None device_path = instance_tasks.device_path mount_point = CONF.get(datastore_manager).mount_point volume_info = {'block_device': None, 'device_path': device_path, 'mount_point': mount_point, 'volumes': None, } config = new_tasks._render_config(flavor) new_tasks._guest_prepare(flavor['ram'], volume_info, packages=packages, databases=None, users=None, backup_info=backup_info, config_contents=config.config_contents) #rds-end def restart(self, context, instance_id): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.restart() def detach_replica(self, context, instance_id): slave = models.BuiltInstanceTasks.load(context, instance_id) master_id = slave.slave_of_id master = models.BuiltInstanceTasks.load(context, master_id) slave.detach_replica(master) def _set_task_status(self, instances, status): for instance in instances: setattr(instance.db_info, 'task_status', status) instance.db_info.save() def promote_to_replica_source(self, context, instance_id): def _promote_to_replica_source(old_master, master_candidate, replica_models): # First, we transition from the old master to new as quickly as # possible to minimize the scope of unrecoverable error old_master.make_read_only(True) master_ips = old_master.detach_public_ips() slave_ips = master_candidate.detach_public_ips() latest_txn_id = old_master.get_latest_txn_id() master_candidate.wait_for_txn(latest_txn_id) master_candidate.detach_replica(old_master, for_failover=True) master_candidate.enable_as_master() old_master.attach_replica(master_candidate) master_candidate.attach_public_ips(master_ips) master_candidate.make_read_only(False) old_master.attach_public_ips(slave_ips) # At this point, should something go wrong, there # should be a working master with some number of working slaves, # and possibly some number of "orphaned" slaves exception_replicas = [] for replica in replica_models: try: replica.wait_for_txn(latest_txn_id) if replica.id != master_candidate.id: replica.detach_replica(old_master, for_failover=True) replica.attach_replica(master_candidate) except exception.TroveError: msg = _("promote-to-replica-source: Unable to migrate " "replica %(slave)s from old replica source " "%(old_master)s to new source %(new_master)s.") msg_values = { "slave": replica.id, "old_master": old_master.id, "new_master": master_candidate.id } LOG.exception(msg % msg_values) exception_replicas.append(replica.id) try: old_master.demote_replication_master() except Exception: LOG.exception(_("Exception demoting old replica source")) exception_replicas.append(old_master) self._set_task_status([old_master] + replica_models, InstanceTasks.NONE) if exception_replicas: self._set_task_status(exception_replicas, InstanceTasks.PROMOTION_ERROR) msg = _("promote-to-replica-source %(id)s: The following " "replicas may not have been switched: %(replicas)s") msg_values = { "id": master_candidate.id, "replicas": exception_replicas } raise ReplicationSlaveAttachError(msg % msg_values) master_candidate = BuiltInstanceTasks.load(context, instance_id) old_master = BuiltInstanceTasks.load(context, master_candidate.slave_of_id) replicas = [] for replica_dbinfo in old_master.slaves: if replica_dbinfo.id == instance_id: replica = master_candidate else: replica = BuiltInstanceTasks.load(context, replica_dbinfo.id) replicas.append(replica) try: _promote_to_replica_source(old_master, master_candidate, replicas) except ReplicationSlaveAttachError: raise except Exception: self._set_task_status([old_master] + replicas, InstanceTasks.PROMOTION_ERROR) raise # pulled out to facilitate testing def _get_replica_txns(self, replica_models): return [[repl] + repl.get_last_txn() for repl in replica_models] def _most_current_replica(self, old_master, replica_models): last_txns = self._get_replica_txns(replica_models) master_ids = [txn[1] for txn in last_txns if txn[1]] if len(Set(master_ids)) > 1: raise TroveError(_("Replicas of %s not all replicating" " from same master") % old_master.id) return sorted(last_txns, key=lambda x: x[2], reverse=True)[0][0] def eject_replica_source(self, context, instance_id): def _eject_replica_source(old_master, replica_models): master_candidate = self._most_current_replica(old_master, replica_models) master_ips = old_master.detach_public_ips() slave_ips = master_candidate.detach_public_ips() master_candidate.detach_replica(old_master, for_failover=True) master_candidate.enable_as_master() master_candidate.attach_public_ips(master_ips) master_candidate.make_read_only(False) old_master.attach_public_ips(slave_ips) exception_replicas = [] for replica in replica_models: try: if replica.id != master_candidate.id: replica.detach_replica(old_master, for_failover=True) replica.attach_replica(master_candidate) except exception.TroveError: msg = _("eject-replica-source: Unable to migrate " "replica %(slave)s from old replica source " "%(old_master)s to new source %(new_master)s.") msg_values = { "slave": replica.id, "old_master": old_master.id, "new_master": master_candidate.id } LOG.exception(msg % msg_values) exception_replicas.append(replica.id) self._set_task_status([old_master] + replica_models, InstanceTasks.NONE) if exception_replicas: self._set_task_status(exception_replicas, InstanceTasks.EJECTION_ERROR) msg = _("eject-replica-source %(id)s: The following " "replicas may not have been switched: %(replicas)s") msg_values = { "id": master_candidate.id, "replicas": exception_replicas } raise ReplicationSlaveAttachError(msg % msg_values) master = BuiltInstanceTasks.load(context, instance_id) replicas = [BuiltInstanceTasks.load(context, dbinfo.id) for dbinfo in master.slaves] try: _eject_replica_source(master, replicas) except ReplicationSlaveAttachError: raise except Exception: self._set_task_status([master] + replicas, InstanceTasks.EJECTION_ERROR) raise def migrate(self, context, instance_id, host): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.migrate(host) def delete_instance(self, context, instance_id): try: instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.delete_async() except exception.UnprocessableEntity: instance_tasks = models.FreshInstanceTasks.load(context, instance_id) instance_tasks.delete_async() def delete_backup(self, context, backup_id): models.BackupTasks.delete_backup(context, backup_id) def create_backup(self, context, backup_info, instance_id): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.create_backup(backup_info) def _create_replication_slave(self, context, instance_id, name, flavor, image_id, databases, users, datastore_manager, packages, volume_size, availability_zone, root_password, nics, overrides, slave_of_id, backup_id): if type(instance_id) in [list]: ids = instance_id root_passwords = root_password else: ids = [instance_id] root_passwords = [root_password] replica_number = 0 replica_backup_id = backup_id replica_backup_created = False replicas = [] try: for replica_index in range(0, len(ids)): try: replica_number += 1 LOG.debug("Creating replica %d of %d." % (replica_number, len(ids))) instance_tasks = FreshInstanceTasks.load( context, ids[replica_index]) snapshot = instance_tasks.get_replication_master_snapshot( context, slave_of_id, flavor, replica_backup_id, replica_number=replica_number) replica_backup_id = snapshot['dataset']['snapshot_id'] replica_backup_created = True instance_tasks.create_instance( flavor, image_id, databases, users, datastore_manager, packages, volume_size, replica_backup_id, availability_zone, root_passwords[replica_index], nics, overrides, None, snapshot) replicas.append(instance_tasks) except Exception: # if it's the first replica, then we shouldn't continue LOG.exception(_( "Could not create replica %(num)d of %(count)d.") % {'num': replica_number, 'count': len(instance_id)}) if replica_number == 1: raise for replica in replicas: replica.wait_for_instance(CONF.restore_usage_timeout, flavor) finally: if replica_backup_created: Backup.delete(context, replica_backup_id) def create_instance(self, context, instance_id, name, flavor, image_id, databases, users, datastore_manager, packages, volume_size, backup_id, availability_zone, root_password, nics, overrides, slave_of_id, cluster_config): if slave_of_id: self._create_replication_slave(context, instance_id, name, flavor, image_id, databases, users, datastore_manager, packages, volume_size, availability_zone, root_password, nics, overrides, slave_of_id, backup_id) else: if type(instance_id) in [list]: raise AttributeError(_( "Cannot create multiple non-replica instances.")) instance_tasks = FreshInstanceTasks.load(context, instance_id) instance_tasks.create_instance(flavor, image_id, databases, users, datastore_manager, packages, volume_size, backup_id, availability_zone, root_password, nics, overrides, cluster_config) timeout = (CONF.restore_usage_timeout if backup_id else CONF.usage_timeout) instance_tasks.wait_for_instance(timeout, flavor) def update_overrides(self, context, instance_id, overrides): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.update_overrides(overrides) def unassign_configuration(self, context, instance_id, flavor, configuration_id): instance_tasks = models.BuiltInstanceTasks.load(context, instance_id) instance_tasks.unassign_configuration(flavor, configuration_id) def create_cluster(self, context, cluster_id): cluster_tasks = models.load_cluster_tasks(context, cluster_id) cluster_tasks.create_cluster(context, cluster_id) def delete_cluster(self, context, cluster_id): cluster_tasks = models.load_cluster_tasks(context, cluster_id) cluster_tasks.delete_cluster(context, cluster_id) if CONF.exists_notification_transformer: @periodic_task.periodic_task( ticks_between_runs=CONF.exists_notification_ticks) def publish_exists_event(self, context): """ Push this in Instance Tasks to fetch a report/collection :param context: currently None as specied in bin script """ mgmtmodels.publish_exist_events(self.exists_transformer, self.admin_context) def __getattr__(self, name): """ We should only get here if Python couldn't find a "real" method. """ def raise_error(msg): raise AttributeError(msg) manager, sep, method = name.partition('_') if not manager: raise_error('Cannot derive manager from attribute name "%s"' % name) task_strategy = strategy.load_taskmanager_strategy(manager) if not task_strategy: raise_error('No task manager strategy for manager "%s"' % manager) if method not in task_strategy.task_manager_manager_actions: raise_error('No method "%s" for task manager strategy for manager' ' "%s"' % (method, manager)) return task_strategy.task_manager_manager_actions.get(method)
apache-2.0
hawkowl/axiom
axiom/test/test_queryutil.py
2
4339
import random from twisted.trial.unittest import TestCase from axiom.store import Store from axiom.item import Item from axiom.attributes import integer from axiom.queryutil import overlapping, AttributeTuple class Segment(Item): typeName = 'test_overlap_segment' schemaVersion = 1 x = integer() y = integer() def __repr__(self): return 'Segment<%d,%d>' % (self.x, self.y) class ABC(Item): typeName = 'test_tuple_queries' schemaVersion = 1 a = integer(allowNone=False) b = integer(allowNone=False) c = integer(allowNone=False) class TestQueryUtilities(TestCase): def testBetweenQuery(self): # From a drawn copy of the docstring: s = Store() G = 3 K = 4 H = C = 5 A = 8 D = 11 E = 17 B = 20 F = I = 22 L = 23 J = 24 AB = Segment(store=s, x=A, y=B) CD = Segment(store=s, x=C, y=D) EF = Segment(store=s, x=E, y=F) GH = Segment(store=s, x=G, y=H) IJ = Segment(store=s, x=I, y=J) KL = Segment(store=s, x=K, y=L) AL = Segment(store=s, x=A, y=L) CB = Segment(store=s, x=C, y=B) CA = Segment(store=s, x=C, y=A) BL = Segment(store=s, x=B, y=L) self.assertEquals( list(s.query(Segment, overlapping(Segment.x, Segment.y, A, B), sort=Segment.storeID.asc)), [AB, CD, EF, KL, AL, CB, CA, BL], ) ('(((A > 2)) ' 'OR ((A == 2) AND (B > 3)) ' 'OR ((A == 2) AND (B == 3) AND (C >= 4)))') def testTupleQueryWithTuples(self): s = Store() s.transact(self._dotestTupleQueryWithTuples, s) def _dotestTupleQueryWithTuples(self, s): L = [] for x in range(3): for y in range(3): for z in range(3): L.append((x, y, z)) shuffledL = L[:] random.shuffle(shuffledL) for a, b, c in shuffledL: ABC(a=a, b=b, c=c, store=s) at = AttributeTuple(ABC.a, ABC.b, ABC.c) for comparee in L: qobj = s.query(ABC, at > comparee, sort=[ABC.a.ascending, ABC.b.ascending, ABC.c.ascending]) self.assertEquals( L[L.index(comparee) + 1:], [(o.a, o.b, o.c) for o in qobj]) for comparee in L: qobj = s.query(ABC, at >= comparee, sort=[ABC.a.ascending, ABC.b.ascending, ABC.c.ascending]) self.assertEquals( L[L.index(comparee):], [(o.a, o.b, o.c) for o in qobj]) for comparee in L: qobj = s.query(ABC, at == comparee, sort=[ABC.a.ascending, ABC.b.ascending, ABC.c.ascending]) self.assertEquals( [comparee], [(o.a, o.b, o.c) for o in qobj]) for comparee in L: qobj = s.query(ABC, at != comparee, sort=[ABC.a.ascending, ABC.b.ascending, ABC.c.ascending]) self.assertEquals( L[:L.index(comparee)] + L[L.index(comparee) + 1:], [(o.a, o.b, o.c) for o in qobj]) for comparee in L: qobj = s.query(ABC, at < comparee, sort=[ABC.a.ascending, ABC.b.ascending, ABC.c.ascending]) self.assertEquals( L[:L.index(comparee)], [(o.a, o.b, o.c) for o in qobj]) for comparee in L: qobj = s.query(ABC, at <= comparee, sort=[ABC.a.ascending, ABC.b.ascending, ABC.c.ascending]) self.assertEquals( L[:L.index(comparee) + 1], [(o.a, o.b, o.c) for o in qobj])
mit
Epirex/android_external_chromium_org
build/android/adb_install_apk.py
29
2722
#!/usr/bin/env python # # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility script to install APKs from the command line quickly.""" import multiprocessing import optparse import os import sys from pylib import android_commands from pylib import constants from pylib.utils import apk_helper from pylib.utils import test_options_parser def AddInstallAPKOption(option_parser): """Adds apk option used to install the APK to the OptionParser.""" test_options_parser.AddBuildTypeOption(option_parser) option_parser.add_option('--apk', help=('The name of the apk containing the ' ' application (with the .apk extension).')) option_parser.add_option('--apk_package', help=('The package name used by the apk containing ' 'the application.')) option_parser.add_option('--keep_data', action='store_true', default=False, help=('Keep the package data when installing ' 'the application.')) def ValidateInstallAPKOption(option_parser, options): """Validates the apk option and potentially qualifies the path.""" if not options.apk: option_parser.error('--apk is mandatory.') if not os.path.exists(options.apk): options.apk = os.path.join(constants.GetOutDirectory(), 'apks', options.apk) def _InstallApk(args): apk_path, apk_package, keep_data, device = args android_commands.AndroidCommands(device=device).ManagedInstall( apk_path, keep_data, apk_package) print '----- Installed on %s -----' % device def main(argv): parser = optparse.OptionParser() AddInstallAPKOption(parser) options, args = parser.parse_args(argv) constants.SetBuildType(options.build_type) ValidateInstallAPKOption(parser, options) if len(args) > 1: raise Exception('Error: Unknown argument:', args[1:]) devices = android_commands.GetAttachedDevices() if not devices: raise Exception('Error: no connected devices') if not options.apk_package: options.apk_package = apk_helper.GetPackageName(options.apk) pool = multiprocessing.Pool(len(devices)) # Send a tuple (apk_path, apk_package, device) per device. pool.map(_InstallApk, zip([options.apk] * len(devices), [options.apk_package] * len(devices), [options.keep_data] * len(devices), devices)) if __name__ == '__main__': sys.exit(main(sys.argv))
bsd-3-clause
bodleian/eulfedora
eulfedora/api.py
1
36676
# file eulfedora/api.py # # Copyright 2010,2011 Emory University Libraries # # 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 csv import logging from urlparse import urljoin import warnings import requests from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor, \ user_agent from StringIO import StringIO import time from eulfedora import __version__ as eulfedora_version from eulfedora.util import datetime_to_fedoratime, \ RequestFailed, ChecksumMismatch, PermissionDenied, parse_rdf logger = logging.getLogger(__name__) # low-level wrappers def _safe_str(s): # helper for _safe_urlencode: utf-8 encode unicode strings, convert # non-strings to strings, and leave plain strings untouched. if isinstance(s, unicode): return s.encode('utf-8') else: return str(s) def _get_items(query, doseq): # helper for _safe_urlencode: emulate urllib.urlencode "doseq" logic if hasattr(query, 'items'): query = query.items() for k, v in query: if isinstance(v, basestring): yield k, v elif doseq and iter(v): # if it's iterable for e in v: yield k, e else: yield k, str(v) _sessions = {} class HTTP_API_Base(object): def __init__(self, base_url, username=None, password=None): # standardize url format; ensure we have a trailing slash, # adding one if necessary if not base_url.endswith('/'): base_url = base_url + '/' # TODO: can we re-use sessions safely across instances? global _sessions # check for an existing session for this fedora if base_url in _sessions: self.session = _sessions[base_url] else: # create a new session and add to global sessions self.session = requests.Session() # Set headers to be passed with every request # NOTE: only headers that will be common for *all* requests # to this fedora should be set in the session # (i.e., do NOT include auth information here) self.session.headers = { 'User-Agent': user_agent('eulfedora', eulfedora_version), # 'user-agent': 'eulfedora/%s (python-requests/%s)' % \ # (eulfedora_version, requests.__version__), 'verify': True, # verify SSL certs by default } _sessions[base_url] = self.session self.base_url = base_url self.username = username self.password = password self.request_options = {} if self.username is not None: # store basic auth option to pass when making requests self.request_options['auth'] = (self.username, self.password) def absurl(self, rel_url): return urljoin(self.base_url, rel_url) def prep_url(self, url): return self.absurl(url) # thinnest possible wrappers around requests calls # - add auth, make urls absolute def _make_request(self, reqmeth, url, *args, **kwargs): # copy base request options and update with any keyword args rqst_options = self.request_options.copy() rqst_options.update(kwargs) start = time.time() response = reqmeth(self.prep_url(url), *args, **rqst_options) logger.debug('%s %s=>%d: %f sec' % (reqmeth.__name__.upper(), url, response.status_code, time.time() - start)) # FIXME: handle 3xx (?) [possibly handled for us by requests] if response.status_code >= requests.codes.bad: # 400 or worse # separate out 401 and 403 (permission errors) to enable # special handling in client code. if response.status_code in (requests.codes.unauthorized, requests.codes.forbidden): raise PermissionDenied(response) elif response.status_code == requests.codes.server_error: # check response content to determine if this is a # ChecksumMismatch or a more generic error if 'Checksum Mismatch' in response.content: raise ChecksumMismatch(response) else: raise RequestFailed(response) else: raise RequestFailed(response) return response def get(self, *args, **kwargs): return self._make_request(self.session.get, *args, **kwargs) def put(self, *args, **kwargs): return self._make_request(self.session.put, *args, **kwargs) def post(self, *args, **kwargs): return self._make_request(self.session.post, *args, **kwargs) def delete(self, *args, **kwargs): return self._make_request(self.session.delete, *args, **kwargs) # also available: head, patch class REST_API(HTTP_API_Base): """ Python object for accessing `Fedora's REST API <http://fedora-commons.org/confluence/display/FCR30/REST+API>`_. """ # always return xml response instead of html version format_xml = { 'format' : 'xml'} ### API-A methods (access) #### # describeRepository not implemented in REST, use API-A-LITE version def findObjects(self, query=None, terms=None, pid=True, chunksize=None, session_token=None): """ Wrapper function for `Fedora REST API findObjects <http://fedora-commons.org/confluence/display/FCR30/REST+API#RESTAPI-findObjects>`_ and `Fedora REST API resumeFindObjects <http://fedora-commons.org/confluence/display/FCR30/REST+API#RESTAPI-resumeFindObjects>`_ One and only one of query or terms must be specified. :param query: string of fields and terms to search for :param terms: phrase search across all fields :param pid: include pid in search results :param chunksize: number of objects to return at a time :param session_token: get an additional chunk of results from a prior search :param parse: optional data parser function; defaults to returning raw string data :rtype: string """ if query is not None and terms is not None: raise Exception("Cannot findObject with both query ('%s') and terms ('%s')" % (query, terms)) http_args = {'resultFormat': 'xml'} if query is not None: http_args['query'] = query if terms is not None: http_args['terms'] = terms if pid: http_args['pid'] = 'true' if session_token: http_args['sessionToken'] = session_token if chunksize: http_args['maxResults'] = chunksize return self.get('objects', params=http_args) def getDatastreamDissemination(self, pid, dsID, asOfDateTime=None, stream=False): """Get a single datastream on a Fedora object; optionally, get the version as of a particular date time. :param pid: object pid :param dsID: datastream id :param asOfDateTime: optional datetime; ``must`` be a non-naive datetime so it can be converted to a date-time format Fedora can understand """ # TODO: Note that this loads the entire datastream content into # memory as a Python string. This will suck for very large # datastreams. Eventually we need to either modify this function or # else add another to return self.open(), allowing users to stream # the result in a with block. # /objects/{pid}/datastreams/{dsID}/content ? [asOfDateTime] [download] http_args = {} if asOfDateTime: http_args['asOfDateTime'] = datetime_to_fedoratime(asOfDateTime) url = 'objects/%(pid)s/datastreams/%(dsid)s/content' % \ {'pid': pid, 'dsid': dsID} return self.get(url, params=http_args, stream=stream) # NOTE: getDissemination was not available in REST API until Fedora 3.3 def getDissemination(self, pid, sdefPid, method, method_params={}, return_http_response=False): # /objects/{pid}/methods/{sdefPid}/{method} ? [method parameters] uri = 'objects/%(pid)s/methods/%(sdefpid)s/%(method)s' % \ {'pid': pid, 'sdefpid': sdefPid, 'method': method} return self.get(uri, params=method_params) def getObjectHistory(self, pid): # /objects/{pid}/versions ? [format] return self.get('objects/%(pid)s/versions' % {'pid': pid}, params=self.format_xml) def getObjectProfile(self, pid, asOfDateTime=None): """Get top-level information aboug a single Fedora object; optionally, retrieve information as of a particular date-time. :param pid: object pid :param asOfDateTime: optional datetime; ``must`` be a non-naive datetime so it can be converted to a date-time format Fedora can understand """ # /objects/{pid} ? [format] [asOfDateTime] http_args = {} if asOfDateTime: http_args['asOfDateTime'] = datetime_to_fedoratime(asOfDateTime) http_args.update(self.format_xml) url = 'objects/%(pid)s' % {'pid': pid} return self.get(url, params=http_args) def listDatastreams(self, pid): """ Get a list of all datastreams for a specified object. Wrapper function for `Fedora REST API listDatastreams <http://fedora-commons.org/confluence/display/FCR30/REST+API#RESTAPI-listDatastreams>`_ :param pid: string object pid :param parse: optional data parser function; defaults to returning raw string data :rtype: string xml data """ # /objects/{pid}/datastreams ? [format, datetime] return self.get('objects/%(pid)s/datastreams' % {'pid': pid}, params=self.format_xml) def listMethods(self, pid, sdefpid=None): # /objects/{pid}/methods ? [format, datetime] # /objects/{pid}/methods/{sdefpid} ? [format, datetime] ## NOTE: getting an error when sdefpid is specified; fedora issue? uri = 'objects/%(pid)s/methods' % {'pid': pid} if sdefpid: uri += '/' + sdefpid return self.get(uri, params=self.format_xml) ### API-M methods (management) #### def addDatastream(self, pid, dsID, dsLabel=None, mimeType=None, logMessage=None, controlGroup=None, dsLocation=None, altIDs=None, versionable=None, dsState=None, formatURI=None, checksumType=None, checksum=None, content=None): # objects/{pid}/datastreams/NEWDS? [opts] # content via multipart file in request content, or dsLocation=URI # one of dsLocation or filename must be specified # if checksum is sent without checksum type, Fedora seems to # ignore it (does not error on invalid checksum with no checksum type) if checksum is not None and checksumType is None: warnings.warn('Fedora will ignore the checksum (%s) because no checksum type is specified' \ % checksum) http_args = {'dsLabel': dsLabel, 'mimeType': mimeType} if logMessage: http_args['logMessage'] = logMessage if controlGroup: http_args['controlGroup'] = controlGroup if dsLocation: http_args['dsLocation'] = dsLocation if altIDs: http_args['altIDs'] = altIDs if versionable is not None: http_args['versionable'] = versionable if dsState: http_args['dsState'] = dsState if formatURI: http_args['formatURI'] = formatURI if checksumType: http_args['checksumType'] = checksumType if checksum: http_args['checksum'] = checksum # Added code to match how content is now handled, see modifyDatastream. extra_args = {} # could be a string or a file-like object if content: if hasattr(content, 'read'): # if content is a file-like object, warn if no checksum if not checksum: logger.warning("File was ingested into fedora without a passed checksum for validation, pid was: %s and dsID was: %s." % (pid, dsID)) extra_args['files'] = {'file': content} # m = MultipartEncoder(fields={'file': content}) # extra_args.update({ # 'data': m, # 'headers': {'Content-Type': m.content_type} # }) else: extra_args['data'] = content # extra_args['data'] # extra_args['files'] = StringIO(content) # set content-type header ? url = 'objects/%s/datastreams/%s' % (pid, dsID) return self.post(url, params=http_args, **extra_args) # expected response: 201 Created (on success) # when pid is invalid, response body contains error message # e.g., no path in db registry for [bogus:pid] # return success/failure and any additional information # return (r.status_code == requests.codes.created, r.content) def addRelationship(self, pid, subject, predicate, object, isLiteral=False, datatype=None): """ Wrapper function for `Fedora REST API addRelationsphi <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-addRelationship>`_ :param pid: persistent id for the object to add the new relationship to :param subject: subject of the relationship; object or datastream URI :param predicate: predicate of the new relationship :param object: object of the relationship :param isLiteral: true if object is literal, false if it is a URI; Fedora has no default; this method defaults to False :param datatype: optional datatype for literal objects :returns: boolean success """ http_args = {'subject': subject, 'predicate': predicate, 'object': object, 'isLiteral': isLiteral} if datatype is not None: http_args['datatype'] = datatype url = 'objects/%(pid)s/relationships/new' % {'pid': pid} r = self.post(url, params=http_args) return r.status_code == requests.codes.ok def compareDatastreamChecksum(self, pid, dsID, asOfDateTime=None): # date time # special case of getDatastream, with validateChecksum = true # currently returns datastream info returned by getDatastream... what should it return? return self.getDatastream(pid, dsID, validateChecksum=True, asOfDateTime=asOfDateTime) def export(self, pid, context=None, format=None, encoding=None): # /objects/{pid}/export ? [format] [context] [encoding] # - if format is not specified, use fedora default (FOXML 1.1) # - if encoding is not specified, use fedora default (UTF-8) # - context should be one of: public, migrate, archive (default is public) http_args = {} if context: http_args['context'] = context if format: http_args['format'] = format if encoding: http_args['encoding'] = encoding uri = 'objects/%s/export' % pid return self.get(uri, params=http_args) def getDatastream(self, pid, dsID, asOfDateTime=None, validateChecksum=False): """Get information about a single datastream on a Fedora object; optionally, get information for the version of the datastream as of a particular date time. :param pid: object pid :param dsID: datastream id :param asOfDateTime: optional datetime; ``must`` be a non-naive datetime so it can be converted to a date-time format Fedora can understand """ # /objects/{pid}/datastreams/{dsID} ? [asOfDateTime] [format] [validateChecksum] http_args = {} if validateChecksum: # fedora only responds to lower-case validateChecksum option http_args['validateChecksum'] = str(validateChecksum).lower() if asOfDateTime: http_args['asOfDateTime'] = datetime_to_fedoratime(asOfDateTime) http_args.update(self.format_xml) uri = 'objects/%(pid)s/datastreams/%(dsid)s' % {'pid': pid, 'dsid': dsID} return self.get(uri, params=http_args) def getDatastreamHistory(self, pid, dsid, format=None): http_args = {} if format is not None: http_args['format'] = format # Fedora docs say the url should be: # /objects/{pid}/datastreams/{dsid}/versions # In Fedora 3.4.3, that 404s but /history does not uri = 'objects/%(pid)s/datastreams/%(dsid)s/history' % \ {'pid': pid, 'dsid': dsid} return self.get(uri, params=http_args) # getDatastreams not implemented in REST API def getNextPID(self, numPIDs=None, namespace=None): """ Wrapper function for `Fedora REST API getNextPid <http://fedora-commons.org/confluence/display/FCR30/REST+API#RESTAPI-getNextPID>`_ :param numPIDs: (optional) get the specified number of pids; by default, returns 1 :param namespace: (optional) get the next pid in the specified pid namespace; otherwise, Fedora will return the next pid in the configured default namespace. :rtype: string (if only 1 pid requested) or list of strings (multiple pids) """ http_args = { 'format': 'xml' } if numPIDs: http_args['numPIDs'] = numPIDs if namespace: http_args['namespace'] = namespace rel_url = 'objects/nextPID' return self.post(rel_url, params=http_args) def getObjectXML(self, pid): """ Return the entire xml for the specified object. :param pid: pid of the object to retrieve :param parse: optional data parser function; defaults to returning raw string data :rtype: string xml content of entire object """ # /objects/{pid}/objectXML return self.get('objects/%(pid)s/objectXML' % {'pid': pid}) def getRelationships(self, pid, subject=None, predicate=None, format=None): ''' Get information about relationships on an object. Wrapper function for `Fedora REST API getRelationships <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-getRelationships>`_ ''' http_args = {} if subject is not None: http_args['subject'] = subject if predicate is not None: http_args['predicate'] = predicate if format is not None: http_args['format'] = format url = 'objects/%(pid)s/relationships' % {'pid': pid} return self.get(url, params=http_args) def ingest(self, text, logMessage=None): """ Ingest a new object into Fedora. Returns the pid of the new object on success. Wrapper function for `Fedora REST API ingest <http://fedora-commons.org/confluence/display/FCR30/REST+API#RESTAPI-ingest>`_ :param text: full text content of the object to be ingested :param logMessage: optional log message :rtype: string """ # FIXME/TODO: add options for ingest with pid, values for label/format/namespace/ownerId, etc? http_args = {} if logMessage: http_args['logMessage'] = logMessage headers = {'Content-Type': 'text/xml'} url = 'objects/new' return self.post(url, data=text, params=http_args, headers=headers) # FIXME: check response status code first? # return r.content # content is new pid def modifyDatastream(self, pid, dsID, dsLabel=None, mimeType=None, logMessage=None, dsLocation=None, altIDs=None, versionable=None, dsState=None, formatURI=None, checksumType=None, checksum=None, content=None, force=False): # /objects/{pid}/datastreams/{dsID} ? [dsLocation] [altIDs] [dsLabel] [versionable] [dsState] [formatURI] [checksumType] [checksum] [mimeType] [logMessage] [force] [ignoreContent] # NOTE: not implementing ignoreContent (unneeded) # content via multipart file in request content, or dsLocation=URI # if dsLocation or content is not specified, datastream content will not be updated # content can be string or a file-like object # Unlike addDatastream, if checksum is sent without checksum # type, Fedora honors it (*does* error on invalid checksum # with no checksum type) - it seems to use the existing # checksum type if a new type is not specified. http_args = {} if dsLabel: http_args['dsLabel'] = dsLabel if mimeType: http_args['mimeType'] = mimeType if logMessage: http_args['logMessage'] = logMessage if dsLocation: http_args['dsLocation'] = dsLocation if altIDs: http_args['altIDs'] = altIDs if versionable is not None: http_args['versionable'] = versionable if dsState: http_args['dsState'] = dsState if formatURI: http_args['formatURI'] = formatURI if checksumType: http_args['checksumType'] = checksumType if checksum: http_args['checksum'] = checksum if force: http_args['force'] = force content_args = {} if content: # content can be either a string or a file-like object if hasattr(content, 'read'): # allow content to be a file # warn about missing checksums for files if not checksum: logger.warning("Updating datastream %s/%s with a file, but no checksum passed" \ % (pid, dsID)) # either way (string or file-like object), set content as request data # (file-like objects supported in requests as of 0.13.1) content_args['data'] = content url = 'objects/%s/datastreams/%s' % (pid, dsID) return self.put(url, params=http_args, **content_args) # expected response: 200 (success) # response body contains error message, if any # return success/failure and any additional information # return r.content # return (r.status_code == requests.codes.ok, r.content) def modifyObject(self, pid, label, ownerId, state, logMessage=None): # /objects/{pid} ? [label] [ownerId] [state] [logMessage] http_args = {'label' : label, 'ownerId' : ownerId, 'state' : state} if logMessage is not None: http_args['logMessage'] = logMessage url = 'objects/%(pid)s' % {'pid': pid} return self.put(url, params=http_args) # returns response code 200 on success # return r.status_code == requests.codes.ok def purgeDatastream(self, pid, dsID, startDT=None, endDT=None, logMessage=None, force=False): """ Purge a datastream, or versions of a dastream, from a Fedora object. :param pid: object pid :param dsID: datastream ID :param startDT: optional start datetime (when purging certain versions) :param endDT: optional end datetime (when purging certain versions) :param logMessage: optional log message :returns: tuple of success/failure and response content; on success, response content is a list of timestamps for the datastream purged; on failure, response content may contain an error message """ # /objects/{pid}/datastreams/{dsID} ? [startDT] [endDT] [logMessage] [force] http_args = {} if logMessage: http_args['logMessage'] = logMessage if startDT: http_args['startDT'] = startDT if endDT: http_args['endDT'] = endDT if force: http_args['force'] = force url = 'objects/%(pid)s/datastreams/%(dsid)s' % {'pid': pid, 'dsid': dsID} return self.delete(url, params=http_args) # as of Fedora 3.4, returns 200 on success with a list of the # timestamps for the versions deleted as response content # NOTE: response content may be useful on error, e.g. # no path in db registry for [bogus:pid] # is there any useful way to pass this info back? # *NOTE*: bug when purging non-existent datastream on a valid pid # - reported here: http://www.fedora-commons.org/jira/browse/FCREPO-690 # - as a possible work-around, could return false when status = 200 # but response body is an empty list (i.e., no datastreams/versions purged) # NOTE: previously returned this # return r.status_code == 200, response.read() def purgeObject(self, pid, logMessage=None): """ Purge an object from Fedora. Wrapper function for `REST API purgeObject <http://fedora-commons.org/confluence/display/FCR30/REST+API#RESTAPI-purgeObject>`_ :param pid: pid of the object to be purged :param logMessage: optional log message """ # FIXME: return success/failure? http_args = {} if logMessage: http_args['logMessage'] = logMessage url = 'objects/%(pid)s' % {'pid': pid} return self.delete(url, params=http_args) # as of Fedora 3.4, returns 200 on success; response content is timestamp # return response.status == requests.codes.ok, response.content def purgeRelationship(self, pid, subject, predicate, object, isLiteral=False, datatype=None): ''' Remove a relationship from an object. Wrapper function for `Fedora REST API purgeRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-purgeRelationship>`_ :returns: boolean; indicates whether or not a relationship was removed ''' http_args = {'subject': subject, 'predicate': predicate, 'object': object, 'isLiteral': isLiteral} if datatype is not None: http_args['datatype'] = datatype url = 'objects/%(pid)s/relationships' % {'pid': pid} r = self.delete(url, params=http_args) # should have a status code of 200; # response body text indicates if a relationship was purged or not return r.status_code == requests.codes.ok and r.content == 'true' def setDatastreamState(self, pid, dsID, dsState): # /objects/{pid}/datastreams/{dsID} ? [dsState] http_args = {'dsState' : dsState} url = 'objects/%(pid)s/datastreams/%(dsid)s' % {'pid': pid, 'dsid': dsID} r = self.put(url, params=http_args) # returns response code 200 on success return r.status_code == requests.codes.ok def setDatastreamVersionable(self, pid, dsID, versionable): # /objects/{pid}/datastreams/{dsID} ? [versionable] http_args = { 'versionable' : versionable } url = 'objects/%(pid)s/datastreams/%(dsid)s' % {'pid': pid, 'dsid': dsID} r = self.put(url, params=http_args) # returns response code 200 on success return r.status_code == requests.codes.ok ### utility methods def upload(self, data, callback=None): ''' Upload a multi-part file for content to ingest. Returns a temporary upload id that can be used as a datstream location. :param data: content string or file-like object to be uploaded :param callback: optional callback method to monitor the upload; see :mod:`requests-toolbelt` documentation for more details: https://toolbelt.readthedocs.org/en/latest/user.html#uploading-data :returns: upload id on success ''' url = 'upload' # fedora only expects content uploaded as multipart file; # make string content into a file-like object so requests.post # sends it the way Fedora expects. if not hasattr(data, 'read'): data = StringIO(data) # use requests-toolbelt multipart encoder to avoid reading # the full content of large files into memory m = MultipartEncoder(fields={'file': data}) if callback is not None: m = MultipartEncoderMonitor(m, callback) try: r = self.post(url, data=m, headers={'Content-Type': m.content_type}) except OverflowError as err: # Python __len__ uses integer so it is limited to system maxint, # and requests and requests-toolbelt use len() throughout. # This results in an overflow error when trying to upload a file # larger than system maxint (2GB on 32-bit OSes). # See http://bugs.python.org/issue12159 msg = 'upload content larger than system maxint (32-bit OS limitation)' logger.error('OverflowError: %s', msg) raise OverflowError(msg) if r.status_code == requests.codes.accepted: return r.content.strip() # returns 202 Accepted on success # content of response should be upload id, if successful # NOTE: the "LITE" APIs are planned to be phased out; when that happens, these functions # (or their equivalents) should be available in the REST API class API_A_LITE(HTTP_API_Base): """ Python object for accessing `Fedora's API-A-LITE <http://fedora-commons.org/confluence/display/FCR30/API-A-LITE>`_. """ def describeRepository(self): """ Get information about a Fedora repository. :rtype: string """ http_args = { 'xml': 'true' } return self.get('describe', params=http_args) class ApiFacade(REST_API, API_A_LITE): """Pull together all Fedora APIs into one place.""" # as of 3.4, REST API covers everything except describeRepository def __init__(self, base_url, username=None, password=None): HTTP_API_Base.__init__(self, base_url, username, password) class UnrecognizedQueryLanguage(EnvironmentError): pass class ResourceIndex(HTTP_API_Base): "Python object for accessing Fedora's Resource Index." RISEARCH_FLUSH_ON_QUERY = False """Specify whether or not RI search queries should specify flush=true to obtain the most recent results. If flush is specified to the query method, that takes precedence. Irrelevant if Fedora RIsearch is configured with syncUpdates = True. """ def find_statements(self, query, language='spo', type='triples', flush=None): """ Run a query in a format supported by the Fedora Resource Index (e.g., SPO or Sparql) and return the results. :param query: query as a string :param language: query language to use; defaults to 'spo' :param type: type of query - tuples or triples; defaults to 'triples' :param flush: flush results to get recent changes; defaults to False :rtype: :class:`rdflib.ConjunctiveGraph` when type is ``triples``; list of dictionaries (keys based on return fields) when type is ``tuples`` """ http_args = { 'type': type, 'lang': language, 'query': query, } if type == 'triples': format = 'N-Triples' elif type == 'tuples': format = 'CSV' # else - error/exception ? http_args['format'] = format return self._query(format, http_args, flush) def count_statements(self, query, language='spo', type='triples', flush=None): """ Run a query in a format supported by the Fedora Resource Index (e.g., SPO or Sparql) and return the count of the results. :param query: query as a string :param language: query language to use; defaults to 'spo' :param flush: flush results to get recent changes; defaults to False :rtype: integer """ format = 'count' http_args = { 'type': type, 'lang': language, 'query': query, 'format': format } return self._query(format, http_args, flush) def _query(self, format, http_args, flush=None): # if flush parameter was not specified, use class setting if flush is None: flush = self.RISEARCH_FLUSH_ON_QUERY http_args['flush'] = 'true' if flush else 'false' # log the actual query so it's easier to see what's happening logger.debug('risearch query type=%(type)s language=%(lang)s format=%(format)s flush=%(flush)s\n%(query)s' % \ http_args) url = 'risearch' try: r = self.get(url, params=http_args) data, abs_url = r.content, r.url # parse the result according to requested format if format == 'N-Triples': return parse_rdf(data, abs_url, format='n3') elif format == 'CSV': # reader expects a file or a list; for now, just split the string # TODO: when we can return url contents as file-like objects, use that return csv.DictReader(data.split('\n')) elif format == 'count': return int(data) # should we return the response as fallback? except RequestFailed, f: if 'Unrecognized query language' in f.detail: raise UnrecognizedQueryLanguage(f.detail) # could also see 'Unsupported output format' else: raise f def spo_search(self, subject=None, predicate=None, object=None): """ Create and run a subject-predicate-object (SPO) search. Any search terms that are not specified will be replaced as a wildcard in the query. :param subject: optional subject to search :param predicate: optional predicate to search :param object: optional object to search :rtype: :class:`rdflib.ConjunctiveGraph` """ spo_query = '%s %s %s' % \ (self.spoencode(subject), self.spoencode(predicate), self.spoencode(object)) return self.find_statements(spo_query) def spoencode(self, val): """ Encode search terms for an SPO query. :param val: string to be encoded :rtype: string """ if val is None: return '*' elif "'" in val: # FIXME: need better handling for literal strings return val else: return '<%s>' % (val,) def get_subjects(self, predicate, object): """ Search for all subjects related to the specified predicate and object. :param predicate: :param object: :rtype: generator of RDF statements """ for statement in self.spo_search(predicate=predicate, object=object): yield str(statement[0]) def get_predicates(self, subject, object): """ Search for all subjects related to the specified subject and object. :param subject: :param object: :rtype: generator of RDF statements """ for statement in self.spo_search(subject=subject, object=object): yield str(statement[1]) def get_objects(self, subject, predicate): """ Search for all subjects related to the specified subject and predicate. :param subject: :param object: :rtype: generator of RDF statements """ for statement in self.spo_search(subject=subject, predicate=predicate): yield str(statement[2]) def sparql_query(self, query, flush=None): """ Run a Sparql query. :param query: sparql query string :rtype: list of dictionary """ return self.find_statements(query, language='sparql', type='tuples', flush=flush)
apache-2.0
wkhtmltopdf/qtwebkit
Tools/Scripts/webkitpy/common/system/executive_unittest.py
124
13048
# Copyright (C) 2010 Google Inc. All rights reserved. # Copyright (C) 2009 Daniel Bates (dbates@intudata.com). 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 Google Inc. 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. import os import errno import signal import subprocess import sys import time # Since we execute this script directly as part of the unit tests, we need to ensure # that Tools/Scripts is in sys.path for the next imports to work correctly. script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) if script_dir not in sys.path: sys.path.append(script_dir) third_party_py = os.path.join(script_dir, "webkitpy", "thirdparty", "autoinstalled") if third_party_py not in sys.path: sys.path.append(third_party_py) import unittest2 as unittest from webkitpy.common.system.executive import Executive, ScriptError from webkitpy.common.system.filesystem_mock import MockFileSystem class ScriptErrorTest(unittest.TestCase): def test_message_with_output(self): error = ScriptError('My custom message!', '', -1) self.assertEqual(error.message_with_output(), 'My custom message!') error = ScriptError('My custom message!', '', -1, 'My output.') self.assertEqual(error.message_with_output(), 'My custom message!\n\nMy output.') error = ScriptError('', 'my_command!', -1, 'My output.', '/Users/username/blah') self.assertEqual(error.message_with_output(), 'Failed to run "\'my_command!\'" exit_code: -1 cwd: /Users/username/blah\n\nMy output.') error = ScriptError('', 'my_command!', -1, 'ab' + '1' * 499) self.assertEqual(error.message_with_output(), 'Failed to run "\'my_command!\'" exit_code: -1\n\nLast 500 characters of output:\nb' + '1' * 499) def test_message_with_tuple(self): error = ScriptError('', ('my', 'command'), -1, 'My output.', '/Users/username/blah') self.assertEqual(error.message_with_output(), 'Failed to run "(\'my\', \'command\')" exit_code: -1 cwd: /Users/username/blah\n\nMy output.') def never_ending_command(): """Arguments for a command that will never end (useful for testing process killing). It should be a process that is unlikely to already be running because all instances will be killed.""" if sys.platform == 'win32': return ['wmic'] return ['yes'] def command_line(cmd, *args): return [sys.executable, __file__, '--' + cmd] + list(args) class ExecutiveTest(unittest.TestCase): def assert_interpreter_for_content(self, intepreter, content): fs = MockFileSystem() tempfile, temp_name = fs.open_binary_tempfile('') tempfile.write(content) tempfile.close() file_interpreter = Executive.interpreter_for_script(temp_name, fs) self.assertEqual(file_interpreter, intepreter) def test_interpreter_for_script(self): self.assert_interpreter_for_content(None, '') self.assert_interpreter_for_content(None, 'abcd\nefgh\nijklm') self.assert_interpreter_for_content(None, '##/usr/bin/perl') self.assert_interpreter_for_content('perl', '#!/usr/bin/env perl') self.assert_interpreter_for_content('perl', '#!/usr/bin/env perl\nfirst\nsecond') self.assert_interpreter_for_content('perl', '#!/usr/bin/perl') self.assert_interpreter_for_content('perl', '#!/usr/bin/perl -w') self.assert_interpreter_for_content(sys.executable, '#!/usr/bin/env python') self.assert_interpreter_for_content(sys.executable, '#!/usr/bin/env python\nfirst\nsecond') self.assert_interpreter_for_content(sys.executable, '#!/usr/bin/python') self.assert_interpreter_for_content('ruby', '#!/usr/bin/env ruby') self.assert_interpreter_for_content('ruby', '#!/usr/bin/env ruby\nfirst\nsecond') self.assert_interpreter_for_content('ruby', '#!/usr/bin/ruby') def test_run_command_with_bad_command(self): def run_bad_command(): Executive().run_command(["foo_bar_command_blah"], error_handler=Executive.ignore_error, return_exit_code=True) self.assertRaises(OSError, run_bad_command) def test_run_command_args_type(self): executive = Executive() self.assertRaises(AssertionError, executive.run_command, "echo") self.assertRaises(AssertionError, executive.run_command, u"echo") executive.run_command(command_line('echo', 'foo')) executive.run_command(tuple(command_line('echo', 'foo'))) def test_auto_stringify_args(self): executive = Executive() executive.run_command(command_line('echo', 1)) executive.popen(command_line('echo', 1), stdout=executive.PIPE).wait() self.assertEqual('echo 1', executive.command_for_printing(['echo', 1])) def test_popen_args(self): executive = Executive() # Explicitly naming the 'args' argument should not thow an exception. executive.popen(args=command_line('echo', 1), stdout=executive.PIPE).wait() def test_run_command_with_unicode(self): """Validate that it is safe to pass unicode() objects to Executive.run* methods, and they will return unicode() objects by default unless decode_output=False""" unicode_tor_input = u"WebKit \u2661 Tor Arne Vestb\u00F8!" if sys.platform == 'win32': encoding = 'mbcs' else: encoding = 'utf-8' encoded_tor = unicode_tor_input.encode(encoding) # On Windows, we expect the unicode->mbcs->unicode roundtrip to be # lossy. On other platforms, we expect a lossless roundtrip. if sys.platform == 'win32': unicode_tor_output = encoded_tor.decode(encoding) else: unicode_tor_output = unicode_tor_input executive = Executive() output = executive.run_command(command_line('cat'), input=unicode_tor_input) self.assertEqual(output, unicode_tor_output) output = executive.run_command(command_line('echo', unicode_tor_input)) self.assertEqual(output, unicode_tor_output) output = executive.run_command(command_line('echo', unicode_tor_input), decode_output=False) self.assertEqual(output, encoded_tor) # Make sure that str() input also works. output = executive.run_command(command_line('cat'), input=encoded_tor, decode_output=False) self.assertEqual(output, encoded_tor) # FIXME: We should only have one run* method to test output = executive.run_and_throw_if_fail(command_line('echo', unicode_tor_input), quiet=True) self.assertEqual(output, unicode_tor_output) output = executive.run_and_throw_if_fail(command_line('echo', unicode_tor_input), quiet=True, decode_output=False) self.assertEqual(output, encoded_tor) def serial_test_kill_process(self): executive = Executive() process = subprocess.Popen(never_ending_command(), stdout=subprocess.PIPE) self.assertEqual(process.poll(), None) # Process is running executive.kill_process(process.pid) # Note: Can't use a ternary since signal.SIGKILL is undefined for sys.platform == "win32" if sys.platform == "win32": # FIXME: https://bugs.webkit.org/show_bug.cgi?id=54790 # We seem to get either 0 or 1 here for some reason. self.assertIn(process.wait(), (0, 1)) elif sys.platform == "cygwin": # FIXME: https://bugs.webkit.org/show_bug.cgi?id=98196 # cygwin seems to give us either SIGABRT or SIGKILL self.assertIn(process.wait(), (-signal.SIGABRT, -signal.SIGKILL)) else: expected_exit_code = -signal.SIGKILL self.assertEqual(process.wait(), expected_exit_code) # Killing again should fail silently. executive.kill_process(process.pid) def serial_test_kill_all(self): executive = Executive() process = subprocess.Popen(never_ending_command(), stdout=subprocess.PIPE) self.assertIsNone(process.poll()) # Process is running executive.kill_all(never_ending_command()[0]) # Note: Can't use a ternary since signal.SIGTERM is undefined for sys.platform == "win32" if sys.platform == "cygwin": expected_exit_code = 0 # os.kill results in exit(0) for this process. self.assertEqual(process.wait(), expected_exit_code) elif sys.platform == "win32": # FIXME: https://bugs.webkit.org/show_bug.cgi?id=54790 # We seem to get either 0 or 1 here for some reason. self.assertIn(process.wait(), (0, 1)) else: expected_exit_code = -signal.SIGTERM self.assertEqual(process.wait(), expected_exit_code) # Killing again should fail silently. executive.kill_all(never_ending_command()[0]) def _assert_windows_image_name(self, name, expected_windows_name): executive = Executive() windows_name = executive._windows_image_name(name) self.assertEqual(windows_name, expected_windows_name) def test_windows_image_name(self): self._assert_windows_image_name("foo", "foo.exe") self._assert_windows_image_name("foo.exe", "foo.exe") self._assert_windows_image_name("foo.com", "foo.com") # If the name looks like an extension, even if it isn't # supposed to, we have no choice but to return the original name. self._assert_windows_image_name("foo.baz", "foo.baz") self._assert_windows_image_name("foo.baz.exe", "foo.baz.exe") def serial_test_check_running_pid(self): executive = Executive() self.assertTrue(executive.check_running_pid(os.getpid())) # Maximum pid number on Linux is 32768 by default self.assertFalse(executive.check_running_pid(100000)) def serial_test_running_pids(self): if sys.platform in ("win32", "cygwin"): return # This function isn't implemented on Windows yet. executive = Executive() pids = executive.running_pids() self.assertIn(os.getpid(), pids) def serial_test_run_in_parallel(self): # We run this test serially to avoid overloading the machine and throwing off the timing. if sys.platform in ("win32", "cygwin"): return # This function isn't implemented properly on windows yet. import multiprocessing NUM_PROCESSES = 4 DELAY_SECS = 0.25 cmd_line = [sys.executable, '-c', 'import time; time.sleep(%f); print "hello"' % DELAY_SECS] cwd = os.getcwd() commands = [tuple([cmd_line, cwd])] * NUM_PROCESSES start = time.time() command_outputs = Executive().run_in_parallel(commands, processes=NUM_PROCESSES) done = time.time() self.assertTrue(done - start < NUM_PROCESSES * DELAY_SECS) self.assertEqual([output[1] for output in command_outputs], ["hello\n"] * NUM_PROCESSES) self.assertEqual([], multiprocessing.active_children()) def test_run_in_parallel_assert_nonempty(self): self.assertRaises(AssertionError, Executive().run_in_parallel, []) def main(platform, stdin, stdout, cmd, args): if platform == 'win32' and hasattr(stdout, 'fileno'): import msvcrt msvcrt.setmode(stdout.fileno(), os.O_BINARY) if cmd == '--cat': stdout.write(stdin.read()) elif cmd == '--echo': stdout.write(' '.join(args)) return 0 if __name__ == '__main__' and len(sys.argv) > 1 and sys.argv[1] in ('--cat', '--echo'): sys.exit(main(sys.platform, sys.stdin, sys.stdout, sys.argv[1], sys.argv[2:]))
gpl-2.0
thezawad/kivy
kivy/vector.py
44
10228
'''Vector ====== The :class:`Vector` represents a 2D vector (x, y). Our implementation is built on top of a Python list. An example of constructing a Vector:: >>> # Construct a point at 82,34 >>> v = Vector(82, 34) >>> v[0] 82 >>> v.x 82 >>> v[1] 34 >>> v.y 34 >>> # Construct by giving a list of 2 values >>> pos = (93, 45) >>> v = Vector(pos) >>> v[0] 93 >>> v.x 93 >>> v[1] 45 >>> v.y 45 Optimized usage --------------- Most of the time, you can use a list for arguments instead of using a Vector. For example, if you want to calculate the distance between 2 points:: a = (10, 10) b = (87, 34) # optimized method print('distance between a and b:', Vector(a).distance(b)) # non-optimized method va = Vector(a) vb = Vector(b) print('distance between a and b:', va.distance(vb)) Vector operators ---------------- The :class:`Vector` supports some numeric operators such as +, -, /:: >>> Vector(1, 1) + Vector(9, 5) [10, 6] >>> Vector(9, 5) - Vector(5, 5) [4, 0] >>> Vector(10, 10) / Vector(2., 4.) [5.0, 2.5] >>> Vector(10, 10) / 5. [2.0, 2.0] You can also use in-place operators:: >>> v = Vector(1, 1) >>> v += 2 >>> v [3, 3] >>> v *= 5 [15, 15] >>> v /= 2. [7.5, 7.5] ''' __all__ = ('Vector', ) import math class Vector(list): '''Vector class. See module documentation for more information. ''' def __init__(self, *largs): if len(largs) == 1: super(Vector, self).__init__(largs[0]) elif len(largs) == 2: super(Vector, self).__init__(largs) else: raise Exception('Invalid vector') def _get_x(self): return self[0] def _set_x(self, x): self[0] = x x = property(_get_x, _set_x) ''':attr:`x` represents the first element in the list. >>> v = Vector(12, 23) >>> v[0] 12 >>> v.x 12 ''' def _get_y(self): return self[1] def _set_y(self, y): self[1] = y y = property(_get_y, _set_y) ''':attr:`y` represents the second element in the list. >>> v = Vector(12, 23) >>> v[1] 23 >>> v.y 23 ''' def __getslice__(self, i, j): try: # use the list __getslice__ method and convert # result to vector return Vector(super(Vector, self).__getslice__(i, j)) except Exception: raise TypeError('vector::FAILURE in __getslice__') def __add__(self, val): return Vector(list(map(lambda x, y: x + y, self, val))) def __iadd__(self, val): if type(val) in (int, float): self.x += val self.y += val else: self.x += val.x self.y += val.y return self def __neg__(self): return Vector([-x for x in self]) def __sub__(self, val): return Vector(list(map(lambda x, y: x - y, self, val))) def __isub__(self, val): if type(val) in (int, float): self.x -= val self.y -= val else: self.x -= val.x self.y -= val.y return self def __mul__(self, val): try: return Vector(list(map(lambda x, y: x * y, self, val))) except Exception: return Vector([x * val for x in self]) def __imul__(self, val): if type(val) in (int, float): self.x *= val self.y *= val else: self.x *= val.x self.y *= val.y return self def __rmul__(self, val): return (self * val) def __truediv__(self, val): try: return Vector(list(map(lambda x, y: x / y, self, val))) except Exception: return Vector([x / val for x in self]) def __div__(self, val): try: return Vector(list(map(lambda x, y: x / y, self, val))) except Exception: return Vector([x / val for x in self]) def __rtruediv__(self, val): try: return Vector(*val) / self except Exception: return Vector(val, val) / self def __rdiv__(self, val): try: return Vector(*val) / self except Exception: return Vector(val, val) / self def __idiv__(self, val): if type(val) in (int, float): self.x /= val self.y /= val else: self.x /= val.x self.y /= val.y return self def length(self): '''Returns the length of a vector. >>> Vector(10, 10).length() 14.142135623730951 >>> pos = (10, 10) >>> Vector(pos).length() 14.142135623730951 ''' return math.sqrt(self[0] ** 2 + self[1] ** 2) def length2(self): '''Returns the length of a vector squared. >>> Vector(10, 10).length2() 200 >>> pos = (10, 10) >>> Vector(pos).length2() 200 ''' return self[0] ** 2 + self[1] ** 2 def distance(self, to): '''Returns the distance between two points. >>> Vector(10, 10).distance((5, 10)) 5. >>> a = (90, 33) >>> b = (76, 34) >>> Vector(a).distance(b) 14.035668847618199 ''' return math.sqrt((self[0] - to[0]) ** 2 + (self[1] - to[1]) ** 2) def distance2(self, to): '''Returns the distance between two points squared. >>> Vector(10, 10).distance2((5, 10)) 25 ''' return (self[0] - to[0]) ** 2 + (self[1] - to[1]) ** 2 def normalize(self): '''Returns a new vector that has the same direction as vec, but has a length of one. >>> v = Vector(88, 33).normalize() >>> v [0.93632917756904444, 0.3511234415883917] >>> v.length() 1.0 ''' if self[0] == 0. and self[1] == 0.: return Vector(0., 0.) return self / self.length() def dot(self, a): '''Computes the dot product of a and b. >>> Vector(2, 4).dot((2, 2)) 12 ''' return self[0] * a[0] + self[1] * a[1] def angle(self, a): '''Computes the angle between a and b, and returns the angle in degrees. >>> Vector(100, 0).angle((0, 100)) -90.0 >>> Vector(87, 23).angle((-77, 10)) -157.7920283010705 ''' angle = -(180 / math.pi) * math.atan2( self[0] * a[1] - self[1] * a[0], self[0] * a[0] + self[1] * a[1]) return angle def rotate(self, angle): '''Rotate the vector with an angle in degrees. >>> v = Vector(100, 0) >>> v.rotate(45) >>> v [70.710678118654755, 70.710678118654741] ''' angle = math.radians(angle) return Vector( (self[0] * math.cos(angle)) - (self[1] * math.sin(angle)), (self[1] * math.cos(angle)) + (self[0] * math.sin(angle))) @staticmethod def line_intersection(v1, v2, v3, v4): ''' Finds the intersection point between the lines (1)v1->v2 and (2)v3->v4 and returns it as a vector object. >>> a = (98, 28) >>> b = (72, 33) >>> c = (10, -5) >>> d = (20, 88) >>> Vector.line_intersection(a, b, c, d) [15.25931928687196, 43.911669367909241] .. warning:: This is a line intersection method, not a segment intersection. For math see: http://en.wikipedia.org/wiki/Line-line_intersection ''' #linear algebar sucks...seriously!! x1, x2, x3, x4 = float(v1[0]), float(v2[0]), float(v3[0]), float(v4[0]) y1, y2, y3, y4 = float(v1[1]), float(v2[1]), float(v3[1]), float(v4[1]) u = (x1 * y2 - y1 * x2) v = (x3 * y4 - y3 * x4) denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if denom == 0: return None px = (u * (x3 - x4) - (x1 - x2) * v) / denom py = (u * (y3 - y4) - (y1 - y2) * v) / denom return Vector(px, py) @staticmethod def segment_intersection(v1, v2, v3, v4): ''' Finds the intersection point between segments (1)v1->v2 and (2)v3->v4 and returns it as a vector object. >>> a = (98, 28) >>> b = (72, 33) >>> c = (10, -5) >>> d = (20, 88) >>> Vector.segment_intersection(a, b, c, d) None >>> a = (0, 0) >>> b = (10, 10) >>> c = (0, 10) >>> d = (10, 0) >>> Vector.segment_intersection(a, b, c, d) [5, 5] ''' #Yaaay! I love linear algebra applied within the realms of geometry. x1, x2, x3, x4 = float(v1[0]), float(v2[0]), float(v3[0]), float(v4[0]) y1, y2, y3, y4 = float(v1[1]), float(v2[1]), float(v3[1]), float(v4[1]) #This is mostly the same as the line_intersection u = (x1 * y2 - y1 * x2) v = (x3 * y4 - y3 * x4) denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if denom == 0: return None px = (u * (x3 - x4) - (x1 - x2) * v) / denom py = (u * (y3 - y4) - (y1 - y2) * v) / denom #Here are the new bits c1 = (x1 <= px <= x2) or (x2 <= px <= x1) c2 = (y1 <= py <= y2) or (y2 <= py <= y1) c3 = (x3 <= px <= x4) or (x4 <= px <= x3) c4 = (y3 <= py <= y4) or (y4 <= py <= y3) if (c1 and c2) and (c3 and c4): return Vector(px, py) else: return None @staticmethod def in_bbox(point, a, b): '''Return True if `point` is in the bounding box defined by `a` and `b`. >>> bmin = (0, 0) >>> bmax = (100, 100) >>> Vector.in_bbox((50, 50), bmin, bmax) True >>> Vector.in_bbox((647, -10), bmin, bmax) False ''' return ((point[0] <= a[0] and point[0] >= b[0] or point[0] <= b[0] and point[0] >= a[0]) and (point[1] <= a[1] and point[1] >= b[1] or point[1] <= b[1] and point[1] >= a[1]))
mit
40223244/cdb-1
static/Brython3.1.1-20150328-091302/Lib/inspect.py
637
78935
"""Get useful information from live Python objects. This module encapsulates the interface provided by the internal special attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion. It also provides some help for examining source code and class layout. Here are some of the useful functions provided by this module: ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(), isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(), isroutine() - check object types getmembers() - get members of an object that satisfy a given condition getfile(), getsourcefile(), getsource() - find an object's source code getdoc(), getcomments() - get documentation on an object getmodule() - determine the module that an object came from getclasstree() - arrange classes so as to represent their hierarchy getargspec(), getargvalues(), getcallargs() - get info about function arguments getfullargspec() - same, with support for Python-3000 features formatargspec(), formatargvalues() - format an argument spec getouterframes(), getinnerframes() - get info about frames currentframe() - get the current stack frame stack(), trace() - get info about frames on the stack or in a traceback signature() - get a Signature object for the callable """ # This module is in the public domain. No warranties. __author__ = ('Ka-Ping Yee <ping@lfw.org>', 'Yury Selivanov <yselivanov@sprymix.com>') import imp import importlib.machinery import itertools import linecache import os import re import sys import tokenize import types import warnings import functools import builtins from operator import attrgetter from collections import namedtuple, OrderedDict # Create constants for the compiler flags in Include/code.h # We try to get them from dis to avoid duplication, but fall # back to hardcoding so the dependency is optional try: from dis import COMPILER_FLAG_NAMES as _flag_names except ImportError: CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40 else: mod_dict = globals() for k, v in _flag_names.items(): mod_dict["CO_" + v] = k # See Include/object.h TPFLAGS_IS_ABSTRACT = 1 << 20 # ----------------------------------------------------------- type-checking def ismodule(object): """Return true if the object is a module. Module objects provide these attributes: __cached__ pathname to byte compiled file __doc__ documentation string __file__ filename (missing for built-in modules)""" return isinstance(object, types.ModuleType) def isclass(object): """Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined""" return isinstance(object, type) def ismethod(object): """Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined __func__ function object containing implementation of method __self__ instance to which this method is bound""" return isinstance(object, types.MethodType) def ismethoddescriptor(object): """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the __func__ attribute (etc) when an object passes ismethod().""" if isclass(object) or ismethod(object) or isfunction(object): # mutual exclusion return False tp = type(object) return hasattr(tp, "__get__") and not hasattr(tp, "__set__") def isdatadescriptor(object): """Return true if the object is a data descriptor. Data descriptors have both a __get__ and a __set__ attribute. Examples are properties (defined in Python) and getsets and members (defined in C). Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed.""" if isclass(object) or ismethod(object) or isfunction(object): # mutual exclusion return False tp = type(object) return hasattr(tp, "__set__") and hasattr(tp, "__get__") if hasattr(types, 'MemberDescriptorType'): # CPython and equivalent def ismemberdescriptor(object): """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.""" return isinstance(object, types.MemberDescriptorType) else: # Other implementations def ismemberdescriptor(object): """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.""" return False if hasattr(types, 'GetSetDescriptorType'): # CPython and equivalent def isgetsetdescriptor(object): """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.""" return isinstance(object, types.GetSetDescriptorType) else: # Other implementations def isgetsetdescriptor(object): """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.""" return False def isfunction(object): """Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined __code__ code object containing compiled function bytecode __defaults__ tuple of any default values for arguments __globals__ global namespace in which this function was defined __annotations__ dict of parameter annotations __kwdefaults__ dict of keyword only parameters with defaults""" return isinstance(object, types.FunctionType) def isgeneratorfunction(object): """Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See help(isfunction) for attributes listing.""" return bool((isfunction(object) or ismethod(object)) and object.__code__.co_flags & CO_GENERATOR) def isgenerator(object): """Return true if the object is a generator. Generator objects provide these attributes: __iter__ defined to support iteration over container close raises a new GeneratorExit exception inside the generator to terminate the iteration gi_code code object gi_frame frame object or possibly None once the generator has been exhausted gi_running set to 1 when generator is executing, 0 otherwise next return the next item from the container send resumes the generator and "sends" a value that becomes the result of the current yield-expression throw used to raise an exception inside the generator""" return isinstance(object, types.GeneratorType) def istraceback(object): """Return true if the object is a traceback. Traceback objects provide these attributes: tb_frame frame object at this level tb_lasti index of last attempted instruction in bytecode tb_lineno current line number in Python source code tb_next next inner traceback object (called by this level)""" return isinstance(object, types.TracebackType) def isframe(object): """Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) f_builtins built-in namespace seen by this frame f_code code object being executed in this frame f_globals global namespace seen by this frame f_lasti index of last attempted instruction in bytecode f_lineno current line number in Python source code f_locals local namespace seen by this frame f_trace tracing function for this frame, or None""" return isinstance(object, types.FrameType) def iscode(object): """Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg co_lnotab encoded mapping of line numbers to bytecode indices co_name name with which this code object was defined co_names tuple of names of local variables co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables""" return isinstance(object, types.CodeType) def isbuiltin(object): """Return true if the object is a built-in function or method. Built-in functions and methods provide these attributes: __doc__ documentation string __name__ original name of this function or method __self__ instance to which a method is bound, or None""" return isinstance(object, types.BuiltinFunctionType) def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object)) def isabstract(object): """Return true if the object is an abstract base class (ABC).""" return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT) def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" if isclass(object): mro = (object,) + getmro(object) else: mro = () results = [] for key in dir(object): # First try to get the value via __dict__. Some descriptors don't # like calling their __get__ (see bug #1785). for base in mro: if key in base.__dict__: value = base.__dict__[key] break else: try: value = getattr(object, key) except AttributeError: continue if not predicate or predicate(value): results.append((key, value)) results.sort() return results Attribute = namedtuple('Attribute', 'name kind defining_class object') def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained directly from the defining class's __dict__, not via getattr. This is especially important for data attributes: C.data is just a data object, but C.__dict__['data'] may be a data descriptor with additional info, like a __doc__ string. """ mro = getmro(cls) names = dir(cls) result = [] for name in names: # Get the object associated with the name, and where it was defined. # Getting an obj from the __dict__ sometimes reveals more than # using getattr. Static and class methods are dramatic examples. # Furthermore, some objects may raise an Exception when fetched with # getattr(). This is the case with some descriptors (bug #1785). # Thus, we only use getattr() as a last resort. homecls = None for base in (cls,) + mro: if name in base.__dict__: obj = base.__dict__[name] homecls = base break else: obj = getattr(cls, name) homecls = getattr(obj, "__objclass__", homecls) # Classify the object. if isinstance(obj, staticmethod): kind = "static method" elif isinstance(obj, classmethod): kind = "class method" elif isinstance(obj, property): kind = "property" elif ismethoddescriptor(obj): kind = "method" elif isdatadescriptor(obj): kind = "data" else: obj_via_getattr = getattr(cls, name) if (isfunction(obj_via_getattr) or ismethoddescriptor(obj_via_getattr)): kind = "method" else: kind = "data" obj = obj_via_getattr result.append(Attribute(name, kind, homecls, obj)) return result # ----------------------------------------------------------- class helpers def getmro(cls): "Return tuple of base classes (including cls) in method resolution order." return cls.__mro__ # -------------------------------------------------- source code extraction def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" expline = line.expandtabs() return len(expline) - len(expline.lstrip()) def getdoc(object): """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.""" try: doc = object.__doc__ except AttributeError: return None if not isinstance(doc, str): return None return cleandoc(doc) def cleandoc(doc): """Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed.""" try: lines = doc.expandtabs().split('\n') except UnicodeError: return None else: # Find minimum indentation of any non-blank lines after first line. margin = sys.maxsize for line in lines[1:]: content = len(line.lstrip()) if content: indent = len(line) - content margin = min(margin, indent) # Remove indentation. if lines: lines[0] = lines[0].lstrip() if margin < sys.maxsize: for i in range(1, len(lines)): lines[i] = lines[i][margin:] # Remove any trailing or leading blank lines. while lines and not lines[-1]: lines.pop() while lines and not lines[0]: lines.pop(0) return '\n'.join(lines) def getfile(object): """Work out which source or compiled file an object was defined in.""" if ismodule(object): if hasattr(object, '__file__'): return object.__file__ raise TypeError('{!r} is a built-in module'.format(object)) if isclass(object): object = sys.modules.get(object.__module__) if hasattr(object, '__file__'): return object.__file__ raise TypeError('{!r} is a built-in class'.format(object)) if ismethod(object): object = object.__func__ if isfunction(object): object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): return object.co_filename raise TypeError('{!r} is not a module, class, method, ' 'function, traceback, frame, or code object'.format(object)) ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type') def getmoduleinfo(path): """Get the module name, suffix, mode, and module type for a given file.""" warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning, 2) filename = os.path.basename(path) suffixes = [(-len(suffix), suffix, mode, mtype) for suffix, mode, mtype in imp.get_suffixes()] suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix, mode, mtype in suffixes: if filename[neglen:] == suffix: return ModuleInfo(filename[:neglen], suffix, mode, mtype) def getmodulename(path): """Return the module name for a given file, or None.""" fname = os.path.basename(path) # Check for paths that look like an actual module file suffixes = [(-len(suffix), suffix) for suffix in importlib.machinery.all_suffixes()] suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix in suffixes: if fname.endswith(suffix): return fname[:neglen] return None def getsourcefile(object): """Return the filename that can be used to locate an object's source. Return None if no way can be identified to get the source. """ filename = getfile(object) all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:] all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:] if any(filename.endswith(s) for s in all_bytecode_suffixes): filename = (os.path.splitext(filename)[0] + importlib.machinery.SOURCE_SUFFIXES[0]) elif any(filename.endswith(s) for s in importlib.machinery.EXTENSION_SUFFIXES): return None if os.path.exists(filename): return filename # only return a non-existent filename if the module has a PEP 302 loader if hasattr(getmodule(object, filename), '__loader__'): return filename # or it is in the linecache if filename in linecache.cache: return filename def getabsfile(object, _filename=None): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" if _filename is None: _filename = getsourcefile(object) or getfile(object) return os.path.normcase(os.path.abspath(_filename)) modulesbyfile = {} _filesbymodname = {} def getmodule(object, _filename=None): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if hasattr(object, '__module__'): return sys.modules.get(object.__module__) # Try the filename to modulename cache if _filename is not None and _filename in modulesbyfile: return sys.modules.get(modulesbyfile[_filename]) # Try the cache again with the absolute file name try: file = getabsfile(object, _filename) except TypeError: return None if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) # Update the filename to module name cache and check yet again # Copy sys.modules in order to cope with changes while iterating for modname, module in list(sys.modules.items()): if ismodule(module) and hasattr(module, '__file__'): f = module.__file__ if f == _filesbymodname.get(modname, None): # Have already mapped this module, so skip it continue _filesbymodname[modname] = f f = getabsfile(module) # Always map to the name the module knows itself by modulesbyfile[f] = modulesbyfile[ os.path.realpath(f)] = module.__name__ if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) # Check the main module main = sys.modules['__main__'] if not hasattr(object, '__name__'): return None if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main # Check builtins builtin = sys.modules['builtins'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getfile(object) sourcefile = getsourcefile(object) if not sourcefile and file[:1] + file[-1:] != '<>': raise IOError('source code not available') file = sourcefile if sourcefile else file module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise IOError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^(\s*)class\s*' + name + r'\b') # make some effort to find the best matching class definition: # use the one with the least indentation, which is the one # that's most probably not inside a function definition. candidates = [] for i in range(len(lines)): match = pat.match(lines[i]) if match: # if it's at toplevel, it's already the best one if lines[i][0] == 'c': return lines, i # else add whitespace to candidate list candidates.append((match.group(1), i)) if candidates: # this will sort by whitespace, and by line number, # less whitespace first candidates.sort() return lines, candidates[0][1] else: raise IOError('could not find class definition') if ismethod(object): object = object.__func__ if isfunction(object): object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError('could not find code object') def getcomments(object): """Get lines of comments immediately preceding an object's source code. Returns None when source can't be found. """ try: lines, lnum = findsource(object) except (IOError, TypeError): return None if ismodule(object): # Look for a comment block at the top of the file. start = 0 if lines and lines[0][:2] == '#!': start = 1 while start < len(lines) and lines[start].strip() in ('', '#'): start = start + 1 if start < len(lines) and lines[start][:1] == '#': comments = [] end = start while end < len(lines) and lines[end][:1] == '#': comments.append(lines[end].expandtabs()) end = end + 1 return ''.join(comments) # Look for a preceding block of comments at the same indentation. elif lnum > 0: indent = indentsize(lines[lnum]) end = lnum - 1 if end >= 0 and lines[end].lstrip()[:1] == '#' and \ indentsize(lines[end]) == indent: comments = [lines[end].expandtabs().lstrip()] if end > 0: end = end - 1 comment = lines[end].expandtabs().lstrip() while comment[:1] == '#' and indentsize(lines[end]) == indent: comments[:0] = [comment] end = end - 1 if end < 0: break comment = lines[end].expandtabs().lstrip() while comments and comments[0].strip() == '#': comments[:1] = [] while comments and comments[-1].strip() == '#': comments[-1:] = [] return ''.join(comments) class EndOfBlock(Exception): pass class BlockFinder: """Provide a tokeneater() method to detect the end of a code block.""" def __init__(self): self.indent = 0 self.islambda = False self.started = False self.passline = False self.last = 1 def tokeneater(self, type, token, srowcol, erowcol, line): if not self.started: # look for the first "def", "class" or "lambda" if token in ("def", "class", "lambda"): if token == "lambda": self.islambda = True self.started = True self.passline = True # skip to the end of the line elif type == tokenize.NEWLINE: self.passline = False # stop skipping when a NEWLINE is seen self.last = srowcol[0] if self.islambda: # lambdas always end at the first NEWLINE raise EndOfBlock elif self.passline: pass elif type == tokenize.INDENT: self.indent = self.indent + 1 self.passline = True elif type == tokenize.DEDENT: self.indent = self.indent - 1 # the end of matching indent/dedent pairs end a block # (note that this only works for "def"/"class" blocks, # not e.g. for "if: else:" or "try: finally:" blocks) if self.indent <= 0: raise EndOfBlock elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL): # any other token on the same indentation level end the previous # block as well, except the pseudo-tokens COMMENT and NL. raise EndOfBlock def getblock(lines): """Extract the block of code at the top of the given list of lines.""" blockfinder = BlockFinder() try: tokens = tokenize.generate_tokens(iter(lines).__next__) for _token in tokens: blockfinder.tokeneater(*_token) except (EndOfBlock, IndentationError): pass return lines[:blockfinder.last] def getsourcelines(object): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = findsource(object) if ismodule(object): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1 def getsource(object): """Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = getsourcelines(object) return ''.join(lines) # --------------------------------------------------- class tree extraction def walktree(classes, children, parent): """Recursive helper function for getclasstree().""" results = [] classes.sort(key=attrgetter('__module__', '__name__')) for c in classes: results.append((c, c.__bases__)) if c in children: results.append(walktree(children[c], children, c)) return results def getclasstree(classes, unique=False): """Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the 'unique' argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.""" children = {} roots = [] for c in classes: if c.__bases__: for parent in c.__bases__: if not parent in children: children[parent] = [] if c not in children[parent]: children[parent].append(c) if unique and parent in classes: break elif c not in roots: roots.append(c) for parent in children: if parent not in classes: roots.append(parent) return walktree(roots, children, None) # ------------------------------------------------ argument list extraction Arguments = namedtuple('Arguments', 'args, varargs, varkw') def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is the list of argument names. Keyword-only arguments are appended. 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" args, varargs, kwonlyargs, varkw = _getfullargs(co) return Arguments(args + kwonlyargs, varargs, varkw) def _getfullargs(co): """Get information about the arguments accepted by a code object. Four things are returned: (args, varargs, kwonlyargs, varkw), where 'args' and 'kwonlyargs' are lists of argument names, and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError('{!r} is not a code object'.format(co)) nargs = co.co_argcount names = co.co_varnames nkwargs = co.co_kwonlyargcount args = list(names[:nargs]) kwonlyargs = list(names[nargs:nargs+nkwargs]) step = 0 nargs += nkwargs varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, kwonlyargs, varkw ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names. 'args' will include keyword-only argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Use the getfullargspec() API for Python-3000 code, as annotations and keyword arguments are supported. getargspec() will raise ValueError if the func has either annotations or keyword arguments. """ args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ getfullargspec(func) if kwonlyargs or ann: raise ValueError("Function has keyword-only arguments or annotations" ", use getfullargspec() API which can support them") return ArgSpec(args, varargs, varkw, defaults) FullArgSpec = namedtuple('FullArgSpec', 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations') def getfullargspec(func): """Get the names and default values of a function's arguments. A tuple of seven things is returned: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations). 'args' is a list of the argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. 'kwonlyargs' is a list of keyword-only argument names. 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults. 'annotations' is a dictionary mapping argument names to annotations. The first four items in the tuple correspond to getargspec(). """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError('{!r} is not a Python function'.format(func)) args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__) return FullArgSpec(args, varargs, varkw, func.__defaults__, kwonlyargs, func.__kwdefaults__, func.__annotations__) ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals') def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return ArgInfo(args, varargs, varkw, frame.f_locals) def formatannotation(annotation, base_module=None): if isinstance(annotation, type): if annotation.__module__ in ('builtins', base_module): return annotation.__name__ return annotation.__module__+'.'+annotation.__name__ return repr(annotation) def formatannotationrelativeto(object): module = getattr(object, '__module__', None) def _formatannotation(annotation): return formatannotation(annotation, module) return _formatannotation #brython fix me def formatargspec(args, varargs=None, varkw=None, defaults=None, kwonlyargs=(), kwonlydefaults={}, annotations={}, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), formatreturns=lambda text: ' -> ' + text, formatannotation=formatannotation): """Format an argument spec from the values returned by getargspec or getfullargspec. The first seven arguments are (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). The other five arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The last argument is an optional function to format the sequence of arguments.""" def formatargandannotation(arg): result = formatarg(arg) if arg in annotations: result += ': ' + formatannotation(annotations[arg]) return result specs = [] if defaults: firstdefault = len(args) - len(defaults) for i, arg in enumerate(args): spec = formatargandannotation(arg) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs is not None: specs.append(formatvarargs(formatargandannotation(varargs))) else: if kwonlyargs: specs.append('*') if kwonlyargs: for kwonlyarg in kwonlyargs: spec = formatargandannotation(kwonlyarg) if kwonlydefaults and kwonlyarg in kwonlydefaults: spec += formatvalue(kwonlydefaults[kwonlyarg]) specs.append(spec) if varkw is not None: specs.append(formatvarkw(formatargandannotation(varkw))) result = '(' + ', '.join(specs) + ')' if 'return' in annotations: result += formatreturns(formatannotation(annotations['return'])) return result #brython fix me #def formatargvalues(args, varargs, varkw, locals, # formatarg=str, # formatvarargs=lambda name: '*' + name, # formatvarkw=lambda name: '**' + name, # formatvalue=lambda value: '=' + repr(value)): # """Format an argument spec from the 4 values returned by getargvalues. # The first four arguments are (args, varargs, varkw, locals). The # next four arguments are the corresponding optional formatting functions # that are called to turn names and values into strings. The ninth # argument is an optional function to format the sequence of arguments.""" # def convert(name, locals=locals, # formatarg=formatarg, formatvalue=formatvalue): # return formatarg(name) + formatvalue(locals[name]) # specs = [] # for i in range(len(args)): # specs.append(convert(args[i])) # if varargs: # specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) # if varkw: # specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) # return '(' + ', '.join(specs) + ')' def _missing_arguments(f_name, argnames, pos, values): names = [repr(name) for name in argnames if name not in values] missing = len(names) if missing == 1: s = names[0] elif missing == 2: s = "{} and {}".format(*names) else: tail = ", {} and {}".format(names[-2:]) del names[-2:] s = ", ".join(names) + tail raise TypeError("%s() missing %i required %s argument%s: %s" % (f_name, missing, "positional" if pos else "keyword-only", "" if missing == 1 else "s", s)) def _too_many(f_name, args, kwonly, varargs, defcount, given, values): atleast = len(args) - defcount kwonly_given = len([arg for arg in kwonly if arg in values]) if varargs: plural = atleast != 1 sig = "at least %d" % (atleast,) elif defcount: plural = True sig = "from %d to %d" % (atleast, len(args)) else: plural = len(args) != 1 sig = str(len(args)) kwonly_sig = "" if kwonly_given: msg = " positional argument%s (and %d keyword-only argument%s)" kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given, "s" if kwonly_given != 1 else "")) raise TypeError("%s() takes %s positional argument%s but %d%s %s given" % (f_name, sig, "s" if plural else "", given, kwonly_sig, "was" if given == 1 and not kwonly_given else "were")) def getcallargs(func, *positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" spec = getfullargspec(func) args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec f_name = func.__name__ arg2value = {} if ismethod(func) and func.__self__ is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.__self__,) + positional num_pos = len(positional) num_args = len(args) num_defaults = len(defaults) if defaults else 0 n = min(num_pos, num_args) for i in range(n): arg2value[args[i]] = positional[i] if varargs: arg2value[varargs] = tuple(positional[n:]) possible_kwargs = set(args + kwonlyargs) if varkw: arg2value[varkw] = {} for kw, value in named.items(): if kw not in possible_kwargs: if not varkw: raise TypeError("%s() got an unexpected keyword argument %r" % (f_name, kw)) arg2value[varkw][kw] = value continue if kw in arg2value: raise TypeError("%s() got multiple values for argument %r" % (f_name, kw)) arg2value[kw] = value if num_pos > num_args and not varargs: _too_many(f_name, args, kwonlyargs, varargs, num_defaults, num_pos, arg2value) if num_pos < num_args: req = args[:num_args - num_defaults] for arg in req: if arg not in arg2value: _missing_arguments(f_name, req, True, arg2value) for i, arg in enumerate(args[num_args - num_defaults:]): if arg not in arg2value: arg2value[arg] = defaults[i] missing = 0 for kwarg in kwonlyargs: if kwarg not in arg2value: if kwarg in kwonlydefaults: arg2value[kwarg] = kwonlydefaults[kwarg] else: missing += 1 if missing: _missing_arguments(f_name, kwonlyargs, False, arg2value) return arg2value ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound') def getclosurevars(func): """ Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError("'{!r}' is not a Python function".format(func)) code = func.__code__ # Nonlocal references are named in co_freevars and resolved # by looking them up in __closure__ by positional index if func.__closure__ is None: nonlocal_vars = {} else: nonlocal_vars = { var : cell.cell_contents for var, cell in zip(code.co_freevars, func.__closure__) } # Global and builtin references are named in co_names and resolved # by looking them up in __globals__ or __builtins__ global_ns = func.__globals__ builtin_ns = global_ns.get("__builtins__", builtins.__dict__) if ismodule(builtin_ns): builtin_ns = builtin_ns.__dict__ global_vars = {} builtin_vars = {} unbound_names = set() for name in code.co_names: if name in ("None", "True", "False"): # Because these used to be builtins instead of keywords, they # may still show up as name references. We ignore them. continue try: global_vars[name] = global_ns[name] except KeyError: try: builtin_vars[name] = builtin_ns[name] except KeyError: unbound_names.add(name) return ClosureVars(nonlocal_vars, global_vars, builtin_vars, unbound_names) # -------------------------------------------------- stack frame extraction Traceback = namedtuple('Traceback', 'filename lineno function code_context index') def getframeinfo(frame, context=1): """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.""" if istraceback(frame): lineno = frame.tb_lineno frame = frame.tb_frame else: lineno = frame.f_lineno if not isframe(frame): raise TypeError('{!r} is not a frame or traceback object'.format(frame)) filename = getsourcefile(frame) or getfile(frame) if context > 0: start = lineno - 1 - context//2 try: lines, lnum = findsource(frame) except IOError: lines = index = None else: start = max(start, 1) start = max(0, min(start, len(lines) - context)) lines = lines[start:start+context] index = lineno - 1 - start else: lines = index = None return Traceback(filename, lineno, frame.f_code.co_name, lines, index) def getlineno(frame): """Get the line number from a frame object, allowing for optimization.""" # FrameType.f_lineno is now a descriptor that grovels co_lnotab return frame.f_lineno def getouterframes(frame, context=1): """Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while frame: framelist.append((frame,) + getframeinfo(frame, context)) frame = frame.f_back return framelist def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) tb = tb.tb_next return framelist def currentframe(): """Return the frame of the caller or None if this is not possible.""" return sys._getframe(1) if hasattr(sys, "_getframe") else None def stack(context=1): """Return a list of records for the stack above the caller's frame.""" return getouterframes(sys._getframe(1), context) def trace(context=1): """Return a list of records for the stack below the current exception.""" return getinnerframes(sys.exc_info()[2], context) # ------------------------------------------------ static version of getattr _sentinel = object() def _static_getmro(klass): return type.__dict__['__mro__'].__get__(klass) def _check_instance(obj, attr): instance_dict = {} try: instance_dict = object.__getattribute__(obj, "__dict__") except AttributeError: pass return dict.get(instance_dict, attr, _sentinel) def _check_class(klass, attr): for entry in _static_getmro(klass): if _shadowed_dict(type(entry)) is _sentinel: try: return entry.__dict__[attr] except KeyError: pass return _sentinel def _is_type(obj): try: _static_getmro(obj) except TypeError: return False return True def _shadowed_dict(klass): dict_attr = type.__dict__["__dict__"] for entry in _static_getmro(klass): try: class_dict = dict_attr.__get__(entry)["__dict__"] except KeyError: pass else: if not (type(class_dict) is types.GetSetDescriptorType and class_dict.__name__ == "__dict__" and class_dict.__objclass__ is entry): return class_dict return _sentinel def getattr_static(obj, attr, default=_sentinel): """Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can't (like descriptors that raise AttributeError). It can also return descriptor objects instead of instance members in some cases. See the documentation for details. """ instance_result = _sentinel if not _is_type(obj): klass = type(obj) dict_attr = _shadowed_dict(klass) if (dict_attr is _sentinel or type(dict_attr) is types.MemberDescriptorType): instance_result = _check_instance(obj, attr) else: klass = obj klass_result = _check_class(klass, attr) if instance_result is not _sentinel and klass_result is not _sentinel: if (_check_class(type(klass_result), '__get__') is not _sentinel and _check_class(type(klass_result), '__set__') is not _sentinel): return klass_result if instance_result is not _sentinel: return instance_result if klass_result is not _sentinel: return klass_result if obj is klass: # for types we check the metaclass too for entry in _static_getmro(type(klass)): if _shadowed_dict(type(entry)) is _sentinel: try: return entry.__dict__[attr] except KeyError: pass if default is not _sentinel: return default raise AttributeError(attr) # ------------------------------------------------ generator introspection GEN_CREATED = 'GEN_CREATED' GEN_RUNNING = 'GEN_RUNNING' GEN_SUSPENDED = 'GEN_SUSPENDED' GEN_CLOSED = 'GEN_CLOSED' def getgeneratorstate(generator): """Get current state of a generator-iterator. Possible states are: GEN_CREATED: Waiting to start execution. GEN_RUNNING: Currently being executed by the interpreter. GEN_SUSPENDED: Currently suspended at a yield expression. GEN_CLOSED: Execution has completed. """ if generator.gi_running: return GEN_RUNNING if generator.gi_frame is None: return GEN_CLOSED if generator.gi_frame.f_lasti == -1: return GEN_CREATED return GEN_SUSPENDED def getgeneratorlocals(generator): """ Get the mapping of generator local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.""" if not isgenerator(generator): raise TypeError("'{!r}' is not a Python generator".format(generator)) frame = getattr(generator, "gi_frame", None) if frame is not None: return generator.gi_frame.f_locals else: return {} ############################################################################### ### Function Signature Object (PEP 362) ############################################################################### _WrapperDescriptor = type(type.__call__) _MethodWrapper = type(all.__call__) _NonUserDefinedCallables = (_WrapperDescriptor, _MethodWrapper, types.BuiltinFunctionType) def _get_user_defined_method(cls, method_name): try: meth = getattr(cls, method_name) except AttributeError: return else: if not isinstance(meth, _NonUserDefinedCallables): # Once '__signature__' will be added to 'C'-level # callables, this check won't be necessary return meth def signature(obj): '''Get a signature object for the passed callable.''' if not callable(obj): raise TypeError('{!r} is not a callable object'.format(obj)) if isinstance(obj, types.MethodType): # In this case we skip the first parameter of the underlying # function (usually `self` or `cls`). sig = signature(obj.__func__) return sig.replace(parameters=tuple(sig.parameters.values())[1:]) try: sig = obj.__signature__ except AttributeError: pass else: if sig is not None: return sig try: # Was this function wrapped by a decorator? wrapped = obj.__wrapped__ except AttributeError: pass else: return signature(wrapped) if isinstance(obj, types.FunctionType): return Signature.from_function(obj) if isinstance(obj, functools.partial): sig = signature(obj.func) new_params = OrderedDict(sig.parameters.items()) partial_args = obj.args or () partial_keywords = obj.keywords or {} try: ba = sig.bind_partial(*partial_args, **partial_keywords) except TypeError as ex: msg = 'partial object {!r} has incorrect arguments'.format(obj) raise ValueError(msg) from ex for arg_name, arg_value in ba.arguments.items(): param = new_params[arg_name] if arg_name in partial_keywords: # We set a new default value, because the following code # is correct: # # >>> def foo(a): print(a) # >>> print(partial(partial(foo, a=10), a=20)()) # 20 # >>> print(partial(partial(foo, a=10), a=20)(a=30)) # 30 # # So, with 'partial' objects, passing a keyword argument is # like setting a new default value for the corresponding # parameter # # We also mark this parameter with '_partial_kwarg' # flag. Later, in '_bind', the 'default' value of this # parameter will be added to 'kwargs', to simulate # the 'functools.partial' real call. new_params[arg_name] = param.replace(default=arg_value, _partial_kwarg=True) elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and not param._partial_kwarg): new_params.pop(arg_name) return sig.replace(parameters=new_params.values()) sig = None if isinstance(obj, type): # obj is a class or a metaclass # First, let's see if it has an overloaded __call__ defined # in its metaclass call = _get_user_defined_method(type(obj), '__call__') if call is not None: sig = signature(call) else: # Now we check if the 'obj' class has a '__new__' method new = _get_user_defined_method(obj, '__new__') if new is not None: sig = signature(new) else: # Finally, we should have at least __init__ implemented init = _get_user_defined_method(obj, '__init__') if init is not None: sig = signature(init) elif not isinstance(obj, _NonUserDefinedCallables): # An object with __call__ # We also check that the 'obj' is not an instance of # _WrapperDescriptor or _MethodWrapper to avoid # infinite recursion (and even potential segfault) call = _get_user_defined_method(type(obj), '__call__') if call is not None: sig = signature(call) if sig is not None: # For classes and objects we skip the first parameter of their # __call__, __new__, or __init__ methods return sig.replace(parameters=tuple(sig.parameters.values())[1:]) if isinstance(obj, types.BuiltinFunctionType): # Raise a nicer error message for builtins msg = 'no signature found for builtin function {!r}'.format(obj) raise ValueError(msg) raise ValueError('callable {!r} is not supported by signature'.format(obj)) class _void: '''A private marker - used in Parameter & Signature''' class _empty: pass class _ParameterKind(int): def __new__(self, *args, name): obj = int.__new__(self, *args) obj._name = name return obj def __str__(self): return self._name def __repr__(self): return '<_ParameterKind: {!r}>'.format(self._name) _POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY') _POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD') _VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL') _KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY') _VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD') class Parameter: '''Represents a parameter in a function signature. Has the following public attributes: * name : str The name of the parameter as a string. * default : object The default value for the parameter if specified. If the parameter has no default value, this attribute is not set. * annotation The annotation for the parameter if specified. If the parameter has no annotation, this attribute is not set. * kind : str Describes how argument values are bound to the parameter. Possible values: `Parameter.POSITIONAL_ONLY`, `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`. ''' __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg') POSITIONAL_ONLY = _POSITIONAL_ONLY POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD VAR_POSITIONAL = _VAR_POSITIONAL KEYWORD_ONLY = _KEYWORD_ONLY VAR_KEYWORD = _VAR_KEYWORD empty = _empty def __init__(self, name, kind, *, default=_empty, annotation=_empty, _partial_kwarg=False): if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): raise ValueError("invalid value for 'Parameter.kind' attribute") self._kind = kind if default is not _empty: if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): msg = '{} parameters cannot have default values'.format(kind) raise ValueError(msg) self._default = default self._annotation = annotation if name is None: if kind != _POSITIONAL_ONLY: raise ValueError("None is not a valid name for a " "non-positional-only parameter") self._name = name else: name = str(name) if kind != _POSITIONAL_ONLY and not name.isidentifier(): msg = '{!r} is not a valid parameter name'.format(name) raise ValueError(msg) self._name = name self._partial_kwarg = _partial_kwarg @property def name(self): return self._name @property def default(self): return self._default @property def annotation(self): return self._annotation @property def kind(self): return self._kind def replace(self, *, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void): '''Creates a customized copy of the Parameter.''' if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default if _partial_kwarg is _void: _partial_kwarg = self._partial_kwarg return type(self)(name, kind, default=default, annotation=annotation, _partial_kwarg=_partial_kwarg) def __str__(self): kind = self.kind formatted = self._name if kind == _POSITIONAL_ONLY: if formatted is None: formatted = '' formatted = '<{}>'.format(formatted) # Add annotation and default value if self._annotation is not _empty: formatted = '{}:{}'.format(formatted, formatannotation(self._annotation)) if self._default is not _empty: formatted = '{}={}'.format(formatted, repr(self._default)) if kind == _VAR_POSITIONAL: formatted = '*' + formatted elif kind == _VAR_KEYWORD: formatted = '**' + formatted return formatted def __repr__(self): return '<{} at {:#x} {!r}>'.format(self.__class__.__name__, id(self), self.name) def __eq__(self, other): return (issubclass(other.__class__, Parameter) and self._name == other._name and self._kind == other._kind and self._default == other._default and self._annotation == other._annotation) def __ne__(self, other): return not self.__eq__(other) class BoundArguments: '''Result of `Signature.bind` call. Holds the mapping of arguments to the function's parameters. Has the following public attributes: * arguments : OrderedDict An ordered mutable mapping of parameters' names to arguments' values. Does not contain arguments' default values. * signature : Signature The Signature object that created this instance. * args : tuple Tuple of positional arguments values. * kwargs : dict Dict of keyword arguments values. ''' def __init__(self, signature, arguments): self.arguments = arguments self._signature = signature @property def signature(self): return self._signature @property def args(self): args = [] for param_name, param in self._signature.parameters.items(): if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or param._partial_kwarg): # Keyword arguments mapped by 'functools.partial' # (Parameter._partial_kwarg is True) are mapped # in 'BoundArguments.kwargs', along with VAR_KEYWORD & # KEYWORD_ONLY break try: arg = self.arguments[param_name] except KeyError: # We're done here. Other arguments # will be mapped in 'BoundArguments.kwargs' break else: if param.kind == _VAR_POSITIONAL: # *args args.extend(arg) else: # plain argument args.append(arg) return tuple(args) @property def kwargs(self): kwargs = {} kwargs_started = False for param_name, param in self._signature.parameters.items(): if not kwargs_started: if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or param._partial_kwarg): kwargs_started = True else: if param_name not in self.arguments: kwargs_started = True continue if not kwargs_started: continue try: arg = self.arguments[param_name] except KeyError: pass else: if param.kind == _VAR_KEYWORD: # **kwargs kwargs.update(arg) else: # plain keyword argument kwargs[param_name] = arg return kwargs def __eq__(self, other): return (issubclass(other.__class__, BoundArguments) and self.signature == other.signature and self.arguments == other.arguments) def __ne__(self, other): return not self.__eq__(other) class Signature: '''A Signature object represents the overall signature of a function. It stores a Parameter object for each parameter accepted by the function, as well as information specific to the function itself. A Signature object has the following public attributes and methods: * parameters : OrderedDict An ordered mapping of parameters' names to the corresponding Parameter objects (keyword-only arguments are in the same order as listed in `code.co_varnames`). * return_annotation : object The annotation for the return type of the function if specified. If the function has no annotation for its return type, this attribute is not set. * bind(*args, **kwargs) -> BoundArguments Creates a mapping from positional and keyword arguments to parameters. * bind_partial(*args, **kwargs) -> BoundArguments Creates a partial mapping from positional and keyword arguments to parameters (simulating 'functools.partial' behavior.) ''' __slots__ = ('_return_annotation', '_parameters') _parameter_cls = Parameter _bound_arguments_cls = BoundArguments empty = _empty def __init__(self, parameters=None, *, return_annotation=_empty, __validate_parameters__=True): '''Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional. ''' if parameters is None: params = OrderedDict() else: if __validate_parameters__: params = OrderedDict() top_kind = _POSITIONAL_ONLY for idx, param in enumerate(parameters): kind = param.kind if kind < top_kind: msg = 'wrong parameter order: {} before {}' msg = msg.format(top_kind, param.kind) raise ValueError(msg) else: top_kind = kind name = param.name if name is None: name = str(idx) param = param.replace(name=name) if name in params: msg = 'duplicate parameter name: {!r}'.format(name) raise ValueError(msg) params[name] = param else: params = OrderedDict(((param.name, param) for param in parameters)) self._parameters = types.MappingProxyType(params) self._return_annotation = return_annotation @classmethod def from_function(cls, func): '''Constructs Signature for the given python function''' if not isinstance(func, types.FunctionType): raise TypeError('{!r} is not a Python function'.format(func)) Parameter = cls._parameter_cls # Parameter information. func_code = func.__code__ pos_count = func_code.co_argcount arg_names = func_code.co_varnames positional = tuple(arg_names[:pos_count]) keyword_only_count = func_code.co_kwonlyargcount keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)] annotations = func.__annotations__ defaults = func.__defaults__ kwdefaults = func.__kwdefaults__ if defaults: pos_default_count = len(defaults) else: pos_default_count = 0 parameters = [] # Non-keyword-only parameters w/o defaults. non_default_count = pos_count - pos_default_count for name in positional[:non_default_count]: annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD)) # ... w/ defaults. for offset, name in enumerate(positional[non_default_count:]): annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD, default=defaults[offset])) # *args if func_code.co_flags & 0x04: name = arg_names[pos_count + keyword_only_count] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_POSITIONAL)) # Keyword-only parameters. for name in keyword_only: default = _empty if kwdefaults is not None: default = kwdefaults.get(name, _empty) annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_KEYWORD_ONLY, default=default)) # **kwargs if func_code.co_flags & 0x08: index = pos_count + keyword_only_count if func_code.co_flags & 0x04: index += 1 name = arg_names[index] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_KEYWORD)) return cls(parameters, return_annotation=annotations.get('return', _empty), __validate_parameters__=False) @property def parameters(self): return self._parameters @property def return_annotation(self): return self._return_annotation def replace(self, *, parameters=_void, return_annotation=_void): '''Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. ''' if parameters is _void: parameters = self.parameters.values() if return_annotation is _void: return_annotation = self._return_annotation return type(self)(parameters, return_annotation=return_annotation) def __eq__(self, other): if (not issubclass(type(other), Signature) or self.return_annotation != other.return_annotation or len(self.parameters) != len(other.parameters)): return False other_positions = {param: idx for idx, param in enumerate(other.parameters.keys())} for idx, (param_name, param) in enumerate(self.parameters.items()): if param.kind == _KEYWORD_ONLY: try: other_param = other.parameters[param_name] except KeyError: return False else: if param != other_param: return False else: try: other_idx = other_positions[param_name] except KeyError: return False else: if (idx != other_idx or param != other.parameters[param_name]): return False return True def __ne__(self, other): return not self.__eq__(other) def _bind(self, args, kwargs, *, partial=False): '''Private method. Don't use directly.''' arguments = OrderedDict() parameters = iter(self.parameters.values()) parameters_ex = () arg_vals = iter(args) if partial: # Support for binding arguments to 'functools.partial' objects. # See 'functools.partial' case in 'signature()' implementation # for details. for param_name, param in self.parameters.items(): if (param._partial_kwarg and param_name not in kwargs): # Simulating 'functools.partial' behavior kwargs[param_name] = param.default while True: # Let's iterate through the positional arguments and corresponding # parameters try: arg_val = next(arg_vals) except StopIteration: # No more positional arguments try: param = next(parameters) except StopIteration: # No more parameters. That's it. Just need to check that # we have no `kwargs` after this while loop break else: if param.kind == _VAR_POSITIONAL: # That's OK, just empty *args. Let's start parsing # kwargs break elif param.name in kwargs: if param.kind == _POSITIONAL_ONLY: msg = '{arg!r} parameter is positional only, ' \ 'but was passed as a keyword' msg = msg.format(arg=param.name) raise TypeError(msg) from None parameters_ex = (param,) break elif (param.kind == _VAR_KEYWORD or param.default is not _empty): # That's fine too - we have a default value for this # parameter. So, lets start parsing `kwargs`, starting # with the current parameter parameters_ex = (param,) break else: if partial: parameters_ex = (param,) break else: msg = '{arg!r} parameter lacking default value' msg = msg.format(arg=param.name) raise TypeError(msg) from None else: # We have a positional argument to process try: param = next(parameters) except StopIteration: raise TypeError('too many positional arguments') from None else: if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): # Looks like we have no parameter for this positional # argument raise TypeError('too many positional arguments') if param.kind == _VAR_POSITIONAL: # We have an '*args'-like argument, let's fill it with # all positional arguments we have left and move on to # the next phase values = [arg_val] values.extend(arg_vals) arguments[param.name] = tuple(values) break if param.name in kwargs: raise TypeError('multiple values for argument ' '{arg!r}'.format(arg=param.name)) arguments[param.name] = arg_val # Now, we iterate through the remaining parameters to process # keyword arguments kwargs_param = None for param in itertools.chain(parameters_ex, parameters): if param.kind == _POSITIONAL_ONLY: # This should never happen in case of a properly built # Signature object (but let's have this check here # to ensure correct behaviour just in case) raise TypeError('{arg!r} parameter is positional only, ' 'but was passed as a keyword'. \ format(arg=param.name)) if param.kind == _VAR_KEYWORD: # Memorize that we have a '**kwargs'-like parameter kwargs_param = param continue param_name = param.name try: arg_val = kwargs.pop(param_name) except KeyError: # We have no value for this parameter. It's fine though, # if it has a default value, or it is an '*args'-like # parameter, left alone by the processing of positional # arguments. if (not partial and param.kind != _VAR_POSITIONAL and param.default is _empty): raise TypeError('{arg!r} parameter lacking default value'. \ format(arg=param_name)) from None else: arguments[param_name] = arg_val if kwargs: if kwargs_param is not None: # Process our '**kwargs'-like parameter arguments[kwargs_param.name] = kwargs else: raise TypeError('too many keyword arguments') return self._bound_arguments_cls(self, arguments) def bind(__bind_self, *args, **kwargs): '''Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return __bind_self._bind(args, kwargs) def bind_partial(__bind_self, *args, **kwargs): '''Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return __bind_self._bind(args, kwargs, partial=True) def __str__(self): result = [] render_kw_only_separator = True for idx, param in enumerate(self.parameters.values()): formatted = str(param) kind = param.kind if kind == _VAR_POSITIONAL: # OK, we have an '*args'-like parameter, so we won't need # a '*' to separate keyword-only arguments render_kw_only_separator = False elif kind == _KEYWORD_ONLY and render_kw_only_separator: # We have a keyword-only parameter to render and we haven't # rendered an '*args'-like parameter before, so add a '*' # separator to the parameters list ("foo(arg1, *, arg2)" case) result.append('*') # This condition should be only triggered once, so # reset the flag render_kw_only_separator = False result.append(formatted) rendered = '({})'.format(', '.join(result)) if self.return_annotation is not _empty: anno = formatannotation(self.return_annotation) rendered += ' -> {}'.format(anno) return rendered
gpl-3.0
tonioo/modoboa-public-api
modoboa_public_api/tests.py
1
7163
"""API test cases.""" from django.core.urlresolvers import reverse from django.test import TestCase from rest_framework.test import APIClient from . import factories from . import models class InstanceViewSetTestCase(TestCase): """TestCase for InstanceViewSet.""" @classmethod def setUpTestData(cls): """Create some data.""" factories.ModoboaExtensionFactory(name="modoboa-amavis") factories.ModoboaExtensionFactory(name="modoboa-stats") cls.md_instance = factories.ModoboaInstanceFactory( hostname="mail.pouet.fr", ip_address="127.0.0.1") def setUp(self): """Replace client.""" super(InstanceViewSetTestCase, self).setUp() self.client = APIClient() def test_create(self): """Test creation of instance.""" url = reverse("instance-list") # Minimal set data = { "hostname": "mail.example.tld", "known_version": "1.0.0" } response = self.client.post(url, data=data, format="json") self.assertEqual(response.status_code, 201) # Full set data.update({ "hostname": "mail.example2.tld", "domain_counter": 10, "mailbox_counter": 10, "alias_counter": 10, "domain_alias_counter": 10, "extensions": ["modoboa-amavis"], }) response = self.client.post(url, data=data, format="json") self.assertEqual(response.status_code, 201) instance = response.json() instance = models.ModoboaInstance.objects.get(pk=instance["pk"]) self.assertTrue( instance.extensions.filter(name="modoboa-amavis").exists()) def test_update(self): """Test instance update.""" url = reverse("instance-detail", args=[9999]) data = { "hostname": "mail.pouet.fr", "known_version": "1.2.3", "domain_counter": 10, "extensions": [ "modoboa-amavis", "modoboa_stats"] } response = self.client.put(url, data=data, format="json") self.assertEqual(response.status_code, 404) url = reverse("instance-detail", args=[self.md_instance.pk]) response = self.client.put(url, data=data, format="json") self.assertEqual(response.status_code, 200) self.md_instance.refresh_from_db() self.assertEqual(self.md_instance.domain_counter, 10) self.assertEqual(self.md_instance.extensions.count(), 2) self.assertTrue( self.md_instance.extensions.filter( name="modoboa-amavis").exists()) self.assertTrue( self.md_instance.extensions.filter( name="modoboa-stats").exists()) data["extensions"] = ["modoboa-amavis"] url = reverse("instance-detail", args=[self.md_instance.pk]) response = self.client.put(url, data=data, format="json") self.assertEqual(response.status_code, 200) self.md_instance.refresh_from_db() self.assertEqual(self.md_instance.extensions.count(), 1) def test_update_dev_version(self): """Test update with a dev version.""" data = { "hostname": "mail.pouet.fr", "known_version": "1.10.2.dev5+ga327ccf0", "domain_counter": 10, "extensions": [ "modoboa-amavis", "modoboa_stats"] } url = reverse("instance-detail", args=[self.md_instance.pk]) response = self.client.put(url, data=data, format="json") self.assertEqual(response.status_code, 200) self.md_instance.refresh_from_db() self.assertEqual( self.md_instance.known_version, data["known_version"]) def test_search(self): """Test instance search.""" url = "{}?hostname={}".format( reverse("instance-search"), "mail.pouet.fr") response = self.client.get(url) self.assertEqual(response.status_code, 200) instance = response.json() self.assertEqual(instance["pk"], self.md_instance.pk) url = "{}?hostname={}".format( reverse("instance-search"), "mail.pouet.com") response = self.client.get(url) self.assertEqual(response.status_code, 404) response = self.client.get(reverse("instance-search")) self.assertEqual(response.status_code, 400) class VersionViewSetTestCase(TestCase): """TestCase for VersionViewSet.""" @classmethod def setUpTestData(cls): """Create some data.""" factories.ModoboaExtensionFactory(name="modoboa-amavis") factories.ModoboaExtensionFactory(name="modoboa-stats") factories.ModoboaExtensionFactory(name="modoboa-webmail") def setUp(self): """Replace client.""" super(VersionViewSetTestCase, self).setUp() self.client = APIClient() def test_list(self): """Test list.""" url = reverse("version-list") response = self.client.get(url) self.assertEqual(response.status_code, 200) versions = response.json() self.assertEqual(len(versions), 4) # Deprecated viewsets class ExtensionViewSetTestCase(TestCase): """TestCase for ExtensionViewSet.""" @classmethod def setUpTestData(cls): """Create some data.""" factories.ModoboaExtensionFactory(name="modoboa-amavis") factories.ModoboaExtensionFactory(name="modoboa-stats") factories.ModoboaExtensionFactory(name="modoboa-webmail") def setUp(self): """Replace client.""" super(ExtensionViewSetTestCase, self).setUp() self.client = APIClient() def test_list(self): """Test list.""" url = reverse("extension-list") response = self.client.get(url) self.assertEqual(response.status_code, 200) versions = response.json() self.assertEqual(len(versions), 3) class CurrentVersionAPI(TestCase): """Current version test cases.""" def setUp(self): """Replace client.""" super(CurrentVersionAPI, self).setUp() self.client = APIClient() def test_current_version(self): """Check API call.""" url = reverse("current_version") url = "{}?client_version={}&client_site={}".format( url, "1.0.0", "mail.pouet.com") response = self.client.get(url) self.assertEqual(response.status_code, 200) content = response.json() self.assertIn("version", content) self.assertIn("changelog_url", content) self.assertTrue( models.ModoboaInstance.objects.filter( hostname="mail.pouet.com", known_version="1.0.0") .exists()) def test_bad_version(self): """Check that API does not crash.""" url = reverse("current_version") url = "{}?client_version={}&client_site={}".format( url, "1.2.0-rc2", "mail.pouet.com") response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertTrue( models.ModoboaInstance.objects.filter( hostname="mail.pouet.com", known_version="1.2.0") .exists())
mit
e-schumann/proxy_doodle
external/boost/tools/build/test/project_glob.py
44
6098
#!/usr/bin/python # Copyright (C) 2003. Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # Test the 'glob' rule in Jamfile context. import BoostBuild def test_basic(): t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "") t.write("d1/a.cpp", "int main() {}\n") t.write("d1/jamfile.jam", "exe a : [ glob *.cpp ] ../d2/d//l ;") t.write("d2/d/l.cpp", """\ #if defined(_WIN32) __declspec(dllexport) void force_import_lib_creation() {} #endif """) t.write("d2/d/jamfile.jam", "lib l : [ glob *.cpp ] ;") t.write("d3/d/jamfile.jam", "exe a : [ glob ../*.cpp ] ;") t.write("d3/a.cpp", "int main() {}\n") t.run_build_system(subdir="d1") t.expect_addition("d1/bin/$toolset/debug/a.exe") t.run_build_system(subdir="d3/d") t.expect_addition("d3/d/bin/$toolset/debug/a.exe") t.rm("d2/d/bin") t.run_build_system(subdir="d2/d") t.expect_addition("d2/d/bin/$toolset/debug/l.dll") t.cleanup() def test_source_location(): """ Test that when 'source-location' is explicitly-specified glob works relative to the source location. """ t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "") t.write("d1/a.cpp", "very bad non-compilable file\n") t.write("d1/src/a.cpp", "int main() {}\n") t.write("d1/jamfile.jam", """\ project : source-location src ; exe a : [ glob *.cpp ] ../d2/d//l ; """) t.write("d2/d/l.cpp", """\ #if defined(_WIN32) __declspec(dllexport) void force_import_lib_creation() {} #endif """) t.write("d2/d/jamfile.jam", "lib l : [ glob *.cpp ] ;") t.run_build_system(subdir="d1") t.expect_addition("d1/bin/$toolset/debug/a.exe") t.cleanup() def test_wildcards_and_exclusion_patterns(): """ Test that wildcards can include directories. Also test exclusion patterns. """ t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "") t.write("d1/src/foo/a.cpp", "void bar(); int main() { bar(); }\n") t.write("d1/src/bar/b.cpp", "void bar() {}\n") t.write("d1/src/bar/bad.cpp", "very bad non-compilable file\n") t.write("d1/jamfile.jam", """\ project : source-location src ; exe a : [ glob foo/*.cpp bar/*.cpp : bar/bad* ] ../d2/d//l ; """) t.write("d2/d/l.cpp", """\ #if defined(_WIN32) __declspec(dllexport) void force_import_lib_creation() {} #endif """) t.write("d2/d/jamfile.jam", "lib l : [ glob *.cpp ] ;") t.run_build_system(subdir="d1") t.expect_addition("d1/bin/$toolset/debug/a.exe") t.cleanup() def test_glob_tree(): """Test that 'glob-tree' works.""" t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "") t.write("d1/src/foo/a.cpp", "void bar(); int main() { bar(); }\n") t.write("d1/src/bar/b.cpp", "void bar() {}\n") t.write("d1/src/bar/bad.cpp", "very bad non-compilable file\n") t.write("d1/jamfile.jam", """\ project : source-location src ; exe a : [ glob-tree *.cpp : bad* ] ../d2/d//l ; """) t.write("d2/d/l.cpp", """\ #if defined(_WIN32) __declspec(dllexport) void force_import_lib_creation() {} #endif """) t.write("d2/d/jamfile.jam", "lib l : [ glob *.cpp ] ;") t.run_build_system(subdir="d1") t.expect_addition("d1/bin/$toolset/debug/a.exe") t.cleanup() def test_directory_names_in_glob_tree(): """Test that directory names in patterns for 'glob-tree' are rejected.""" t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "") t.write("d1/src/a.cpp", "very bad non-compilable file\n") t.write("d1/src/foo/a.cpp", "void bar(); int main() { bar(); }\n") t.write("d1/src/bar/b.cpp", "void bar() {}\n") t.write("d1/src/bar/bad.cpp", "very bad non-compilable file\n") t.write("d1/jamfile.jam", """\ project : source-location src ; exe a : [ glob-tree foo/*.cpp bar/*.cpp : bad* ] ../d2/d//l ; """) t.write("d2/d/l.cpp", """\ #if defined(_WIN32) __declspec(dllexport) void force_import_lib_creation() {} #endif """) t.write("d2/d/jamfile.jam", "lib l : [ glob *.cpp ] ;") t.run_build_system(subdir="d1", status=1) t.expect_output_lines("error: The patterns * may not include directory") t.cleanup() def test_glob_with_absolute_names(): """Test that 'glob' works with absolute names.""" t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "") t.write("d1/src/a.cpp", "very bad non-compilable file\n") t.write("d1/src/foo/a.cpp", "void bar(); int main() { bar(); }\n") t.write("d1/src/bar/b.cpp", "void bar() {}\n") # Note that to get the current dir, we use bjam's PWD, not Python's # os.getcwd(), because the former will always return a long path while the # latter might return a short path, which would confuse path.glob. t.write("d1/jamfile.jam", """\ project : source-location src ; local pwd = [ PWD ] ; # Always absolute. exe a : [ glob $(pwd)/src/foo/*.cpp $(pwd)/src/bar/*.cpp ] ../d2/d//l ; """) t.write("d2/d/l.cpp", """\ #if defined(_WIN32) __declspec(dllexport) void force_import_lib_creation() {} #endif """) t.write("d2/d/jamfile.jam", "lib l : [ glob *.cpp ] ;") t.run_build_system(subdir="d1") t.expect_addition("d1/bin/$toolset/debug/a.exe") t.cleanup() def test_glob_excludes_in_subdirectory(): """ Regression test: glob excludes used to be broken when building from a subdirectory. """ t = BoostBuild.Tester(use_test_config=False) t.write("jamroot.jam", "build-project p ;") t.write("p/p.c", "int main() {}\n") t.write("p/p_x.c", "very bad non-compilable file\n") t.write("p/jamfile.jam", "exe p : [ glob *.c : p_x.c ] ;") t.run_build_system(subdir="p") t.expect_addition("p/bin/$toolset/debug/p.exe") t.cleanup() test_basic() test_source_location() test_wildcards_and_exclusion_patterns() test_glob_tree() test_directory_names_in_glob_tree() test_glob_with_absolute_names() test_glob_excludes_in_subdirectory()
mit
LaMi-/pmatic
ccu_pkg/python/lib/python2.7/encodings/cp1006.py
593
13824
""" Python Character Mapping Codec cp1006 generated from 'MAPPINGS/VENDORS/MISC/CP1006.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp1006', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x04' # 0x04 -> END OF TRANSMISSION u'\x05' # 0x05 -> ENQUIRY u'\x06' # 0x06 -> ACKNOWLEDGE u'\x07' # 0x07 -> BELL u'\x08' # 0x08 -> BACKSPACE u'\t' # 0x09 -> HORIZONTAL TABULATION u'\n' # 0x0A -> LINE FEED u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x14' # 0x14 -> DEVICE CONTROL FOUR u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x16 -> SYNCHRONOUS IDLE u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x1a' # 0x1A -> SUBSTITUTE u'\x1b' # 0x1B -> ESCAPE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> DELETE u'\x80' # 0x80 -> <control> u'\x81' # 0x81 -> <control> u'\x82' # 0x82 -> <control> u'\x83' # 0x83 -> <control> u'\x84' # 0x84 -> <control> u'\x85' # 0x85 -> <control> u'\x86' # 0x86 -> <control> u'\x87' # 0x87 -> <control> u'\x88' # 0x88 -> <control> u'\x89' # 0x89 -> <control> u'\x8a' # 0x8A -> <control> u'\x8b' # 0x8B -> <control> u'\x8c' # 0x8C -> <control> u'\x8d' # 0x8D -> <control> u'\x8e' # 0x8E -> <control> u'\x8f' # 0x8F -> <control> u'\x90' # 0x90 -> <control> u'\x91' # 0x91 -> <control> u'\x92' # 0x92 -> <control> u'\x93' # 0x93 -> <control> u'\x94' # 0x94 -> <control> u'\x95' # 0x95 -> <control> u'\x96' # 0x96 -> <control> u'\x97' # 0x97 -> <control> u'\x98' # 0x98 -> <control> u'\x99' # 0x99 -> <control> u'\x9a' # 0x9A -> <control> u'\x9b' # 0x9B -> <control> u'\x9c' # 0x9C -> <control> u'\x9d' # 0x9D -> <control> u'\x9e' # 0x9E -> <control> u'\x9f' # 0x9F -> <control> u'\xa0' # 0xA0 -> NO-BREAK SPACE u'\u06f0' # 0xA1 -> EXTENDED ARABIC-INDIC DIGIT ZERO u'\u06f1' # 0xA2 -> EXTENDED ARABIC-INDIC DIGIT ONE u'\u06f2' # 0xA3 -> EXTENDED ARABIC-INDIC DIGIT TWO u'\u06f3' # 0xA4 -> EXTENDED ARABIC-INDIC DIGIT THREE u'\u06f4' # 0xA5 -> EXTENDED ARABIC-INDIC DIGIT FOUR u'\u06f5' # 0xA6 -> EXTENDED ARABIC-INDIC DIGIT FIVE u'\u06f6' # 0xA7 -> EXTENDED ARABIC-INDIC DIGIT SIX u'\u06f7' # 0xA8 -> EXTENDED ARABIC-INDIC DIGIT SEVEN u'\u06f8' # 0xA9 -> EXTENDED ARABIC-INDIC DIGIT EIGHT u'\u06f9' # 0xAA -> EXTENDED ARABIC-INDIC DIGIT NINE u'\u060c' # 0xAB -> ARABIC COMMA u'\u061b' # 0xAC -> ARABIC SEMICOLON u'\xad' # 0xAD -> SOFT HYPHEN u'\u061f' # 0xAE -> ARABIC QUESTION MARK u'\ufe81' # 0xAF -> ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM u'\ufe8d' # 0xB0 -> ARABIC LETTER ALEF ISOLATED FORM u'\ufe8e' # 0xB1 -> ARABIC LETTER ALEF FINAL FORM u'\ufe8e' # 0xB2 -> ARABIC LETTER ALEF FINAL FORM u'\ufe8f' # 0xB3 -> ARABIC LETTER BEH ISOLATED FORM u'\ufe91' # 0xB4 -> ARABIC LETTER BEH INITIAL FORM u'\ufb56' # 0xB5 -> ARABIC LETTER PEH ISOLATED FORM u'\ufb58' # 0xB6 -> ARABIC LETTER PEH INITIAL FORM u'\ufe93' # 0xB7 -> ARABIC LETTER TEH MARBUTA ISOLATED FORM u'\ufe95' # 0xB8 -> ARABIC LETTER TEH ISOLATED FORM u'\ufe97' # 0xB9 -> ARABIC LETTER TEH INITIAL FORM u'\ufb66' # 0xBA -> ARABIC LETTER TTEH ISOLATED FORM u'\ufb68' # 0xBB -> ARABIC LETTER TTEH INITIAL FORM u'\ufe99' # 0xBC -> ARABIC LETTER THEH ISOLATED FORM u'\ufe9b' # 0xBD -> ARABIC LETTER THEH INITIAL FORM u'\ufe9d' # 0xBE -> ARABIC LETTER JEEM ISOLATED FORM u'\ufe9f' # 0xBF -> ARABIC LETTER JEEM INITIAL FORM u'\ufb7a' # 0xC0 -> ARABIC LETTER TCHEH ISOLATED FORM u'\ufb7c' # 0xC1 -> ARABIC LETTER TCHEH INITIAL FORM u'\ufea1' # 0xC2 -> ARABIC LETTER HAH ISOLATED FORM u'\ufea3' # 0xC3 -> ARABIC LETTER HAH INITIAL FORM u'\ufea5' # 0xC4 -> ARABIC LETTER KHAH ISOLATED FORM u'\ufea7' # 0xC5 -> ARABIC LETTER KHAH INITIAL FORM u'\ufea9' # 0xC6 -> ARABIC LETTER DAL ISOLATED FORM u'\ufb84' # 0xC7 -> ARABIC LETTER DAHAL ISOLATED FORMN u'\ufeab' # 0xC8 -> ARABIC LETTER THAL ISOLATED FORM u'\ufead' # 0xC9 -> ARABIC LETTER REH ISOLATED FORM u'\ufb8c' # 0xCA -> ARABIC LETTER RREH ISOLATED FORM u'\ufeaf' # 0xCB -> ARABIC LETTER ZAIN ISOLATED FORM u'\ufb8a' # 0xCC -> ARABIC LETTER JEH ISOLATED FORM u'\ufeb1' # 0xCD -> ARABIC LETTER SEEN ISOLATED FORM u'\ufeb3' # 0xCE -> ARABIC LETTER SEEN INITIAL FORM u'\ufeb5' # 0xCF -> ARABIC LETTER SHEEN ISOLATED FORM u'\ufeb7' # 0xD0 -> ARABIC LETTER SHEEN INITIAL FORM u'\ufeb9' # 0xD1 -> ARABIC LETTER SAD ISOLATED FORM u'\ufebb' # 0xD2 -> ARABIC LETTER SAD INITIAL FORM u'\ufebd' # 0xD3 -> ARABIC LETTER DAD ISOLATED FORM u'\ufebf' # 0xD4 -> ARABIC LETTER DAD INITIAL FORM u'\ufec1' # 0xD5 -> ARABIC LETTER TAH ISOLATED FORM u'\ufec5' # 0xD6 -> ARABIC LETTER ZAH ISOLATED FORM u'\ufec9' # 0xD7 -> ARABIC LETTER AIN ISOLATED FORM u'\ufeca' # 0xD8 -> ARABIC LETTER AIN FINAL FORM u'\ufecb' # 0xD9 -> ARABIC LETTER AIN INITIAL FORM u'\ufecc' # 0xDA -> ARABIC LETTER AIN MEDIAL FORM u'\ufecd' # 0xDB -> ARABIC LETTER GHAIN ISOLATED FORM u'\ufece' # 0xDC -> ARABIC LETTER GHAIN FINAL FORM u'\ufecf' # 0xDD -> ARABIC LETTER GHAIN INITIAL FORM u'\ufed0' # 0xDE -> ARABIC LETTER GHAIN MEDIAL FORM u'\ufed1' # 0xDF -> ARABIC LETTER FEH ISOLATED FORM u'\ufed3' # 0xE0 -> ARABIC LETTER FEH INITIAL FORM u'\ufed5' # 0xE1 -> ARABIC LETTER QAF ISOLATED FORM u'\ufed7' # 0xE2 -> ARABIC LETTER QAF INITIAL FORM u'\ufed9' # 0xE3 -> ARABIC LETTER KAF ISOLATED FORM u'\ufedb' # 0xE4 -> ARABIC LETTER KAF INITIAL FORM u'\ufb92' # 0xE5 -> ARABIC LETTER GAF ISOLATED FORM u'\ufb94' # 0xE6 -> ARABIC LETTER GAF INITIAL FORM u'\ufedd' # 0xE7 -> ARABIC LETTER LAM ISOLATED FORM u'\ufedf' # 0xE8 -> ARABIC LETTER LAM INITIAL FORM u'\ufee0' # 0xE9 -> ARABIC LETTER LAM MEDIAL FORM u'\ufee1' # 0xEA -> ARABIC LETTER MEEM ISOLATED FORM u'\ufee3' # 0xEB -> ARABIC LETTER MEEM INITIAL FORM u'\ufb9e' # 0xEC -> ARABIC LETTER NOON GHUNNA ISOLATED FORM u'\ufee5' # 0xED -> ARABIC LETTER NOON ISOLATED FORM u'\ufee7' # 0xEE -> ARABIC LETTER NOON INITIAL FORM u'\ufe85' # 0xEF -> ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM u'\ufeed' # 0xF0 -> ARABIC LETTER WAW ISOLATED FORM u'\ufba6' # 0xF1 -> ARABIC LETTER HEH GOAL ISOLATED FORM u'\ufba8' # 0xF2 -> ARABIC LETTER HEH GOAL INITIAL FORM u'\ufba9' # 0xF3 -> ARABIC LETTER HEH GOAL MEDIAL FORM u'\ufbaa' # 0xF4 -> ARABIC LETTER HEH DOACHASHMEE ISOLATED FORM u'\ufe80' # 0xF5 -> ARABIC LETTER HAMZA ISOLATED FORM u'\ufe89' # 0xF6 -> ARABIC LETTER YEH WITH HAMZA ABOVE ISOLATED FORM u'\ufe8a' # 0xF7 -> ARABIC LETTER YEH WITH HAMZA ABOVE FINAL FORM u'\ufe8b' # 0xF8 -> ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM u'\ufef1' # 0xF9 -> ARABIC LETTER YEH ISOLATED FORM u'\ufef2' # 0xFA -> ARABIC LETTER YEH FINAL FORM u'\ufef3' # 0xFB -> ARABIC LETTER YEH INITIAL FORM u'\ufbb0' # 0xFC -> ARABIC LETTER YEH BARREE WITH HAMZA ABOVE ISOLATED FORM u'\ufbae' # 0xFD -> ARABIC LETTER YEH BARREE ISOLATED FORM u'\ufe7c' # 0xFE -> ARABIC SHADDA ISOLATED FORM u'\ufe7d' # 0xFF -> ARABIC SHADDA MEDIAL FORM ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
gpl-2.0
mwoehlke/gtest
test/gtest_env_var_test.py
2408
3487
#!/usr/bin/env python # # Copyright 2008, Google 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 Google Inc. 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. """Verifies that Google Test correctly parses environment variables.""" __author__ = 'wan@google.com (Zhanyong Wan)' import os import gtest_test_utils IS_WINDOWS = os.name == 'nt' IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_') environ = os.environ.copy() def AssertEq(expected, actual): if expected != actual: print 'Expected: %s' % (expected,) print ' Actual: %s' % (actual,) raise AssertionError def SetEnvVar(env_var, value): """Sets the env variable to 'value'; unsets it when 'value' is None.""" if value is not None: environ[env_var] = value elif env_var in environ: del environ[env_var] def GetFlag(flag): """Runs gtest_env_var_test_ and returns its output.""" args = [COMMAND] if flag is not None: args += [flag] return gtest_test_utils.Subprocess(args, env=environ).output def TestFlag(flag, test_val, default_val): """Verifies that the given flag is affected by the corresponding env var.""" env_var = 'GTEST_' + flag.upper() SetEnvVar(env_var, test_val) AssertEq(test_val, GetFlag(flag)) SetEnvVar(env_var, None) AssertEq(default_val, GetFlag(flag)) class GTestEnvVarTest(gtest_test_utils.TestCase): def testEnvVarAffectsFlag(self): """Tests that environment variable should affect the corresponding flag.""" TestFlag('break_on_failure', '1', '0') TestFlag('color', 'yes', 'auto') TestFlag('filter', 'FooTest.Bar', '*') TestFlag('output', 'xml:tmp/foo.xml', '') TestFlag('print_time', '0', '1') TestFlag('repeat', '999', '1') TestFlag('throw_on_failure', '1', '0') TestFlag('death_test_style', 'threadsafe', 'fast') TestFlag('catch_exceptions', '0', '1') if IS_LINUX: TestFlag('death_test_use_fork', '1', '0') TestFlag('stack_trace_depth', '0', '100') if __name__ == '__main__': gtest_test_utils.Main()
bsd-3-clause
FlaPer87/django-nonrel
django/core/management/commands/testserver.py
73
1408
from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--addrport', action='store', dest='addrport', type='string', default='', help='port number or ipaddr:port to run the server on'), ) help = 'Runs a development server with data from the given fixture(s).' args = '[fixture ...]' requires_model_validation = False def handle(self, *fixture_labels, **options): from django.core.management import call_command from django.db import connection verbosity = int(options.get('verbosity', 1)) addrport = options.get('addrport') # Create a test database. db_name = connection.creation.create_test_db(verbosity=verbosity) # Import the fixture data into the test database. call_command('loaddata', *fixture_labels, **{'verbosity': verbosity}) # Run the development server. Turn off auto-reloading because it causes # a strange error -- it causes this handle() method to be called # multiple times. shutdown_message = '\nServer stopped.\nNote that the test database, %r, has not been deleted. You can explore it on your own.' % db_name call_command('runserver', addrport=addrport, shutdown_message=shutdown_message, use_reloader=False)
bsd-3-clause
svenstaro/ansible
lib/ansible/modules/cloud/rackspace/rax_cbs_attachments.py
56
6794
#!/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/>. # This is a DOCUMENTATION stub specific to this module, it extends # a documentation fragment located in ansible.utils.module_docs_fragments ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: rax_cbs_attachments short_description: Manipulate Rackspace Cloud Block Storage Volume Attachments description: - Manipulate Rackspace Cloud Block Storage Volume Attachments version_added: 1.6 options: device: description: - The device path to attach the volume to, e.g. /dev/xvde default: null required: true volume: description: - Name or id of the volume to attach/detach default: null required: true server: description: - Name or id of the server to attach/detach default: null required: true state: description: - Indicate desired state of the resource choices: - present - absent default: present required: true wait: description: - wait for the volume to be in 'in-use'/'available' state before returning default: "no" choices: - "yes" - "no" wait_timeout: description: - how long before wait gives up, in seconds default: 300 author: - "Christopher H. Laco (@claco)" - "Matt Martz (@sivel)" extends_documentation_fragment: rackspace.openstack ''' EXAMPLES = ''' - name: Attach a Block Storage Volume gather_facts: False hosts: local connection: local tasks: - name: Storage volume attach request local_action: module: rax_cbs_attachments credentials: ~/.raxpub volume: my-volume server: my-server device: /dev/xvdd region: DFW wait: yes state: present register: my_volume ''' try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False def cloud_block_storage_attachments(module, state, volume, server, device, wait, wait_timeout): cbs = pyrax.cloud_blockstorage cs = pyrax.cloudservers if cbs is None or cs is None: module.fail_json(msg='Failed to instantiate client. This ' 'typically indicates an invalid region or an ' 'incorrectly capitalized region name.') changed = False instance = {} volume = rax_find_volume(module, pyrax, volume) if not volume: module.fail_json(msg='No matching storage volumes were found') if state == 'present': server = rax_find_server(module, pyrax, server) if (volume.attachments and volume.attachments[0]['server_id'] == server.id): changed = False elif volume.attachments: module.fail_json(msg='Volume is attached to another server') else: try: volume.attach_to_instance(server, mountpoint=device) changed = True except Exception as e: module.fail_json(msg='%s' % e.message) volume.get() for key, value in vars(volume).items(): if (isinstance(value, NON_CALLABLES) and not key.startswith('_')): instance[key] = value result = dict(changed=changed) if volume.status == 'error': result['msg'] = '%s failed to build' % volume.id elif wait: attempts = wait_timeout / 5 pyrax.utils.wait_until(volume, 'status', 'in-use', interval=5, attempts=attempts) volume.get() result['volume'] = rax_to_dict(volume) if 'msg' in result: module.fail_json(**result) else: module.exit_json(**result) elif state == 'absent': server = rax_find_server(module, pyrax, server) if (volume.attachments and volume.attachments[0]['server_id'] == server.id): try: volume.detach() if wait: pyrax.utils.wait_until(volume, 'status', 'available', interval=3, attempts=0, verbose=False) changed = True except Exception as e: module.fail_json(msg='%s' % e.message) volume.get() changed = True elif volume.attachments: module.fail_json(msg='Volume is attached to another server') result = dict(changed=changed, volume=rax_to_dict(volume)) if volume.status == 'error': result['msg'] = '%s failed to build' % volume.id if 'msg' in result: module.fail_json(**result) else: module.exit_json(**result) module.exit_json(changed=changed, volume=instance) def main(): argument_spec = rax_argument_spec() argument_spec.update( dict( device=dict(required=True), volume=dict(required=True), server=dict(required=True), state=dict(default='present', choices=['present', 'absent']), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=300) ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together() ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') device = module.params.get('device') volume = module.params.get('volume') server = module.params.get('server') state = module.params.get('state') wait = module.params.get('wait') wait_timeout = module.params.get('wait_timeout') setup_rax_module(module, pyrax) cloud_block_storage_attachments(module, state, volume, server, device, wait, wait_timeout) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.rax import * ### invoke the module if __name__ == '__main__': main()
gpl-3.0
master-g/vogenerator
google/protobuf/internal/proto_builder_test.py
122
3770
#! /usr/bin/env python # # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # 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 Google Inc. 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. """Tests for google.protobuf.proto_builder.""" try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict #PY26 try: import unittest2 as unittest except ImportError: import unittest from google.protobuf import descriptor_pb2 from google.protobuf import descriptor_pool from google.protobuf import proto_builder from google.protobuf import text_format class ProtoBuilderTest(unittest.TestCase): def setUp(self): self.ordered_fields = OrderedDict([ ('foo', descriptor_pb2.FieldDescriptorProto.TYPE_INT64), ('bar', descriptor_pb2.FieldDescriptorProto.TYPE_STRING), ]) self._fields = dict(self.ordered_fields) def testMakeSimpleProtoClass(self): """Test that we can create a proto class.""" proto_cls = proto_builder.MakeSimpleProtoClass( self._fields, full_name='net.proto2.python.public.proto_builder_test.Test') proto = proto_cls() proto.foo = 12345 proto.bar = 'asdf' self.assertMultiLineEqual( 'bar: "asdf"\nfoo: 12345\n', text_format.MessageToString(proto)) def testOrderedFields(self): """Test that the field order is maintained when given an OrderedDict.""" proto_cls = proto_builder.MakeSimpleProtoClass( self.ordered_fields, full_name='net.proto2.python.public.proto_builder_test.OrderedTest') proto = proto_cls() proto.foo = 12345 proto.bar = 'asdf' self.assertMultiLineEqual( 'foo: 12345\nbar: "asdf"\n', text_format.MessageToString(proto)) def testMakeSameProtoClassTwice(self): """Test that the DescriptorPool is used.""" pool = descriptor_pool.DescriptorPool() proto_cls1 = proto_builder.MakeSimpleProtoClass( self._fields, full_name='net.proto2.python.public.proto_builder_test.Test', pool=pool) proto_cls2 = proto_builder.MakeSimpleProtoClass( self._fields, full_name='net.proto2.python.public.proto_builder_test.Test', pool=pool) self.assertIs(proto_cls1.DESCRIPTOR, proto_cls2.DESCRIPTOR) if __name__ == '__main__': unittest.main()
mit
georgewhewell/CouchPotatoServer
couchpotato/core/providers/userscript/base.py
9
1894
from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.helpers.encoding import simplifyString from couchpotato.core.helpers.variable import getImdb, md5 from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from urlparse import urlparse log = CPLog(__name__) class UserscriptBase(Plugin): version = 1 includes = [] excludes = [] def __init__(self): addEvent('userscript.get_includes', self.getInclude) addEvent('userscript.get_excludes', self.getExclude) addEvent('userscript.get_provider_version', self.getVersion) addEvent('userscript.get_movie_via_url', self.belongsTo) def search(self, name, year = None): result = fireEvent('movie.search', q = '%s %s' % (name, year), limit = 1, merge = True) if len(result) > 0: movie = fireEvent('movie.info', identifier = result[0].get('imdb'), extended = False, merge = True) return movie else: return None def belongsTo(self, url): host = urlparse(url).hostname host_split = host.split('.') if len(host_split) > 2: host = host[len(host_split[0]):] for include in self.includes: if host in include: return self.getMovie(url) return def getUrl(self, url): return self.getCache(md5(simplifyString(url)), url = url) def getMovie(self, url): try: data = self.getUrl(url) except: data = '' return self.getInfo(getImdb(data)) def getInfo(self, identifier): return fireEvent('movie.info', identifier = identifier, extended = False, merge = True) def getInclude(self): return self.includes def getExclude(self): return self.excludes def getVersion(self): return self.version
gpl-3.0
jbedorf/tensorflow
tensorflow/python/autograph/pyct/transformer_test.py
1
11184
# Copyright 2017 The TensorFlow Authors. 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. # ============================================================================== """Tests for templates module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import transformer from tensorflow.python.platform import test class TransformerTest(test.TestCase): def _simple_context(self): entity_info = transformer.EntityInfo( source_code=None, source_file=None, namespace=None, arg_values=None, arg_types=None) return transformer.Context(entity_info) def test_entity_scope_tracking(self): class TestTransformer(transformer.Base): # The choice of note to assign to is arbitrary. Using Assign because it's # easy to find in the tree. def visit_Assign(self, node): anno.setanno(node, 'enclosing_entities', self.enclosing_entities) return self.generic_visit(node) # This will show up in the lambda function. def visit_BinOp(self, node): anno.setanno(node, 'enclosing_entities', self.enclosing_entities) return self.generic_visit(node) tr = TestTransformer(self._simple_context()) def test_function(): a = 0 class TestClass(object): def test_method(self): b = 0 def inner_function(x): c = 0 d = lambda y: (x + y) return c, d return b, inner_function return a, TestClass node, _ = parser.parse_entity(test_function) node = tr.visit(node) test_function_node = node.body[0] test_class = test_function_node.body[1] test_method = test_class.body[0] inner_function = test_method.body[1] lambda_node = inner_function.body[1].value a = test_function_node.body[0] b = test_method.body[0] c = inner_function.body[0] lambda_expr = lambda_node.body self.assertEqual( (test_function_node,), anno.getanno(a, 'enclosing_entities')) self.assertEqual((test_function_node, test_class, test_method), anno.getanno(b, 'enclosing_entities')) self.assertEqual( (test_function_node, test_class, test_method, inner_function), anno.getanno(c, 'enclosing_entities')) self.assertEqual((test_function_node, test_class, test_method, inner_function, lambda_node), anno.getanno(lambda_expr, 'enclosing_entities')) def assertSameAnno(self, first, second, key): self.assertIs(anno.getanno(first, key), anno.getanno(second, key)) def assertDifferentAnno(self, first, second, key): self.assertIsNot(anno.getanno(first, key), anno.getanno(second, key)) def test_state_tracking(self): class LoopState(object): pass class CondState(object): pass class TestTransformer(transformer.Base): def visit(self, node): anno.setanno(node, 'loop_state', self.state[LoopState].value) anno.setanno(node, 'cond_state', self.state[CondState].value) return super(TestTransformer, self).visit(node) def visit_While(self, node): self.state[LoopState].enter() node = self.generic_visit(node) self.state[LoopState].exit() return node def visit_If(self, node): self.state[CondState].enter() node = self.generic_visit(node) self.state[CondState].exit() return node tr = TestTransformer(self._simple_context()) def test_function(a): a = 1 while a: _ = 'a' if a > 2: _ = 'b' while True: raise '1' if a > 3: _ = 'c' while True: raise '1' node, _ = parser.parse_entity(test_function) node = tr.visit(node) fn_body = node.body[0].body outer_while_body = fn_body[1].body self.assertSameAnno(fn_body[0], outer_while_body[0], 'cond_state') self.assertDifferentAnno(fn_body[0], outer_while_body[0], 'loop_state') first_if_body = outer_while_body[1].body self.assertDifferentAnno(outer_while_body[0], first_if_body[0], 'cond_state') self.assertSameAnno(outer_while_body[0], first_if_body[0], 'loop_state') first_inner_while_body = first_if_body[1].body self.assertSameAnno(first_if_body[0], first_inner_while_body[0], 'cond_state') self.assertDifferentAnno(first_if_body[0], first_inner_while_body[0], 'loop_state') second_if_body = outer_while_body[2].body self.assertDifferentAnno(first_if_body[0], second_if_body[0], 'cond_state') self.assertSameAnno(first_if_body[0], second_if_body[0], 'loop_state') second_inner_while_body = second_if_body[1].body self.assertDifferentAnno(first_inner_while_body[0], second_inner_while_body[0], 'cond_state') self.assertDifferentAnno(first_inner_while_body[0], second_inner_while_body[0], 'loop_state') def test_local_scope_info_stack(self): class TestTransformer(transformer.Base): # Extract all string constants from the block. def visit_Str(self, node): self.set_local('string', self.get_local('string', default='') + node.s) return self.generic_visit(node) def _annotate_result(self, node): self.enter_local_scope() node = self.generic_visit(node) anno.setanno(node, 'test', self.get_local('string')) self.exit_local_scope() return node def visit_While(self, node): return self._annotate_result(node) def visit_For(self, node): return self._annotate_result(node) tr = TestTransformer(self._simple_context()) def test_function(a): """Docstring.""" assert a == 'This should not be counted' for i in range(3): _ = 'a' if i > 2: return 'b' else: _ = 'c' while True: raise '1' return 'nor this' node, _ = parser.parse_entity(test_function) node = tr.visit(node) for_node = node.body[0].body[2] while_node = for_node.body[1].orelse[1] self.assertFalse(anno.hasanno(for_node, 'string')) self.assertEqual('abc', anno.getanno(for_node, 'test')) self.assertFalse(anno.hasanno(while_node, 'string')) self.assertEqual('1', anno.getanno(while_node, 'test')) def test_local_scope_info_stack_checks_integrity(self): class TestTransformer(transformer.Base): def visit_If(self, node): self.enter_local_scope() return self.generic_visit(node) def visit_For(self, node): node = self.generic_visit(node) self.exit_local_scope() return node tr = TestTransformer(self._simple_context()) def no_exit(a): if a > 0: print(a) return None node, _ = parser.parse_entity(no_exit) with self.assertRaises(AssertionError): tr.visit(node) def no_entry(a): for _ in a: print(a) node, _ = parser.parse_entity(no_entry) with self.assertRaises(AssertionError): tr.visit(node) def test_visit_block_postprocessing(self): class TestTransformer(transformer.Base): def _process_body_item(self, node): if isinstance(node, gast.Assign) and (node.value.id == 'y'): if_node = gast.If(gast.Name('x', gast.Load(), None), [node], []) return if_node, if_node.body return node, None def visit_FunctionDef(self, node): node.body = self.visit_block( node.body, after_visit=self._process_body_item) return node def test_function(x, y): z = x z = y return z tr = TestTransformer(self._simple_context()) node, _ = parser.parse_entity(test_function) node = tr.visit(node) node = node.body[0] self.assertEqual(len(node.body), 2) self.assertTrue(isinstance(node.body[0], gast.Assign)) self.assertTrue(isinstance(node.body[1], gast.If)) self.assertTrue(isinstance(node.body[1].body[0], gast.Assign)) self.assertTrue(isinstance(node.body[1].body[1], gast.Return)) def test_robust_error_on_list_visit(self): class BrokenTransformer(transformer.Base): def visit_If(self, node): # This is broken because visit expects a single node, not a list, and # the body of an if is a list. # Importantly, the default error handling in visit also expects a single # node. Therefore, mistakes like this need to trigger a type error # before the visit called here installs its error handler. # That type error can then be caught by the enclosing call to visit, # and correctly blame the If node. self.visit(node.body) return node def test_function(x): if x > 0: return x tr = BrokenTransformer(self._simple_context()) node, _ = parser.parse_entity(test_function) with self.assertRaises(ValueError) as cm: node = tr.visit(node) obtained_message = str(cm.exception) expected_message = r'expected "ast.AST", got "\<(type|class) \'list\'\>"' self.assertRegexpMatches(obtained_message, expected_message) def test_robust_error_on_ast_corruption(self): # A child class should not be able to be so broken that it causes the error # handling in `transformer.Base` to raise an exception. Why not? Because # then the original error location is dropped, and an error handler higher # up in the call stack gives misleading information. # Here we test that the error handling in `visit` completes, and blames the # correct original exception, even if the AST gets corrupted. class NotANode(object): pass class BrokenTransformer(transformer.Base): def visit_If(self, node): node.body = NotANode() raise ValueError('I blew up') def test_function(x): if x > 0: return x tr = BrokenTransformer(self._simple_context()) node, _ = parser.parse_entity(test_function) with self.assertRaises(ValueError) as cm: node = tr.visit(node) obtained_message = str(cm.exception) # The message should reference the exception actually raised, not anything # from the exception handler. expected_substring = 'I blew up' self.assertTrue(expected_substring in obtained_message, obtained_message) if __name__ == '__main__': test.main()
apache-2.0
momingsong/ns-3
src/topology-read/bindings/modulegen__gcc_ILP32.py
28
172229
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.topology_read', 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']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', 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-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## 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') ## 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') ## 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')) ## 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') ## topology-reader-helper.h (module 'topology-read'): ns3::TopologyReaderHelper [class] module.add_class('TopologyReaderHelper') ## 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::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') ## 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']) ## 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::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::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')) ## 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']) ## topology-reader.h (module 'topology-read'): ns3::TopologyReader [class] module.add_class('TopologyReader', parent=root_module['ns3::Object']) ## topology-reader.h (module 'topology-read'): ns3::TopologyReader::Link [class] module.add_class('Link', outer_class=root_module['ns3::TopologyReader']) ## 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> >']) ## 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> >']) ## 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']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## inet-topology-reader.h (module 'topology-read'): ns3::InetTopologyReader [class] module.add_class('InetTopologyReader', parent=root_module['ns3::TopologyReader']) ## 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-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']) ## 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']) ## 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') ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## orbis-topology-reader.h (module 'topology-read'): ns3::OrbisTopologyReader [class] module.add_class('OrbisTopologyReader', parent=root_module['ns3::TopologyReader']) ## rocketfuel-topology-reader.h (module 'topology-read'): ns3::RocketfuelTopologyReader [class] module.add_class('RocketfuelTopologyReader', parent=root_module['ns3::TopologyReader']) ## 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']) ## 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']) module.add_container('std::map< std::string, std::string >', ('std::string', 'std::string'), 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) 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 ( * ) ( 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&') 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_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) 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_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TopologyReaderHelper_methods(root_module, root_module['ns3::TopologyReaderHelper']) 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_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) 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__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__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TopologyReader_methods(root_module, root_module['ns3::TopologyReader']) register_Ns3TopologyReaderLink_methods(root_module, root_module['ns3::TopologyReader::Link']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) 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_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_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3InetTopologyReader_methods(root_module, root_module['ns3::InetTopologyReader']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) 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_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3OrbisTopologyReader_methods(root_module, root_module['ns3::OrbisTopologyReader']) register_Ns3RocketfuelTopologyReader_methods(root_module, root_module['ns3::RocketfuelTopologyReader']) 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_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) 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']) 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_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_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_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::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'): 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_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_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', [], 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_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_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_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_Ns3TopologyReaderHelper_methods(root_module, cls): ## topology-reader-helper.h (module 'topology-read'): ns3::TopologyReaderHelper::TopologyReaderHelper(ns3::TopologyReaderHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::TopologyReaderHelper const &', 'arg0')]) ## topology-reader-helper.h (module 'topology-read'): ns3::TopologyReaderHelper::TopologyReaderHelper() [constructor] cls.add_constructor([]) ## topology-reader-helper.h (module 'topology-read'): ns3::Ptr<ns3::TopologyReader> ns3::TopologyReaderHelper::GetTopologyReader() [member function] cls.add_method('GetTopologyReader', 'ns3::Ptr< ns3::TopologyReader >', []) ## topology-reader-helper.h (module 'topology-read'): void ns3::TopologyReaderHelper::SetFileName(std::string const fileName) [member function] cls.add_method('SetFileName', 'void', [param('std::string const', 'fileName')]) ## topology-reader-helper.h (module 'topology-read'): void ns3::TopologyReaderHelper::SetFileType(std::string const fileType) [member function] cls.add_method('SetFileType', 'void', [param('std::string const', 'fileType')]) 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) [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')]) ## 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) [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')]) ## 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) [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')]) ## 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'): 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 tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) 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) 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) 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_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'): 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_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__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__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_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_Ns3TopologyReader_methods(root_module, cls): ## topology-reader.h (module 'topology-read'): ns3::TopologyReader::TopologyReader() [constructor] cls.add_constructor([]) ## topology-reader.h (module 'topology-read'): void ns3::TopologyReader::AddLink(ns3::TopologyReader::Link link) [member function] cls.add_method('AddLink', 'void', [param('ns3::TopologyReader::Link', 'link')]) ## topology-reader.h (module 'topology-read'): std::string ns3::TopologyReader::GetFileName() const [member function] cls.add_method('GetFileName', 'std::string', [], is_const=True) ## topology-reader.h (module 'topology-read'): static ns3::TypeId ns3::TopologyReader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## topology-reader.h (module 'topology-read'): std::_List_const_iterator<ns3::TopologyReader::Link> ns3::TopologyReader::LinksBegin() const [member function] cls.add_method('LinksBegin', 'std::_List_const_iterator< ns3::TopologyReader::Link >', [], is_const=True) ## topology-reader.h (module 'topology-read'): bool ns3::TopologyReader::LinksEmpty() const [member function] cls.add_method('LinksEmpty', 'bool', [], is_const=True) ## topology-reader.h (module 'topology-read'): std::_List_const_iterator<ns3::TopologyReader::Link> ns3::TopologyReader::LinksEnd() const [member function] cls.add_method('LinksEnd', 'std::_List_const_iterator< ns3::TopologyReader::Link >', [], is_const=True) ## topology-reader.h (module 'topology-read'): int ns3::TopologyReader::LinksSize() const [member function] cls.add_method('LinksSize', 'int', [], is_const=True) ## topology-reader.h (module 'topology-read'): ns3::NodeContainer ns3::TopologyReader::Read() [member function] cls.add_method('Read', 'ns3::NodeContainer', [], is_pure_virtual=True, is_virtual=True) ## topology-reader.h (module 'topology-read'): void ns3::TopologyReader::SetFileName(std::string const & fileName) [member function] cls.add_method('SetFileName', 'void', [param('std::string const &', 'fileName')]) return def register_Ns3TopologyReaderLink_methods(root_module, cls): ## topology-reader.h (module 'topology-read'): ns3::TopologyReader::Link::Link(ns3::TopologyReader::Link const & arg0) [copy constructor] cls.add_constructor([param('ns3::TopologyReader::Link const &', 'arg0')]) ## topology-reader.h (module 'topology-read'): ns3::TopologyReader::Link::Link(ns3::Ptr<ns3::Node> fromPtr, std::string const & fromName, ns3::Ptr<ns3::Node> toPtr, std::string const & toName) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'fromPtr'), param('std::string const &', 'fromName'), param('ns3::Ptr< ns3::Node >', 'toPtr'), param('std::string const &', 'toName')]) ## topology-reader.h (module 'topology-read'): std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > ns3::TopologyReader::Link::AttributesBegin() const [member function] cls.add_method('AttributesBegin', 'std::_Rb_tree_const_iterator< std::pair< std::basic_string< char, std::char_traits< char >, std::allocator< char > > const, std::basic_string< char, std::char_traits< char >, std::allocator< char > > > >', [], is_const=True) ## topology-reader.h (module 'topology-read'): std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > ns3::TopologyReader::Link::AttributesEnd() const [member function] cls.add_method('AttributesEnd', 'std::_Rb_tree_const_iterator< std::pair< std::basic_string< char, std::char_traits< char >, std::allocator< char > > const, std::basic_string< char, std::char_traits< char >, std::allocator< char > > > >', [], is_const=True) ## topology-reader.h (module 'topology-read'): std::string ns3::TopologyReader::Link::GetAttribute(std::string const & name) const [member function] cls.add_method('GetAttribute', 'std::string', [param('std::string const &', 'name')], is_const=True) ## topology-reader.h (module 'topology-read'): bool ns3::TopologyReader::Link::GetAttributeFailSafe(std::string const & name, std::string & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string const &', 'name'), param('std::string &', 'value')], is_const=True) ## topology-reader.h (module 'topology-read'): ns3::Ptr<ns3::Node> ns3::TopologyReader::Link::GetFromNode() const [member function] cls.add_method('GetFromNode', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## topology-reader.h (module 'topology-read'): std::string ns3::TopologyReader::Link::GetFromNodeName() const [member function] cls.add_method('GetFromNodeName', 'std::string', [], is_const=True) ## topology-reader.h (module 'topology-read'): ns3::Ptr<ns3::Node> ns3::TopologyReader::Link::GetToNode() const [member function] cls.add_method('GetToNode', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## topology-reader.h (module 'topology-read'): std::string ns3::TopologyReader::Link::GetToNodeName() const [member function] cls.add_method('GetToNodeName', 'std::string', [], is_const=True) ## topology-reader.h (module 'topology-read'): void ns3::TopologyReader::Link::SetAttribute(std::string const & name, std::string const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string const &', 'name'), param('std::string const &', 'value')]) 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_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_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_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_Ns3InetTopologyReader_methods(root_module, cls): ## inet-topology-reader.h (module 'topology-read'): static ns3::TypeId ns3::InetTopologyReader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## inet-topology-reader.h (module 'topology-read'): ns3::InetTopologyReader::InetTopologyReader() [constructor] cls.add_constructor([]) ## inet-topology-reader.h (module 'topology-read'): ns3::NodeContainer ns3::InetTopologyReader::Read() [member function] cls.add_method('Read', 'ns3::NodeContainer', [], 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_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_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_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_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'): 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_Ns3OrbisTopologyReader_methods(root_module, cls): ## orbis-topology-reader.h (module 'topology-read'): static ns3::TypeId ns3::OrbisTopologyReader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## orbis-topology-reader.h (module 'topology-read'): ns3::OrbisTopologyReader::OrbisTopologyReader() [constructor] cls.add_constructor([]) ## orbis-topology-reader.h (module 'topology-read'): ns3::NodeContainer ns3::OrbisTopologyReader::Read() [member function] cls.add_method('Read', 'ns3::NodeContainer', [], is_virtual=True) return def register_Ns3RocketfuelTopologyReader_methods(root_module, cls): ## rocketfuel-topology-reader.h (module 'topology-read'): static ns3::TypeId ns3::RocketfuelTopologyReader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## rocketfuel-topology-reader.h (module 'topology-read'): ns3::RocketfuelTopologyReader::RocketfuelTopologyReader() [constructor] cls.add_constructor([]) ## rocketfuel-topology-reader.h (module 'topology-read'): ns3::NodeContainer ns3::RocketfuelTopologyReader::Read() [member function] cls.add_method('Read', 'ns3::NodeContainer', [], 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_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_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_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) 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 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()
gpl-2.0
ryanneufeld/OctoPrint
src/octoprint/util/avr_isp/stk500v2.py
56
4607
import os, struct, sys, time from serial import Serial from serial import SerialException import ispBase, intelHex class Stk500v2(ispBase.IspBase): def __init__(self): self.serial = None self.seq = 1 self.lastAddr = -1 self.progressCallback = None def connect(self, port = 'COM22', speed = 115200): if self.serial != None: self.close() try: self.serial = Serial(str(port), speed, timeout=1, writeTimeout=10000) except SerialException as e: raise ispBase.IspError("Failed to open serial port") except: raise ispBase.IspError("Unexpected error while connecting to serial port:" + port + ":" + str(sys.exc_info()[0])) self.seq = 1 #Reset the controller self.serial.setDTR(1) time.sleep(0.1) self.serial.setDTR(0) time.sleep(0.2) self.sendMessage([1]) if self.sendMessage([0x10, 0xc8, 0x64, 0x19, 0x20, 0x00, 0x53, 0x03, 0xac, 0x53, 0x00, 0x00]) != [0x10, 0x00]: self.close() raise ispBase.IspError("Failed to enter programming mode") def close(self): if self.serial != None: self.serial.close() self.serial = None #Leave ISP does not reset the serial port, only resets the device, and returns the serial port after disconnecting it from the programming interface. # This allows you to use the serial port without opening it again. def leaveISP(self): if self.serial != None: if self.sendMessage([0x11]) != [0x11, 0x00]: raise ispBase.IspError("Failed to leave programming mode") ret = self.serial self.serial = None return ret return None def isConnected(self): return self.serial != None def sendISP(self, data): recv = self.sendMessage([0x1D, 4, 4, 0, data[0], data[1], data[2], data[3]]) return recv[2:6] def writeFlash(self, flashData): #Set load addr to 0, in case we have more then 64k flash we need to enable the address extension pageSize = self.chip['pageSize'] * 2 flashSize = pageSize * self.chip['pageCount'] if flashSize > 0xFFFF: self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00]) else: self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00]) loadCount = (len(flashData) + pageSize - 1) / pageSize for i in xrange(0, loadCount): recv = self.sendMessage([0x13, pageSize >> 8, pageSize & 0xFF, 0xc1, 0x0a, 0x40, 0x4c, 0x20, 0x00, 0x00] + flashData[(i * pageSize):(i * pageSize + pageSize)]) if self.progressCallback != None: self.progressCallback(i + 1, loadCount*2) def verifyFlash(self, flashData): #Set load addr to 0, in case we have more then 64k flash we need to enable the address extension flashSize = self.chip['pageSize'] * 2 * self.chip['pageCount'] if flashSize > 0xFFFF: self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00]) else: self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00]) loadCount = (len(flashData) + 0xFF) / 0x100 for i in xrange(0, loadCount): recv = self.sendMessage([0x14, 0x01, 0x00, 0x20])[2:0x102] if self.progressCallback != None: self.progressCallback(loadCount + i + 1, loadCount*2) for j in xrange(0, 0x100): if i * 0x100 + j < len(flashData) and flashData[i * 0x100 + j] != recv[j]: raise ispBase.IspError('Verify error at: 0x%x' % (i * 0x100 + j)) def sendMessage(self, data): message = struct.pack(">BBHB", 0x1B, self.seq, len(data), 0x0E) for c in data: message += struct.pack(">B", c) checksum = 0 for c in message: checksum ^= ord(c) message += struct.pack(">B", checksum) try: self.serial.write(message) self.serial.flush() except SerialTimeoutException: raise ispBase.IspError('Serial send timeout') self.seq = (self.seq + 1) & 0xFF return self.recvMessage() def recvMessage(self): state = 'Start' checksum = 0 while True: s = self.serial.read() if len(s) < 1: raise ispBase.IspError("Timeout") b = struct.unpack(">B", s)[0] checksum ^= b #print(hex(b)) if state == 'Start': if b == 0x1B: state = 'GetSeq' checksum = 0x1B elif state == 'GetSeq': state = 'MsgSize1' elif state == 'MsgSize1': msgSize = b << 8 state = 'MsgSize2' elif state == 'MsgSize2': msgSize |= b state = 'Token' elif state == 'Token': if b != 0x0E: state = 'Start' else: state = 'Data' data = [] elif state == 'Data': data.append(b) if len(data) == msgSize: state = 'Checksum' elif state == 'Checksum': if checksum != 0: state = 'Start' else: return data def main(): programmer = Stk500v2() programmer.connect(port = sys.argv[1]) programmer.programChip(intelHex.readHex(sys.argv[2])) sys.exit(1) if __name__ == '__main__': main()
agpl-3.0
SystemsBioinformatics/vonda
vonda/colormaps/yellowcyan.py
1
30949
colorbar = """ <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2434" y="0" id="rect11" style="fill:rgb(255,255,0);stroke:rgb(255,255,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2438" y="0" id="rect13" style="fill:rgb(249,249,0);stroke:rgb(249,249,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2442" y="0" id="rect15" style="fill:rgb(244,244,0);stroke:rgb(244,244,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2446" y="0" id="rect17" style="fill:rgb(239,239,0);stroke:rgb(239,239,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2450" y="0" id="rect19" style="fill:rgb(234,234,0);stroke:rgb(234,234,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2454" y="0" id="rect21" style="fill:rgb(229,229,0);stroke:rgb(229,229,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2458" y="0" id="rect23" style="fill:rgb(224,224,0);stroke:rgb(224,224,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2462" y="0" id="rect25" style="fill:rgb(219,219,0);stroke:rgb(219,219,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2466" y="0" id="rect27" style="fill:rgb(214,214,0);stroke:rgb(214,214,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2470" y="0" id="rect29" style="fill:rgb(209,209,0);stroke:rgb(209,209,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2474" y="0" id="rect31" style="fill:rgb(204,204,0);stroke:rgb(204,204,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2478" y="0" id="rect33" style="fill:rgb(198,198,0);stroke:rgb(198,198,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2482" y="0" id="rect35" style="fill:rgb(193,193,0);stroke:rgb(193,193,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2486" y="0" id="rect37" style="fill:rgb(188,188,0);stroke:rgb(188,188,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2490" y="0" id="rect39" style="fill:rgb(183,183,0);stroke:rgb(183,183,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2494" y="0" id="rect41" style="fill:rgb(178,178,0);stroke:rgb(178,178,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2498" y="0" id="rect43" style="fill:rgb(173,173,0);stroke:rgb(173,173,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2502" y="0" id="rect45" style="fill:rgb(168,168,0);stroke:rgb(168,168,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2506" y="0" id="rect47" style="fill:rgb(163,163,0);stroke:rgb(163,163,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2510" y="0" id="rect49" style="fill:rgb(158,158,0);stroke:rgb(158,158,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2514" y="0" id="rect51" style="fill:rgb(153,153,0);stroke:rgb(153,153,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2518" y="0" id="rect53" style="fill:rgb(147,147,0);stroke:rgb(147,147,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2522" y="0" id="rect55" style="fill:rgb(142,142,0);stroke:rgb(142,142,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2526" y="0" id="rect57" style="fill:rgb(137,137,0);stroke:rgb(137,137,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2530" y="0" id="rect59" style="fill:rgb(132,132,0);stroke:rgb(132,132,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2534" y="0" id="rect61" style="fill:rgb(127,127,0);stroke:rgb(127,127,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2538" y="0" id="rect63" style="fill:rgb(122,122,0);stroke:rgb(122,122,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2542" y="0" id="rect65" style="fill:rgb(117,117,0);stroke:rgb(117,117,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2546" y="0" id="rect67" style="fill:rgb(112,112,0);stroke:rgb(112,112,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2550" y="0" id="rect69" style="fill:rgb(107,107,0);stroke:rgb(107,107,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2554" y="0" id="rect71" style="fill:rgb(102,102,0);stroke:rgb(102,102,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2558" y="0" id="rect73" style="fill:rgb(96,96,0);stroke:rgb(96,96,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2562" y="0" id="rect75" style="fill:rgb(91,91,0);stroke:rgb(91,91,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2566" y="0" id="rect77" style="fill:rgb(86,86,0);stroke:rgb(86,86,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2570" y="0" id="rect79" style="fill:rgb(81,81,0);stroke:rgb(81,81,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2574" y="0" id="rect81" style="fill:rgb(76,76,0);stroke:rgb(76,76,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2578" y="0" id="rect83" style="fill:rgb(71,71,0);stroke:rgb(71,71,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2582" y="0" id="rect85" style="fill:rgb(66,66,0);stroke:rgb(66,66,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2586" y="0" id="rect87" style="fill:rgb(61,61,0);stroke:rgb(61,61,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2590" y="0" id="rect89" style="fill:rgb(56,56,0);stroke:rgb(56,56,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2594" y="0" id="rect91" style="fill:rgb(51,51,0);stroke:rgb(51,51,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2598" y="0" id="rect93" style="fill:rgb(45,45,0);stroke:rgb(45,45,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2602" y="0" id="rect95" style="fill:rgb(40,40,0);stroke:rgb(40,40,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2606" y="0" id="rect97" style="fill:rgb(35,35,0);stroke:rgb(35,35,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2610" y="0" id="rect99" style="fill:rgb(30,30,0);stroke:rgb(30,30,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2614" y="0" id="rect101" style="fill:rgb(25,25,0);stroke:rgb(25,25,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2618" y="0" id="rect103" style="fill:rgb(20,20,0);stroke:rgb(20,20,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2622" y="0" id="rect105" style="fill:rgb(15,15,0);stroke:rgb(15,15,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2626" y="0" id="rect107" style="fill:rgb(10,10,0);stroke:rgb(10,10,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2630" y="0" id="rect109" style="fill:rgb(5,5,0);stroke:rgb(5,5,0);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2634" y="0" id="rect111" style="fill:rgb(0,5,5);stroke:rgb(0,5,5);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2638" y="0" id="rect113" style="fill:rgb(0,10,10);stroke:rgb(0,10,10);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2642" y="0" id="rect115" style="fill:rgb(0,15,15);stroke:rgb(0,15,15);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2646" y="0" id="rect117" style="fill:rgb(0,20,20);stroke:rgb(0,20,20);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2650" y="0" id="rect119" style="fill:rgb(0,25,25);stroke:rgb(0,25,25);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2654" y="0" id="rect121" style="fill:rgb(0,30,30);stroke:rgb(0,30,30);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2658" y="0" id="rect123" style="fill:rgb(0,35,35);stroke:rgb(0,35,35);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2662" y="0" id="rect125" style="fill:rgb(0,40,40);stroke:rgb(0,40,40);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2666" y="0" id="rect127" style="fill:rgb(0,45,45);stroke:rgb(0,45,45);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2670" y="0" id="rect129" style="fill:rgb(0,51,51);stroke:rgb(0,51,51);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2674" y="0" id="rect131" style="fill:rgb(0,56,56);stroke:rgb(0,56,56);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2678" y="0" id="rect133" style="fill:rgb(0,61,61);stroke:rgb(0,61,61);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2682" y="0" id="rect135" style="fill:rgb(0,66,66);stroke:rgb(0,66,66);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2686" y="0" id="rect137" style="fill:rgb(0,71,71);stroke:rgb(0,71,71);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2690" y="0" id="rect139" style="fill:rgb(0,76,76);stroke:rgb(0,76,76);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2694" y="0" id="rect141" style="fill:rgb(0,81,81);stroke:rgb(0,81,81);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2698" y="0" id="rect143" style="fill:rgb(0,86,86);stroke:rgb(0,86,86);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2702" y="0" id="rect145" style="fill:rgb(0,91,91);stroke:rgb(0,91,91);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2706" y="0" id="rect147" style="fill:rgb(0,96,96);stroke:rgb(0,96,96);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2710" y="0" id="rect149" style="fill:rgb(0,102,102);stroke:rgb(0,102,102);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2714" y="0" id="rect151" style="fill:rgb(0,107,107);stroke:rgb(0,107,107);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2718" y="0" id="rect153" style="fill:rgb(0,112,112);stroke:rgb(0,112,112);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2722" y="0" id="rect155" style="fill:rgb(0,117,117);stroke:rgb(0,117,117);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2726" y="0" id="rect157" style="fill:rgb(0,122,122);stroke:rgb(0,122,122);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2730" y="0" id="rect159" style="fill:rgb(0,127,127);stroke:rgb(0,127,127);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2734" y="0" id="rect161" style="fill:rgb(0,132,132);stroke:rgb(0,132,132);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2738" y="0" id="rect163" style="fill:rgb(0,137,137);stroke:rgb(0,137,137);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2742" y="0" id="rect165" style="fill:rgb(0,142,142);stroke:rgb(0,142,142);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2746" y="0" id="rect167" style="fill:rgb(0,147,147);stroke:rgb(0,147,147);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2750" y="0" id="rect169" style="fill:rgb(0,153,153);stroke:rgb(0,153,153);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2754" y="0" id="rect171" style="fill:rgb(0,158,158);stroke:rgb(0,158,158);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2758" y="0" id="rect173" style="fill:rgb(0,163,163);stroke:rgb(0,163,163);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2762" y="0" id="rect175" style="fill:rgb(0,168,168);stroke:rgb(0,168,168);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2766" y="0" id="rect177" style="fill:rgb(0,173,173);stroke:rgb(0,173,173);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2770" y="0" id="rect179" style="fill:rgb(0,178,178);stroke:rgb(0,178,178);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2774" y="0" id="rect181" style="fill:rgb(0,183,183);stroke:rgb(0,183,183);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2778" y="0" id="rect183" style="fill:rgb(0,188,188);stroke:rgb(0,188,188);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2782" y="0" id="rect185" style="fill:rgb(0,193,193);stroke:rgb(0,193,193);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2786" y="0" id="rect187" style="fill:rgb(0,198,198);stroke:rgb(0,198,198);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2790" y="0" id="rect189" style="fill:rgb(0,204,204);stroke:rgb(0,204,204);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2794" y="0" id="rect191" style="fill:rgb(0,209,209);stroke:rgb(0,209,209);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2798" y="0" id="rect193" style="fill:rgb(0,214,214);stroke:rgb(0,214,214);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2802" y="0" id="rect195" style="fill:rgb(0,219,219);stroke:rgb(0,219,219);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2806" y="0" id="rect197" style="fill:rgb(0,224,224);stroke:rgb(0,224,224);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2810" y="0" id="rect199" style="fill:rgb(0,229,229);stroke:rgb(0,229,229);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2814" y="0" id="rect201" style="fill:rgb(0,234,234);stroke:rgb(0,234,234);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2818" y="0" id="rect203" style="fill:rgb(0,239,239);stroke:rgb(0,239,239);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2822" y="0" id="rect205" style="fill:rgb(0,244,244);stroke:rgb(0,244,244);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2826" y="0" id="rect207" style="fill:rgb(0,249,249);stroke:rgb(0,249,249);" /> </a> <a title="value_between_lb_and_ub" xlink:href="http://value_between_lb_and_ub" target="_blank"> <rect width="4.0495" height= "48" x="2830" y="0" id="rect209" style="fill:rgb(0,255,255);stroke:rgb(0,255,255);" /> </a> """
gpl-3.0
danieljaouen/ansible
lib/ansible/modules/cloud/webfaction/webfaction_domain.py
51
4973
#!/usr/bin/python # # (c) Quentin Stafford-Fraser 2015 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # Create Webfaction domains and subdomains using Ansible and the Webfaction API from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: webfaction_domain short_description: Add or remove domains and subdomains on Webfaction description: - Add or remove domains or subdomains on a Webfaction host. Further documentation at https://github.com/quentinsf/ansible-webfaction. author: Quentin Stafford-Fraser (@quentinsf) version_added: "2.0" notes: - If you are I(deleting) domains by using C(state=absent), then note that if you specify subdomains, just those particular subdomains will be deleted. If you don't specify subdomains, the domain will be deleted. - > You can run playbooks that use this on a local machine, or on a Webfaction host, or elsewhere, since the scripts use the remote webfaction API. The location is not important. However, running them on multiple hosts I(simultaneously) is best avoided. If you don't specify I(localhost) as your host, you may want to add C(serial: 1) to the plays. - See `the webfaction API <https://docs.webfaction.com/xmlrpc-api/>`_ for more info. options: name: description: - The name of the domain required: true state: description: - Whether the domain should exist choices: ['present', 'absent'] default: "present" subdomains: description: - Any subdomains to create. default: [] login_name: description: - The webfaction account to use required: true login_password: description: - The webfaction password to use required: true ''' EXAMPLES = ''' - name: Create a test domain webfaction_domain: name: mydomain.com state: present subdomains: - www - blog login_name: "{{webfaction_user}}" login_password: "{{webfaction_passwd}}" - name: Delete test domain and any subdomains webfaction_domain: name: mydomain.com state: absent login_name: "{{webfaction_user}}" login_password: "{{webfaction_passwd}}" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves import xmlrpc_client webfaction = xmlrpc_client.ServerProxy('https://api.webfaction.com/') def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True), state=dict(required=False, choices=['present', 'absent'], default='present'), subdomains=dict(required=False, default=[], type='list'), login_name=dict(required=True), login_password=dict(required=True, no_log=True), ), supports_check_mode=True ) domain_name = module.params['name'] domain_state = module.params['state'] domain_subdomains = module.params['subdomains'] session_id, account = webfaction.login( module.params['login_name'], module.params['login_password'] ) domain_list = webfaction.list_domains(session_id) domain_map = dict([(i['domain'], i) for i in domain_list]) existing_domain = domain_map.get(domain_name) result = {} # Here's where the real stuff happens if domain_state == 'present': # Does an app with this name already exist? if existing_domain: if set(existing_domain['subdomains']) >= set(domain_subdomains): # If it exists with the right subdomains, we don't change anything. module.exit_json( changed=False, ) positional_args = [session_id, domain_name] + domain_subdomains if not module.check_mode: # If this isn't a dry run, create the app # print positional_args result.update( webfaction.create_domain( *positional_args ) ) elif domain_state == 'absent': # If the app's already not there, nothing changed. if not existing_domain: module.exit_json( changed=False, ) positional_args = [session_id, domain_name] + domain_subdomains if not module.check_mode: # If this isn't a dry run, delete the app result.update( webfaction.delete_domain(*positional_args) ) else: module.fail_json(msg="Unknown state specified: {}".format(domain_state)) module.exit_json( changed=True, result=result ) if __name__ == '__main__': main()
gpl-3.0
GitHublong/hue
desktop/core/ext-py/boto-2.38.0/boto/cloudhsm/layer1.py
135
16187
# Copyright (c) 2015 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. # import boto from boto.compat import json from boto.connection import AWSQueryConnection from boto.regioninfo import RegionInfo from boto.exception import JSONResponseError from boto.cloudhsm import exceptions class CloudHSMConnection(AWSQueryConnection): """ AWS CloudHSM Service """ APIVersion = "2014-05-30" DefaultRegionName = "us-east-1" DefaultRegionEndpoint = "cloudhsm.us-east-1.amazonaws.com" ServiceName = "CloudHSM" TargetPrefix = "CloudHsmFrontendService" ResponseError = JSONResponseError _faults = { "InvalidRequestException": exceptions.InvalidRequestException, "CloudHsmServiceException": exceptions.CloudHsmServiceException, "CloudHsmInternalException": exceptions.CloudHsmInternalException, } def __init__(self, **kwargs): region = kwargs.pop('region', None) if not region: region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) if 'host' not in kwargs or kwargs['host'] is None: kwargs['host'] = region.endpoint super(CloudHSMConnection, self).__init__(**kwargs) self.region = region def _required_auth_capability(self): return ['hmac-v4'] def create_hapg(self, label): """ Creates a high-availability partition group. A high- availability partition group is a group of partitions that spans multiple physical HSMs. :type label: string :param label: The label of the new high-availability partition group. """ params = {'Label': label, } return self.make_request(action='CreateHapg', body=json.dumps(params)) def create_hsm(self, subnet_id, ssh_key, iam_role_arn, subscription_type, eni_ip=None, external_id=None, client_token=None, syslog_ip=None): """ Creates an uninitialized HSM instance. Running this command provisions an HSM appliance and will result in charges to your AWS account for the HSM. :type subnet_id: string :param subnet_id: The identifier of the subnet in your VPC in which to place the HSM. :type ssh_key: string :param ssh_key: The SSH public key to install on the HSM. :type eni_ip: string :param eni_ip: The IP address to assign to the HSM's ENI. :type iam_role_arn: string :param iam_role_arn: The ARN of an IAM role to enable the AWS CloudHSM service to allocate an ENI on your behalf. :type external_id: string :param external_id: The external ID from **IamRoleArn**, if present. :type subscription_type: string :param subscription_type: The subscription type. :type client_token: string :param client_token: A user-defined token to ensure idempotence. Subsequent calls to this action with the same token will be ignored. :type syslog_ip: string :param syslog_ip: The IP address for the syslog monitoring server. """ params = { 'SubnetId': subnet_id, 'SshKey': ssh_key, 'IamRoleArn': iam_role_arn, 'SubscriptionType': subscription_type, } if eni_ip is not None: params['EniIp'] = eni_ip if external_id is not None: params['ExternalId'] = external_id if client_token is not None: params['ClientToken'] = client_token if syslog_ip is not None: params['SyslogIp'] = syslog_ip return self.make_request(action='CreateHsm', body=json.dumps(params)) def create_luna_client(self, certificate, label=None): """ Creates an HSM client. :type label: string :param label: The label for the client. :type certificate: string :param certificate: The contents of a Base64-Encoded X.509 v3 certificate to be installed on the HSMs used by this client. """ params = {'Certificate': certificate, } if label is not None: params['Label'] = label return self.make_request(action='CreateLunaClient', body=json.dumps(params)) def delete_hapg(self, hapg_arn): """ Deletes a high-availability partition group. :type hapg_arn: string :param hapg_arn: The ARN of the high-availability partition group to delete. """ params = {'HapgArn': hapg_arn, } return self.make_request(action='DeleteHapg', body=json.dumps(params)) def delete_hsm(self, hsm_arn): """ Deletes an HSM. Once complete, this operation cannot be undone and your key material cannot be recovered. :type hsm_arn: string :param hsm_arn: The ARN of the HSM to delete. """ params = {'HsmArn': hsm_arn, } return self.make_request(action='DeleteHsm', body=json.dumps(params)) def delete_luna_client(self, client_arn): """ Deletes a client. :type client_arn: string :param client_arn: The ARN of the client to delete. """ params = {'ClientArn': client_arn, } return self.make_request(action='DeleteLunaClient', body=json.dumps(params)) def describe_hapg(self, hapg_arn): """ Retrieves information about a high-availability partition group. :type hapg_arn: string :param hapg_arn: The ARN of the high-availability partition group to describe. """ params = {'HapgArn': hapg_arn, } return self.make_request(action='DescribeHapg', body=json.dumps(params)) def describe_hsm(self, hsm_arn=None, hsm_serial_number=None): """ Retrieves information about an HSM. You can identify the HSM by its ARN or its serial number. :type hsm_arn: string :param hsm_arn: The ARN of the HSM. Either the HsmArn or the SerialNumber parameter must be specified. :type hsm_serial_number: string :param hsm_serial_number: The serial number of the HSM. Either the HsmArn or the HsmSerialNumber parameter must be specified. """ params = {} if hsm_arn is not None: params['HsmArn'] = hsm_arn if hsm_serial_number is not None: params['HsmSerialNumber'] = hsm_serial_number return self.make_request(action='DescribeHsm', body=json.dumps(params)) def describe_luna_client(self, client_arn=None, certificate_fingerprint=None): """ Retrieves information about an HSM client. :type client_arn: string :param client_arn: The ARN of the client. :type certificate_fingerprint: string :param certificate_fingerprint: The certificate fingerprint. """ params = {} if client_arn is not None: params['ClientArn'] = client_arn if certificate_fingerprint is not None: params['CertificateFingerprint'] = certificate_fingerprint return self.make_request(action='DescribeLunaClient', body=json.dumps(params)) def get_config(self, client_arn, client_version, hapg_list): """ Gets the configuration files necessary to connect to all high availability partition groups the client is associated with. :type client_arn: string :param client_arn: The ARN of the client. :type client_version: string :param client_version: The client version. :type hapg_list: list :param hapg_list: A list of ARNs that identify the high-availability partition groups that are associated with the client. """ params = { 'ClientArn': client_arn, 'ClientVersion': client_version, 'HapgList': hapg_list, } return self.make_request(action='GetConfig', body=json.dumps(params)) def list_available_zones(self): """ Lists the Availability Zones that have available AWS CloudHSM capacity. """ params = {} return self.make_request(action='ListAvailableZones', body=json.dumps(params)) def list_hapgs(self, next_token=None): """ Lists the high-availability partition groups for the account. This operation supports pagination with the use of the NextToken member. If more results are available, the NextToken member of the response contains a token that you pass in the next call to ListHapgs to retrieve the next set of items. :type next_token: string :param next_token: The NextToken value from a previous call to ListHapgs. Pass null if this is the first call. """ params = {} if next_token is not None: params['NextToken'] = next_token return self.make_request(action='ListHapgs', body=json.dumps(params)) def list_hsms(self, next_token=None): """ Retrieves the identifiers of all of the HSMs provisioned for the current customer. This operation supports pagination with the use of the NextToken member. If more results are available, the NextToken member of the response contains a token that you pass in the next call to ListHsms to retrieve the next set of items. :type next_token: string :param next_token: The NextToken value from a previous call to ListHsms. Pass null if this is the first call. """ params = {} if next_token is not None: params['NextToken'] = next_token return self.make_request(action='ListHsms', body=json.dumps(params)) def list_luna_clients(self, next_token=None): """ Lists all of the clients. This operation supports pagination with the use of the NextToken member. If more results are available, the NextToken member of the response contains a token that you pass in the next call to ListLunaClients to retrieve the next set of items. :type next_token: string :param next_token: The NextToken value from a previous call to ListLunaClients. Pass null if this is the first call. """ params = {} if next_token is not None: params['NextToken'] = next_token return self.make_request(action='ListLunaClients', body=json.dumps(params)) def modify_hapg(self, hapg_arn, label=None, partition_serial_list=None): """ Modifies an existing high-availability partition group. :type hapg_arn: string :param hapg_arn: The ARN of the high-availability partition group to modify. :type label: string :param label: The new label for the high-availability partition group. :type partition_serial_list: list :param partition_serial_list: The list of partition serial numbers to make members of the high-availability partition group. """ params = {'HapgArn': hapg_arn, } if label is not None: params['Label'] = label if partition_serial_list is not None: params['PartitionSerialList'] = partition_serial_list return self.make_request(action='ModifyHapg', body=json.dumps(params)) def modify_hsm(self, hsm_arn, subnet_id=None, eni_ip=None, iam_role_arn=None, external_id=None, syslog_ip=None): """ Modifies an HSM. :type hsm_arn: string :param hsm_arn: The ARN of the HSM to modify. :type subnet_id: string :param subnet_id: The new identifier of the subnet that the HSM is in. :type eni_ip: string :param eni_ip: The new IP address for the elastic network interface attached to the HSM. :type iam_role_arn: string :param iam_role_arn: The new IAM role ARN. :type external_id: string :param external_id: The new external ID. :type syslog_ip: string :param syslog_ip: The new IP address for the syslog monitoring server. """ params = {'HsmArn': hsm_arn, } if subnet_id is not None: params['SubnetId'] = subnet_id if eni_ip is not None: params['EniIp'] = eni_ip if iam_role_arn is not None: params['IamRoleArn'] = iam_role_arn if external_id is not None: params['ExternalId'] = external_id if syslog_ip is not None: params['SyslogIp'] = syslog_ip return self.make_request(action='ModifyHsm', body=json.dumps(params)) def modify_luna_client(self, client_arn, certificate): """ Modifies the certificate used by the client. This action can potentially start a workflow to install the new certificate on the client's HSMs. :type client_arn: string :param client_arn: The ARN of the client. :type certificate: string :param certificate: The new certificate for the client. """ params = { 'ClientArn': client_arn, 'Certificate': certificate, } return self.make_request(action='ModifyLunaClient', body=json.dumps(params)) def make_request(self, action, body): headers = { 'X-Amz-Target': '%s.%s' % (self.TargetPrefix, action), 'Host': self.region.endpoint, 'Content-Type': 'application/x-amz-json-1.1', 'Content-Length': str(len(body)), } http_request = self.build_base_http_request( method='POST', path='/', auth_path='/', params={}, headers=headers, data=body) response = self._mexe(http_request, sender=None, override_num_retries=10) response_body = response.read().decode('utf-8') boto.log.debug(response_body) if response.status == 200: if response_body: return json.loads(response_body) else: json_body = json.loads(response_body) fault_name = json_body.get('__type', None) exception_class = self._faults.get(fault_name, self.ResponseError) raise exception_class(response.status, response.reason, body=json_body)
apache-2.0
hunter-87/binocular-dense-stereo
PCV/tools/rof.py
9
1855
from numpy import * def denoise(im,U_init,tolerance=0.1,tau=0.125,tv_weight=100): """ An implementation of the Rudin-Osher-Fatemi (ROF) denoising model using the numerical procedure presented in Eq. (11) of A. Chambolle (2005). Implemented using periodic boundary conditions. Input: noisy input image (grayscale), initial guess for U, weight of the TV-regularizing term, steplength, tolerance for the stop criterion Output: denoised and detextured image, texture residual. """ m,n = im.shape #size of noisy image # initialize U = U_init Px = zeros((m, n)) #x-component to the dual field Py = zeros((m, n)) #y-component of the dual field error = 1 while (error > tolerance): Uold = U # gradient of primal variable GradUx = roll(U,-1,axis=1)-U # x-component of U's gradient GradUy = roll(U,-1,axis=0)-U # y-component of U's gradient # update the dual varible PxNew = Px + (tau/tv_weight)*GradUx # non-normalized update of x-component (dual) PyNew = Py + (tau/tv_weight)*GradUy # non-normalized update of y-component (dual) NormNew = maximum(1,sqrt(PxNew**2+PyNew**2)) Px = PxNew/NormNew # update of x-component (dual) Py = PyNew/NormNew # update of y-component (dual) # update the primal variable RxPx = roll(Px,1,axis=1) # right x-translation of x-component RyPy = roll(Py,1,axis=0) # right y-translation of y-component DivP = (Px-RxPx)+(Py-RyPy) # divergence of the dual field. U = im + tv_weight*DivP # update of the primal variable # update of error error = linalg.norm(U-Uold)/sqrt(n*m); return U,im-U # denoised image and texture residual
gpl-2.0
osvalr/odoo
openerp/workflow/workitem.py
294
14389
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2014 OpenERP S.A. (<http://openerp.com). # # 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/>. # ############################################################################## # # TODO: # cr.execute('delete from wkf_triggers where model=%s and res_id=%s', (res_type,res_id)) # import logging import instance from openerp.workflow.helpers import Session from openerp.workflow.helpers import Record from openerp.workflow.helpers import WorkflowActivity logger = logging.getLogger(__name__) import openerp from openerp.tools.safe_eval import safe_eval as eval class Environment(dict): """ Dictionary class used as an environment to evaluate workflow code (such as the condition on transitions). This environment provides sybmols for cr, uid, id, model name, model instance, column names, and all the record (the one obtained by browsing the provided ID) attributes. """ def __init__(self, session, record): self.cr = session.cr self.uid = session.uid self.model = record.model self.id = record.id self.ids = [record.id] self.obj = openerp.registry(self.cr.dbname)[self.model] def __getitem__(self, key): records = self.obj.browse(self.cr, self.uid, self.ids) if hasattr(records, key): return getattr(records, key) else: return super(Environment, self).__getitem__(key) class WorkflowItem(object): def __init__(self, session, record, work_item_values): assert isinstance(session, Session) assert isinstance(record, Record) self.session = session self.record = record if not work_item_values: work_item_values = {} assert isinstance(work_item_values, dict) self.workitem = work_item_values @classmethod def create(cls, session, record, activity, instance_id, stack): assert isinstance(session, Session) assert isinstance(record, Record) assert isinstance(activity, dict) assert isinstance(instance_id, (long, int)) assert isinstance(stack, list) cr = session.cr cr.execute("select nextval('wkf_workitem_id_seq')") id_new = cr.fetchone()[0] cr.execute("insert into wkf_workitem (id,act_id,inst_id,state) values (%s,%s,%s,'active')", (id_new, activity['id'], instance_id)) cr.execute('select * from wkf_workitem where id=%s',(id_new,)) work_item_values = cr.dictfetchone() logger.info('Created workflow item in activity %s', activity['id'], extra={'ident': (session.uid, record.model, record.id)}) workflow_item = WorkflowItem(session, record, work_item_values) workflow_item.process(stack=stack) @classmethod def create_all(cls, session, record, activities, instance_id, stack): assert isinstance(activities, list) for activity in activities: cls.create(session, record, activity, instance_id, stack) def process(self, signal=None, force_running=False, stack=None): assert isinstance(force_running, bool) assert stack is not None cr = self.session.cr cr.execute('select * from wkf_activity where id=%s', (self.workitem['act_id'],)) activity = cr.dictfetchone() triggers = False if self.workitem['state'] == 'active': triggers = True if not self._execute(activity, stack): return False if force_running or self.workitem['state'] == 'complete': ok = self._split_test(activity['split_mode'], signal, stack) triggers = triggers and not ok if triggers: cr.execute('select * from wkf_transition where act_from=%s ORDER BY sequence,id', (self.workitem['act_id'],)) for trans in cr.dictfetchall(): if trans['trigger_model']: ids = self.wkf_expr_eval_expr(trans['trigger_expr_id']) for res_id in ids: cr.execute('select nextval(\'wkf_triggers_id_seq\')') id =cr.fetchone()[0] cr.execute('insert into wkf_triggers (model,res_id,instance_id,workitem_id,id) values (%s,%s,%s,%s,%s)', (trans['trigger_model'],res_id, self.workitem['inst_id'], self.workitem['id'], id)) return True def _execute(self, activity, stack): """Send a signal to parenrt workflow (signal: subflow.signal_name)""" result = True cr = self.session.cr signal_todo = [] if (self.workitem['state']=='active') and activity['signal_send']: # signal_send']: cr.execute("select i.id,w.osv,i.res_id from wkf_instance i left join wkf w on (i.wkf_id=w.id) where i.id IN (select inst_id from wkf_workitem where subflow_id=%s)", (self.workitem['inst_id'],)) for instance_id, model_name, record_id in cr.fetchall(): record = Record(model_name, record_id) signal_todo.append((instance_id, record, activity['signal_send'])) if activity['kind'] == WorkflowActivity.KIND_DUMMY: if self.workitem['state']=='active': self._state_set(activity, 'complete') if activity['action_id']: res2 = self.wkf_expr_execute_action(activity) if res2: stack.append(res2) result=res2 elif activity['kind'] == WorkflowActivity.KIND_FUNCTION: if self.workitem['state']=='active': self._state_set(activity, 'running') returned_action = self.wkf_expr_execute(activity) if type(returned_action) in (dict,): stack.append(returned_action) if activity['action_id']: res2 = self.wkf_expr_execute_action(activity) # A client action has been returned if res2: stack.append(res2) result=res2 self._state_set(activity, 'complete') elif activity['kind'] == WorkflowActivity.KIND_STOPALL: if self.workitem['state']=='active': self._state_set(activity, 'running') cr.execute('delete from wkf_workitem where inst_id=%s and id<>%s', (self.workitem['inst_id'], self.workitem['id'])) if activity['action']: self.wkf_expr_execute(activity) self._state_set(activity, 'complete') elif activity['kind'] == WorkflowActivity.KIND_SUBFLOW: if self.workitem['state']=='active': self._state_set(activity, 'running') if activity.get('action', False): id_new = self.wkf_expr_execute(activity) if not id_new: cr.execute('delete from wkf_workitem where id=%s', (self.workitem['id'],)) return False assert type(id_new)==type(1) or type(id_new)==type(1L), 'Wrong return value: '+str(id_new)+' '+str(type(id_new)) cr.execute('select id from wkf_instance where res_id=%s and wkf_id=%s', (id_new, activity['subflow_id'])) id_new = cr.fetchone()[0] else: inst = instance.WorkflowInstance(self.session, self.record) id_new = inst.create(activity['subflow_id']) cr.execute('update wkf_workitem set subflow_id=%s where id=%s', (id_new, self.workitem['id'])) self.workitem['subflow_id'] = id_new if self.workitem['state']=='running': cr.execute("select state from wkf_instance where id=%s", (self.workitem['subflow_id'],)) state = cr.fetchone()[0] if state=='complete': self._state_set(activity, 'complete') for instance_id, record, signal_send in signal_todo: wi = instance.WorkflowInstance(self.session, record, {'id': instance_id}) wi.validate(signal_send, force_running=True) return result def _state_set(self, activity, state): self.session.cr.execute('update wkf_workitem set state=%s where id=%s', (state, self.workitem['id'])) self.workitem['state'] = state logger.info('Changed state of work item %s to "%s" in activity %s', self.workitem['id'], state, activity['id'], extra={'ident': (self.session.uid, self.record.model, self.record.id)}) def _split_test(self, split_mode, signal, stack): cr = self.session.cr cr.execute('select * from wkf_transition where act_from=%s ORDER BY sequence,id', (self.workitem['act_id'],)) test = False transitions = [] alltrans = cr.dictfetchall() if split_mode in ('XOR', 'OR'): for transition in alltrans: if self.wkf_expr_check(transition,signal): test = True transitions.append((transition['id'], self.workitem['inst_id'])) if split_mode=='XOR': break else: test = True for transition in alltrans: if not self.wkf_expr_check(transition, signal): test = False break cr.execute('select count(*) from wkf_witm_trans where trans_id=%s and inst_id=%s', (transition['id'], self.workitem['inst_id'])) if not cr.fetchone()[0]: transitions.append((transition['id'], self.workitem['inst_id'])) if test and transitions: cr.executemany('insert into wkf_witm_trans (trans_id,inst_id) values (%s,%s)', transitions) cr.execute('delete from wkf_workitem where id=%s', (self.workitem['id'],)) for t in transitions: self._join_test(t[0], t[1], stack) return True return False def _join_test(self, trans_id, inst_id, stack): cr = self.session.cr cr.execute('select * from wkf_activity where id=(select act_to from wkf_transition where id=%s)', (trans_id,)) activity = cr.dictfetchone() if activity['join_mode']=='XOR': WorkflowItem.create(self.session, self.record, activity, inst_id, stack=stack) cr.execute('delete from wkf_witm_trans where inst_id=%s and trans_id=%s', (inst_id,trans_id)) else: cr.execute('select id from wkf_transition where act_to=%s ORDER BY sequence,id', (activity['id'],)) trans_ids = cr.fetchall() ok = True for (id,) in trans_ids: cr.execute('select count(*) from wkf_witm_trans where trans_id=%s and inst_id=%s', (id,inst_id)) res = cr.fetchone()[0] if not res: ok = False break if ok: for (id,) in trans_ids: cr.execute('delete from wkf_witm_trans where trans_id=%s and inst_id=%s', (id,inst_id)) WorkflowItem.create(self.session, self.record, activity, inst_id, stack=stack) def wkf_expr_eval_expr(self, lines): """ Evaluate each line of ``lines`` with the ``Environment`` environment, returning the value of the last line. """ assert lines, 'You used a NULL action in a workflow, use dummy node instead.' result = False for line in lines.split('\n'): line = line.strip() if not line: continue if line == 'True': result = True elif line == 'False': result = False else: env = Environment(self.session, self.record) result = eval(line, env, nocopy=True) return result def wkf_expr_execute_action(self, activity): """ Evaluate the ir.actions.server action specified in the activity. """ context = { 'active_model': self.record.model, 'active_id': self.record.id, 'active_ids': [self.record.id] } ir_actions_server = openerp.registry(self.session.cr.dbname)['ir.actions.server'] result = ir_actions_server.run(self.session.cr, self.session.uid, [activity['action_id']], context) return result def wkf_expr_execute(self, activity): """ Evaluate the action specified in the activity. """ return self.wkf_expr_eval_expr(activity['action']) def wkf_expr_check(self, transition, signal): """ Test if a transition can be taken. The transition can be taken if: - the signal name matches, - the uid is SUPERUSER_ID or the user groups contains the transition's group, - the condition evaluates to a truish value. """ if transition['signal'] and signal != transition['signal']: return False if self.session.uid != openerp.SUPERUSER_ID and transition['group_id']: registry = openerp.registry(self.session.cr.dbname) user_groups = registry['res.users'].read(self.session.cr, self.session.uid, [self.session.uid], ['groups_id'])[0]['groups_id'] if transition['group_id'] not in user_groups: return False return self.wkf_expr_eval_expr(transition['condition']) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
arnaud-morvan/QGIS
python/plugins/processing/algs/grass7/ext/r_colors.py
8
3608
# -*- coding: utf-8 -*- """ *************************************************************************** r_colors.py ----------- Date : February 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr *************************************************************************** * * * 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 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Médéric Ribreux' __date__ = 'February 2016' __copyright__ = '(C) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from processing.algs.grass7.Grass7Utils import Grass7Utils from processing.tools.system import getTempFilename def checkParameterValuesBeforeExecuting(alg, parameters, context): """ Verify if we have the right parameters """ txtRules = alg.parameterAsString(parameters, 'rules_txt', context) rules = alg.parameterAsString(parameters, 'rules', context) if txtRules and rules: return False, alg.tr("You need to set either inline rules or a rules file!") return True, None def processInputs(alg, parameters, context, feedback): # import all rasters with their color tables (and their bands) # We need to import all the bands and color tables of the input rasters rasters = alg.parameterAsLayerList(parameters, 'map', context) for idx, layer in enumerate(rasters): layerName = 'map_{}'.format(idx) # Add a raster layer alg.loadRasterLayer(layerName, layer, False, None) # Optional raster layer to copy from raster = alg.parameterAsString(parameters, 'raster', context) if raster: alg.loadRasterLayerFromParameter('raster', parameters, context, False, None) alg.postInputs() def processCommand(alg, parameters, context, feedback): # Handle inline rules txtRules = alg.parameterAsString(parameters, 'txtrules', context) if txtRules: # Creates a temporary txt file tempRulesName = getTempFilename() # Inject rules into temporary txt file with open(tempRulesName, "w") as tempRules: tempRules.write(txtRules) alg.removeParameter('txtrules') parameters['rules'] = tempRulesName alg.processCommand(parameters, context, feedback, True) def processOutputs(alg, parameters, context, feedback): createOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_OPT, context) metaOpt = alg.parameterAsString(parameters, alg.GRASS_RASTER_FORMAT_META, context) # Export all rasters with their color tables (and their bands) rasters = alg.parameterAsLayerList(parameters, 'map', context) outputDir = alg.parameterAsString(parameters, 'output_dir', context) for idx, raster in enumerate(rasters): rasterName = 'map_{}'.format(idx) fileName = os.path.join(outputDir, rasterName) outFormat = Grass7Utils.getRasterFormatFromFilename(fileName) alg.exportRasterLayer(alg.exportedLayers[rasterName], fileName, True, outFormat, createOpt, metaOpt)
gpl-2.0
shaananc/security-proj2
bindings/python/apidefs/gcc-LP64/ns3_module_wifi.py
4
385222
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers def register_types(module): root_module = module.get_root() ## wifi-mac-header.h: ns3::WifiMacType [enumeration] module.add_enum('WifiMacType', ['WIFI_MAC_CTL_RTS', 'WIFI_MAC_CTL_CTS', 'WIFI_MAC_CTL_ACK', 'WIFI_MAC_CTL_BACKREQ', 'WIFI_MAC_CTL_BACKRESP', 'WIFI_MAC_MGT_BEACON', 'WIFI_MAC_MGT_ASSOCIATION_REQUEST', 'WIFI_MAC_MGT_ASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_DISASSOCIATION', 'WIFI_MAC_MGT_REASSOCIATION_REQUEST', 'WIFI_MAC_MGT_REASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_PROBE_REQUEST', 'WIFI_MAC_MGT_PROBE_RESPONSE', 'WIFI_MAC_MGT_AUTHENTICATION', 'WIFI_MAC_MGT_DEAUTHENTICATION', 'WIFI_MAC_MGT_ACTION', 'WIFI_MAC_MGT_ACTION_NO_ACK', 'WIFI_MAC_MGT_MULTIHOP_ACTION', 'WIFI_MAC_DATA', 'WIFI_MAC_DATA_CFACK', 'WIFI_MAC_DATA_CFPOLL', 'WIFI_MAC_DATA_CFACK_CFPOLL', 'WIFI_MAC_DATA_NULL', 'WIFI_MAC_DATA_NULL_CFACK', 'WIFI_MAC_DATA_NULL_CFPOLL', 'WIFI_MAC_DATA_NULL_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA', 'WIFI_MAC_QOSDATA_CFACK', 'WIFI_MAC_QOSDATA_CFPOLL', 'WIFI_MAC_QOSDATA_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA_NULL', 'WIFI_MAC_QOSDATA_NULL_CFPOLL', 'WIFI_MAC_QOSDATA_NULL_CFACK_CFPOLL']) ## wifi-preamble.h: ns3::WifiPreamble [enumeration] module.add_enum('WifiPreamble', ['WIFI_PREAMBLE_LONG', 'WIFI_PREAMBLE_SHORT']) ## wifi-mode.h: ns3::WifiModulationClass [enumeration] module.add_enum('WifiModulationClass', ['WIFI_MOD_CLASS_UNKNOWN', 'WIFI_MOD_CLASS_IR', 'WIFI_MOD_CLASS_FHSS', 'WIFI_MOD_CLASS_DSSS', 'WIFI_MOD_CLASS_ERP_PBCC', 'WIFI_MOD_CLASS_DSSS_OFDM', 'WIFI_MOD_CLASS_ERP_OFDM', 'WIFI_MOD_CLASS_OFDM', 'WIFI_MOD_CLASS_HT']) ## wifi-phy-standard.h: ns3::WifiPhyStandard [enumeration] module.add_enum('WifiPhyStandard', ['WIFI_PHY_STANDARD_80211a', 'WIFI_PHY_STANDARD_80211b', 'WIFI_PHY_STANDARD_80211_10Mhz', 'WIFI_PHY_STANDARD_80211_5Mhz', 'WIFI_PHY_STANDARD_holland', 'WIFI_PHY_STANDARD_80211p_CCH', 'WIFI_PHY_STANDARD_80211p_SCH', 'WIFI_PHY_UNKNOWN']) ## qos-utils.h: ns3::AcIndex [enumeration] module.add_enum('AcIndex', ['AC_BE', 'AC_BK', 'AC_VI', 'AC_VO', 'AC_BE_NQOS', 'AC_UNDEF']) ## ctrl-headers.h: ns3::BlockAckType [enumeration] module.add_enum('BlockAckType', ['BASIC_BLOCK_ACK', 'COMPRESSED_BLOCK_ACK', 'MULTI_TID_BLOCK_ACK']) ## qos-tag.h: ns3::UserPriority [enumeration] module.add_enum('UserPriority', ['UP_BK', 'UP_BE', 'UP_EE', 'UP_CL', 'UP_VI', 'UP_VO', 'UP_NC']) ## wifi-mode.h: ns3::WifiCodeRate [enumeration] module.add_enum('WifiCodeRate', ['WIFI_CODE_RATE_UNDEFINED', 'WIFI_CODE_RATE_3_4', 'WIFI_CODE_RATE_2_3', 'WIFI_CODE_RATE_1_2']) ## edca-txop-n.h: ns3::TypeOfStation [enumeration] module.add_enum('TypeOfStation', ['STA', 'AP', 'ADHOC_STA']) ## block-ack-manager.h: ns3::Bar [struct] module.add_class('Bar') ## block-ack-agreement.h: ns3::BlockAckAgreement [class] module.add_class('BlockAckAgreement') ## block-ack-manager.h: ns3::BlockAckManager [class] module.add_class('BlockAckManager') ## capability-information.h: ns3::CapabilityInformation [class] module.add_class('CapabilityInformation') ## dcf-manager.h: ns3::DcfManager [class] module.add_class('DcfManager') ## dcf-manager.h: ns3::DcfState [class] module.add_class('DcfState', allow_subclassing=True) ## dsss-error-rate-model.h: ns3::DsssErrorRateModel [class] module.add_class('DsssErrorRateModel') ## interference-helper.h: ns3::InterferenceHelper [class] module.add_class('InterferenceHelper') ## interference-helper.h: ns3::InterferenceHelper::SnrPer [struct] module.add_class('SnrPer', outer_class=root_module['ns3::InterferenceHelper']) ## mac-low.h: ns3::MacLowBlockAckEventListener [class] module.add_class('MacLowBlockAckEventListener', allow_subclassing=True) ## mac-low.h: ns3::MacLowDcfListener [class] module.add_class('MacLowDcfListener', allow_subclassing=True) ## mac-low.h: ns3::MacLowTransmissionListener [class] module.add_class('MacLowTransmissionListener', allow_subclassing=True) ## mac-low.h: ns3::MacLowTransmissionParameters [class] module.add_class('MacLowTransmissionParameters') ## mac-rx-middle.h: ns3::MacRxMiddle [class] module.add_class('MacRxMiddle') ## originator-block-ack-agreement.h: ns3::OriginatorBlockAckAgreement [class] module.add_class('OriginatorBlockAckAgreement', parent=root_module['ns3::BlockAckAgreement']) ## originator-block-ack-agreement.h: ns3::OriginatorBlockAckAgreement::State [enumeration] module.add_enum('State', ['PENDING', 'ESTABLISHED', 'INACTIVE', 'UNSUCCESSFUL'], outer_class=root_module['ns3::OriginatorBlockAckAgreement']) ## minstrel-wifi-manager.h: ns3::RateInfo [struct] module.add_class('RateInfo') ## status-code.h: ns3::StatusCode [class] module.add_class('StatusCode') ## wifi-mode.h: ns3::WifiMode [class] module.add_class('WifiMode') ## wifi-mode.h: ns3::WifiModeFactory [class] module.add_class('WifiModeFactory') ## wifi-phy.h: ns3::WifiPhyListener [class] module.add_class('WifiPhyListener', allow_subclassing=True) ## wifi-remote-station-manager.h: ns3::WifiRemoteStation [struct] module.add_class('WifiRemoteStation') ## wifi-remote-station-manager.h: ns3::WifiRemoteStationInfo [class] module.add_class('WifiRemoteStationInfo') ## wifi-remote-station-manager.h: ns3::WifiRemoteStationState [struct] module.add_class('WifiRemoteStationState') ## wifi-remote-station-manager.h: ns3::WifiRemoteStationState [enumeration] module.add_enum('', ['BRAND_NEW', 'DISASSOC', 'WAIT_ASSOC_TX_OK', 'GOT_ASSOC_TX_OK'], outer_class=root_module['ns3::WifiRemoteStationState']) ## mgt-headers.h: ns3::MgtAddBaRequestHeader [class] module.add_class('MgtAddBaRequestHeader', parent=root_module['ns3::Header']) ## mgt-headers.h: ns3::MgtAddBaResponseHeader [class] module.add_class('MgtAddBaResponseHeader', parent=root_module['ns3::Header']) ## mgt-headers.h: ns3::MgtAssocRequestHeader [class] module.add_class('MgtAssocRequestHeader', parent=root_module['ns3::Header']) ## mgt-headers.h: ns3::MgtAssocResponseHeader [class] module.add_class('MgtAssocResponseHeader', parent=root_module['ns3::Header']) ## mgt-headers.h: ns3::MgtDelBaHeader [class] module.add_class('MgtDelBaHeader', parent=root_module['ns3::Header']) ## mgt-headers.h: ns3::MgtProbeRequestHeader [class] module.add_class('MgtProbeRequestHeader', parent=root_module['ns3::Header']) ## mgt-headers.h: ns3::MgtProbeResponseHeader [class] module.add_class('MgtProbeResponseHeader', parent=root_module['ns3::Header']) ## qos-tag.h: ns3::QosTag [class] module.add_class('QosTag', parent=root_module['ns3::Tag']) ## simple-ref-count.h: ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::InterferenceHelper::Event', 'ns3::empty', 'ns3::DefaultDeleter<ns3::InterferenceHelper::Event>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h: ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::WifiInformationElement', 'ns3::empty', 'ns3::DefaultDeleter<ns3::WifiInformationElement>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## mgt-headers.h: ns3::WifiActionHeader [class] module.add_class('WifiActionHeader', parent=root_module['ns3::Header']) ## mgt-headers.h: ns3::WifiActionHeader::CategoryValue [enumeration] module.add_enum('CategoryValue', ['BLOCK_ACK', 'MESH_PEERING_MGT', 'MESH_LINK_METRIC', 'MESH_PATH_SELECTION', 'MESH_INTERWORKING', 'MESH_RESOURCE_COORDINATION', 'MESH_PROXY_FORWARDING'], outer_class=root_module['ns3::WifiActionHeader']) ## mgt-headers.h: ns3::WifiActionHeader::PeerLinkMgtActionValue [enumeration] module.add_enum('PeerLinkMgtActionValue', ['PEER_LINK_OPEN', 'PEER_LINK_CONFIRM', 'PEER_LINK_CLOSE'], outer_class=root_module['ns3::WifiActionHeader']) ## mgt-headers.h: ns3::WifiActionHeader::LinkMetricActionValue [enumeration] module.add_enum('LinkMetricActionValue', ['LINK_METRIC_REQUEST', 'LINK_METRIC_REPORT'], outer_class=root_module['ns3::WifiActionHeader']) ## mgt-headers.h: ns3::WifiActionHeader::PathSelectionActionValue [enumeration] module.add_enum('PathSelectionActionValue', ['PATH_SELECTION'], outer_class=root_module['ns3::WifiActionHeader']) ## mgt-headers.h: ns3::WifiActionHeader::InterworkActionValue [enumeration] module.add_enum('InterworkActionValue', ['PORTAL_ANNOUNCEMENT'], outer_class=root_module['ns3::WifiActionHeader']) ## mgt-headers.h: ns3::WifiActionHeader::ResourceCoordinationActionValue [enumeration] module.add_enum('ResourceCoordinationActionValue', ['CONGESTION_CONTROL_NOTIFICATION', 'MDA_SETUP_REQUEST', 'MDA_SETUP_REPLY', 'MDAOP_ADVERTISMENT_REQUEST', 'MDAOP_ADVERTISMENTS', 'MDAOP_SET_TEARDOWN', 'BEACON_TIMING_REQUEST', 'BEACON_TIMING_RESPONSE', 'TBTT_ADJUSTMENT_REQUEST', 'MESH_CHANNEL_SWITCH_ANNOUNCEMENT'], outer_class=root_module['ns3::WifiActionHeader']) ## mgt-headers.h: ns3::WifiActionHeader::BlockAckActionValue [enumeration] module.add_enum('BlockAckActionValue', ['BLOCK_ACK_ADDBA_REQUEST', 'BLOCK_ACK_ADDBA_RESPONSE', 'BLOCK_ACK_DELBA'], outer_class=root_module['ns3::WifiActionHeader']) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue [union] module.add_class('ActionValue', outer_class=root_module['ns3::WifiActionHeader']) ## wifi-information-element.h: ns3::WifiInformationElement [class] module.add_class('WifiInformationElement', parent=root_module['ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >']) ## wifi-information-element-vector.h: ns3::WifiInformationElementVector [class] module.add_class('WifiInformationElementVector', parent=root_module['ns3::Header']) ## wifi-mac.h: ns3::WifiMac [class] module.add_class('WifiMac', parent=root_module['ns3::Object']) ## wifi-mac-header.h: ns3::WifiMacHeader [class] module.add_class('WifiMacHeader', parent=root_module['ns3::Header']) ## wifi-mac-header.h: ns3::WifiMacHeader::QosAckPolicy [enumeration] module.add_enum('QosAckPolicy', ['NORMAL_ACK', 'NO_ACK', 'NO_EXPLICIT_ACK', 'BLOCK_ACK'], outer_class=root_module['ns3::WifiMacHeader']) ## wifi-mac-header.h: ns3::WifiMacHeader::AddressType [enumeration] module.add_enum('AddressType', ['ADDR1', 'ADDR2', 'ADDR3', 'ADDR4'], outer_class=root_module['ns3::WifiMacHeader']) ## wifi-phy.h: ns3::WifiPhy [class] module.add_class('WifiPhy', parent=root_module['ns3::Object']) ## wifi-phy.h: ns3::WifiPhy::State [enumeration] module.add_enum('State', ['IDLE', 'CCA_BUSY', 'TX', 'RX', 'SWITCHING'], outer_class=root_module['ns3::WifiPhy']) ## wifi-remote-station-manager.h: ns3::WifiRemoteStationManager [class] module.add_class('WifiRemoteStationManager', parent=root_module['ns3::Object']) ## yans-wifi-phy.h: ns3::YansWifiPhy [class] module.add_class('YansWifiPhy', parent=root_module['ns3::WifiPhy']) ## aarf-wifi-manager.h: ns3::AarfWifiManager [class] module.add_class('AarfWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## aarfcd-wifi-manager.h: ns3::AarfcdWifiManager [class] module.add_class('AarfcdWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## adhoc-wifi-mac.h: ns3::AdhocWifiMac [class] module.add_class('AdhocWifiMac', parent=root_module['ns3::WifiMac']) ## amrr-wifi-manager.h: ns3::AmrrWifiManager [class] module.add_class('AmrrWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## amsdu-subframe-header.h: ns3::AmsduSubframeHeader [class] module.add_class('AmsduSubframeHeader', parent=root_module['ns3::Header']) ## arf-wifi-manager.h: ns3::ArfWifiManager [class] module.add_class('ArfWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## cara-wifi-manager.h: ns3::CaraWifiManager [class] module.add_class('CaraWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## constant-rate-wifi-manager.h: ns3::ConstantRateWifiManager [class] module.add_class('ConstantRateWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## ctrl-headers.h: ns3::CtrlBAckRequestHeader [class] module.add_class('CtrlBAckRequestHeader', parent=root_module['ns3::Header']) ## ctrl-headers.h: ns3::CtrlBAckResponseHeader [class] module.add_class('CtrlBAckResponseHeader', parent=root_module['ns3::Header']) ## dcf.h: ns3::Dcf [class] module.add_class('Dcf', parent=root_module['ns3::Object']) ## edca-txop-n.h: ns3::EdcaTxopN [class] module.add_class('EdcaTxopN', parent=root_module['ns3::Dcf']) ## error-rate-model.h: ns3::ErrorRateModel [class] module.add_class('ErrorRateModel', parent=root_module['ns3::Object']) ## ideal-wifi-manager.h: ns3::IdealWifiManager [class] module.add_class('IdealWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## mac-low.h: ns3::MacLow [class] module.add_class('MacLow', parent=root_module['ns3::Object']) ## mgt-headers.h: ns3::MgtBeaconHeader [class] module.add_class('MgtBeaconHeader', parent=root_module['ns3::MgtProbeResponseHeader']) ## minstrel-wifi-manager.h: ns3::MinstrelWifiManager [class] module.add_class('MinstrelWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## msdu-aggregator.h: ns3::MsduAggregator [class] module.add_class('MsduAggregator', parent=root_module['ns3::Object']) ## nist-error-rate-model.h: ns3::NistErrorRateModel [class] module.add_class('NistErrorRateModel', parent=root_module['ns3::ErrorRateModel']) ## nqap-wifi-mac.h: ns3::NqapWifiMac [class] module.add_class('NqapWifiMac', parent=root_module['ns3::WifiMac']) ## nqsta-wifi-mac.h: ns3::NqstaWifiMac [class] module.add_class('NqstaWifiMac', parent=root_module['ns3::WifiMac']) ## onoe-wifi-manager.h: ns3::OnoeWifiManager [class] module.add_class('OnoeWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## qadhoc-wifi-mac.h: ns3::QadhocWifiMac [class] module.add_class('QadhocWifiMac', parent=root_module['ns3::WifiMac']) ## qap-wifi-mac.h: ns3::QapWifiMac [class] module.add_class('QapWifiMac', parent=root_module['ns3::WifiMac']) ## qsta-wifi-mac.h: ns3::QstaWifiMac [class] module.add_class('QstaWifiMac', parent=root_module['ns3::WifiMac']) ## rraa-wifi-manager.h: ns3::RraaWifiManager [class] module.add_class('RraaWifiManager', parent=root_module['ns3::WifiRemoteStationManager']) ## ssid.h: ns3::Ssid [class] module.add_class('Ssid', parent=root_module['ns3::WifiInformationElement']) ## ssid.h: ns3::SsidChecker [class] module.add_class('SsidChecker', parent=root_module['ns3::AttributeChecker']) ## ssid.h: ns3::SsidValue [class] module.add_class('SsidValue', parent=root_module['ns3::AttributeValue']) ## supported-rates.h: ns3::SupportedRates [class] module.add_class('SupportedRates', parent=root_module['ns3::WifiInformationElement']) ## wifi-channel.h: ns3::WifiChannel [class] module.add_class('WifiChannel', parent=root_module['ns3::Channel']) ## wifi-mode.h: ns3::WifiModeChecker [class] module.add_class('WifiModeChecker', parent=root_module['ns3::AttributeChecker']) ## wifi-mode.h: ns3::WifiModeValue [class] module.add_class('WifiModeValue', parent=root_module['ns3::AttributeValue']) ## wifi-net-device.h: ns3::WifiNetDevice [class] module.add_class('WifiNetDevice', parent=root_module['ns3::NetDevice']) ## yans-error-rate-model.h: ns3::YansErrorRateModel [class] module.add_class('YansErrorRateModel', parent=root_module['ns3::ErrorRateModel']) ## yans-wifi-channel.h: ns3::YansWifiChannel [class] module.add_class('YansWifiChannel', parent=root_module['ns3::WifiChannel']) ## dca-txop.h: ns3::DcaTxop [class] module.add_class('DcaTxop', parent=root_module['ns3::Dcf']) module.add_container('ns3::WifiModeList', 'ns3::WifiMode', container_type='vector') typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >', 'ns3::WifiModeListIterator') typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >*', 'ns3::WifiModeListIterator*') typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >&', 'ns3::WifiModeListIterator&') typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >', 'ns3::WifiModeList') typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >*', 'ns3::WifiModeList*') typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >&', 'ns3::WifiModeList&') typehandlers.add_type_alias('uint8_t', 'ns3::WifiInformationElementId') typehandlers.add_type_alias('uint8_t*', 'ns3::WifiInformationElementId*') typehandlers.add_type_alias('uint8_t&', 'ns3::WifiInformationElementId&') typehandlers.add_type_alias('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >', 'ns3::MinstrelRate') typehandlers.add_type_alias('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >*', 'ns3::MinstrelRate*') typehandlers.add_type_alias('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >&', 'ns3::MinstrelRate&') typehandlers.add_type_alias('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >', 'ns3::SampleRate') typehandlers.add_type_alias('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >*', 'ns3::SampleRate*') typehandlers.add_type_alias('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >&', 'ns3::SampleRate&') ## Register a nested module for the namespace Config nested_module = module.add_cpp_namespace('Config') register_types_ns3_Config(nested_module) ## 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 addressUtils nested_module = module.add_cpp_namespace('addressUtils') register_types_ns3_addressUtils(nested_module) ## Register a nested module for the namespace aodv nested_module = module.add_cpp_namespace('aodv') register_types_ns3_aodv(nested_module) ## Register a nested module for the namespace dot11s nested_module = module.add_cpp_namespace('dot11s') register_types_ns3_dot11s(nested_module) ## Register a nested module for the namespace flame nested_module = module.add_cpp_namespace('flame') register_types_ns3_flame(nested_module) ## Register a nested module for the namespace internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) ## Register a nested module for the namespace olsr nested_module = module.add_cpp_namespace('olsr') register_types_ns3_olsr(nested_module) def register_types_ns3_Config(module): root_module = module.get_root() def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_addressUtils(module): root_module = module.get_root() def register_types_ns3_aodv(module): root_module = module.get_root() def register_types_ns3_dot11s(module): root_module = module.get_root() def register_types_ns3_flame(module): root_module = module.get_root() def register_types_ns3_internal(module): root_module = module.get_root() def register_types_ns3_olsr(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Bar_methods(root_module, root_module['ns3::Bar']) register_Ns3BlockAckAgreement_methods(root_module, root_module['ns3::BlockAckAgreement']) register_Ns3BlockAckManager_methods(root_module, root_module['ns3::BlockAckManager']) register_Ns3CapabilityInformation_methods(root_module, root_module['ns3::CapabilityInformation']) register_Ns3DcfManager_methods(root_module, root_module['ns3::DcfManager']) register_Ns3DcfState_methods(root_module, root_module['ns3::DcfState']) register_Ns3DsssErrorRateModel_methods(root_module, root_module['ns3::DsssErrorRateModel']) register_Ns3InterferenceHelper_methods(root_module, root_module['ns3::InterferenceHelper']) register_Ns3InterferenceHelperSnrPer_methods(root_module, root_module['ns3::InterferenceHelper::SnrPer']) register_Ns3MacLowBlockAckEventListener_methods(root_module, root_module['ns3::MacLowBlockAckEventListener']) register_Ns3MacLowDcfListener_methods(root_module, root_module['ns3::MacLowDcfListener']) register_Ns3MacLowTransmissionListener_methods(root_module, root_module['ns3::MacLowTransmissionListener']) register_Ns3MacLowTransmissionParameters_methods(root_module, root_module['ns3::MacLowTransmissionParameters']) register_Ns3MacRxMiddle_methods(root_module, root_module['ns3::MacRxMiddle']) register_Ns3OriginatorBlockAckAgreement_methods(root_module, root_module['ns3::OriginatorBlockAckAgreement']) register_Ns3RateInfo_methods(root_module, root_module['ns3::RateInfo']) register_Ns3StatusCode_methods(root_module, root_module['ns3::StatusCode']) register_Ns3WifiMode_methods(root_module, root_module['ns3::WifiMode']) register_Ns3WifiModeFactory_methods(root_module, root_module['ns3::WifiModeFactory']) register_Ns3WifiPhyListener_methods(root_module, root_module['ns3::WifiPhyListener']) register_Ns3WifiRemoteStation_methods(root_module, root_module['ns3::WifiRemoteStation']) register_Ns3WifiRemoteStationInfo_methods(root_module, root_module['ns3::WifiRemoteStationInfo']) register_Ns3WifiRemoteStationState_methods(root_module, root_module['ns3::WifiRemoteStationState']) register_Ns3MgtAddBaRequestHeader_methods(root_module, root_module['ns3::MgtAddBaRequestHeader']) register_Ns3MgtAddBaResponseHeader_methods(root_module, root_module['ns3::MgtAddBaResponseHeader']) register_Ns3MgtAssocRequestHeader_methods(root_module, root_module['ns3::MgtAssocRequestHeader']) register_Ns3MgtAssocResponseHeader_methods(root_module, root_module['ns3::MgtAssocResponseHeader']) register_Ns3MgtDelBaHeader_methods(root_module, root_module['ns3::MgtDelBaHeader']) register_Ns3MgtProbeRequestHeader_methods(root_module, root_module['ns3::MgtProbeRequestHeader']) register_Ns3MgtProbeResponseHeader_methods(root_module, root_module['ns3::MgtProbeResponseHeader']) register_Ns3QosTag_methods(root_module, root_module['ns3::QosTag']) register_Ns3WifiActionHeader_methods(root_module, root_module['ns3::WifiActionHeader']) register_Ns3WifiActionHeaderActionValue_methods(root_module, root_module['ns3::WifiActionHeader::ActionValue']) register_Ns3WifiInformationElement_methods(root_module, root_module['ns3::WifiInformationElement']) register_Ns3WifiInformationElementVector_methods(root_module, root_module['ns3::WifiInformationElementVector']) register_Ns3WifiMac_methods(root_module, root_module['ns3::WifiMac']) register_Ns3WifiMacHeader_methods(root_module, root_module['ns3::WifiMacHeader']) register_Ns3WifiPhy_methods(root_module, root_module['ns3::WifiPhy']) register_Ns3WifiRemoteStationManager_methods(root_module, root_module['ns3::WifiRemoteStationManager']) register_Ns3YansWifiPhy_methods(root_module, root_module['ns3::YansWifiPhy']) register_Ns3AarfWifiManager_methods(root_module, root_module['ns3::AarfWifiManager']) register_Ns3AarfcdWifiManager_methods(root_module, root_module['ns3::AarfcdWifiManager']) register_Ns3AdhocWifiMac_methods(root_module, root_module['ns3::AdhocWifiMac']) register_Ns3AmrrWifiManager_methods(root_module, root_module['ns3::AmrrWifiManager']) register_Ns3AmsduSubframeHeader_methods(root_module, root_module['ns3::AmsduSubframeHeader']) register_Ns3ArfWifiManager_methods(root_module, root_module['ns3::ArfWifiManager']) register_Ns3CaraWifiManager_methods(root_module, root_module['ns3::CaraWifiManager']) register_Ns3ConstantRateWifiManager_methods(root_module, root_module['ns3::ConstantRateWifiManager']) register_Ns3CtrlBAckRequestHeader_methods(root_module, root_module['ns3::CtrlBAckRequestHeader']) register_Ns3CtrlBAckResponseHeader_methods(root_module, root_module['ns3::CtrlBAckResponseHeader']) register_Ns3Dcf_methods(root_module, root_module['ns3::Dcf']) register_Ns3EdcaTxopN_methods(root_module, root_module['ns3::EdcaTxopN']) register_Ns3ErrorRateModel_methods(root_module, root_module['ns3::ErrorRateModel']) register_Ns3IdealWifiManager_methods(root_module, root_module['ns3::IdealWifiManager']) register_Ns3MacLow_methods(root_module, root_module['ns3::MacLow']) register_Ns3MgtBeaconHeader_methods(root_module, root_module['ns3::MgtBeaconHeader']) register_Ns3MinstrelWifiManager_methods(root_module, root_module['ns3::MinstrelWifiManager']) register_Ns3MsduAggregator_methods(root_module, root_module['ns3::MsduAggregator']) register_Ns3NistErrorRateModel_methods(root_module, root_module['ns3::NistErrorRateModel']) register_Ns3NqapWifiMac_methods(root_module, root_module['ns3::NqapWifiMac']) register_Ns3NqstaWifiMac_methods(root_module, root_module['ns3::NqstaWifiMac']) register_Ns3OnoeWifiManager_methods(root_module, root_module['ns3::OnoeWifiManager']) register_Ns3QadhocWifiMac_methods(root_module, root_module['ns3::QadhocWifiMac']) register_Ns3QapWifiMac_methods(root_module, root_module['ns3::QapWifiMac']) register_Ns3QstaWifiMac_methods(root_module, root_module['ns3::QstaWifiMac']) register_Ns3RraaWifiManager_methods(root_module, root_module['ns3::RraaWifiManager']) register_Ns3Ssid_methods(root_module, root_module['ns3::Ssid']) register_Ns3SsidChecker_methods(root_module, root_module['ns3::SsidChecker']) register_Ns3SsidValue_methods(root_module, root_module['ns3::SsidValue']) register_Ns3SupportedRates_methods(root_module, root_module['ns3::SupportedRates']) register_Ns3WifiChannel_methods(root_module, root_module['ns3::WifiChannel']) register_Ns3WifiModeChecker_methods(root_module, root_module['ns3::WifiModeChecker']) register_Ns3WifiModeValue_methods(root_module, root_module['ns3::WifiModeValue']) register_Ns3WifiNetDevice_methods(root_module, root_module['ns3::WifiNetDevice']) register_Ns3YansErrorRateModel_methods(root_module, root_module['ns3::YansErrorRateModel']) register_Ns3YansWifiChannel_methods(root_module, root_module['ns3::YansWifiChannel']) register_Ns3DcaTxop_methods(root_module, root_module['ns3::DcaTxop']) return def register_Ns3Bar_methods(root_module, cls): ## block-ack-manager.h: ns3::Bar::Bar(ns3::Bar const & arg0) [copy constructor] cls.add_constructor([param('ns3::Bar const &', 'arg0')]) ## block-ack-manager.h: ns3::Bar::Bar() [constructor] cls.add_constructor([]) ## block-ack-manager.h: ns3::Bar::Bar(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address recipient, uint8_t tid, bool immediate) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('bool', 'immediate')]) ## block-ack-manager.h: ns3::Bar::bar [variable] cls.add_instance_attribute('bar', 'ns3::Ptr< ns3::Packet const >', is_const=False) ## block-ack-manager.h: ns3::Bar::immediate [variable] cls.add_instance_attribute('immediate', 'bool', is_const=False) ## block-ack-manager.h: ns3::Bar::recipient [variable] cls.add_instance_attribute('recipient', 'ns3::Mac48Address', is_const=False) ## block-ack-manager.h: ns3::Bar::tid [variable] cls.add_instance_attribute('tid', 'uint8_t', is_const=False) return def register_Ns3BlockAckAgreement_methods(root_module, cls): ## block-ack-agreement.h: ns3::BlockAckAgreement::BlockAckAgreement(ns3::BlockAckAgreement const & arg0) [copy constructor] cls.add_constructor([param('ns3::BlockAckAgreement const &', 'arg0')]) ## block-ack-agreement.h: ns3::BlockAckAgreement::BlockAckAgreement() [constructor] cls.add_constructor([]) ## block-ack-agreement.h: ns3::BlockAckAgreement::BlockAckAgreement(ns3::Mac48Address peer, uint8_t tid) [constructor] cls.add_constructor([param('ns3::Mac48Address', 'peer'), param('uint8_t', 'tid')]) ## block-ack-agreement.h: uint16_t ns3::BlockAckAgreement::GetBufferSize() const [member function] cls.add_method('GetBufferSize', 'uint16_t', [], is_const=True) ## block-ack-agreement.h: ns3::Mac48Address ns3::BlockAckAgreement::GetPeer() const [member function] cls.add_method('GetPeer', 'ns3::Mac48Address', [], is_const=True) ## block-ack-agreement.h: uint16_t ns3::BlockAckAgreement::GetStartingSequence() const [member function] cls.add_method('GetStartingSequence', 'uint16_t', [], is_const=True) ## block-ack-agreement.h: uint16_t ns3::BlockAckAgreement::GetStartingSequenceControl() const [member function] cls.add_method('GetStartingSequenceControl', 'uint16_t', [], is_const=True) ## block-ack-agreement.h: uint8_t ns3::BlockAckAgreement::GetTid() const [member function] cls.add_method('GetTid', 'uint8_t', [], is_const=True) ## block-ack-agreement.h: uint16_t ns3::BlockAckAgreement::GetTimeout() const [member function] cls.add_method('GetTimeout', 'uint16_t', [], is_const=True) ## block-ack-agreement.h: bool ns3::BlockAckAgreement::IsAmsduSupported() const [member function] cls.add_method('IsAmsduSupported', 'bool', [], is_const=True) ## block-ack-agreement.h: bool ns3::BlockAckAgreement::IsImmediateBlockAck() const [member function] cls.add_method('IsImmediateBlockAck', 'bool', [], is_const=True) ## block-ack-agreement.h: void ns3::BlockAckAgreement::SetAmsduSupport(bool supported) [member function] cls.add_method('SetAmsduSupport', 'void', [param('bool', 'supported')]) ## block-ack-agreement.h: void ns3::BlockAckAgreement::SetBufferSize(uint16_t bufferSize) [member function] cls.add_method('SetBufferSize', 'void', [param('uint16_t', 'bufferSize')]) ## block-ack-agreement.h: void ns3::BlockAckAgreement::SetDelayedBlockAck() [member function] cls.add_method('SetDelayedBlockAck', 'void', []) ## block-ack-agreement.h: void ns3::BlockAckAgreement::SetImmediateBlockAck() [member function] cls.add_method('SetImmediateBlockAck', 'void', []) ## block-ack-agreement.h: void ns3::BlockAckAgreement::SetStartingSequence(uint16_t seq) [member function] cls.add_method('SetStartingSequence', 'void', [param('uint16_t', 'seq')]) ## block-ack-agreement.h: void ns3::BlockAckAgreement::SetTimeout(uint16_t timeout) [member function] cls.add_method('SetTimeout', 'void', [param('uint16_t', 'timeout')]) return def register_Ns3BlockAckManager_methods(root_module, cls): ## block-ack-manager.h: ns3::BlockAckManager::BlockAckManager() [constructor] cls.add_constructor([]) ## block-ack-manager.h: void ns3::BlockAckManager::CreateAgreement(ns3::MgtAddBaRequestHeader const * reqHdr, ns3::Mac48Address recipient) [member function] cls.add_method('CreateAgreement', 'void', [param('ns3::MgtAddBaRequestHeader const *', 'reqHdr'), param('ns3::Mac48Address', 'recipient')]) ## block-ack-manager.h: void ns3::BlockAckManager::DestroyAgreement(ns3::Mac48Address recipient, uint8_t tid) [member function] cls.add_method('DestroyAgreement', 'void', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')]) ## block-ack-manager.h: bool ns3::BlockAckManager::ExistsAgreement(ns3::Mac48Address recipient, uint8_t tid) const [member function] cls.add_method('ExistsAgreement', 'bool', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')], is_const=True) ## block-ack-manager.h: bool ns3::BlockAckManager::ExistsAgreementInState(ns3::Mac48Address recipient, uint8_t tid, ns3::OriginatorBlockAckAgreement::State state) const [member function] cls.add_method('ExistsAgreementInState', 'bool', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('ns3::OriginatorBlockAckAgreement::State', 'state')], is_const=True) ## block-ack-manager.h: uint32_t ns3::BlockAckManager::GetNBufferedPackets(ns3::Mac48Address recipient, uint8_t tid) const [member function] cls.add_method('GetNBufferedPackets', 'uint32_t', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')], is_const=True) ## block-ack-manager.h: uint32_t ns3::BlockAckManager::GetNRetryNeededPackets(ns3::Mac48Address recipient, uint8_t tid) const [member function] cls.add_method('GetNRetryNeededPackets', 'uint32_t', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')], is_const=True) ## block-ack-manager.h: ns3::Ptr<ns3::Packet const> ns3::BlockAckManager::GetNextPacket(ns3::WifiMacHeader & hdr) [member function] cls.add_method('GetNextPacket', 'ns3::Ptr< ns3::Packet const >', [param('ns3::WifiMacHeader &', 'hdr')]) ## block-ack-manager.h: uint32_t ns3::BlockAckManager::GetNextPacketSize() const [member function] cls.add_method('GetNextPacketSize', 'uint32_t', [], is_const=True) ## block-ack-manager.h: bool ns3::BlockAckManager::HasBar(ns3::Bar & bar) [member function] cls.add_method('HasBar', 'bool', [param('ns3::Bar &', 'bar')]) ## block-ack-manager.h: bool ns3::BlockAckManager::HasOtherFragments(uint16_t sequenceNumber) const [member function] cls.add_method('HasOtherFragments', 'bool', [param('uint16_t', 'sequenceNumber')], is_const=True) ## block-ack-manager.h: bool ns3::BlockAckManager::HasPackets() const [member function] cls.add_method('HasPackets', 'bool', [], is_const=True) ## block-ack-manager.h: void ns3::BlockAckManager::NotifyAgreementEstablished(ns3::Mac48Address recipient, uint8_t tid, uint16_t startingSeq) [member function] cls.add_method('NotifyAgreementEstablished', 'void', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('uint16_t', 'startingSeq')]) ## block-ack-manager.h: void ns3::BlockAckManager::NotifyAgreementUnsuccessful(ns3::Mac48Address recipient, uint8_t tid) [member function] cls.add_method('NotifyAgreementUnsuccessful', 'void', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')]) ## block-ack-manager.h: void ns3::BlockAckManager::NotifyGotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address recipient) [member function] cls.add_method('NotifyGotBlockAck', 'void', [param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'recipient')]) ## block-ack-manager.h: void ns3::BlockAckManager::NotifyMpduTransmission(ns3::Mac48Address recipient, uint8_t tid) [member function] cls.add_method('NotifyMpduTransmission', 'void', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')]) ## block-ack-manager.h: void ns3::BlockAckManager::SetBlockAckInactivityCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, bool, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetBlockAckInactivityCallback', 'void', [param('ns3::Callback< void, ns3::Mac48Address, unsigned char, bool, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## block-ack-manager.h: void ns3::BlockAckManager::SetBlockAckThreshold(uint8_t nPackets) [member function] cls.add_method('SetBlockAckThreshold', 'void', [param('uint8_t', 'nPackets')]) ## block-ack-manager.h: void ns3::BlockAckManager::SetBlockAckType(ns3::BlockAckType bAckType) [member function] cls.add_method('SetBlockAckType', 'void', [param('ns3::BlockAckType', 'bAckType')]) ## block-ack-manager.h: void ns3::BlockAckManager::SetBlockDestinationCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetBlockDestinationCallback', 'void', [param('ns3::Callback< void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## block-ack-manager.h: void ns3::BlockAckManager::SetMaxPacketDelay(ns3::Time maxDelay) [member function] cls.add_method('SetMaxPacketDelay', 'void', [param('ns3::Time', 'maxDelay')]) ## block-ack-manager.h: void ns3::BlockAckManager::SetQueue(ns3::Ptr<ns3::WifiMacQueue> queue) [member function] cls.add_method('SetQueue', 'void', [param('ns3::Ptr< ns3::WifiMacQueue >', 'queue')]) ## block-ack-manager.h: void ns3::BlockAckManager::SetTxMiddle(ns3::MacTxMiddle * txMiddle) [member function] cls.add_method('SetTxMiddle', 'void', [param('ns3::MacTxMiddle *', 'txMiddle')]) ## block-ack-manager.h: void ns3::BlockAckManager::SetUnblockDestinationCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetUnblockDestinationCallback', 'void', [param('ns3::Callback< void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## block-ack-manager.h: void ns3::BlockAckManager::StorePacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr, ns3::Time tStamp) [member function] cls.add_method('StorePacket', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr'), param('ns3::Time', 'tStamp')]) ## block-ack-manager.h: bool ns3::BlockAckManager::SwitchToBlockAckIfNeeded(ns3::Mac48Address recipient, uint8_t tid, uint16_t startingSeq) [member function] cls.add_method('SwitchToBlockAckIfNeeded', 'bool', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('uint16_t', 'startingSeq')]) ## block-ack-manager.h: void ns3::BlockAckManager::TearDownBlockAck(ns3::Mac48Address recipient, uint8_t tid) [member function] cls.add_method('TearDownBlockAck', 'void', [param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')]) ## block-ack-manager.h: void ns3::BlockAckManager::UpdateAgreement(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address recipient) [member function] cls.add_method('UpdateAgreement', 'void', [param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'recipient')]) return def register_Ns3CapabilityInformation_methods(root_module, cls): ## capability-information.h: ns3::CapabilityInformation::CapabilityInformation(ns3::CapabilityInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::CapabilityInformation const &', 'arg0')]) ## capability-information.h: ns3::CapabilityInformation::CapabilityInformation() [constructor] cls.add_constructor([]) ## capability-information.h: ns3::Buffer::Iterator ns3::CapabilityInformation::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## capability-information.h: uint32_t ns3::CapabilityInformation::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## capability-information.h: bool ns3::CapabilityInformation::IsEss() const [member function] cls.add_method('IsEss', 'bool', [], is_const=True) ## capability-information.h: bool ns3::CapabilityInformation::IsIbss() const [member function] cls.add_method('IsIbss', 'bool', [], is_const=True) ## capability-information.h: ns3::Buffer::Iterator ns3::CapabilityInformation::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) ## capability-information.h: void ns3::CapabilityInformation::SetEss() [member function] cls.add_method('SetEss', 'void', []) ## capability-information.h: void ns3::CapabilityInformation::SetIbss() [member function] cls.add_method('SetIbss', 'void', []) return def register_Ns3DcfManager_methods(root_module, cls): ## dcf-manager.h: ns3::DcfManager::DcfManager(ns3::DcfManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::DcfManager const &', 'arg0')]) ## dcf-manager.h: ns3::DcfManager::DcfManager() [constructor] cls.add_constructor([]) ## dcf-manager.h: void ns3::DcfManager::Add(ns3::DcfState * dcf) [member function] cls.add_method('Add', 'void', [param('ns3::DcfState *', 'dcf')]) ## dcf-manager.h: ns3::Time ns3::DcfManager::GetEifsNoDifs() const [member function] cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_const=True) ## dcf-manager.h: void ns3::DcfManager::NotifyAckTimeoutResetNow() [member function] cls.add_method('NotifyAckTimeoutResetNow', 'void', []) ## dcf-manager.h: void ns3::DcfManager::NotifyAckTimeoutStartNow(ns3::Time duration) [member function] cls.add_method('NotifyAckTimeoutStartNow', 'void', [param('ns3::Time', 'duration')]) ## dcf-manager.h: void ns3::DcfManager::NotifyCtsTimeoutResetNow() [member function] cls.add_method('NotifyCtsTimeoutResetNow', 'void', []) ## dcf-manager.h: void ns3::DcfManager::NotifyCtsTimeoutStartNow(ns3::Time duration) [member function] cls.add_method('NotifyCtsTimeoutStartNow', 'void', [param('ns3::Time', 'duration')]) ## dcf-manager.h: void ns3::DcfManager::NotifyMaybeCcaBusyStartNow(ns3::Time duration) [member function] cls.add_method('NotifyMaybeCcaBusyStartNow', 'void', [param('ns3::Time', 'duration')]) ## dcf-manager.h: void ns3::DcfManager::NotifyNavResetNow(ns3::Time duration) [member function] cls.add_method('NotifyNavResetNow', 'void', [param('ns3::Time', 'duration')]) ## dcf-manager.h: void ns3::DcfManager::NotifyNavStartNow(ns3::Time duration) [member function] cls.add_method('NotifyNavStartNow', 'void', [param('ns3::Time', 'duration')]) ## dcf-manager.h: void ns3::DcfManager::NotifyRxEndErrorNow() [member function] cls.add_method('NotifyRxEndErrorNow', 'void', []) ## dcf-manager.h: void ns3::DcfManager::NotifyRxEndOkNow() [member function] cls.add_method('NotifyRxEndOkNow', 'void', []) ## dcf-manager.h: void ns3::DcfManager::NotifyRxStartNow(ns3::Time duration) [member function] cls.add_method('NotifyRxStartNow', 'void', [param('ns3::Time', 'duration')]) ## dcf-manager.h: void ns3::DcfManager::NotifySwitchingStartNow(ns3::Time duration) [member function] cls.add_method('NotifySwitchingStartNow', 'void', [param('ns3::Time', 'duration')]) ## dcf-manager.h: void ns3::DcfManager::NotifyTxStartNow(ns3::Time duration) [member function] cls.add_method('NotifyTxStartNow', 'void', [param('ns3::Time', 'duration')]) ## dcf-manager.h: void ns3::DcfManager::RequestAccess(ns3::DcfState * state) [member function] cls.add_method('RequestAccess', 'void', [param('ns3::DcfState *', 'state')]) ## dcf-manager.h: void ns3::DcfManager::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function] cls.add_method('SetEifsNoDifs', 'void', [param('ns3::Time', 'eifsNoDifs')]) ## dcf-manager.h: void ns3::DcfManager::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')]) ## dcf-manager.h: void ns3::DcfManager::SetSlot(ns3::Time slotTime) [member function] cls.add_method('SetSlot', 'void', [param('ns3::Time', 'slotTime')]) ## dcf-manager.h: void ns3::DcfManager::SetupLowListener(ns3::Ptr<ns3::MacLow> low) [member function] cls.add_method('SetupLowListener', 'void', [param('ns3::Ptr< ns3::MacLow >', 'low')]) ## dcf-manager.h: void ns3::DcfManager::SetupPhyListener(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetupPhyListener', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')]) return def register_Ns3DcfState_methods(root_module, cls): ## dcf-manager.h: ns3::DcfState::DcfState(ns3::DcfState const & arg0) [copy constructor] cls.add_constructor([param('ns3::DcfState const &', 'arg0')]) ## dcf-manager.h: ns3::DcfState::DcfState() [constructor] cls.add_constructor([]) ## dcf-manager.h: uint32_t ns3::DcfState::GetAifsn() const [member function] cls.add_method('GetAifsn', 'uint32_t', [], is_const=True) ## dcf-manager.h: uint32_t ns3::DcfState::GetCw() const [member function] cls.add_method('GetCw', 'uint32_t', [], is_const=True) ## dcf-manager.h: uint32_t ns3::DcfState::GetCwMax() const [member function] cls.add_method('GetCwMax', 'uint32_t', [], is_const=True) ## dcf-manager.h: uint32_t ns3::DcfState::GetCwMin() const [member function] cls.add_method('GetCwMin', 'uint32_t', [], is_const=True) ## dcf-manager.h: bool ns3::DcfState::IsAccessRequested() const [member function] cls.add_method('IsAccessRequested', 'bool', [], is_const=True) ## dcf-manager.h: void ns3::DcfState::ResetCw() [member function] cls.add_method('ResetCw', 'void', []) ## dcf-manager.h: void ns3::DcfState::SetAifsn(uint32_t aifsn) [member function] cls.add_method('SetAifsn', 'void', [param('uint32_t', 'aifsn')]) ## dcf-manager.h: void ns3::DcfState::SetCwMax(uint32_t maxCw) [member function] cls.add_method('SetCwMax', 'void', [param('uint32_t', 'maxCw')]) ## dcf-manager.h: void ns3::DcfState::SetCwMin(uint32_t minCw) [member function] cls.add_method('SetCwMin', 'void', [param('uint32_t', 'minCw')]) ## dcf-manager.h: void ns3::DcfState::StartBackoffNow(uint32_t nSlots) [member function] cls.add_method('StartBackoffNow', 'void', [param('uint32_t', 'nSlots')]) ## dcf-manager.h: void ns3::DcfState::UpdateFailedCw() [member function] cls.add_method('UpdateFailedCw', 'void', []) ## dcf-manager.h: void ns3::DcfState::DoNotifyAccessGranted() [member function] cls.add_method('DoNotifyAccessGranted', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## dcf-manager.h: void ns3::DcfState::DoNotifyChannelSwitching() [member function] cls.add_method('DoNotifyChannelSwitching', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## dcf-manager.h: void ns3::DcfState::DoNotifyCollision() [member function] cls.add_method('DoNotifyCollision', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## dcf-manager.h: void ns3::DcfState::DoNotifyInternalCollision() [member function] cls.add_method('DoNotifyInternalCollision', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3DsssErrorRateModel_methods(root_module, cls): ## dsss-error-rate-model.h: ns3::DsssErrorRateModel::DsssErrorRateModel() [constructor] cls.add_constructor([]) ## dsss-error-rate-model.h: ns3::DsssErrorRateModel::DsssErrorRateModel(ns3::DsssErrorRateModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::DsssErrorRateModel const &', 'arg0')]) ## dsss-error-rate-model.h: static double ns3::DsssErrorRateModel::DqpskFunction(double x) [member function] cls.add_method('DqpskFunction', 'double', [param('double', 'x')], is_static=True) ## dsss-error-rate-model.h: static double ns3::DsssErrorRateModel::GetDsssDbpskSuccessRate(double sinr, uint32_t nbits) [member function] cls.add_method('GetDsssDbpskSuccessRate', 'double', [param('double', 'sinr'), param('uint32_t', 'nbits')], is_static=True) ## dsss-error-rate-model.h: static double ns3::DsssErrorRateModel::GetDsssDqpskCck11SuccessRate(double sinr, uint32_t nbits) [member function] cls.add_method('GetDsssDqpskCck11SuccessRate', 'double', [param('double', 'sinr'), param('uint32_t', 'nbits')], is_static=True) ## dsss-error-rate-model.h: static double ns3::DsssErrorRateModel::GetDsssDqpskCck5_5SuccessRate(double sinr, uint32_t nbits) [member function] cls.add_method('GetDsssDqpskCck5_5SuccessRate', 'double', [param('double', 'sinr'), param('uint32_t', 'nbits')], is_static=True) ## dsss-error-rate-model.h: static double ns3::DsssErrorRateModel::GetDsssDqpskSuccessRate(double sinr, uint32_t nbits) [member function] cls.add_method('GetDsssDqpskSuccessRate', 'double', [param('double', 'sinr'), param('uint32_t', 'nbits')], is_static=True) return def register_Ns3InterferenceHelper_methods(root_module, cls): ## interference-helper.h: ns3::InterferenceHelper::InterferenceHelper() [constructor] cls.add_constructor([]) ## interference-helper.h: ns3::Ptr<ns3::InterferenceHelper::Event> ns3::InterferenceHelper::Add(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble, ns3::Time duration, double rxPower) [member function] cls.add_method('Add', 'ns3::Ptr< ns3::InterferenceHelper::Event >', [param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble'), param('ns3::Time', 'duration'), param('double', 'rxPower')]) ## interference-helper.h: ns3::InterferenceHelper::SnrPer ns3::InterferenceHelper::CalculateSnrPer(ns3::Ptr<ns3::InterferenceHelper::Event> event) [member function] cls.add_method('CalculateSnrPer', 'ns3::InterferenceHelper::SnrPer', [param('ns3::Ptr< ns3::InterferenceHelper::Event >', 'event')]) ## interference-helper.h: static ns3::Time ns3::InterferenceHelper::CalculateTxDuration(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function] cls.add_method('CalculateTxDuration', 'ns3::Time', [param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## interference-helper.h: void ns3::InterferenceHelper::EraseEvents() [member function] cls.add_method('EraseEvents', 'void', []) ## interference-helper.h: ns3::Time ns3::InterferenceHelper::GetEnergyDuration(double energyW) [member function] cls.add_method('GetEnergyDuration', 'ns3::Time', [param('double', 'energyW')]) ## interference-helper.h: ns3::Ptr<ns3::ErrorRateModel> ns3::InterferenceHelper::GetErrorRateModel() const [member function] cls.add_method('GetErrorRateModel', 'ns3::Ptr< ns3::ErrorRateModel >', [], is_const=True) ## interference-helper.h: double ns3::InterferenceHelper::GetNoiseFigure() const [member function] cls.add_method('GetNoiseFigure', 'double', [], is_const=True) ## interference-helper.h: static uint32_t ns3::InterferenceHelper::GetPayloadDurationMicroSeconds(uint32_t size, ns3::WifiMode payloadMode) [member function] cls.add_method('GetPayloadDurationMicroSeconds', 'uint32_t', [param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode')], is_static=True) ## interference-helper.h: static uint32_t ns3::InterferenceHelper::GetPlcpHeaderDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function] cls.add_method('GetPlcpHeaderDurationMicroSeconds', 'uint32_t', [param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## interference-helper.h: static ns3::WifiMode ns3::InterferenceHelper::GetPlcpHeaderMode(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function] cls.add_method('GetPlcpHeaderMode', 'ns3::WifiMode', [param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## interference-helper.h: static uint32_t ns3::InterferenceHelper::GetPlcpPreambleDurationMicroSeconds(ns3::WifiMode mode, ns3::WifiPreamble preamble) [member function] cls.add_method('GetPlcpPreambleDurationMicroSeconds', 'uint32_t', [param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## interference-helper.h: void ns3::InterferenceHelper::NotifyRxEnd() [member function] cls.add_method('NotifyRxEnd', 'void', []) ## interference-helper.h: void ns3::InterferenceHelper::NotifyRxStart() [member function] cls.add_method('NotifyRxStart', 'void', []) ## interference-helper.h: void ns3::InterferenceHelper::SetErrorRateModel(ns3::Ptr<ns3::ErrorRateModel> rate) [member function] cls.add_method('SetErrorRateModel', 'void', [param('ns3::Ptr< ns3::ErrorRateModel >', 'rate')]) ## interference-helper.h: void ns3::InterferenceHelper::SetNoiseFigure(double value) [member function] cls.add_method('SetNoiseFigure', 'void', [param('double', 'value')]) return def register_Ns3InterferenceHelperSnrPer_methods(root_module, cls): ## interference-helper.h: ns3::InterferenceHelper::SnrPer::SnrPer() [constructor] cls.add_constructor([]) ## interference-helper.h: ns3::InterferenceHelper::SnrPer::SnrPer(ns3::InterferenceHelper::SnrPer const & arg0) [copy constructor] cls.add_constructor([param('ns3::InterferenceHelper::SnrPer const &', 'arg0')]) ## interference-helper.h: ns3::InterferenceHelper::SnrPer::per [variable] cls.add_instance_attribute('per', 'double', is_const=False) ## interference-helper.h: ns3::InterferenceHelper::SnrPer::snr [variable] cls.add_instance_attribute('snr', 'double', is_const=False) return def register_Ns3MacLowBlockAckEventListener_methods(root_module, cls): ## mac-low.h: ns3::MacLowBlockAckEventListener::MacLowBlockAckEventListener(ns3::MacLowBlockAckEventListener const & arg0) [copy constructor] cls.add_constructor([param('ns3::MacLowBlockAckEventListener const &', 'arg0')]) ## mac-low.h: ns3::MacLowBlockAckEventListener::MacLowBlockAckEventListener() [constructor] cls.add_constructor([]) ## mac-low.h: void ns3::MacLowBlockAckEventListener::BlockAckInactivityTimeout(ns3::Mac48Address originator, uint8_t tid) [member function] cls.add_method('BlockAckInactivityTimeout', 'void', [param('ns3::Mac48Address', 'originator'), param('uint8_t', 'tid')], is_pure_virtual=True, is_virtual=True) return def register_Ns3MacLowDcfListener_methods(root_module, cls): ## mac-low.h: ns3::MacLowDcfListener::MacLowDcfListener(ns3::MacLowDcfListener const & arg0) [copy constructor] cls.add_constructor([param('ns3::MacLowDcfListener const &', 'arg0')]) ## mac-low.h: ns3::MacLowDcfListener::MacLowDcfListener() [constructor] cls.add_constructor([]) ## mac-low.h: void ns3::MacLowDcfListener::AckTimeoutReset() [member function] cls.add_method('AckTimeoutReset', 'void', [], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowDcfListener::AckTimeoutStart(ns3::Time duration) [member function] cls.add_method('AckTimeoutStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowDcfListener::CtsTimeoutReset() [member function] cls.add_method('CtsTimeoutReset', 'void', [], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowDcfListener::CtsTimeoutStart(ns3::Time duration) [member function] cls.add_method('CtsTimeoutStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowDcfListener::NavReset(ns3::Time duration) [member function] cls.add_method('NavReset', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowDcfListener::NavStart(ns3::Time duration) [member function] cls.add_method('NavStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) return def register_Ns3MacLowTransmissionListener_methods(root_module, cls): ## mac-low.h: ns3::MacLowTransmissionListener::MacLowTransmissionListener(ns3::MacLowTransmissionListener const & arg0) [copy constructor] cls.add_constructor([param('ns3::MacLowTransmissionListener const &', 'arg0')]) ## mac-low.h: ns3::MacLowTransmissionListener::MacLowTransmissionListener() [constructor] cls.add_constructor([]) ## mac-low.h: void ns3::MacLowTransmissionListener::Cancel() [member function] cls.add_method('Cancel', 'void', [], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowTransmissionListener::GotAck(double snr, ns3::WifiMode txMode) [member function] cls.add_method('GotAck', 'void', [param('double', 'snr'), param('ns3::WifiMode', 'txMode')], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowTransmissionListener::GotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address source) [member function] cls.add_method('GotBlockAck', 'void', [param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'source')], is_virtual=True) ## mac-low.h: void ns3::MacLowTransmissionListener::GotCts(double snr, ns3::WifiMode txMode) [member function] cls.add_method('GotCts', 'void', [param('double', 'snr'), param('ns3::WifiMode', 'txMode')], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowTransmissionListener::MissedAck() [member function] cls.add_method('MissedAck', 'void', [], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowTransmissionListener::MissedBlockAck() [member function] cls.add_method('MissedBlockAck', 'void', [], is_virtual=True) ## mac-low.h: void ns3::MacLowTransmissionListener::MissedCts() [member function] cls.add_method('MissedCts', 'void', [], is_pure_virtual=True, is_virtual=True) ## mac-low.h: void ns3::MacLowTransmissionListener::StartNext() [member function] cls.add_method('StartNext', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3MacLowTransmissionParameters_methods(root_module, cls): cls.add_output_stream_operator() ## mac-low.h: ns3::MacLowTransmissionParameters::MacLowTransmissionParameters(ns3::MacLowTransmissionParameters const & arg0) [copy constructor] cls.add_constructor([param('ns3::MacLowTransmissionParameters const &', 'arg0')]) ## mac-low.h: ns3::MacLowTransmissionParameters::MacLowTransmissionParameters() [constructor] cls.add_constructor([]) ## mac-low.h: void ns3::MacLowTransmissionParameters::DisableAck() [member function] cls.add_method('DisableAck', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::DisableNextData() [member function] cls.add_method('DisableNextData', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::DisableOverrideDurationId() [member function] cls.add_method('DisableOverrideDurationId', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::DisableRts() [member function] cls.add_method('DisableRts', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableAck() [member function] cls.add_method('EnableAck', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableBasicBlockAck() [member function] cls.add_method('EnableBasicBlockAck', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableCompressedBlockAck() [member function] cls.add_method('EnableCompressedBlockAck', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableFastAck() [member function] cls.add_method('EnableFastAck', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableMultiTidBlockAck() [member function] cls.add_method('EnableMultiTidBlockAck', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableNextData(uint32_t size) [member function] cls.add_method('EnableNextData', 'void', [param('uint32_t', 'size')]) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableOverrideDurationId(ns3::Time durationId) [member function] cls.add_method('EnableOverrideDurationId', 'void', [param('ns3::Time', 'durationId')]) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableRts() [member function] cls.add_method('EnableRts', 'void', []) ## mac-low.h: void ns3::MacLowTransmissionParameters::EnableSuperFastAck() [member function] cls.add_method('EnableSuperFastAck', 'void', []) ## mac-low.h: ns3::Time ns3::MacLowTransmissionParameters::GetDurationId() const [member function] cls.add_method('GetDurationId', 'ns3::Time', [], is_const=True) ## mac-low.h: uint32_t ns3::MacLowTransmissionParameters::GetNextPacketSize() const [member function] cls.add_method('GetNextPacketSize', 'uint32_t', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::HasDurationId() const [member function] cls.add_method('HasDurationId', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::HasNextPacket() const [member function] cls.add_method('HasNextPacket', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::MustSendRts() const [member function] cls.add_method('MustSendRts', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::MustWaitAck() const [member function] cls.add_method('MustWaitAck', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::MustWaitBasicBlockAck() const [member function] cls.add_method('MustWaitBasicBlockAck', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::MustWaitCompressedBlockAck() const [member function] cls.add_method('MustWaitCompressedBlockAck', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::MustWaitFastAck() const [member function] cls.add_method('MustWaitFastAck', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::MustWaitMultiTidBlockAck() const [member function] cls.add_method('MustWaitMultiTidBlockAck', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::MustWaitNormalAck() const [member function] cls.add_method('MustWaitNormalAck', 'bool', [], is_const=True) ## mac-low.h: bool ns3::MacLowTransmissionParameters::MustWaitSuperFastAck() const [member function] cls.add_method('MustWaitSuperFastAck', 'bool', [], is_const=True) return def register_Ns3MacRxMiddle_methods(root_module, cls): ## mac-rx-middle.h: ns3::MacRxMiddle::MacRxMiddle(ns3::MacRxMiddle const & arg0) [copy constructor] cls.add_constructor([param('ns3::MacRxMiddle const &', 'arg0')]) ## mac-rx-middle.h: ns3::MacRxMiddle::MacRxMiddle() [constructor] cls.add_constructor([]) ## mac-rx-middle.h: void ns3::MacRxMiddle::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')]) ## mac-rx-middle.h: void ns3::MacRxMiddle::SetForwardCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::WifiMacHeader const*, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetForwardCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::WifiMacHeader const *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) return def register_Ns3OriginatorBlockAckAgreement_methods(root_module, cls): ## originator-block-ack-agreement.h: ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement(ns3::OriginatorBlockAckAgreement const & arg0) [copy constructor] cls.add_constructor([param('ns3::OriginatorBlockAckAgreement const &', 'arg0')]) ## originator-block-ack-agreement.h: ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement() [constructor] cls.add_constructor([]) ## originator-block-ack-agreement.h: ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement(ns3::Mac48Address recipient, uint8_t tid) [constructor] cls.add_constructor([param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')]) ## originator-block-ack-agreement.h: void ns3::OriginatorBlockAckAgreement::CompleteExchange() [member function] cls.add_method('CompleteExchange', 'void', []) ## originator-block-ack-agreement.h: bool ns3::OriginatorBlockAckAgreement::IsEstablished() const [member function] cls.add_method('IsEstablished', 'bool', [], is_const=True) ## originator-block-ack-agreement.h: bool ns3::OriginatorBlockAckAgreement::IsInactive() const [member function] cls.add_method('IsInactive', 'bool', [], is_const=True) ## originator-block-ack-agreement.h: bool ns3::OriginatorBlockAckAgreement::IsPending() const [member function] cls.add_method('IsPending', 'bool', [], is_const=True) ## originator-block-ack-agreement.h: bool ns3::OriginatorBlockAckAgreement::IsUnsuccessful() const [member function] cls.add_method('IsUnsuccessful', 'bool', [], is_const=True) ## originator-block-ack-agreement.h: bool ns3::OriginatorBlockAckAgreement::NeedBlockAckRequest() const [member function] cls.add_method('NeedBlockAckRequest', 'bool', [], is_const=True) ## originator-block-ack-agreement.h: void ns3::OriginatorBlockAckAgreement::NotifyMpduTransmission() [member function] cls.add_method('NotifyMpduTransmission', 'void', []) ## originator-block-ack-agreement.h: void ns3::OriginatorBlockAckAgreement::SetState(ns3::OriginatorBlockAckAgreement::State state) [member function] cls.add_method('SetState', 'void', [param('ns3::OriginatorBlockAckAgreement::State', 'state')]) return def register_Ns3RateInfo_methods(root_module, cls): ## minstrel-wifi-manager.h: ns3::RateInfo::RateInfo() [constructor] cls.add_constructor([]) ## minstrel-wifi-manager.h: ns3::RateInfo::RateInfo(ns3::RateInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::RateInfo const &', 'arg0')]) ## minstrel-wifi-manager.h: ns3::RateInfo::adjustedRetryCount [variable] cls.add_instance_attribute('adjustedRetryCount', 'uint32_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::attemptHist [variable] cls.add_instance_attribute('attemptHist', 'uint64_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::ewmaProb [variable] cls.add_instance_attribute('ewmaProb', 'uint32_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::numRateAttempt [variable] cls.add_instance_attribute('numRateAttempt', 'uint32_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::numRateSuccess [variable] cls.add_instance_attribute('numRateSuccess', 'uint32_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::perfectTxTime [variable] cls.add_instance_attribute('perfectTxTime', 'ns3::Time', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::prevNumRateAttempt [variable] cls.add_instance_attribute('prevNumRateAttempt', 'uint32_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::prevNumRateSuccess [variable] cls.add_instance_attribute('prevNumRateSuccess', 'uint32_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::prob [variable] cls.add_instance_attribute('prob', 'uint32_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::retryCount [variable] cls.add_instance_attribute('retryCount', 'uint32_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::successHist [variable] cls.add_instance_attribute('successHist', 'uint64_t', is_const=False) ## minstrel-wifi-manager.h: ns3::RateInfo::throughput [variable] cls.add_instance_attribute('throughput', 'uint32_t', is_const=False) return def register_Ns3StatusCode_methods(root_module, cls): cls.add_output_stream_operator() ## status-code.h: ns3::StatusCode::StatusCode(ns3::StatusCode const & arg0) [copy constructor] cls.add_constructor([param('ns3::StatusCode const &', 'arg0')]) ## status-code.h: ns3::StatusCode::StatusCode() [constructor] cls.add_constructor([]) ## status-code.h: ns3::Buffer::Iterator ns3::StatusCode::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')]) ## status-code.h: uint32_t ns3::StatusCode::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## status-code.h: bool ns3::StatusCode::IsSuccess() const [member function] cls.add_method('IsSuccess', 'bool', [], is_const=True) ## status-code.h: ns3::Buffer::Iterator ns3::StatusCode::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'start')], is_const=True) ## status-code.h: void ns3::StatusCode::SetFailure() [member function] cls.add_method('SetFailure', 'void', []) ## status-code.h: void ns3::StatusCode::SetSuccess() [member function] cls.add_method('SetSuccess', 'void', []) return def register_Ns3WifiMode_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## wifi-mode.h: ns3::WifiMode::WifiMode(ns3::WifiMode const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiMode const &', 'arg0')]) ## wifi-mode.h: ns3::WifiMode::WifiMode() [constructor] cls.add_constructor([]) ## wifi-mode.h: ns3::WifiMode::WifiMode(std::string name) [constructor] cls.add_constructor([param('std::string', 'name')]) ## wifi-mode.h: uint32_t ns3::WifiMode::GetBandwidth() const [member function] cls.add_method('GetBandwidth', 'uint32_t', [], is_const=True) ## wifi-mode.h: ns3::WifiCodeRate ns3::WifiMode::GetCodeRate() const [member function] cls.add_method('GetCodeRate', 'ns3::WifiCodeRate', [], is_const=True) ## wifi-mode.h: uint8_t ns3::WifiMode::GetConstellationSize() const [member function] cls.add_method('GetConstellationSize', 'uint8_t', [], is_const=True) ## wifi-mode.h: uint32_t ns3::WifiMode::GetDataRate() const [member function] cls.add_method('GetDataRate', 'uint32_t', [], is_const=True) ## wifi-mode.h: ns3::WifiModulationClass ns3::WifiMode::GetModulationClass() const [member function] cls.add_method('GetModulationClass', 'ns3::WifiModulationClass', [], is_const=True) ## wifi-mode.h: uint32_t ns3::WifiMode::GetPhyRate() const [member function] cls.add_method('GetPhyRate', 'uint32_t', [], is_const=True) ## wifi-mode.h: uint32_t ns3::WifiMode::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## wifi-mode.h: std::string ns3::WifiMode::GetUniqueName() const [member function] cls.add_method('GetUniqueName', 'std::string', [], is_const=True) ## wifi-mode.h: bool ns3::WifiMode::IsMandatory() const [member function] cls.add_method('IsMandatory', 'bool', [], is_const=True) return def register_Ns3WifiModeFactory_methods(root_module, cls): ## wifi-mode.h: ns3::WifiModeFactory::WifiModeFactory(ns3::WifiModeFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiModeFactory const &', 'arg0')]) ## wifi-mode.h: static ns3::WifiMode ns3::WifiModeFactory::CreateWifiMode(std::string uniqueName, ns3::WifiModulationClass modClass, bool isMandatory, uint32_t bandwidth, uint32_t dataRate, ns3::WifiCodeRate codingRate, uint8_t constellationSize) [member function] cls.add_method('CreateWifiMode', 'ns3::WifiMode', [param('std::string', 'uniqueName'), param('ns3::WifiModulationClass', 'modClass'), param('bool', 'isMandatory'), param('uint32_t', 'bandwidth'), param('uint32_t', 'dataRate'), param('ns3::WifiCodeRate', 'codingRate'), param('uint8_t', 'constellationSize')], is_static=True) return def register_Ns3WifiPhyListener_methods(root_module, cls): ## wifi-phy.h: ns3::WifiPhyListener::WifiPhyListener() [constructor] cls.add_constructor([]) ## wifi-phy.h: ns3::WifiPhyListener::WifiPhyListener(ns3::WifiPhyListener const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiPhyListener const &', 'arg0')]) ## wifi-phy.h: void ns3::WifiPhyListener::NotifyMaybeCcaBusyStart(ns3::Time duration) [member function] cls.add_method('NotifyMaybeCcaBusyStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhyListener::NotifyRxEndError() [member function] cls.add_method('NotifyRxEndError', 'void', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhyListener::NotifyRxEndOk() [member function] cls.add_method('NotifyRxEndOk', 'void', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhyListener::NotifyRxStart(ns3::Time duration) [member function] cls.add_method('NotifyRxStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhyListener::NotifySwitchingStart(ns3::Time duration) [member function] cls.add_method('NotifySwitchingStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhyListener::NotifyTxStart(ns3::Time duration) [member function] cls.add_method('NotifyTxStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) return def register_Ns3WifiRemoteStation_methods(root_module, cls): ## wifi-remote-station-manager.h: ns3::WifiRemoteStation::WifiRemoteStation() [constructor] cls.add_constructor([]) ## wifi-remote-station-manager.h: ns3::WifiRemoteStation::WifiRemoteStation(ns3::WifiRemoteStation const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiRemoteStation const &', 'arg0')]) ## wifi-remote-station-manager.h: ns3::WifiRemoteStation::m_slrc [variable] cls.add_instance_attribute('m_slrc', 'uint32_t', is_const=False) ## wifi-remote-station-manager.h: ns3::WifiRemoteStation::m_ssrc [variable] cls.add_instance_attribute('m_ssrc', 'uint32_t', is_const=False) ## wifi-remote-station-manager.h: ns3::WifiRemoteStation::m_state [variable] cls.add_instance_attribute('m_state', 'ns3::WifiRemoteStationState *', is_const=False) ## wifi-remote-station-manager.h: ns3::WifiRemoteStation::m_tid [variable] cls.add_instance_attribute('m_tid', 'uint8_t', is_const=False) return def register_Ns3WifiRemoteStationInfo_methods(root_module, cls): ## wifi-remote-station-manager.h: ns3::WifiRemoteStationInfo::WifiRemoteStationInfo(ns3::WifiRemoteStationInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiRemoteStationInfo const &', 'arg0')]) ## wifi-remote-station-manager.h: ns3::WifiRemoteStationInfo::WifiRemoteStationInfo() [constructor] cls.add_constructor([]) ## wifi-remote-station-manager.h: double ns3::WifiRemoteStationInfo::GetFrameErrorRate() const [member function] cls.add_method('GetFrameErrorRate', 'double', [], is_const=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationInfo::NotifyTxFailed() [member function] cls.add_method('NotifyTxFailed', 'void', []) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationInfo::NotifyTxSuccess(uint32_t retryCounter) [member function] cls.add_method('NotifyTxSuccess', 'void', [param('uint32_t', 'retryCounter')]) return def register_Ns3WifiRemoteStationState_methods(root_module, cls): ## wifi-remote-station-manager.h: ns3::WifiRemoteStationState::WifiRemoteStationState() [constructor] cls.add_constructor([]) ## wifi-remote-station-manager.h: ns3::WifiRemoteStationState::WifiRemoteStationState(ns3::WifiRemoteStationState const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiRemoteStationState const &', 'arg0')]) ## wifi-remote-station-manager.h: ns3::WifiRemoteStationState::m_address [variable] cls.add_instance_attribute('m_address', 'ns3::Mac48Address', is_const=False) ## wifi-remote-station-manager.h: ns3::WifiRemoteStationState::m_info [variable] cls.add_instance_attribute('m_info', 'ns3::WifiRemoteStationInfo', is_const=False) ## wifi-remote-station-manager.h: ns3::WifiRemoteStationState::m_operationalRateSet [variable] cls.add_instance_attribute('m_operationalRateSet', 'ns3::WifiModeList', is_const=False) return def register_Ns3MgtAddBaRequestHeader_methods(root_module, cls): ## mgt-headers.h: ns3::MgtAddBaRequestHeader::MgtAddBaRequestHeader(ns3::MgtAddBaRequestHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::MgtAddBaRequestHeader const &', 'arg0')]) ## mgt-headers.h: ns3::MgtAddBaRequestHeader::MgtAddBaRequestHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: uint32_t ns3::MgtAddBaRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mgt-headers.h: uint16_t ns3::MgtAddBaRequestHeader::GetBufferSize() const [member function] cls.add_method('GetBufferSize', 'uint16_t', [], is_const=True) ## mgt-headers.h: ns3::TypeId ns3::MgtAddBaRequestHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint32_t ns3::MgtAddBaRequestHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint16_t ns3::MgtAddBaRequestHeader::GetStartingSequence() const [member function] cls.add_method('GetStartingSequence', 'uint16_t', [], is_const=True) ## mgt-headers.h: uint8_t ns3::MgtAddBaRequestHeader::GetTid() const [member function] cls.add_method('GetTid', 'uint8_t', [], is_const=True) ## mgt-headers.h: uint16_t ns3::MgtAddBaRequestHeader::GetTimeout() const [member function] cls.add_method('GetTimeout', 'uint16_t', [], is_const=True) ## mgt-headers.h: static ns3::TypeId ns3::MgtAddBaRequestHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mgt-headers.h: bool ns3::MgtAddBaRequestHeader::IsAmsduSupported() const [member function] cls.add_method('IsAmsduSupported', 'bool', [], is_const=True) ## mgt-headers.h: bool ns3::MgtAddBaRequestHeader::IsImmediateBlockAck() const [member function] cls.add_method('IsImmediateBlockAck', 'bool', [], is_const=True) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::SetAmsduSupport(bool supported) [member function] cls.add_method('SetAmsduSupport', 'void', [param('bool', 'supported')]) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::SetBufferSize(uint16_t size) [member function] cls.add_method('SetBufferSize', 'void', [param('uint16_t', 'size')]) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::SetDelayedBlockAck() [member function] cls.add_method('SetDelayedBlockAck', 'void', []) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::SetImmediateBlockAck() [member function] cls.add_method('SetImmediateBlockAck', 'void', []) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::SetStartingSequence(uint16_t seq) [member function] cls.add_method('SetStartingSequence', 'void', [param('uint16_t', 'seq')]) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::SetTid(uint8_t tid) [member function] cls.add_method('SetTid', 'void', [param('uint8_t', 'tid')]) ## mgt-headers.h: void ns3::MgtAddBaRequestHeader::SetTimeout(uint16_t timeout) [member function] cls.add_method('SetTimeout', 'void', [param('uint16_t', 'timeout')]) return def register_Ns3MgtAddBaResponseHeader_methods(root_module, cls): ## mgt-headers.h: ns3::MgtAddBaResponseHeader::MgtAddBaResponseHeader(ns3::MgtAddBaResponseHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::MgtAddBaResponseHeader const &', 'arg0')]) ## mgt-headers.h: ns3::MgtAddBaResponseHeader::MgtAddBaResponseHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: uint32_t ns3::MgtAddBaResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mgt-headers.h: uint16_t ns3::MgtAddBaResponseHeader::GetBufferSize() const [member function] cls.add_method('GetBufferSize', 'uint16_t', [], is_const=True) ## mgt-headers.h: ns3::TypeId ns3::MgtAddBaResponseHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint32_t ns3::MgtAddBaResponseHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mgt-headers.h: ns3::StatusCode ns3::MgtAddBaResponseHeader::GetStatusCode() const [member function] cls.add_method('GetStatusCode', 'ns3::StatusCode', [], is_const=True) ## mgt-headers.h: uint8_t ns3::MgtAddBaResponseHeader::GetTid() const [member function] cls.add_method('GetTid', 'uint8_t', [], is_const=True) ## mgt-headers.h: uint16_t ns3::MgtAddBaResponseHeader::GetTimeout() const [member function] cls.add_method('GetTimeout', 'uint16_t', [], is_const=True) ## mgt-headers.h: static ns3::TypeId ns3::MgtAddBaResponseHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mgt-headers.h: bool ns3::MgtAddBaResponseHeader::IsAmsduSupported() const [member function] cls.add_method('IsAmsduSupported', 'bool', [], is_const=True) ## mgt-headers.h: bool ns3::MgtAddBaResponseHeader::IsImmediateBlockAck() const [member function] cls.add_method('IsImmediateBlockAck', 'bool', [], is_const=True) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::SetAmsduSupport(bool supported) [member function] cls.add_method('SetAmsduSupport', 'void', [param('bool', 'supported')]) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::SetBufferSize(uint16_t size) [member function] cls.add_method('SetBufferSize', 'void', [param('uint16_t', 'size')]) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::SetDelayedBlockAck() [member function] cls.add_method('SetDelayedBlockAck', 'void', []) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::SetImmediateBlockAck() [member function] cls.add_method('SetImmediateBlockAck', 'void', []) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::SetStatusCode(ns3::StatusCode code) [member function] cls.add_method('SetStatusCode', 'void', [param('ns3::StatusCode', 'code')]) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::SetTid(uint8_t tid) [member function] cls.add_method('SetTid', 'void', [param('uint8_t', 'tid')]) ## mgt-headers.h: void ns3::MgtAddBaResponseHeader::SetTimeout(uint16_t timeout) [member function] cls.add_method('SetTimeout', 'void', [param('uint16_t', 'timeout')]) return def register_Ns3MgtAssocRequestHeader_methods(root_module, cls): ## mgt-headers.h: ns3::MgtAssocRequestHeader::MgtAssocRequestHeader(ns3::MgtAssocRequestHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::MgtAssocRequestHeader const &', 'arg0')]) ## mgt-headers.h: ns3::MgtAssocRequestHeader::MgtAssocRequestHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: uint32_t ns3::MgtAssocRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mgt-headers.h: ns3::TypeId ns3::MgtAssocRequestHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint16_t ns3::MgtAssocRequestHeader::GetListenInterval() const [member function] cls.add_method('GetListenInterval', 'uint16_t', [], is_const=True) ## mgt-headers.h: uint32_t ns3::MgtAssocRequestHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mgt-headers.h: ns3::Ssid ns3::MgtAssocRequestHeader::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True) ## mgt-headers.h: ns3::SupportedRates ns3::MgtAssocRequestHeader::GetSupportedRates() const [member function] cls.add_method('GetSupportedRates', 'ns3::SupportedRates', [], is_const=True) ## mgt-headers.h: static ns3::TypeId ns3::MgtAssocRequestHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mgt-headers.h: void ns3::MgtAssocRequestHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtAssocRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtAssocRequestHeader::SetListenInterval(uint16_t interval) [member function] cls.add_method('SetListenInterval', 'void', [param('uint16_t', 'interval')]) ## mgt-headers.h: void ns3::MgtAssocRequestHeader::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')]) ## mgt-headers.h: void ns3::MgtAssocRequestHeader::SetSupportedRates(ns3::SupportedRates rates) [member function] cls.add_method('SetSupportedRates', 'void', [param('ns3::SupportedRates', 'rates')]) return def register_Ns3MgtAssocResponseHeader_methods(root_module, cls): ## mgt-headers.h: ns3::MgtAssocResponseHeader::MgtAssocResponseHeader(ns3::MgtAssocResponseHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::MgtAssocResponseHeader const &', 'arg0')]) ## mgt-headers.h: ns3::MgtAssocResponseHeader::MgtAssocResponseHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: uint32_t ns3::MgtAssocResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mgt-headers.h: ns3::TypeId ns3::MgtAssocResponseHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint32_t ns3::MgtAssocResponseHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mgt-headers.h: ns3::StatusCode ns3::MgtAssocResponseHeader::GetStatusCode() [member function] cls.add_method('GetStatusCode', 'ns3::StatusCode', []) ## mgt-headers.h: ns3::SupportedRates ns3::MgtAssocResponseHeader::GetSupportedRates() [member function] cls.add_method('GetSupportedRates', 'ns3::SupportedRates', []) ## mgt-headers.h: static ns3::TypeId ns3::MgtAssocResponseHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mgt-headers.h: void ns3::MgtAssocResponseHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtAssocResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtAssocResponseHeader::SetStatusCode(ns3::StatusCode code) [member function] cls.add_method('SetStatusCode', 'void', [param('ns3::StatusCode', 'code')]) ## mgt-headers.h: void ns3::MgtAssocResponseHeader::SetSupportedRates(ns3::SupportedRates rates) [member function] cls.add_method('SetSupportedRates', 'void', [param('ns3::SupportedRates', 'rates')]) return def register_Ns3MgtDelBaHeader_methods(root_module, cls): ## mgt-headers.h: ns3::MgtDelBaHeader::MgtDelBaHeader(ns3::MgtDelBaHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::MgtDelBaHeader const &', 'arg0')]) ## mgt-headers.h: ns3::MgtDelBaHeader::MgtDelBaHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: uint32_t ns3::MgtDelBaHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mgt-headers.h: ns3::TypeId ns3::MgtDelBaHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint32_t ns3::MgtDelBaHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint8_t ns3::MgtDelBaHeader::GetTid() const [member function] cls.add_method('GetTid', 'uint8_t', [], is_const=True) ## mgt-headers.h: static ns3::TypeId ns3::MgtDelBaHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mgt-headers.h: bool ns3::MgtDelBaHeader::IsByOriginator() const [member function] cls.add_method('IsByOriginator', 'bool', [], is_const=True) ## mgt-headers.h: void ns3::MgtDelBaHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtDelBaHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtDelBaHeader::SetByOriginator() [member function] cls.add_method('SetByOriginator', 'void', []) ## mgt-headers.h: void ns3::MgtDelBaHeader::SetByRecipient() [member function] cls.add_method('SetByRecipient', 'void', []) ## mgt-headers.h: void ns3::MgtDelBaHeader::SetTid(uint8_t arg0) [member function] cls.add_method('SetTid', 'void', [param('uint8_t', 'arg0')]) return def register_Ns3MgtProbeRequestHeader_methods(root_module, cls): ## mgt-headers.h: ns3::MgtProbeRequestHeader::MgtProbeRequestHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: ns3::MgtProbeRequestHeader::MgtProbeRequestHeader(ns3::MgtProbeRequestHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::MgtProbeRequestHeader const &', 'arg0')]) ## mgt-headers.h: uint32_t ns3::MgtProbeRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mgt-headers.h: ns3::TypeId ns3::MgtProbeRequestHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint32_t ns3::MgtProbeRequestHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mgt-headers.h: ns3::Ssid ns3::MgtProbeRequestHeader::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True) ## mgt-headers.h: ns3::SupportedRates ns3::MgtProbeRequestHeader::GetSupportedRates() const [member function] cls.add_method('GetSupportedRates', 'ns3::SupportedRates', [], is_const=True) ## mgt-headers.h: static ns3::TypeId ns3::MgtProbeRequestHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mgt-headers.h: void ns3::MgtProbeRequestHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtProbeRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtProbeRequestHeader::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')]) ## mgt-headers.h: void ns3::MgtProbeRequestHeader::SetSupportedRates(ns3::SupportedRates rates) [member function] cls.add_method('SetSupportedRates', 'void', [param('ns3::SupportedRates', 'rates')]) return def register_Ns3MgtProbeResponseHeader_methods(root_module, cls): ## mgt-headers.h: ns3::MgtProbeResponseHeader::MgtProbeResponseHeader(ns3::MgtProbeResponseHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::MgtProbeResponseHeader const &', 'arg0')]) ## mgt-headers.h: ns3::MgtProbeResponseHeader::MgtProbeResponseHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: uint32_t ns3::MgtProbeResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mgt-headers.h: uint64_t ns3::MgtProbeResponseHeader::GetBeaconIntervalUs() const [member function] cls.add_method('GetBeaconIntervalUs', 'uint64_t', [], is_const=True) ## mgt-headers.h: ns3::TypeId ns3::MgtProbeResponseHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint32_t ns3::MgtProbeResponseHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mgt-headers.h: ns3::Ssid ns3::MgtProbeResponseHeader::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True) ## mgt-headers.h: ns3::SupportedRates ns3::MgtProbeResponseHeader::GetSupportedRates() const [member function] cls.add_method('GetSupportedRates', 'ns3::SupportedRates', [], is_const=True) ## mgt-headers.h: uint64_t ns3::MgtProbeResponseHeader::GetTimestamp() [member function] cls.add_method('GetTimestamp', 'uint64_t', []) ## mgt-headers.h: static ns3::TypeId ns3::MgtProbeResponseHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mgt-headers.h: void ns3::MgtProbeResponseHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtProbeResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::MgtProbeResponseHeader::SetBeaconIntervalUs(uint64_t us) [member function] cls.add_method('SetBeaconIntervalUs', 'void', [param('uint64_t', 'us')]) ## mgt-headers.h: void ns3::MgtProbeResponseHeader::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')]) ## mgt-headers.h: void ns3::MgtProbeResponseHeader::SetSupportedRates(ns3::SupportedRates rates) [member function] cls.add_method('SetSupportedRates', 'void', [param('ns3::SupportedRates', 'rates')]) return def register_Ns3QosTag_methods(root_module, cls): ## qos-tag.h: ns3::QosTag::QosTag(ns3::QosTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::QosTag const &', 'arg0')]) ## qos-tag.h: ns3::QosTag::QosTag() [constructor] cls.add_constructor([]) ## qos-tag.h: ns3::QosTag::QosTag(uint8_t tid) [constructor] cls.add_constructor([param('uint8_t', 'tid')]) ## qos-tag.h: void ns3::QosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## qos-tag.h: ns3::TypeId ns3::QosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## qos-tag.h: uint32_t ns3::QosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## qos-tag.h: uint8_t ns3::QosTag::GetTid() const [member function] cls.add_method('GetTid', 'uint8_t', [], is_const=True) ## qos-tag.h: static ns3::TypeId ns3::QosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## qos-tag.h: void ns3::QosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## qos-tag.h: void ns3::QosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## qos-tag.h: void ns3::QosTag::SetTid(uint8_t tid) [member function] cls.add_method('SetTid', 'void', [param('uint8_t', 'tid')]) ## qos-tag.h: void ns3::QosTag::SetUserPriority(ns3::UserPriority up) [member function] cls.add_method('SetUserPriority', 'void', [param('ns3::UserPriority', 'up')]) return def register_Ns3WifiActionHeader_methods(root_module, cls): ## mgt-headers.h: ns3::WifiActionHeader::WifiActionHeader(ns3::WifiActionHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiActionHeader const &', 'arg0')]) ## mgt-headers.h: ns3::WifiActionHeader::WifiActionHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: uint32_t ns3::WifiActionHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue ns3::WifiActionHeader::GetAction() [member function] cls.add_method('GetAction', 'ns3::WifiActionHeader::ActionValue', []) ## mgt-headers.h: ns3::WifiActionHeader::CategoryValue ns3::WifiActionHeader::GetCategory() [member function] cls.add_method('GetCategory', 'ns3::WifiActionHeader::CategoryValue', []) ## mgt-headers.h: ns3::TypeId ns3::WifiActionHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## mgt-headers.h: uint32_t ns3::WifiActionHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## mgt-headers.h: static ns3::TypeId ns3::WifiActionHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mgt-headers.h: void ns3::WifiActionHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::WifiActionHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## mgt-headers.h: void ns3::WifiActionHeader::SetAction(ns3::WifiActionHeader::CategoryValue type, ns3::WifiActionHeader::ActionValue action) [member function] cls.add_method('SetAction', 'void', [param('ns3::WifiActionHeader::CategoryValue', 'type'), param('ns3::WifiActionHeader::ActionValue', 'action')]) return def register_Ns3WifiActionHeaderActionValue_methods(root_module, cls): ## mgt-headers.h: ns3::WifiActionHeader::ActionValue::ActionValue() [constructor] cls.add_constructor([]) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue::ActionValue(ns3::WifiActionHeader::ActionValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiActionHeader::ActionValue const &', 'arg0')]) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue::blockAck [variable] cls.add_instance_attribute('blockAck', 'ns3::WifiActionHeader::BlockAckActionValue', is_const=False) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue::interwork [variable] cls.add_instance_attribute('interwork', 'ns3::WifiActionHeader::InterworkActionValue', is_const=False) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue::linkMetrtic [variable] cls.add_instance_attribute('linkMetrtic', 'ns3::WifiActionHeader::LinkMetricActionValue', is_const=False) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue::pathSelection [variable] cls.add_instance_attribute('pathSelection', 'ns3::WifiActionHeader::PathSelectionActionValue', is_const=False) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue::peerLink [variable] cls.add_instance_attribute('peerLink', 'ns3::WifiActionHeader::PeerLinkMgtActionValue', is_const=False) ## mgt-headers.h: ns3::WifiActionHeader::ActionValue::resourceCoordination [variable] cls.add_instance_attribute('resourceCoordination', 'ns3::WifiActionHeader::ResourceCoordinationActionValue', is_const=False) return def register_Ns3WifiInformationElement_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('==') ## wifi-information-element.h: ns3::WifiInformationElement::WifiInformationElement() [constructor] cls.add_constructor([]) ## wifi-information-element.h: ns3::WifiInformationElement::WifiInformationElement(ns3::WifiInformationElement const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiInformationElement const &', 'arg0')]) ## wifi-information-element.h: ns3::Buffer::Iterator ns3::WifiInformationElement::Deserialize(ns3::Buffer::Iterator i) [member function] cls.add_method('Deserialize', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'i')]) ## wifi-information-element.h: ns3::Buffer::Iterator ns3::WifiInformationElement::DeserializeIfPresent(ns3::Buffer::Iterator i) [member function] cls.add_method('DeserializeIfPresent', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'i')]) ## wifi-information-element.h: uint8_t ns3::WifiInformationElement::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function] cls.add_method('DeserializeInformationField', 'uint8_t', [param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')], is_pure_virtual=True, is_virtual=True) ## wifi-information-element.h: ns3::WifiInformationElementId ns3::WifiInformationElement::ElementId() const [member function] cls.add_method('ElementId', 'ns3::WifiInformationElementId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-information-element.h: uint8_t ns3::WifiInformationElement::GetInformationFieldSize() const [member function] cls.add_method('GetInformationFieldSize', 'uint8_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-information-element.h: uint16_t ns3::WifiInformationElement::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint16_t', [], is_const=True) ## wifi-information-element.h: void ns3::WifiInformationElement::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wifi-information-element.h: ns3::Buffer::Iterator ns3::WifiInformationElement::Serialize(ns3::Buffer::Iterator i) const [member function] cls.add_method('Serialize', 'ns3::Buffer::Iterator', [param('ns3::Buffer::Iterator', 'i')], is_const=True) ## wifi-information-element.h: void ns3::WifiInformationElement::SerializeInformationField(ns3::Buffer::Iterator start) const [member function] cls.add_method('SerializeInformationField', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3WifiInformationElementVector_methods(root_module, cls): cls.add_binary_comparison_operator('==') ## wifi-information-element-vector.h: ns3::WifiInformationElementVector::WifiInformationElementVector(ns3::WifiInformationElementVector const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiInformationElementVector const &', 'arg0')]) ## wifi-information-element-vector.h: ns3::WifiInformationElementVector::WifiInformationElementVector() [constructor] cls.add_constructor([]) ## wifi-information-element-vector.h: bool ns3::WifiInformationElementVector::AddInformationElement(ns3::Ptr<ns3::WifiInformationElement> element) [member function] cls.add_method('AddInformationElement', 'bool', [param('ns3::Ptr< ns3::WifiInformationElement >', 'element')]) ## wifi-information-element-vector.h: __gnu_cxx::__normal_iterator<ns3::Ptr<ns3::WifiInformationElement>*,std::vector<ns3::Ptr<ns3::WifiInformationElement>, std::allocator<ns3::Ptr<ns3::WifiInformationElement> > > > ns3::WifiInformationElementVector::Begin() [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::WifiInformationElement >, std::vector< ns3::Ptr< ns3::WifiInformationElement > > >', []) ## wifi-information-element-vector.h: uint32_t ns3::WifiInformationElementVector::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wifi-information-element-vector.h: uint32_t ns3::WifiInformationElementVector::DeserializeSingleIe(ns3::Buffer::Iterator start) [member function] cls.add_method('DeserializeSingleIe', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wifi-information-element-vector.h: __gnu_cxx::__normal_iterator<ns3::Ptr<ns3::WifiInformationElement>*,std::vector<ns3::Ptr<ns3::WifiInformationElement>, std::allocator<ns3::Ptr<ns3::WifiInformationElement> > > > ns3::WifiInformationElementVector::End() [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::WifiInformationElement >, std::vector< ns3::Ptr< ns3::WifiInformationElement > > >', []) ## wifi-information-element-vector.h: ns3::Ptr<ns3::WifiInformationElement> ns3::WifiInformationElementVector::FindFirst(ns3::WifiInformationElementId id) const [member function] cls.add_method('FindFirst', 'ns3::Ptr< ns3::WifiInformationElement >', [param('ns3::WifiInformationElementId', 'id')], is_const=True) ## wifi-information-element-vector.h: ns3::TypeId ns3::WifiInformationElementVector::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wifi-information-element-vector.h: uint32_t ns3::WifiInformationElementVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wifi-information-element-vector.h: static ns3::TypeId ns3::WifiInformationElementVector::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wifi-information-element-vector.h: void ns3::WifiInformationElementVector::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wifi-information-element-vector.h: void ns3::WifiInformationElementVector::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## wifi-information-element-vector.h: void ns3::WifiInformationElementVector::SetMaxSize(uint16_t size) [member function] cls.add_method('SetMaxSize', 'void', [param('uint16_t', 'size')]) ## wifi-information-element-vector.h: uint32_t ns3::WifiInformationElementVector::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True, visibility='protected') return def register_Ns3WifiMac_methods(root_module, cls): ## wifi-mac.h: ns3::WifiMac::WifiMac() [constructor] cls.add_constructor([]) ## wifi-mac.h: ns3::WifiMac::WifiMac(ns3::WifiMac const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiMac const &', 'arg0')]) ## wifi-mac.h: void ns3::WifiMac::ConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('ConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')]) ## wifi-mac.h: void ns3::WifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetAckTimeout() const [member function] cls.add_method('GetAckTimeout', 'ns3::Time', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Mac48Address ns3::WifiMac::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Mac48Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetBasicBlockAckTimeout() const [member function] cls.add_method('GetBasicBlockAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Mac48Address ns3::WifiMac::GetBssid() const [member function] cls.add_method('GetBssid', 'ns3::Mac48Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetCompressedBlockAckTimeout() const [member function] cls.add_method('GetCompressedBlockAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetCtsTimeout() const [member function] cls.add_method('GetCtsTimeout', 'ns3::Time', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetEifsNoDifs() const [member function] cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetMaxPropagationDelay() const [member function] cls.add_method('GetMaxPropagationDelay', 'ns3::Time', [], is_const=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetMsduLifetime() const [member function] cls.add_method('GetMsduLifetime', 'ns3::Time', [], is_const=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetPifs() const [member function] cls.add_method('GetPifs', 'ns3::Time', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetSifs() const [member function] cls.add_method('GetSifs', 'ns3::Time', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Time ns3::WifiMac::GetSlot() const [member function] cls.add_method('GetSlot', 'ns3::Time', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: ns3::Ssid ns3::WifiMac::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: static ns3::TypeId ns3::WifiMac::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wifi-mac.h: void ns3::WifiMac::NotifyPromiscRx(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyPromiscRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-mac.h: void ns3::WifiMac::NotifyRx(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-mac.h: void ns3::WifiMac::NotifyRxDrop(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyRxDrop', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-mac.h: void ns3::WifiMac::NotifyTx(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyTx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-mac.h: void ns3::WifiMac::NotifyTxDrop(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyTxDrop', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-mac.h: void ns3::WifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function] cls.add_method('SetAckTimeout', 'void', [param('ns3::Time', 'ackTimeout')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetAddress(ns3::Mac48Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Mac48Address', 'address')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetBasicBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')], is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetCompressedBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')], is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function] cls.add_method('SetCtsTimeout', 'void', [param('ns3::Time', 'ctsTimeout')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function] cls.add_method('SetEifsNoDifs', 'void', [param('ns3::Time', 'eifsNoDifs')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function] cls.add_method('SetForwardUpCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function] cls.add_method('SetLinkDownCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function] cls.add_method('SetLinkUpCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetMaxPropagationDelay(ns3::Time delay) [member function] cls.add_method('SetMaxPropagationDelay', 'void', [param('ns3::Time', 'delay')]) ## wifi-mac.h: void ns3::WifiMac::SetPifs(ns3::Time pifs) [member function] cls.add_method('SetPifs', 'void', [param('ns3::Time', 'pifs')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetSlot(ns3::Time slotTime) [member function] cls.add_method('SetSlot', 'void', [param('ns3::Time', 'slotTime')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetWifiPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')], is_pure_virtual=True, is_virtual=True) ## wifi-mac.h: bool ns3::WifiMac::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-mac.h: void ns3::WifiMac::ConfigureCCHDcf(ns3::Ptr<ns3::Dcf> dcf, uint32_t cwmin, uint32_t cwmax, ns3::AcIndex ac) [member function] cls.add_method('ConfigureCCHDcf', 'void', [param('ns3::Ptr< ns3::Dcf >', 'dcf'), param('uint32_t', 'cwmin'), param('uint32_t', 'cwmax'), param('ns3::AcIndex', 'ac')], visibility='protected') ## wifi-mac.h: void ns3::WifiMac::ConfigureDcf(ns3::Ptr<ns3::Dcf> dcf, uint32_t cwmin, uint32_t cwmax, ns3::AcIndex ac) [member function] cls.add_method('ConfigureDcf', 'void', [param('ns3::Ptr< ns3::Dcf >', 'dcf'), param('uint32_t', 'cwmin'), param('uint32_t', 'cwmax'), param('ns3::AcIndex', 'ac')], visibility='protected') ## wifi-mac.h: void ns3::WifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('FinishConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3WifiMacHeader_methods(root_module, cls): ## wifi-mac-header.h: ns3::WifiMacHeader::WifiMacHeader(ns3::WifiMacHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiMacHeader const &', 'arg0')]) ## wifi-mac-header.h: ns3::WifiMacHeader::WifiMacHeader() [constructor] cls.add_constructor([]) ## wifi-mac-header.h: uint32_t ns3::WifiMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## wifi-mac-header.h: ns3::Mac48Address ns3::WifiMacHeader::GetAddr1() const [member function] cls.add_method('GetAddr1', 'ns3::Mac48Address', [], is_const=True) ## wifi-mac-header.h: ns3::Mac48Address ns3::WifiMacHeader::GetAddr2() const [member function] cls.add_method('GetAddr2', 'ns3::Mac48Address', [], is_const=True) ## wifi-mac-header.h: ns3::Mac48Address ns3::WifiMacHeader::GetAddr3() const [member function] cls.add_method('GetAddr3', 'ns3::Mac48Address', [], is_const=True) ## wifi-mac-header.h: ns3::Mac48Address ns3::WifiMacHeader::GetAddr4() const [member function] cls.add_method('GetAddr4', 'ns3::Mac48Address', [], is_const=True) ## wifi-mac-header.h: ns3::Time ns3::WifiMacHeader::GetDuration() const [member function] cls.add_method('GetDuration', 'ns3::Time', [], is_const=True) ## wifi-mac-header.h: uint16_t ns3::WifiMacHeader::GetFragmentNumber() const [member function] cls.add_method('GetFragmentNumber', 'uint16_t', [], is_const=True) ## wifi-mac-header.h: ns3::TypeId ns3::WifiMacHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## wifi-mac-header.h: ns3::WifiMacHeader::QosAckPolicy ns3::WifiMacHeader::GetQosAckPolicy() const [member function] cls.add_method('GetQosAckPolicy', 'ns3::WifiMacHeader::QosAckPolicy', [], is_const=True) ## wifi-mac-header.h: uint8_t ns3::WifiMacHeader::GetQosTid() const [member function] cls.add_method('GetQosTid', 'uint8_t', [], is_const=True) ## wifi-mac-header.h: uint8_t ns3::WifiMacHeader::GetQosTxopLimit() const [member function] cls.add_method('GetQosTxopLimit', 'uint8_t', [], is_const=True) ## wifi-mac-header.h: uint16_t ns3::WifiMacHeader::GetRawDuration() const [member function] cls.add_method('GetRawDuration', 'uint16_t', [], is_const=True) ## wifi-mac-header.h: uint16_t ns3::WifiMacHeader::GetSequenceControl() const [member function] cls.add_method('GetSequenceControl', 'uint16_t', [], is_const=True) ## wifi-mac-header.h: uint16_t ns3::WifiMacHeader::GetSequenceNumber() const [member function] cls.add_method('GetSequenceNumber', 'uint16_t', [], is_const=True) ## wifi-mac-header.h: uint32_t ns3::WifiMacHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## wifi-mac-header.h: uint32_t ns3::WifiMacHeader::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## wifi-mac-header.h: ns3::WifiMacType ns3::WifiMacHeader::GetType() const [member function] cls.add_method('GetType', 'ns3::WifiMacType', [], is_const=True) ## wifi-mac-header.h: static ns3::TypeId ns3::WifiMacHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wifi-mac-header.h: char const * ns3::WifiMacHeader::GetTypeString() const [member function] cls.add_method('GetTypeString', 'char const *', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsAck() const [member function] cls.add_method('IsAck', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsAction() const [member function] cls.add_method('IsAction', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsAssocReq() const [member function] cls.add_method('IsAssocReq', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsAssocResp() const [member function] cls.add_method('IsAssocResp', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsAuthentication() const [member function] cls.add_method('IsAuthentication', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsBeacon() const [member function] cls.add_method('IsBeacon', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsBlockAck() const [member function] cls.add_method('IsBlockAck', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsBlockAckReq() const [member function] cls.add_method('IsBlockAckReq', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsCfpoll() const [member function] cls.add_method('IsCfpoll', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsCtl() const [member function] cls.add_method('IsCtl', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsCts() const [member function] cls.add_method('IsCts', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsData() const [member function] cls.add_method('IsData', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsDeauthentication() const [member function] cls.add_method('IsDeauthentication', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsDisassociation() const [member function] cls.add_method('IsDisassociation', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsFromDs() const [member function] cls.add_method('IsFromDs', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsMgt() const [member function] cls.add_method('IsMgt', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsMoreFragments() const [member function] cls.add_method('IsMoreFragments', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsMultihopAction() const [member function] cls.add_method('IsMultihopAction', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsProbeReq() const [member function] cls.add_method('IsProbeReq', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsProbeResp() const [member function] cls.add_method('IsProbeResp', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsQosAck() const [member function] cls.add_method('IsQosAck', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsQosAmsdu() const [member function] cls.add_method('IsQosAmsdu', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsQosBlockAck() const [member function] cls.add_method('IsQosBlockAck', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsQosData() const [member function] cls.add_method('IsQosData', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsQosEosp() const [member function] cls.add_method('IsQosEosp', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsQosNoAck() const [member function] cls.add_method('IsQosNoAck', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsReassocReq() const [member function] cls.add_method('IsReassocReq', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsReassocResp() const [member function] cls.add_method('IsReassocResp', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsRetry() const [member function] cls.add_method('IsRetry', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsRts() const [member function] cls.add_method('IsRts', 'bool', [], is_const=True) ## wifi-mac-header.h: bool ns3::WifiMacHeader::IsToDs() const [member function] cls.add_method('IsToDs', 'bool', [], is_const=True) ## wifi-mac-header.h: void ns3::WifiMacHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## wifi-mac-header.h: void ns3::WifiMacHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetAction() [member function] cls.add_method('SetAction', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetAddr1(ns3::Mac48Address address) [member function] cls.add_method('SetAddr1', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetAddr2(ns3::Mac48Address address) [member function] cls.add_method('SetAddr2', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetAddr3(ns3::Mac48Address address) [member function] cls.add_method('SetAddr3', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetAddr4(ns3::Mac48Address address) [member function] cls.add_method('SetAddr4', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetAssocReq() [member function] cls.add_method('SetAssocReq', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetAssocResp() [member function] cls.add_method('SetAssocResp', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetBeacon() [member function] cls.add_method('SetBeacon', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetBlockAck() [member function] cls.add_method('SetBlockAck', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetBlockAckReq() [member function] cls.add_method('SetBlockAckReq', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetDsFrom() [member function] cls.add_method('SetDsFrom', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetDsNotFrom() [member function] cls.add_method('SetDsNotFrom', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetDsNotTo() [member function] cls.add_method('SetDsNotTo', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetDsTo() [member function] cls.add_method('SetDsTo', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetDuration(ns3::Time duration) [member function] cls.add_method('SetDuration', 'void', [param('ns3::Time', 'duration')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetFragmentNumber(uint8_t frag) [member function] cls.add_method('SetFragmentNumber', 'void', [param('uint8_t', 'frag')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetId(uint16_t id) [member function] cls.add_method('SetId', 'void', [param('uint16_t', 'id')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetMultihopAction() [member function] cls.add_method('SetMultihopAction', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetNoMoreFragments() [member function] cls.add_method('SetNoMoreFragments', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetNoRetry() [member function] cls.add_method('SetNoRetry', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetProbeReq() [member function] cls.add_method('SetProbeReq', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetProbeResp() [member function] cls.add_method('SetProbeResp', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosAckPolicy(ns3::WifiMacHeader::QosAckPolicy arg0) [member function] cls.add_method('SetQosAckPolicy', 'void', [param('ns3::WifiMacHeader::QosAckPolicy', 'arg0')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosAmsdu() [member function] cls.add_method('SetQosAmsdu', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosBlockAck() [member function] cls.add_method('SetQosBlockAck', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosEosp() [member function] cls.add_method('SetQosEosp', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosNoAck() [member function] cls.add_method('SetQosNoAck', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosNoAmsdu() [member function] cls.add_method('SetQosNoAmsdu', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosNoEosp() [member function] cls.add_method('SetQosNoEosp', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosNormalAck() [member function] cls.add_method('SetQosNormalAck', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosTid(uint8_t tid) [member function] cls.add_method('SetQosTid', 'void', [param('uint8_t', 'tid')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetQosTxopLimit(uint8_t txop) [member function] cls.add_method('SetQosTxopLimit', 'void', [param('uint8_t', 'txop')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetRawDuration(uint16_t duration) [member function] cls.add_method('SetRawDuration', 'void', [param('uint16_t', 'duration')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetRetry() [member function] cls.add_method('SetRetry', 'void', []) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetSequenceNumber(uint16_t seq) [member function] cls.add_method('SetSequenceNumber', 'void', [param('uint16_t', 'seq')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetType(ns3::WifiMacType type) [member function] cls.add_method('SetType', 'void', [param('ns3::WifiMacType', 'type')]) ## wifi-mac-header.h: void ns3::WifiMacHeader::SetTypeData() [member function] cls.add_method('SetTypeData', 'void', []) return def register_Ns3WifiPhy_methods(root_module, cls): ## wifi-phy.h: ns3::WifiPhy::WifiPhy(ns3::WifiPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiPhy const &', 'arg0')]) ## wifi-phy.h: ns3::WifiPhy::WifiPhy() [constructor] cls.add_constructor([]) ## wifi-phy.h: double ns3::WifiPhy::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function] cls.add_method('CalculateSnr', 'double', [param('ns3::WifiMode', 'txMode'), param('double', 'ber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: ns3::Time ns3::WifiPhy::CalculateTxDuration(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) const [member function] cls.add_method('CalculateTxDuration', 'ns3::Time', [param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhy::ConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('ConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: ns3::Ptr<ns3::WifiChannel> ns3::WifiPhy::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::WifiChannel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: uint16_t ns3::WifiPhy::GetChannelNumber() const [member function] cls.add_method('GetChannelNumber', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: ns3::Time ns3::WifiPhy::GetDelayUntilIdle() [member function] cls.add_method('GetDelayUntilIdle', 'ns3::Time', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetDsssRate11Mbps() [member function] cls.add_method('GetDsssRate11Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetDsssRate1Mbps() [member function] cls.add_method('GetDsssRate1Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetDsssRate2Mbps() [member function] cls.add_method('GetDsssRate2Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetDsssRate5_5Mbps() [member function] cls.add_method('GetDsssRate5_5Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: ns3::Time ns3::WifiPhy::GetLastRxStartTime() const [member function] cls.add_method('GetLastRxStartTime', 'ns3::Time', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: ns3::WifiMode ns3::WifiPhy::GetMode(uint32_t mode) const [member function] cls.add_method('GetMode', 'ns3::WifiMode', [param('uint32_t', 'mode')], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: uint32_t ns3::WifiPhy::GetNModes() const [member function] cls.add_method('GetNModes', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: uint32_t ns3::WifiPhy::GetNTxPower() const [member function] cls.add_method('GetNTxPower', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12Mbps() [member function] cls.add_method('GetOfdmRate12Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate12MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate12MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate13_5MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate13_5MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18Mbps() [member function] cls.add_method('GetOfdmRate18Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate18MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate1_5MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate1_5MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24Mbps() [member function] cls.add_method('GetOfdmRate24Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate24MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate27MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate27MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate2_25MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate2_25MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate36Mbps() [member function] cls.add_method('GetOfdmRate36Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate3MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate3MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate48Mbps() [member function] cls.add_method('GetOfdmRate48Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate4_5MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate4_5MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate54Mbps() [member function] cls.add_method('GetOfdmRate54Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6Mbps() [member function] cls.add_method('GetOfdmRate6Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate6MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate6MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9Mbps() [member function] cls.add_method('GetOfdmRate9Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate9MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate9MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h: ns3::Time ns3::WifiPhy::GetStateDuration() [member function] cls.add_method('GetStateDuration', 'ns3::Time', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: double ns3::WifiPhy::GetTxPowerEnd() const [member function] cls.add_method('GetTxPowerEnd', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: double ns3::WifiPhy::GetTxPowerStart() const [member function] cls.add_method('GetTxPowerStart', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h: static ns3::TypeId ns3::WifiPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wifi-phy.h: bool ns3::WifiPhy::IsStateBusy() [member function] cls.add_method('IsStateBusy', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: bool ns3::WifiPhy::IsStateCcaBusy() [member function] cls.add_method('IsStateCcaBusy', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: bool ns3::WifiPhy::IsStateIdle() [member function] cls.add_method('IsStateIdle', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: bool ns3::WifiPhy::IsStateRx() [member function] cls.add_method('IsStateRx', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: bool ns3::WifiPhy::IsStateSwitching() [member function] cls.add_method('IsStateSwitching', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: bool ns3::WifiPhy::IsStateTx() [member function] cls.add_method('IsStateTx', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhy::NotifyPromiscSniffRx(ns3::Ptr<ns3::Packet const> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble, double signalDbm, double noiseDbm) [member function] cls.add_method('NotifyPromiscSniffRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble'), param('double', 'signalDbm'), param('double', 'noiseDbm')]) ## wifi-phy.h: void ns3::WifiPhy::NotifyPromiscSniffTx(ns3::Ptr<ns3::Packet const> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble) [member function] cls.add_method('NotifyPromiscSniffTx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble')]) ## wifi-phy.h: void ns3::WifiPhy::NotifyRxBegin(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyRxBegin', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h: void ns3::WifiPhy::NotifyRxDrop(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyRxDrop', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h: void ns3::WifiPhy::NotifyRxEnd(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyRxEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h: void ns3::WifiPhy::NotifyTxBegin(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyTxBegin', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h: void ns3::WifiPhy::NotifyTxDrop(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyTxDrop', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h: void ns3::WifiPhy::NotifyTxEnd(ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NotifyTxEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h: void ns3::WifiPhy::RegisterListener(ns3::WifiPhyListener * listener) [member function] cls.add_method('RegisterListener', 'void', [param('ns3::WifiPhyListener *', 'listener')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhy::SendPacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPowerLevel) [member function] cls.add_method('SendPacket', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPowerLevel')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhy::SetChannelNumber(uint16_t id) [member function] cls.add_method('SetChannelNumber', 'void', [param('uint16_t', 'id')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhy::SetReceiveErrorCallback(ns3::Callback<void,ns3::Ptr<const ns3::Packet>,double,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('SetReceiveErrorCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h: void ns3::WifiPhy::SetReceiveOkCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,double,ns3::WifiMode,ns3::WifiPreamble,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('SetReceiveOkCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::WifiMode, ns3::WifiPreamble, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) return def register_Ns3WifiRemoteStationManager_methods(root_module, cls): ## wifi-remote-station-manager.h: ns3::WifiRemoteStationManager::WifiRemoteStationManager(ns3::WifiRemoteStationManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiRemoteStationManager const &', 'arg0')]) ## wifi-remote-station-manager.h: ns3::WifiRemoteStationManager::WifiRemoteStationManager() [constructor] cls.add_constructor([]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::AddBasicMode(ns3::WifiMode mode) [member function] cls.add_method('AddBasicMode', 'void', [param('ns3::WifiMode', 'mode')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::AddSupportedMode(ns3::Mac48Address address, ns3::WifiMode mode) [member function] cls.add_method('AddSupportedMode', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'mode')]) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::GetAckMode(ns3::Mac48Address address, ns3::WifiMode dataMode) [member function] cls.add_method('GetAckMode', 'ns3::WifiMode', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'dataMode')]) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::GetBasicMode(uint32_t i) const [member function] cls.add_method('GetBasicMode', 'ns3::WifiMode', [param('uint32_t', 'i')], is_const=True) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::GetCtsMode(ns3::Mac48Address address, ns3::WifiMode rtsMode) [member function] cls.add_method('GetCtsMode', 'ns3::WifiMode', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'rtsMode')]) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::GetDataMode(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fullPacketSize) [member function] cls.add_method('GetDataMode', 'ns3::WifiMode', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fullPacketSize')]) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::GetDefaultMode() const [member function] cls.add_method('GetDefaultMode', 'ns3::WifiMode', [], is_const=True) ## wifi-remote-station-manager.h: uint32_t ns3::WifiRemoteStationManager::GetFragmentOffset(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function] cls.add_method('GetFragmentOffset', 'uint32_t', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')]) ## wifi-remote-station-manager.h: uint32_t ns3::WifiRemoteStationManager::GetFragmentSize(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function] cls.add_method('GetFragmentSize', 'uint32_t', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')]) ## wifi-remote-station-manager.h: uint32_t ns3::WifiRemoteStationManager::GetFragmentationThreshold() const [member function] cls.add_method('GetFragmentationThreshold', 'uint32_t', [], is_const=True) ## wifi-remote-station-manager.h: ns3::WifiRemoteStationInfo ns3::WifiRemoteStationManager::GetInfo(ns3::Mac48Address address) [member function] cls.add_method('GetInfo', 'ns3::WifiRemoteStationInfo', [param('ns3::Mac48Address', 'address')]) ## wifi-remote-station-manager.h: uint32_t ns3::WifiRemoteStationManager::GetMaxSlrc() const [member function] cls.add_method('GetMaxSlrc', 'uint32_t', [], is_const=True) ## wifi-remote-station-manager.h: uint32_t ns3::WifiRemoteStationManager::GetMaxSsrc() const [member function] cls.add_method('GetMaxSsrc', 'uint32_t', [], is_const=True) ## wifi-remote-station-manager.h: uint32_t ns3::WifiRemoteStationManager::GetNBasicModes() const [member function] cls.add_method('GetNBasicModes', 'uint32_t', [], is_const=True) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::GetNonUnicastMode() const [member function] cls.add_method('GetNonUnicastMode', 'ns3::WifiMode', [], is_const=True) ## wifi-remote-station-manager.h: uint32_t ns3::WifiRemoteStationManager::GetRtsCtsThreshold() const [member function] cls.add_method('GetRtsCtsThreshold', 'uint32_t', [], is_const=True) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::GetRtsMode(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('GetRtsMode', 'ns3::WifiMode', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-remote-station-manager.h: static ns3::TypeId ns3::WifiRemoteStationManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::IsAssociated(ns3::Mac48Address address) const [member function] cls.add_method('IsAssociated', 'bool', [param('ns3::Mac48Address', 'address')], is_const=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::IsBrandNew(ns3::Mac48Address address) const [member function] cls.add_method('IsBrandNew', 'bool', [param('ns3::Mac48Address', 'address')], is_const=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::IsLastFragment(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function] cls.add_method('IsLastFragment', 'bool', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')]) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::IsWaitAssocTxOk(ns3::Mac48Address address) const [member function] cls.add_method('IsWaitAssocTxOk', 'bool', [param('ns3::Mac48Address', 'address')], is_const=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::NeedDataRetransmission(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NeedDataRetransmission', 'bool', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::NeedFragmentation(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NeedFragmentation', 'bool', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::NeedRts(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NeedRts', 'bool', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::NeedRtsRetransmission(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function] cls.add_method('NeedRtsRetransmission', 'bool', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::PrepareForQueue(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fullPacketSize) [member function] cls.add_method('PrepareForQueue', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fullPacketSize')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::RecordDisassociated(ns3::Mac48Address address) [member function] cls.add_method('RecordDisassociated', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::RecordGotAssocTxFailed(ns3::Mac48Address address) [member function] cls.add_method('RecordGotAssocTxFailed', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::RecordGotAssocTxOk(ns3::Mac48Address address) [member function] cls.add_method('RecordGotAssocTxOk', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::RecordWaitAssocTxOk(ns3::Mac48Address address) [member function] cls.add_method('RecordWaitAssocTxOk', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::ReportDataFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function] cls.add_method('ReportDataFailed', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::ReportDataOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('ReportDataOk', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::ReportFinalDataFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function] cls.add_method('ReportFinalDataFailed', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::ReportFinalRtsFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function] cls.add_method('ReportFinalRtsFailed', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::ReportRtsFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function] cls.add_method('ReportRtsFailed', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::ReportRtsOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('ReportRtsOk', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::ReportRxOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('ReportRxOk', 'void', [param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::Reset() [member function] cls.add_method('Reset', 'void', []) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::Reset(ns3::Mac48Address address) [member function] cls.add_method('Reset', 'void', [param('ns3::Mac48Address', 'address')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::SetFragmentationThreshold(uint32_t threshold) [member function] cls.add_method('SetFragmentationThreshold', 'void', [param('uint32_t', 'threshold')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::SetMaxSlrc(uint32_t maxSlrc) [member function] cls.add_method('SetMaxSlrc', 'void', [param('uint32_t', 'maxSlrc')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::SetMaxSsrc(uint32_t maxSsrc) [member function] cls.add_method('SetMaxSsrc', 'void', [param('uint32_t', 'maxSsrc')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::SetRtsCtsThreshold(uint32_t threshold) [member function] cls.add_method('SetRtsCtsThreshold', 'void', [param('uint32_t', 'threshold')]) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetupPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## wifi-remote-station-manager.h: uint32_t ns3::WifiRemoteStationManager::GetNSupported(ns3::WifiRemoteStation const * station) const [member function] cls.add_method('GetNSupported', 'uint32_t', [param('ns3::WifiRemoteStation const *', 'station')], is_const=True, visibility='protected') ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::GetSupported(ns3::WifiRemoteStation const * station, uint32_t i) const [member function] cls.add_method('GetSupported', 'ns3::WifiMode', [param('ns3::WifiRemoteStation const *', 'station'), param('uint32_t', 'i')], is_const=True, visibility='protected') ## wifi-remote-station-manager.h: ns3::WifiRemoteStation * ns3::WifiRemoteStationManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: ns3::WifiMode ns3::WifiRemoteStationManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::DoNeedDataRetransmission(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function] cls.add_method('DoNeedDataRetransmission', 'bool', [param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')], visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::DoNeedFragmentation(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function] cls.add_method('DoNeedFragmentation', 'bool', [param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')], visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function] cls.add_method('DoNeedRts', 'bool', [param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')], visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::DoNeedRtsRetransmission(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function] cls.add_method('DoNeedRtsRetransmission', 'bool', [param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')], visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: void ns3::WifiRemoteStationManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], is_pure_virtual=True, visibility='private', is_virtual=True) ## wifi-remote-station-manager.h: bool ns3::WifiRemoteStationManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3YansWifiPhy_methods(root_module, cls): ## yans-wifi-phy.h: static ns3::TypeId ns3::YansWifiPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## yans-wifi-phy.h: ns3::YansWifiPhy::YansWifiPhy() [constructor] cls.add_constructor([]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetChannel(ns3::Ptr<ns3::YansWifiChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::YansWifiChannel >', 'channel')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetChannelNumber(uint16_t id) [member function] cls.add_method('SetChannelNumber', 'void', [param('uint16_t', 'id')], is_virtual=True) ## yans-wifi-phy.h: uint16_t ns3::YansWifiPhy::GetChannelNumber() const [member function] cls.add_method('GetChannelNumber', 'uint16_t', [], is_const=True, is_virtual=True) ## yans-wifi-phy.h: double ns3::YansWifiPhy::GetChannelFrequencyMhz() const [member function] cls.add_method('GetChannelFrequencyMhz', 'double', [], is_const=True) ## yans-wifi-phy.h: void ns3::YansWifiPhy::StartReceivePacket(ns3::Ptr<ns3::Packet> packet, double rxPowerDbm, ns3::WifiMode mode, ns3::WifiPreamble preamble) [member function] cls.add_method('StartReceivePacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDbm'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetRxNoiseFigure(double noiseFigureDb) [member function] cls.add_method('SetRxNoiseFigure', 'void', [param('double', 'noiseFigureDb')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetTxPowerStart(double start) [member function] cls.add_method('SetTxPowerStart', 'void', [param('double', 'start')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetTxPowerEnd(double end) [member function] cls.add_method('SetTxPowerEnd', 'void', [param('double', 'end')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetNTxPower(uint32_t n) [member function] cls.add_method('SetNTxPower', 'void', [param('uint32_t', 'n')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetTxGain(double gain) [member function] cls.add_method('SetTxGain', 'void', [param('double', 'gain')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetRxGain(double gain) [member function] cls.add_method('SetRxGain', 'void', [param('double', 'gain')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetEdThreshold(double threshold) [member function] cls.add_method('SetEdThreshold', 'void', [param('double', 'threshold')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetCcaMode1Threshold(double threshold) [member function] cls.add_method('SetCcaMode1Threshold', 'void', [param('double', 'threshold')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetErrorRateModel(ns3::Ptr<ns3::ErrorRateModel> rate) [member function] cls.add_method('SetErrorRateModel', 'void', [param('ns3::Ptr< ns3::ErrorRateModel >', 'rate')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetDevice(ns3::Ptr<ns3::Object> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::Object >', 'device')]) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetMobility(ns3::Ptr<ns3::Object> mobility) [member function] cls.add_method('SetMobility', 'void', [param('ns3::Ptr< ns3::Object >', 'mobility')]) ## yans-wifi-phy.h: double ns3::YansWifiPhy::GetRxNoiseFigure() const [member function] cls.add_method('GetRxNoiseFigure', 'double', [], is_const=True) ## yans-wifi-phy.h: double ns3::YansWifiPhy::GetTxGain() const [member function] cls.add_method('GetTxGain', 'double', [], is_const=True) ## yans-wifi-phy.h: double ns3::YansWifiPhy::GetRxGain() const [member function] cls.add_method('GetRxGain', 'double', [], is_const=True) ## yans-wifi-phy.h: double ns3::YansWifiPhy::GetEdThreshold() const [member function] cls.add_method('GetEdThreshold', 'double', [], is_const=True) ## yans-wifi-phy.h: double ns3::YansWifiPhy::GetCcaMode1Threshold() const [member function] cls.add_method('GetCcaMode1Threshold', 'double', [], is_const=True) ## yans-wifi-phy.h: ns3::Ptr<ns3::ErrorRateModel> ns3::YansWifiPhy::GetErrorRateModel() const [member function] cls.add_method('GetErrorRateModel', 'ns3::Ptr< ns3::ErrorRateModel >', [], is_const=True) ## yans-wifi-phy.h: ns3::Ptr<ns3::Object> ns3::YansWifiPhy::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## yans-wifi-phy.h: ns3::Ptr<ns3::Object> ns3::YansWifiPhy::GetMobility() [member function] cls.add_method('GetMobility', 'ns3::Ptr< ns3::Object >', []) ## yans-wifi-phy.h: double ns3::YansWifiPhy::GetTxPowerStart() const [member function] cls.add_method('GetTxPowerStart', 'double', [], is_const=True, is_virtual=True) ## yans-wifi-phy.h: double ns3::YansWifiPhy::GetTxPowerEnd() const [member function] cls.add_method('GetTxPowerEnd', 'double', [], is_const=True, is_virtual=True) ## yans-wifi-phy.h: uint32_t ns3::YansWifiPhy::GetNTxPower() const [member function] cls.add_method('GetNTxPower', 'uint32_t', [], is_const=True, is_virtual=True) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetReceiveOkCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,double,ns3::WifiMode,ns3::WifiPreamble,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('SetReceiveOkCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::WifiMode, ns3::WifiPreamble, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SetReceiveErrorCallback(ns3::Callback<void,ns3::Ptr<const ns3::Packet>,double,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('SetReceiveErrorCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## yans-wifi-phy.h: void ns3::YansWifiPhy::SendPacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPowerLevel) [member function] cls.add_method('SendPacket', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPowerLevel')], is_virtual=True) ## yans-wifi-phy.h: void ns3::YansWifiPhy::RegisterListener(ns3::WifiPhyListener * listener) [member function] cls.add_method('RegisterListener', 'void', [param('ns3::WifiPhyListener *', 'listener')], is_virtual=True) ## yans-wifi-phy.h: bool ns3::YansWifiPhy::IsStateCcaBusy() [member function] cls.add_method('IsStateCcaBusy', 'bool', [], is_virtual=True) ## yans-wifi-phy.h: bool ns3::YansWifiPhy::IsStateIdle() [member function] cls.add_method('IsStateIdle', 'bool', [], is_virtual=True) ## yans-wifi-phy.h: bool ns3::YansWifiPhy::IsStateBusy() [member function] cls.add_method('IsStateBusy', 'bool', [], is_virtual=True) ## yans-wifi-phy.h: bool ns3::YansWifiPhy::IsStateRx() [member function] cls.add_method('IsStateRx', 'bool', [], is_virtual=True) ## yans-wifi-phy.h: bool ns3::YansWifiPhy::IsStateTx() [member function] cls.add_method('IsStateTx', 'bool', [], is_virtual=True) ## yans-wifi-phy.h: bool ns3::YansWifiPhy::IsStateSwitching() [member function] cls.add_method('IsStateSwitching', 'bool', [], is_virtual=True) ## yans-wifi-phy.h: ns3::Time ns3::YansWifiPhy::GetStateDuration() [member function] cls.add_method('GetStateDuration', 'ns3::Time', [], is_virtual=True) ## yans-wifi-phy.h: ns3::Time ns3::YansWifiPhy::GetDelayUntilIdle() [member function] cls.add_method('GetDelayUntilIdle', 'ns3::Time', [], is_virtual=True) ## yans-wifi-phy.h: ns3::Time ns3::YansWifiPhy::GetLastRxStartTime() const [member function] cls.add_method('GetLastRxStartTime', 'ns3::Time', [], is_const=True, is_virtual=True) ## yans-wifi-phy.h: ns3::Time ns3::YansWifiPhy::CalculateTxDuration(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) const [member function] cls.add_method('CalculateTxDuration', 'ns3::Time', [param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_const=True, is_virtual=True) ## yans-wifi-phy.h: uint32_t ns3::YansWifiPhy::GetNModes() const [member function] cls.add_method('GetNModes', 'uint32_t', [], is_const=True, is_virtual=True) ## yans-wifi-phy.h: ns3::WifiMode ns3::YansWifiPhy::GetMode(uint32_t mode) const [member function] cls.add_method('GetMode', 'ns3::WifiMode', [param('uint32_t', 'mode')], is_const=True, is_virtual=True) ## yans-wifi-phy.h: double ns3::YansWifiPhy::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function] cls.add_method('CalculateSnr', 'double', [param('ns3::WifiMode', 'txMode'), param('double', 'ber')], is_const=True, is_virtual=True) ## yans-wifi-phy.h: ns3::Ptr<ns3::WifiChannel> ns3::YansWifiPhy::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::WifiChannel >', [], is_const=True, is_virtual=True) ## yans-wifi-phy.h: void ns3::YansWifiPhy::ConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('ConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], is_virtual=True) ## yans-wifi-phy.h: void ns3::YansWifiPhy::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3AarfWifiManager_methods(root_module, cls): ## aarf-wifi-manager.h: ns3::AarfWifiManager::AarfWifiManager(ns3::AarfWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::AarfWifiManager const &', 'arg0')]) ## aarf-wifi-manager.h: ns3::AarfWifiManager::AarfWifiManager() [constructor] cls.add_constructor([]) ## aarf-wifi-manager.h: static ns3::TypeId ns3::AarfWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aarf-wifi-manager.h: ns3::WifiRemoteStation * ns3::AarfWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## aarf-wifi-manager.h: ns3::WifiMode ns3::AarfWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: ns3::WifiMode ns3::AarfWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: void ns3::AarfWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: void ns3::AarfWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: void ns3::AarfWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: void ns3::AarfWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: void ns3::AarfWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: void ns3::AarfWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: void ns3::AarfWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## aarf-wifi-manager.h: bool ns3::AarfWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3AarfcdWifiManager_methods(root_module, cls): ## aarfcd-wifi-manager.h: ns3::AarfcdWifiManager::AarfcdWifiManager(ns3::AarfcdWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::AarfcdWifiManager const &', 'arg0')]) ## aarfcd-wifi-manager.h: ns3::AarfcdWifiManager::AarfcdWifiManager() [constructor] cls.add_constructor([]) ## aarfcd-wifi-manager.h: static ns3::TypeId ns3::AarfcdWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aarfcd-wifi-manager.h: ns3::WifiRemoteStation * ns3::AarfcdWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: ns3::WifiMode ns3::AarfcdWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: ns3::WifiMode ns3::AarfcdWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: bool ns3::AarfcdWifiManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function] cls.add_method('DoNeedRts', 'bool', [param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: void ns3::AarfcdWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: void ns3::AarfcdWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: void ns3::AarfcdWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: void ns3::AarfcdWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: void ns3::AarfcdWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: void ns3::AarfcdWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: void ns3::AarfcdWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## aarfcd-wifi-manager.h: bool ns3::AarfcdWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3AdhocWifiMac_methods(root_module, cls): ## adhoc-wifi-mac.h: static ns3::TypeId ns3::AdhocWifiMac::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## adhoc-wifi-mac.h: ns3::AdhocWifiMac::AdhocWifiMac() [constructor] cls.add_constructor([]) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetSlot(ns3::Time slotTime) [member function] cls.add_method('SetSlot', 'void', [param('ns3::Time', 'slotTime')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function] cls.add_method('SetEifsNoDifs', 'void', [param('ns3::Time', 'eifsNoDifs')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function] cls.add_method('SetAckTimeout', 'void', [param('ns3::Time', 'ackTimeout')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function] cls.add_method('SetCtsTimeout', 'void', [param('ns3::Time', 'ctsTimeout')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetPifs(ns3::Time pifs) [member function] cls.add_method('SetPifs', 'void', [param('ns3::Time', 'pifs')], is_virtual=True) ## adhoc-wifi-mac.h: ns3::Time ns3::AdhocWifiMac::GetSlot() const [member function] cls.add_method('GetSlot', 'ns3::Time', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: ns3::Time ns3::AdhocWifiMac::GetSifs() const [member function] cls.add_method('GetSifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: ns3::Time ns3::AdhocWifiMac::GetEifsNoDifs() const [member function] cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: ns3::Time ns3::AdhocWifiMac::GetAckTimeout() const [member function] cls.add_method('GetAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: ns3::Time ns3::AdhocWifiMac::GetCtsTimeout() const [member function] cls.add_method('GetCtsTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: ns3::Time ns3::AdhocWifiMac::GetPifs() const [member function] cls.add_method('GetPifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetWifiPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')], is_virtual=True) ## adhoc-wifi-mac.h: bool ns3::AdhocWifiMac::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function] cls.add_method('SetForwardUpCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function] cls.add_method('SetLinkUpCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function] cls.add_method('SetLinkDownCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')], is_virtual=True) ## adhoc-wifi-mac.h: ns3::Mac48Address ns3::AdhocWifiMac::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: ns3::Ssid ns3::AdhocWifiMac::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetAddress(ns3::Mac48Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Mac48Address', 'address')], is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')], is_virtual=True) ## adhoc-wifi-mac.h: ns3::Mac48Address ns3::AdhocWifiMac::GetBssid() const [member function] cls.add_method('GetBssid', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) ## adhoc-wifi-mac.h: void ns3::AdhocWifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('FinishConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], visibility='private', is_virtual=True) return def register_Ns3AmrrWifiManager_methods(root_module, cls): ## amrr-wifi-manager.h: ns3::AmrrWifiManager::AmrrWifiManager(ns3::AmrrWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::AmrrWifiManager const &', 'arg0')]) ## amrr-wifi-manager.h: ns3::AmrrWifiManager::AmrrWifiManager() [constructor] cls.add_constructor([]) ## amrr-wifi-manager.h: static ns3::TypeId ns3::AmrrWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## amrr-wifi-manager.h: ns3::WifiRemoteStation * ns3::AmrrWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## amrr-wifi-manager.h: ns3::WifiMode ns3::AmrrWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: ns3::WifiMode ns3::AmrrWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: void ns3::AmrrWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: void ns3::AmrrWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: void ns3::AmrrWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: void ns3::AmrrWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: void ns3::AmrrWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: void ns3::AmrrWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: void ns3::AmrrWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## amrr-wifi-manager.h: bool ns3::AmrrWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3AmsduSubframeHeader_methods(root_module, cls): ## amsdu-subframe-header.h: ns3::AmsduSubframeHeader::AmsduSubframeHeader(ns3::AmsduSubframeHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::AmsduSubframeHeader const &', 'arg0')]) ## amsdu-subframe-header.h: ns3::AmsduSubframeHeader::AmsduSubframeHeader() [constructor] cls.add_constructor([]) ## amsdu-subframe-header.h: uint32_t ns3::AmsduSubframeHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## amsdu-subframe-header.h: ns3::Mac48Address ns3::AmsduSubframeHeader::GetDestinationAddr() const [member function] cls.add_method('GetDestinationAddr', 'ns3::Mac48Address', [], is_const=True) ## amsdu-subframe-header.h: ns3::TypeId ns3::AmsduSubframeHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## amsdu-subframe-header.h: uint16_t ns3::AmsduSubframeHeader::GetLength() const [member function] cls.add_method('GetLength', 'uint16_t', [], is_const=True) ## amsdu-subframe-header.h: uint32_t ns3::AmsduSubframeHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## amsdu-subframe-header.h: ns3::Mac48Address ns3::AmsduSubframeHeader::GetSourceAddr() const [member function] cls.add_method('GetSourceAddr', 'ns3::Mac48Address', [], is_const=True) ## amsdu-subframe-header.h: static ns3::TypeId ns3::AmsduSubframeHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## amsdu-subframe-header.h: void ns3::AmsduSubframeHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## amsdu-subframe-header.h: void ns3::AmsduSubframeHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## amsdu-subframe-header.h: void ns3::AmsduSubframeHeader::SetDestinationAddr(ns3::Mac48Address to) [member function] cls.add_method('SetDestinationAddr', 'void', [param('ns3::Mac48Address', 'to')]) ## amsdu-subframe-header.h: void ns3::AmsduSubframeHeader::SetLength(uint16_t arg0) [member function] cls.add_method('SetLength', 'void', [param('uint16_t', 'arg0')]) ## amsdu-subframe-header.h: void ns3::AmsduSubframeHeader::SetSourceAddr(ns3::Mac48Address to) [member function] cls.add_method('SetSourceAddr', 'void', [param('ns3::Mac48Address', 'to')]) return def register_Ns3ArfWifiManager_methods(root_module, cls): ## arf-wifi-manager.h: ns3::ArfWifiManager::ArfWifiManager(ns3::ArfWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::ArfWifiManager const &', 'arg0')]) ## arf-wifi-manager.h: ns3::ArfWifiManager::ArfWifiManager() [constructor] cls.add_constructor([]) ## arf-wifi-manager.h: static ns3::TypeId ns3::ArfWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## arf-wifi-manager.h: ns3::WifiRemoteStation * ns3::ArfWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## arf-wifi-manager.h: ns3::WifiMode ns3::ArfWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: ns3::WifiMode ns3::ArfWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: void ns3::ArfWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: void ns3::ArfWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: void ns3::ArfWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: void ns3::ArfWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: void ns3::ArfWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: void ns3::ArfWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: void ns3::ArfWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## arf-wifi-manager.h: bool ns3::ArfWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3CaraWifiManager_methods(root_module, cls): ## cara-wifi-manager.h: ns3::CaraWifiManager::CaraWifiManager(ns3::CaraWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::CaraWifiManager const &', 'arg0')]) ## cara-wifi-manager.h: ns3::CaraWifiManager::CaraWifiManager() [constructor] cls.add_constructor([]) ## cara-wifi-manager.h: static ns3::TypeId ns3::CaraWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## cara-wifi-manager.h: ns3::WifiRemoteStation * ns3::CaraWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## cara-wifi-manager.h: ns3::WifiMode ns3::CaraWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: ns3::WifiMode ns3::CaraWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: bool ns3::CaraWifiManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function] cls.add_method('DoNeedRts', 'bool', [param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: void ns3::CaraWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: void ns3::CaraWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: void ns3::CaraWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: void ns3::CaraWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: void ns3::CaraWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: void ns3::CaraWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: void ns3::CaraWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## cara-wifi-manager.h: bool ns3::CaraWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3ConstantRateWifiManager_methods(root_module, cls): ## constant-rate-wifi-manager.h: ns3::ConstantRateWifiManager::ConstantRateWifiManager(ns3::ConstantRateWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantRateWifiManager const &', 'arg0')]) ## constant-rate-wifi-manager.h: ns3::ConstantRateWifiManager::ConstantRateWifiManager() [constructor] cls.add_constructor([]) ## constant-rate-wifi-manager.h: static ns3::TypeId ns3::ConstantRateWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-rate-wifi-manager.h: ns3::WifiRemoteStation * ns3::ConstantRateWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: ns3::WifiMode ns3::ConstantRateWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: ns3::WifiMode ns3::ConstantRateWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: void ns3::ConstantRateWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: void ns3::ConstantRateWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: void ns3::ConstantRateWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: void ns3::ConstantRateWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: void ns3::ConstantRateWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: void ns3::ConstantRateWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: void ns3::ConstantRateWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## constant-rate-wifi-manager.h: bool ns3::ConstantRateWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3CtrlBAckRequestHeader_methods(root_module, cls): ## ctrl-headers.h: ns3::CtrlBAckRequestHeader::CtrlBAckRequestHeader(ns3::CtrlBAckRequestHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::CtrlBAckRequestHeader const &', 'arg0')]) ## ctrl-headers.h: ns3::CtrlBAckRequestHeader::CtrlBAckRequestHeader() [constructor] cls.add_constructor([]) ## ctrl-headers.h: uint32_t ns3::CtrlBAckRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ctrl-headers.h: ns3::TypeId ns3::CtrlBAckRequestHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ctrl-headers.h: uint32_t ns3::CtrlBAckRequestHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ctrl-headers.h: uint16_t ns3::CtrlBAckRequestHeader::GetStartingSequence() const [member function] cls.add_method('GetStartingSequence', 'uint16_t', [], is_const=True) ## ctrl-headers.h: uint16_t ns3::CtrlBAckRequestHeader::GetStartingSequenceControl() const [member function] cls.add_method('GetStartingSequenceControl', 'uint16_t', [], is_const=True) ## ctrl-headers.h: uint8_t ns3::CtrlBAckRequestHeader::GetTidInfo() const [member function] cls.add_method('GetTidInfo', 'uint8_t', [], is_const=True) ## ctrl-headers.h: static ns3::TypeId ns3::CtrlBAckRequestHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ctrl-headers.h: bool ns3::CtrlBAckRequestHeader::IsBasic() const [member function] cls.add_method('IsBasic', 'bool', [], is_const=True) ## ctrl-headers.h: bool ns3::CtrlBAckRequestHeader::IsCompressed() const [member function] cls.add_method('IsCompressed', 'bool', [], is_const=True) ## ctrl-headers.h: bool ns3::CtrlBAckRequestHeader::IsMultiTid() const [member function] cls.add_method('IsMultiTid', 'bool', [], is_const=True) ## ctrl-headers.h: bool ns3::CtrlBAckRequestHeader::MustSendHtImmediateAck() const [member function] cls.add_method('MustSendHtImmediateAck', 'bool', [], is_const=True) ## ctrl-headers.h: void ns3::CtrlBAckRequestHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ctrl-headers.h: void ns3::CtrlBAckRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ctrl-headers.h: void ns3::CtrlBAckRequestHeader::SetHtImmediateAck(bool immediateAck) [member function] cls.add_method('SetHtImmediateAck', 'void', [param('bool', 'immediateAck')]) ## ctrl-headers.h: void ns3::CtrlBAckRequestHeader::SetStartingSequence(uint16_t seq) [member function] cls.add_method('SetStartingSequence', 'void', [param('uint16_t', 'seq')]) ## ctrl-headers.h: void ns3::CtrlBAckRequestHeader::SetTidInfo(uint8_t tid) [member function] cls.add_method('SetTidInfo', 'void', [param('uint8_t', 'tid')]) ## ctrl-headers.h: void ns3::CtrlBAckRequestHeader::SetType(ns3::BlockAckType type) [member function] cls.add_method('SetType', 'void', [param('ns3::BlockAckType', 'type')]) return def register_Ns3CtrlBAckResponseHeader_methods(root_module, cls): ## ctrl-headers.h: ns3::CtrlBAckResponseHeader::CtrlBAckResponseHeader(ns3::CtrlBAckResponseHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::CtrlBAckResponseHeader const &', 'arg0')]) ## ctrl-headers.h: ns3::CtrlBAckResponseHeader::CtrlBAckResponseHeader() [constructor] cls.add_constructor([]) ## ctrl-headers.h: uint32_t ns3::CtrlBAckResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ctrl-headers.h: ns3::TypeId ns3::CtrlBAckResponseHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ctrl-headers.h: uint32_t ns3::CtrlBAckResponseHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ctrl-headers.h: uint16_t ns3::CtrlBAckResponseHeader::GetStartingSequence() const [member function] cls.add_method('GetStartingSequence', 'uint16_t', [], is_const=True) ## ctrl-headers.h: uint16_t ns3::CtrlBAckResponseHeader::GetStartingSequenceControl() const [member function] cls.add_method('GetStartingSequenceControl', 'uint16_t', [], is_const=True) ## ctrl-headers.h: uint8_t ns3::CtrlBAckResponseHeader::GetTidInfo() const [member function] cls.add_method('GetTidInfo', 'uint8_t', [], is_const=True) ## ctrl-headers.h: static ns3::TypeId ns3::CtrlBAckResponseHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ctrl-headers.h: bool ns3::CtrlBAckResponseHeader::IsBasic() const [member function] cls.add_method('IsBasic', 'bool', [], is_const=True) ## ctrl-headers.h: bool ns3::CtrlBAckResponseHeader::IsCompressed() const [member function] cls.add_method('IsCompressed', 'bool', [], is_const=True) ## ctrl-headers.h: bool ns3::CtrlBAckResponseHeader::IsFragmentReceived(uint16_t seq, uint8_t frag) const [member function] cls.add_method('IsFragmentReceived', 'bool', [param('uint16_t', 'seq'), param('uint8_t', 'frag')], is_const=True) ## ctrl-headers.h: bool ns3::CtrlBAckResponseHeader::IsMultiTid() const [member function] cls.add_method('IsMultiTid', 'bool', [], is_const=True) ## ctrl-headers.h: bool ns3::CtrlBAckResponseHeader::IsPacketReceived(uint16_t seq) const [member function] cls.add_method('IsPacketReceived', 'bool', [param('uint16_t', 'seq')], is_const=True) ## ctrl-headers.h: bool ns3::CtrlBAckResponseHeader::MustSendHtImmediateAck() const [member function] cls.add_method('MustSendHtImmediateAck', 'bool', [], is_const=True) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::SetHtImmediateAck(bool immeadiateAck) [member function] cls.add_method('SetHtImmediateAck', 'void', [param('bool', 'immeadiateAck')]) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::SetReceivedFragment(uint16_t seq, uint8_t frag) [member function] cls.add_method('SetReceivedFragment', 'void', [param('uint16_t', 'seq'), param('uint8_t', 'frag')]) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::SetReceivedPacket(uint16_t seq) [member function] cls.add_method('SetReceivedPacket', 'void', [param('uint16_t', 'seq')]) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::SetStartingSequence(uint16_t seq) [member function] cls.add_method('SetStartingSequence', 'void', [param('uint16_t', 'seq')]) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::SetStartingSequenceControl(uint16_t seqControl) [member function] cls.add_method('SetStartingSequenceControl', 'void', [param('uint16_t', 'seqControl')]) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::SetTidInfo(uint8_t tid) [member function] cls.add_method('SetTidInfo', 'void', [param('uint8_t', 'tid')]) ## ctrl-headers.h: void ns3::CtrlBAckResponseHeader::SetType(ns3::BlockAckType type) [member function] cls.add_method('SetType', 'void', [param('ns3::BlockAckType', 'type')]) return def register_Ns3Dcf_methods(root_module, cls): ## dcf.h: ns3::Dcf::Dcf() [constructor] cls.add_constructor([]) ## dcf.h: ns3::Dcf::Dcf(ns3::Dcf const & arg0) [copy constructor] cls.add_constructor([param('ns3::Dcf const &', 'arg0')]) ## dcf.h: uint32_t ns3::Dcf::GetAifsn() const [member function] cls.add_method('GetAifsn', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## dcf.h: uint32_t ns3::Dcf::GetMaxCw() const [member function] cls.add_method('GetMaxCw', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## dcf.h: uint32_t ns3::Dcf::GetMinCw() const [member function] cls.add_method('GetMinCw', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## dcf.h: static ns3::TypeId ns3::Dcf::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dcf.h: void ns3::Dcf::SetAifsn(uint32_t aifsn) [member function] cls.add_method('SetAifsn', 'void', [param('uint32_t', 'aifsn')], is_pure_virtual=True, is_virtual=True) ## dcf.h: void ns3::Dcf::SetMaxCw(uint32_t maxCw) [member function] cls.add_method('SetMaxCw', 'void', [param('uint32_t', 'maxCw')], is_pure_virtual=True, is_virtual=True) ## dcf.h: void ns3::Dcf::SetMinCw(uint32_t minCw) [member function] cls.add_method('SetMinCw', 'void', [param('uint32_t', 'minCw')], is_pure_virtual=True, is_virtual=True) return def register_Ns3EdcaTxopN_methods(root_module, cls): ## edca-txop-n.h: static ns3::TypeId ns3::EdcaTxopN::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## edca-txop-n.h: ns3::EdcaTxopN::EdcaTxopN() [constructor] cls.add_constructor([]) ## edca-txop-n.h: void ns3::EdcaTxopN::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## edca-txop-n.h: void ns3::EdcaTxopN::SetLow(ns3::Ptr<ns3::MacLow> low) [member function] cls.add_method('SetLow', 'void', [param('ns3::Ptr< ns3::MacLow >', 'low')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetTxMiddle(ns3::MacTxMiddle * txMiddle) [member function] cls.add_method('SetTxMiddle', 'void', [param('ns3::MacTxMiddle *', 'txMiddle')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetManager(ns3::DcfManager * manager) [member function] cls.add_method('SetManager', 'void', [param('ns3::DcfManager *', 'manager')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetTxOkCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetTxOkCallback', 'void', [param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetTxFailedCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetTxFailedCallback', 'void', [param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> remoteManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'remoteManager')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetTypeOfStation(ns3::TypeOfStation type) [member function] cls.add_method('SetTypeOfStation', 'void', [param('ns3::TypeOfStation', 'type')]) ## edca-txop-n.h: ns3::TypeOfStation ns3::EdcaTxopN::GetTypeOfStation() const [member function] cls.add_method('GetTypeOfStation', 'ns3::TypeOfStation', [], is_const=True) ## edca-txop-n.h: void ns3::EdcaTxopN::SetMaxQueueSize(uint32_t size) [member function] cls.add_method('SetMaxQueueSize', 'void', [param('uint32_t', 'size')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetMaxQueueDelay(ns3::Time delay) [member function] cls.add_method('SetMaxQueueDelay', 'void', [param('ns3::Time', 'delay')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetMinCw(uint32_t minCw) [member function] cls.add_method('SetMinCw', 'void', [param('uint32_t', 'minCw')], is_virtual=True) ## edca-txop-n.h: void ns3::EdcaTxopN::SetMaxCw(uint32_t maxCw) [member function] cls.add_method('SetMaxCw', 'void', [param('uint32_t', 'maxCw')], is_virtual=True) ## edca-txop-n.h: void ns3::EdcaTxopN::SetAifsn(uint32_t aifsn) [member function] cls.add_method('SetAifsn', 'void', [param('uint32_t', 'aifsn')], is_virtual=True) ## edca-txop-n.h: uint32_t ns3::EdcaTxopN::GetMinCw() const [member function] cls.add_method('GetMinCw', 'uint32_t', [], is_const=True, is_virtual=True) ## edca-txop-n.h: uint32_t ns3::EdcaTxopN::GetMaxCw() const [member function] cls.add_method('GetMaxCw', 'uint32_t', [], is_const=True, is_virtual=True) ## edca-txop-n.h: uint32_t ns3::EdcaTxopN::GetAifsn() const [member function] cls.add_method('GetAifsn', 'uint32_t', [], is_const=True, is_virtual=True) ## edca-txop-n.h: ns3::Ptr<ns3::MacLow> ns3::EdcaTxopN::Low() [member function] cls.add_method('Low', 'ns3::Ptr< ns3::MacLow >', []) ## edca-txop-n.h: ns3::Ptr<ns3::MsduAggregator> ns3::EdcaTxopN::GetMsduAggregator() const [member function] cls.add_method('GetMsduAggregator', 'ns3::Ptr< ns3::MsduAggregator >', [], is_const=True) ## edca-txop-n.h: bool ns3::EdcaTxopN::NeedsAccess() const [member function] cls.add_method('NeedsAccess', 'bool', [], is_const=True) ## edca-txop-n.h: void ns3::EdcaTxopN::NotifyAccessGranted() [member function] cls.add_method('NotifyAccessGranted', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::NotifyInternalCollision() [member function] cls.add_method('NotifyInternalCollision', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::NotifyCollision() [member function] cls.add_method('NotifyCollision', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::NotifyChannelSwitching() [member function] cls.add_method('NotifyChannelSwitching', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::GotCts(double snr, ns3::WifiMode txMode) [member function] cls.add_method('GotCts', 'void', [param('double', 'snr'), param('ns3::WifiMode', 'txMode')]) ## edca-txop-n.h: void ns3::EdcaTxopN::MissedCts() [member function] cls.add_method('MissedCts', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::GotAck(double snr, ns3::WifiMode txMode) [member function] cls.add_method('GotAck', 'void', [param('double', 'snr'), param('ns3::WifiMode', 'txMode')]) ## edca-txop-n.h: void ns3::EdcaTxopN::GotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address recipient) [member function] cls.add_method('GotBlockAck', 'void', [param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'recipient')]) ## edca-txop-n.h: void ns3::EdcaTxopN::MissedBlockAck() [member function] cls.add_method('MissedBlockAck', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::GotAddBaResponse(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address recipient) [member function] cls.add_method('GotAddBaResponse', 'void', [param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'recipient')]) ## edca-txop-n.h: void ns3::EdcaTxopN::GotDelBaFrame(ns3::MgtDelBaHeader const * delBaHdr, ns3::Mac48Address recipient) [member function] cls.add_method('GotDelBaFrame', 'void', [param('ns3::MgtDelBaHeader const *', 'delBaHdr'), param('ns3::Mac48Address', 'recipient')]) ## edca-txop-n.h: void ns3::EdcaTxopN::MissedAck() [member function] cls.add_method('MissedAck', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::StartNext() [member function] cls.add_method('StartNext', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::RestartAccessIfNeeded() [member function] cls.add_method('RestartAccessIfNeeded', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::StartAccessIfNeeded() [member function] cls.add_method('StartAccessIfNeeded', 'void', []) ## edca-txop-n.h: bool ns3::EdcaTxopN::NeedRts() [member function] cls.add_method('NeedRts', 'bool', []) ## edca-txop-n.h: bool ns3::EdcaTxopN::NeedRtsRetransmission() [member function] cls.add_method('NeedRtsRetransmission', 'bool', []) ## edca-txop-n.h: bool ns3::EdcaTxopN::NeedDataRetransmission() [member function] cls.add_method('NeedDataRetransmission', 'bool', []) ## edca-txop-n.h: bool ns3::EdcaTxopN::NeedFragmentation() const [member function] cls.add_method('NeedFragmentation', 'bool', [], is_const=True) ## edca-txop-n.h: uint32_t ns3::EdcaTxopN::GetNextFragmentSize() [member function] cls.add_method('GetNextFragmentSize', 'uint32_t', []) ## edca-txop-n.h: uint32_t ns3::EdcaTxopN::GetFragmentSize() [member function] cls.add_method('GetFragmentSize', 'uint32_t', []) ## edca-txop-n.h: uint32_t ns3::EdcaTxopN::GetFragmentOffset() [member function] cls.add_method('GetFragmentOffset', 'uint32_t', []) ## edca-txop-n.h: bool ns3::EdcaTxopN::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## edca-txop-n.h: void ns3::EdcaTxopN::NextFragment() [member function] cls.add_method('NextFragment', 'void', []) ## edca-txop-n.h: ns3::Ptr<ns3::Packet> ns3::EdcaTxopN::GetFragmentPacket(ns3::WifiMacHeader * hdr) [member function] cls.add_method('GetFragmentPacket', 'ns3::Ptr< ns3::Packet >', [param('ns3::WifiMacHeader *', 'hdr')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetAccessCategory(ns3::AcIndex ac) [member function] cls.add_method('SetAccessCategory', 'void', [param('ns3::AcIndex', 'ac')]) ## edca-txop-n.h: void ns3::EdcaTxopN::Queue(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function] cls.add_method('Queue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SetMsduAggregator(ns3::Ptr<ns3::MsduAggregator> aggr) [member function] cls.add_method('SetMsduAggregator', 'void', [param('ns3::Ptr< ns3::MsduAggregator >', 'aggr')]) ## edca-txop-n.h: void ns3::EdcaTxopN::PushFront(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function] cls.add_method('PushFront', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')]) ## edca-txop-n.h: void ns3::EdcaTxopN::CompleteConfig() [member function] cls.add_method('CompleteConfig', 'void', []) ## edca-txop-n.h: void ns3::EdcaTxopN::SetBlockAckThreshold(uint8_t threshold) [member function] cls.add_method('SetBlockAckThreshold', 'void', [param('uint8_t', 'threshold')]) ## edca-txop-n.h: uint8_t ns3::EdcaTxopN::GetBlockAckThreshold() const [member function] cls.add_method('GetBlockAckThreshold', 'uint8_t', [], is_const=True) ## edca-txop-n.h: void ns3::EdcaTxopN::SetBlockAckInactivityTimeout(uint16_t timeout) [member function] cls.add_method('SetBlockAckInactivityTimeout', 'void', [param('uint16_t', 'timeout')]) ## edca-txop-n.h: void ns3::EdcaTxopN::SendDelbaFrame(ns3::Mac48Address addr, uint8_t tid, bool byOriginator) [member function] cls.add_method('SendDelbaFrame', 'void', [param('ns3::Mac48Address', 'addr'), param('uint8_t', 'tid'), param('bool', 'byOriginator')]) ## edca-txop-n.h: void ns3::EdcaTxopN::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) return def register_Ns3ErrorRateModel_methods(root_module, cls): ## error-rate-model.h: ns3::ErrorRateModel::ErrorRateModel() [constructor] cls.add_constructor([]) ## error-rate-model.h: ns3::ErrorRateModel::ErrorRateModel(ns3::ErrorRateModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ErrorRateModel const &', 'arg0')]) ## error-rate-model.h: double ns3::ErrorRateModel::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function] cls.add_method('CalculateSnr', 'double', [param('ns3::WifiMode', 'txMode'), param('double', 'ber')], is_const=True) ## error-rate-model.h: double ns3::ErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function] cls.add_method('GetChunkSuccessRate', 'double', [param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')], is_pure_virtual=True, is_const=True, is_virtual=True) ## error-rate-model.h: static ns3::TypeId ns3::ErrorRateModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3IdealWifiManager_methods(root_module, cls): ## ideal-wifi-manager.h: ns3::IdealWifiManager::IdealWifiManager(ns3::IdealWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::IdealWifiManager const &', 'arg0')]) ## ideal-wifi-manager.h: ns3::IdealWifiManager::IdealWifiManager() [constructor] cls.add_constructor([]) ## ideal-wifi-manager.h: static ns3::TypeId ns3::IdealWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ideal-wifi-manager.h: void ns3::IdealWifiManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetupPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## ideal-wifi-manager.h: ns3::WifiRemoteStation * ns3::IdealWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## ideal-wifi-manager.h: ns3::WifiMode ns3::IdealWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: ns3::WifiMode ns3::IdealWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: void ns3::IdealWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: void ns3::IdealWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: void ns3::IdealWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: void ns3::IdealWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: void ns3::IdealWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: void ns3::IdealWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: void ns3::IdealWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## ideal-wifi-manager.h: bool ns3::IdealWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3MacLow_methods(root_module, cls): ## mac-low.h: ns3::MacLow::MacLow(ns3::MacLow const & arg0) [copy constructor] cls.add_constructor([param('ns3::MacLow const &', 'arg0')]) ## mac-low.h: ns3::MacLow::MacLow() [constructor] cls.add_constructor([]) ## mac-low.h: ns3::Time ns3::MacLow::CalculateTransmissionTime(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const * hdr, ns3::MacLowTransmissionParameters const & parameters) const [member function] cls.add_method('CalculateTransmissionTime', 'ns3::Time', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr'), param('ns3::MacLowTransmissionParameters const &', 'parameters')], is_const=True) ## mac-low.h: void ns3::MacLow::CreateBlockAckAgreement(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address originator, uint16_t startingSeq) [member function] cls.add_method('CreateBlockAckAgreement', 'void', [param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'originator'), param('uint16_t', 'startingSeq')]) ## mac-low.h: void ns3::MacLow::DestroyBlockAckAgreement(ns3::Mac48Address originator, uint8_t tid) [member function] cls.add_method('DestroyBlockAckAgreement', 'void', [param('ns3::Mac48Address', 'originator'), param('uint8_t', 'tid')]) ## mac-low.h: ns3::Time ns3::MacLow::GetAckTimeout() const [member function] cls.add_method('GetAckTimeout', 'ns3::Time', [], is_const=True) ## mac-low.h: ns3::Mac48Address ns3::MacLow::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Mac48Address', [], is_const=True) ## mac-low.h: ns3::Time ns3::MacLow::GetBasicBlockAckTimeout() const [member function] cls.add_method('GetBasicBlockAckTimeout', 'ns3::Time', [], is_const=True) ## mac-low.h: ns3::Mac48Address ns3::MacLow::GetBssid() const [member function] cls.add_method('GetBssid', 'ns3::Mac48Address', [], is_const=True) ## mac-low.h: ns3::Time ns3::MacLow::GetCompressedBlockAckTimeout() const [member function] cls.add_method('GetCompressedBlockAckTimeout', 'ns3::Time', [], is_const=True) ## mac-low.h: ns3::Time ns3::MacLow::GetCtsTimeout() const [member function] cls.add_method('GetCtsTimeout', 'ns3::Time', [], is_const=True) ## mac-low.h: ns3::Time ns3::MacLow::GetPifs() const [member function] cls.add_method('GetPifs', 'ns3::Time', [], is_const=True) ## mac-low.h: ns3::Time ns3::MacLow::GetSifs() const [member function] cls.add_method('GetSifs', 'ns3::Time', [], is_const=True) ## mac-low.h: ns3::Time ns3::MacLow::GetSlotTime() const [member function] cls.add_method('GetSlotTime', 'ns3::Time', [], is_const=True) ## mac-low.h: void ns3::MacLow::NotifySwitchingStartNow(ns3::Time duration) [member function] cls.add_method('NotifySwitchingStartNow', 'void', [param('ns3::Time', 'duration')]) ## mac-low.h: void ns3::MacLow::ReceiveError(ns3::Ptr<ns3::Packet const> packet, double rxSnr) [member function] cls.add_method('ReceiveError', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'rxSnr')]) ## mac-low.h: void ns3::MacLow::ReceiveOk(ns3::Ptr<ns3::Packet> packet, double rxSnr, ns3::WifiMode txMode, ns3::WifiPreamble preamble) [member function] cls.add_method('ReceiveOk', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode'), param('ns3::WifiPreamble', 'preamble')]) ## mac-low.h: void ns3::MacLow::RegisterBlockAckListenerForAc(ns3::AcIndex ac, ns3::MacLowBlockAckEventListener * listener) [member function] cls.add_method('RegisterBlockAckListenerForAc', 'void', [param('ns3::AcIndex', 'ac'), param('ns3::MacLowBlockAckEventListener *', 'listener')]) ## mac-low.h: void ns3::MacLow::RegisterDcfListener(ns3::MacLowDcfListener * listener) [member function] cls.add_method('RegisterDcfListener', 'void', [param('ns3::MacLowDcfListener *', 'listener')]) ## mac-low.h: void ns3::MacLow::SetAckTimeout(ns3::Time ackTimeout) [member function] cls.add_method('SetAckTimeout', 'void', [param('ns3::Time', 'ackTimeout')]) ## mac-low.h: void ns3::MacLow::SetAddress(ns3::Mac48Address ad) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Mac48Address', 'ad')]) ## mac-low.h: void ns3::MacLow::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetBasicBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')]) ## mac-low.h: void ns3::MacLow::SetBssid(ns3::Mac48Address ad) [member function] cls.add_method('SetBssid', 'void', [param('ns3::Mac48Address', 'ad')]) ## mac-low.h: void ns3::MacLow::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetCompressedBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')]) ## mac-low.h: void ns3::MacLow::SetCtsTimeout(ns3::Time ctsTimeout) [member function] cls.add_method('SetCtsTimeout', 'void', [param('ns3::Time', 'ctsTimeout')]) ## mac-low.h: void ns3::MacLow::SetPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')]) ## mac-low.h: void ns3::MacLow::SetPifs(ns3::Time pifs) [member function] cls.add_method('SetPifs', 'void', [param('ns3::Time', 'pifs')]) ## mac-low.h: void ns3::MacLow::SetRxCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::WifiMacHeader const*, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetRxCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::WifiMacHeader const *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## mac-low.h: void ns3::MacLow::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')]) ## mac-low.h: void ns3::MacLow::SetSlotTime(ns3::Time slotTime) [member function] cls.add_method('SetSlotTime', 'void', [param('ns3::Time', 'slotTime')]) ## mac-low.h: void ns3::MacLow::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> manager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'manager')]) ## mac-low.h: void ns3::MacLow::StartTransmission(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const * hdr, ns3::MacLowTransmissionParameters parameters, ns3::MacLowTransmissionListener * listener) [member function] cls.add_method('StartTransmission', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr'), param('ns3::MacLowTransmissionParameters', 'parameters'), param('ns3::MacLowTransmissionListener *', 'listener')]) ## mac-low.h: void ns3::MacLow::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3MgtBeaconHeader_methods(root_module, cls): ## mgt-headers.h: ns3::MgtBeaconHeader::MgtBeaconHeader() [constructor] cls.add_constructor([]) ## mgt-headers.h: ns3::MgtBeaconHeader::MgtBeaconHeader(ns3::MgtBeaconHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::MgtBeaconHeader const &', 'arg0')]) return def register_Ns3MinstrelWifiManager_methods(root_module, cls): ## minstrel-wifi-manager.h: ns3::MinstrelWifiManager::MinstrelWifiManager(ns3::MinstrelWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::MinstrelWifiManager const &', 'arg0')]) ## minstrel-wifi-manager.h: ns3::MinstrelWifiManager::MinstrelWifiManager() [constructor] cls.add_constructor([]) ## minstrel-wifi-manager.h: static ns3::TypeId ns3::MinstrelWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## minstrel-wifi-manager.h: void ns3::MinstrelWifiManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetupPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## minstrel-wifi-manager.h: ns3::WifiRemoteStation * ns3::MinstrelWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: ns3::WifiMode ns3::MinstrelWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: ns3::WifiMode ns3::MinstrelWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: void ns3::MinstrelWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: void ns3::MinstrelWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: void ns3::MinstrelWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: void ns3::MinstrelWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: void ns3::MinstrelWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: void ns3::MinstrelWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: void ns3::MinstrelWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## minstrel-wifi-manager.h: bool ns3::MinstrelWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3MsduAggregator_methods(root_module, cls): ## msdu-aggregator.h: ns3::MsduAggregator::MsduAggregator() [constructor] cls.add_constructor([]) ## msdu-aggregator.h: ns3::MsduAggregator::MsduAggregator(ns3::MsduAggregator const & arg0) [copy constructor] cls.add_constructor([param('ns3::MsduAggregator const &', 'arg0')]) ## msdu-aggregator.h: bool ns3::MsduAggregator::Aggregate(ns3::Ptr<ns3::Packet const> packet, ns3::Ptr<ns3::Packet> aggregatedPacket, ns3::Mac48Address src, ns3::Mac48Address dest) [member function] cls.add_method('Aggregate', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dest')], is_pure_virtual=True, is_virtual=True) ## msdu-aggregator.h: static std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::AmsduSubframeHeader>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::AmsduSubframeHeader> > > ns3::MsduAggregator::Deaggregate(ns3::Ptr<ns3::Packet> aggregatedPacket) [member function] cls.add_method('Deaggregate', 'std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::AmsduSubframeHeader > >', [param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket')], is_static=True) ## msdu-aggregator.h: static ns3::TypeId ns3::MsduAggregator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3NistErrorRateModel_methods(root_module, cls): ## nist-error-rate-model.h: ns3::NistErrorRateModel::NistErrorRateModel(ns3::NistErrorRateModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::NistErrorRateModel const &', 'arg0')]) ## nist-error-rate-model.h: ns3::NistErrorRateModel::NistErrorRateModel() [constructor] cls.add_constructor([]) ## nist-error-rate-model.h: double ns3::NistErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function] cls.add_method('GetChunkSuccessRate', 'double', [param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')], is_const=True, is_virtual=True) ## nist-error-rate-model.h: static ns3::TypeId ns3::NistErrorRateModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3NqapWifiMac_methods(root_module, cls): ## nqap-wifi-mac.h: static ns3::TypeId ns3::NqapWifiMac::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## nqap-wifi-mac.h: ns3::NqapWifiMac::NqapWifiMac() [constructor] cls.add_constructor([]) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetSlot(ns3::Time slotTime) [member function] cls.add_method('SetSlot', 'void', [param('ns3::Time', 'slotTime')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function] cls.add_method('SetEifsNoDifs', 'void', [param('ns3::Time', 'eifsNoDifs')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function] cls.add_method('SetAckTimeout', 'void', [param('ns3::Time', 'ackTimeout')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function] cls.add_method('SetCtsTimeout', 'void', [param('ns3::Time', 'ctsTimeout')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetPifs(ns3::Time pifs) [member function] cls.add_method('SetPifs', 'void', [param('ns3::Time', 'pifs')], is_virtual=True) ## nqap-wifi-mac.h: ns3::Time ns3::NqapWifiMac::GetSlot() const [member function] cls.add_method('GetSlot', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: ns3::Time ns3::NqapWifiMac::GetSifs() const [member function] cls.add_method('GetSifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: ns3::Time ns3::NqapWifiMac::GetEifsNoDifs() const [member function] cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: ns3::Time ns3::NqapWifiMac::GetAckTimeout() const [member function] cls.add_method('GetAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: ns3::Time ns3::NqapWifiMac::GetCtsTimeout() const [member function] cls.add_method('GetCtsTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: ns3::Time ns3::NqapWifiMac::GetPifs() const [member function] cls.add_method('GetPifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetWifiPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')], is_virtual=True) ## nqap-wifi-mac.h: bool ns3::NqapWifiMac::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function] cls.add_method('SetForwardUpCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function] cls.add_method('SetLinkUpCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function] cls.add_method('SetLinkDownCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')], is_virtual=True) ## nqap-wifi-mac.h: ns3::Mac48Address ns3::NqapWifiMac::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: ns3::Ssid ns3::NqapWifiMac::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetAddress(ns3::Mac48Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Mac48Address', 'address')], is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')], is_virtual=True) ## nqap-wifi-mac.h: ns3::Mac48Address ns3::NqapWifiMac::GetBssid() const [member function] cls.add_method('GetBssid', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::SetBeaconInterval(ns3::Time interval) [member function] cls.add_method('SetBeaconInterval', 'void', [param('ns3::Time', 'interval')]) ## nqap-wifi-mac.h: ns3::Time ns3::NqapWifiMac::GetBeaconInterval() const [member function] cls.add_method('GetBeaconInterval', 'ns3::Time', [], is_const=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::StartBeaconing() [member function] cls.add_method('StartBeaconing', 'void', []) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) ## nqap-wifi-mac.h: void ns3::NqapWifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('FinishConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], visibility='private', is_virtual=True) return def register_Ns3NqstaWifiMac_methods(root_module, cls): ## nqsta-wifi-mac.h: static ns3::TypeId ns3::NqstaWifiMac::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## nqsta-wifi-mac.h: ns3::NqstaWifiMac::NqstaWifiMac() [constructor] cls.add_constructor([]) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetSlot(ns3::Time slotTime) [member function] cls.add_method('SetSlot', 'void', [param('ns3::Time', 'slotTime')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function] cls.add_method('SetEifsNoDifs', 'void', [param('ns3::Time', 'eifsNoDifs')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function] cls.add_method('SetAckTimeout', 'void', [param('ns3::Time', 'ackTimeout')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function] cls.add_method('SetCtsTimeout', 'void', [param('ns3::Time', 'ctsTimeout')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetPifs(ns3::Time pifs) [member function] cls.add_method('SetPifs', 'void', [param('ns3::Time', 'pifs')], is_virtual=True) ## nqsta-wifi-mac.h: ns3::Time ns3::NqstaWifiMac::GetSlot() const [member function] cls.add_method('GetSlot', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: ns3::Time ns3::NqstaWifiMac::GetSifs() const [member function] cls.add_method('GetSifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: ns3::Time ns3::NqstaWifiMac::GetEifsNoDifs() const [member function] cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: ns3::Time ns3::NqstaWifiMac::GetAckTimeout() const [member function] cls.add_method('GetAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: ns3::Time ns3::NqstaWifiMac::GetCtsTimeout() const [member function] cls.add_method('GetCtsTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: ns3::Time ns3::NqstaWifiMac::GetPifs() const [member function] cls.add_method('GetPifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetWifiPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')], is_virtual=True) ## nqsta-wifi-mac.h: bool ns3::NqstaWifiMac::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function] cls.add_method('SetForwardUpCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function] cls.add_method('SetLinkUpCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function] cls.add_method('SetLinkDownCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')], is_virtual=True) ## nqsta-wifi-mac.h: ns3::Mac48Address ns3::NqstaWifiMac::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: ns3::Ssid ns3::NqstaWifiMac::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetAddress(ns3::Mac48Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Mac48Address', 'address')], is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')], is_virtual=True) ## nqsta-wifi-mac.h: ns3::Mac48Address ns3::NqstaWifiMac::GetBssid() const [member function] cls.add_method('GetBssid', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetMaxMissedBeacons(uint32_t missed) [member function] cls.add_method('SetMaxMissedBeacons', 'void', [param('uint32_t', 'missed')]) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetProbeRequestTimeout(ns3::Time timeout) [member function] cls.add_method('SetProbeRequestTimeout', 'void', [param('ns3::Time', 'timeout')]) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::SetAssocRequestTimeout(ns3::Time timeout) [member function] cls.add_method('SetAssocRequestTimeout', 'void', [param('ns3::Time', 'timeout')]) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::StartActiveAssociation() [member function] cls.add_method('StartActiveAssociation', 'void', []) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## nqsta-wifi-mac.h: void ns3::NqstaWifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('FinishConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], visibility='private', is_virtual=True) return def register_Ns3OnoeWifiManager_methods(root_module, cls): ## onoe-wifi-manager.h: ns3::OnoeWifiManager::OnoeWifiManager(ns3::OnoeWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::OnoeWifiManager const &', 'arg0')]) ## onoe-wifi-manager.h: ns3::OnoeWifiManager::OnoeWifiManager() [constructor] cls.add_constructor([]) ## onoe-wifi-manager.h: static ns3::TypeId ns3::OnoeWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## onoe-wifi-manager.h: ns3::WifiRemoteStation * ns3::OnoeWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## onoe-wifi-manager.h: ns3::WifiMode ns3::OnoeWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: ns3::WifiMode ns3::OnoeWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: void ns3::OnoeWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: void ns3::OnoeWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: void ns3::OnoeWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: void ns3::OnoeWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: void ns3::OnoeWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: void ns3::OnoeWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: void ns3::OnoeWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## onoe-wifi-manager.h: bool ns3::OnoeWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3QadhocWifiMac_methods(root_module, cls): ## qadhoc-wifi-mac.h: static ns3::TypeId ns3::QadhocWifiMac::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## qadhoc-wifi-mac.h: ns3::QadhocWifiMac::QadhocWifiMac() [constructor] cls.add_constructor([]) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetSlot(ns3::Time slotTime) [member function] cls.add_method('SetSlot', 'void', [param('ns3::Time', 'slotTime')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function] cls.add_method('SetEifsNoDifs', 'void', [param('ns3::Time', 'eifsNoDifs')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function] cls.add_method('SetAckTimeout', 'void', [param('ns3::Time', 'ackTimeout')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function] cls.add_method('SetCtsTimeout', 'void', [param('ns3::Time', 'ctsTimeout')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetPifs(ns3::Time pifs) [member function] cls.add_method('SetPifs', 'void', [param('ns3::Time', 'pifs')], is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Time ns3::QadhocWifiMac::GetSlot() const [member function] cls.add_method('GetSlot', 'ns3::Time', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Time ns3::QadhocWifiMac::GetSifs() const [member function] cls.add_method('GetSifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Time ns3::QadhocWifiMac::GetEifsNoDifs() const [member function] cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Time ns3::QadhocWifiMac::GetAckTimeout() const [member function] cls.add_method('GetAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Time ns3::QadhocWifiMac::GetCtsTimeout() const [member function] cls.add_method('GetCtsTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Time ns3::QadhocWifiMac::GetPifs() const [member function] cls.add_method('GetPifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetWifiPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')], is_virtual=True) ## qadhoc-wifi-mac.h: bool ns3::QadhocWifiMac::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function] cls.add_method('SetForwardUpCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function] cls.add_method('SetLinkUpCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function] cls.add_method('SetLinkDownCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')], is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Mac48Address ns3::QadhocWifiMac::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Ssid ns3::QadhocWifiMac::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetAddress(ns3::Mac48Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Mac48Address', 'address')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')], is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Mac48Address ns3::QadhocWifiMac::GetBssid() const [member function] cls.add_method('GetBssid', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetBasicBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')], is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetCompressedBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')], is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Time ns3::QadhocWifiMac::GetBasicBlockAckTimeout() const [member function] cls.add_method('GetBasicBlockAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: ns3::Time ns3::QadhocWifiMac::GetCompressedBlockAckTimeout() const [member function] cls.add_method('GetCompressedBlockAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) ## qadhoc-wifi-mac.h: void ns3::QadhocWifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('FinishConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], visibility='private', is_virtual=True) return def register_Ns3QapWifiMac_methods(root_module, cls): ## qap-wifi-mac.h: static ns3::TypeId ns3::QapWifiMac::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## qap-wifi-mac.h: ns3::QapWifiMac::QapWifiMac() [constructor] cls.add_constructor([]) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetSlot(ns3::Time slotTime) [member function] cls.add_method('SetSlot', 'void', [param('ns3::Time', 'slotTime')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function] cls.add_method('SetEifsNoDifs', 'void', [param('ns3::Time', 'eifsNoDifs')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function] cls.add_method('SetAckTimeout', 'void', [param('ns3::Time', 'ackTimeout')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function] cls.add_method('SetCtsTimeout', 'void', [param('ns3::Time', 'ctsTimeout')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetPifs(ns3::Time pifs) [member function] cls.add_method('SetPifs', 'void', [param('ns3::Time', 'pifs')], is_virtual=True) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetSlot() const [member function] cls.add_method('GetSlot', 'ns3::Time', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetSifs() const [member function] cls.add_method('GetSifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetEifsNoDifs() const [member function] cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetAckTimeout() const [member function] cls.add_method('GetAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetCtsTimeout() const [member function] cls.add_method('GetCtsTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetPifs() const [member function] cls.add_method('GetPifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetWifiPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')], is_virtual=True) ## qap-wifi-mac.h: bool ns3::QapWifiMac::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function] cls.add_method('SetForwardUpCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function] cls.add_method('SetLinkUpCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function] cls.add_method('SetLinkDownCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')], is_virtual=True) ## qap-wifi-mac.h: ns3::Mac48Address ns3::QapWifiMac::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: ns3::Ssid ns3::QapWifiMac::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetAddress(ns3::Mac48Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Mac48Address', 'address')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')], is_virtual=True) ## qap-wifi-mac.h: ns3::Mac48Address ns3::QapWifiMac::GetBssid() const [member function] cls.add_method('GetBssid', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetBasicBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')], is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetCompressedBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')], is_virtual=True) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetBasicBlockAckTimeout() const [member function] cls.add_method('GetBasicBlockAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetCompressedBlockAckTimeout() const [member function] cls.add_method('GetCompressedBlockAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::SetBeaconInterval(ns3::Time interval) [member function] cls.add_method('SetBeaconInterval', 'void', [param('ns3::Time', 'interval')]) ## qap-wifi-mac.h: ns3::Time ns3::QapWifiMac::GetBeaconInterval() const [member function] cls.add_method('GetBeaconInterval', 'ns3::Time', [], is_const=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::StartBeaconing() [member function] cls.add_method('StartBeaconing', 'void', []) ## qap-wifi-mac.h: void ns3::QapWifiMac::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) ## qap-wifi-mac.h: void ns3::QapWifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('FinishConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], visibility='private', is_virtual=True) return def register_Ns3QstaWifiMac_methods(root_module, cls): ## qsta-wifi-mac.h: static ns3::TypeId ns3::QstaWifiMac::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## qsta-wifi-mac.h: ns3::QstaWifiMac::QstaWifiMac() [constructor] cls.add_constructor([]) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetSlot(ns3::Time slotTime) [member function] cls.add_method('SetSlot', 'void', [param('ns3::Time', 'slotTime')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetSifs(ns3::Time sifs) [member function] cls.add_method('SetSifs', 'void', [param('ns3::Time', 'sifs')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function] cls.add_method('SetEifsNoDifs', 'void', [param('ns3::Time', 'eifsNoDifs')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function] cls.add_method('SetAckTimeout', 'void', [param('ns3::Time', 'ackTimeout')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function] cls.add_method('SetCtsTimeout', 'void', [param('ns3::Time', 'ctsTimeout')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetPifs(ns3::Time pifs) [member function] cls.add_method('SetPifs', 'void', [param('ns3::Time', 'pifs')], is_virtual=True) ## qsta-wifi-mac.h: ns3::Time ns3::QstaWifiMac::GetSlot() const [member function] cls.add_method('GetSlot', 'ns3::Time', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: ns3::Time ns3::QstaWifiMac::GetSifs() const [member function] cls.add_method('GetSifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: ns3::Time ns3::QstaWifiMac::GetEifsNoDifs() const [member function] cls.add_method('GetEifsNoDifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: ns3::Time ns3::QstaWifiMac::GetAckTimeout() const [member function] cls.add_method('GetAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: ns3::Time ns3::QstaWifiMac::GetCtsTimeout() const [member function] cls.add_method('GetCtsTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: ns3::Time ns3::QstaWifiMac::GetPifs() const [member function] cls.add_method('GetPifs', 'ns3::Time', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetWifiPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function] cls.add_method('Enqueue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')], is_virtual=True) ## qsta-wifi-mac.h: bool ns3::QstaWifiMac::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function] cls.add_method('SetForwardUpCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function] cls.add_method('SetLinkUpCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function] cls.add_method('SetLinkDownCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')], is_virtual=True) ## qsta-wifi-mac.h: ns3::Mac48Address ns3::QstaWifiMac::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: ns3::Ssid ns3::QstaWifiMac::GetSsid() const [member function] cls.add_method('GetSsid', 'ns3::Ssid', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetAddress(ns3::Mac48Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Mac48Address', 'address')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetSsid(ns3::Ssid ssid) [member function] cls.add_method('SetSsid', 'void', [param('ns3::Ssid', 'ssid')], is_virtual=True) ## qsta-wifi-mac.h: ns3::Mac48Address ns3::QstaWifiMac::GetBssid() const [member function] cls.add_method('GetBssid', 'ns3::Mac48Address', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetBasicBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')], is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function] cls.add_method('SetCompressedBlockAckTimeout', 'void', [param('ns3::Time', 'blockAckTimeout')], is_virtual=True) ## qsta-wifi-mac.h: ns3::Time ns3::QstaWifiMac::GetBasicBlockAckTimeout() const [member function] cls.add_method('GetBasicBlockAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: ns3::Time ns3::QstaWifiMac::GetCompressedBlockAckTimeout() const [member function] cls.add_method('GetCompressedBlockAckTimeout', 'ns3::Time', [], is_const=True, is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetMaxMissedBeacons(uint32_t missed) [member function] cls.add_method('SetMaxMissedBeacons', 'void', [param('uint32_t', 'missed')]) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetProbeRequestTimeout(ns3::Time timeout) [member function] cls.add_method('SetProbeRequestTimeout', 'void', [param('ns3::Time', 'timeout')]) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::SetAssocRequestTimeout(ns3::Time timeout) [member function] cls.add_method('SetAssocRequestTimeout', 'void', [param('ns3::Time', 'timeout')]) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::StartActiveAssociation() [member function] cls.add_method('StartActiveAssociation', 'void', []) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## qsta-wifi-mac.h: void ns3::QstaWifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('FinishConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], visibility='private', is_virtual=True) return def register_Ns3RraaWifiManager_methods(root_module, cls): ## rraa-wifi-manager.h: ns3::RraaWifiManager::RraaWifiManager(ns3::RraaWifiManager const & arg0) [copy constructor] cls.add_constructor([param('ns3::RraaWifiManager const &', 'arg0')]) ## rraa-wifi-manager.h: ns3::RraaWifiManager::RraaWifiManager() [constructor] cls.add_constructor([]) ## rraa-wifi-manager.h: static ns3::TypeId ns3::RraaWifiManager::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## rraa-wifi-manager.h: ns3::WifiRemoteStation * ns3::RraaWifiManager::DoCreateStation() const [member function] cls.add_method('DoCreateStation', 'ns3::WifiRemoteStation *', [], is_const=True, visibility='private', is_virtual=True) ## rraa-wifi-manager.h: ns3::WifiMode ns3::RraaWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function] cls.add_method('DoGetDataMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: ns3::WifiMode ns3::RraaWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoGetRtsMode', 'ns3::WifiMode', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: bool ns3::RraaWifiManager::DoNeedRts(ns3::WifiRemoteStation * st, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function] cls.add_method('DoNeedRts', 'bool', [param('ns3::WifiRemoteStation *', 'st'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: void ns3::RraaWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: void ns3::RraaWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function] cls.add_method('DoReportDataOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: void ns3::RraaWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalDataFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: void ns3::RraaWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportFinalRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: void ns3::RraaWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function] cls.add_method('DoReportRtsFailed', 'void', [param('ns3::WifiRemoteStation *', 'station')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: void ns3::RraaWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function] cls.add_method('DoReportRtsOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: void ns3::RraaWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function] cls.add_method('DoReportRxOk', 'void', [param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')], visibility='private', is_virtual=True) ## rraa-wifi-manager.h: bool ns3::RraaWifiManager::IsLowLatency() const [member function] cls.add_method('IsLowLatency', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Ssid_methods(root_module, cls): cls.add_output_stream_operator() ## ssid.h: ns3::Ssid::Ssid(ns3::Ssid const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ssid const &', 'arg0')]) ## ssid.h: ns3::Ssid::Ssid() [constructor] cls.add_constructor([]) ## ssid.h: ns3::Ssid::Ssid(std::string s) [constructor] cls.add_constructor([param('std::string', 's')]) ## ssid.h: ns3::Ssid::Ssid(char const * ssid, uint8_t length) [constructor] cls.add_constructor([param('char const *', 'ssid'), param('uint8_t', 'length')]) ## ssid.h: uint8_t ns3::Ssid::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function] cls.add_method('DeserializeInformationField', 'uint8_t', [param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')], is_virtual=True) ## ssid.h: ns3::WifiInformationElementId ns3::Ssid::ElementId() const [member function] cls.add_method('ElementId', 'ns3::WifiInformationElementId', [], is_const=True, is_virtual=True) ## ssid.h: uint8_t ns3::Ssid::GetInformationFieldSize() const [member function] cls.add_method('GetInformationFieldSize', 'uint8_t', [], is_const=True, is_virtual=True) ## ssid.h: bool ns3::Ssid::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ssid.h: bool ns3::Ssid::IsEqual(ns3::Ssid const & o) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ssid const &', 'o')], is_const=True) ## ssid.h: char * ns3::Ssid::PeekString() const [member function] cls.add_method('PeekString', 'char *', [], is_const=True) ## ssid.h: void ns3::Ssid::SerializeInformationField(ns3::Buffer::Iterator start) const [member function] cls.add_method('SerializeInformationField', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3SsidChecker_methods(root_module, cls): ## ssid.h: ns3::SsidChecker::SsidChecker() [constructor] cls.add_constructor([]) ## ssid.h: ns3::SsidChecker::SsidChecker(ns3::SsidChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::SsidChecker const &', 'arg0')]) return def register_Ns3SsidValue_methods(root_module, cls): ## ssid.h: ns3::SsidValue::SsidValue() [constructor] cls.add_constructor([]) ## ssid.h: ns3::SsidValue::SsidValue(ns3::SsidValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::SsidValue const &', 'arg0')]) ## ssid.h: ns3::SsidValue::SsidValue(ns3::Ssid const & value) [constructor] cls.add_constructor([param('ns3::Ssid const &', 'value')]) ## ssid.h: ns3::Ptr<ns3::AttributeValue> ns3::SsidValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ssid.h: bool ns3::SsidValue::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) ## ssid.h: ns3::Ssid ns3::SsidValue::Get() const [member function] cls.add_method('Get', 'ns3::Ssid', [], is_const=True) ## ssid.h: std::string ns3::SsidValue::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) ## ssid.h: void ns3::SsidValue::Set(ns3::Ssid const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ssid const &', 'value')]) return def register_Ns3SupportedRates_methods(root_module, cls): cls.add_output_stream_operator() ## supported-rates.h: ns3::SupportedRates::SupportedRates(ns3::SupportedRates const & arg0) [copy constructor] cls.add_constructor([param('ns3::SupportedRates const &', 'arg0')]) ## supported-rates.h: ns3::SupportedRates::SupportedRates() [constructor] cls.add_constructor([]) ## supported-rates.h: void ns3::SupportedRates::AddSupportedRate(uint32_t bs) [member function] cls.add_method('AddSupportedRate', 'void', [param('uint32_t', 'bs')]) ## supported-rates.h: uint8_t ns3::SupportedRates::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function] cls.add_method('DeserializeInformationField', 'uint8_t', [param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')], is_virtual=True) ## supported-rates.h: ns3::WifiInformationElementId ns3::SupportedRates::ElementId() const [member function] cls.add_method('ElementId', 'ns3::WifiInformationElementId', [], is_const=True, is_virtual=True) ## supported-rates.h: uint8_t ns3::SupportedRates::GetInformationFieldSize() const [member function] cls.add_method('GetInformationFieldSize', 'uint8_t', [], is_const=True, is_virtual=True) ## supported-rates.h: uint8_t ns3::SupportedRates::GetNRates() const [member function] cls.add_method('GetNRates', 'uint8_t', [], is_const=True) ## supported-rates.h: uint32_t ns3::SupportedRates::GetRate(uint8_t i) const [member function] cls.add_method('GetRate', 'uint32_t', [param('uint8_t', 'i')], is_const=True) ## supported-rates.h: bool ns3::SupportedRates::IsBasicRate(uint32_t bs) const [member function] cls.add_method('IsBasicRate', 'bool', [param('uint32_t', 'bs')], is_const=True) ## supported-rates.h: bool ns3::SupportedRates::IsSupportedRate(uint32_t bs) const [member function] cls.add_method('IsSupportedRate', 'bool', [param('uint32_t', 'bs')], is_const=True) ## supported-rates.h: void ns3::SupportedRates::SerializeInformationField(ns3::Buffer::Iterator start) const [member function] cls.add_method('SerializeInformationField', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## supported-rates.h: void ns3::SupportedRates::SetBasicRate(uint32_t bs) [member function] cls.add_method('SetBasicRate', 'void', [param('uint32_t', 'bs')]) return def register_Ns3WifiChannel_methods(root_module, cls): ## wifi-channel.h: ns3::WifiChannel::WifiChannel() [constructor] cls.add_constructor([]) ## wifi-channel.h: ns3::WifiChannel::WifiChannel(ns3::WifiChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiChannel const &', 'arg0')]) ## wifi-channel.h: static ns3::TypeId ns3::WifiChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3WifiModeChecker_methods(root_module, cls): ## wifi-mode.h: ns3::WifiModeChecker::WifiModeChecker() [constructor] cls.add_constructor([]) ## wifi-mode.h: ns3::WifiModeChecker::WifiModeChecker(ns3::WifiModeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiModeChecker const &', 'arg0')]) return def register_Ns3WifiModeValue_methods(root_module, cls): ## wifi-mode.h: ns3::WifiModeValue::WifiModeValue() [constructor] cls.add_constructor([]) ## wifi-mode.h: ns3::WifiModeValue::WifiModeValue(ns3::WifiModeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiModeValue const &', 'arg0')]) ## wifi-mode.h: ns3::WifiModeValue::WifiModeValue(ns3::WifiMode const & value) [constructor] cls.add_constructor([param('ns3::WifiMode const &', 'value')]) ## wifi-mode.h: ns3::Ptr<ns3::AttributeValue> ns3::WifiModeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## wifi-mode.h: bool ns3::WifiModeValue::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) ## wifi-mode.h: ns3::WifiMode ns3::WifiModeValue::Get() const [member function] cls.add_method('Get', 'ns3::WifiMode', [], is_const=True) ## wifi-mode.h: std::string ns3::WifiModeValue::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) ## wifi-mode.h: void ns3::WifiModeValue::Set(ns3::WifiMode const & value) [member function] cls.add_method('Set', 'void', [param('ns3::WifiMode const &', 'value')]) return def register_Ns3WifiNetDevice_methods(root_module, cls): ## wifi-net-device.h: ns3::WifiNetDevice::WifiNetDevice(ns3::WifiNetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiNetDevice const &', 'arg0')]) ## wifi-net-device.h: ns3::WifiNetDevice::WifiNetDevice() [constructor] cls.add_constructor([]) ## wifi-net-device.h: void ns3::WifiNetDevice::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_virtual=True) ## wifi-net-device.h: ns3::Address ns3::WifiNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## wifi-net-device.h: ns3::Address ns3::WifiNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## wifi-net-device.h: ns3::Ptr<ns3::Channel> ns3::WifiNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## wifi-net-device.h: uint32_t ns3::WifiNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## wifi-net-device.h: ns3::Ptr<ns3::WifiMac> ns3::WifiNetDevice::GetMac() const [member function] cls.add_method('GetMac', 'ns3::Ptr< ns3::WifiMac >', [], is_const=True) ## wifi-net-device.h: uint16_t ns3::WifiNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## wifi-net-device.h: ns3::Address ns3::WifiNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## wifi-net-device.h: ns3::Address ns3::WifiNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## wifi-net-device.h: ns3::Ptr<ns3::Node> ns3::WifiNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## wifi-net-device.h: ns3::Ptr<ns3::WifiPhy> ns3::WifiNetDevice::GetPhy() const [member function] cls.add_method('GetPhy', 'ns3::Ptr< ns3::WifiPhy >', [], is_const=True) ## wifi-net-device.h: ns3::Ptr<ns3::WifiRemoteStationManager> ns3::WifiNetDevice::GetRemoteStationManager() const [member function] cls.add_method('GetRemoteStationManager', 'ns3::Ptr< ns3::WifiRemoteStationManager >', [], is_const=True) ## wifi-net-device.h: static ns3::TypeId ns3::WifiNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wifi-net-device.h: bool ns3::WifiNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## wifi-net-device.h: bool ns3::WifiNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## wifi-net-device.h: bool ns3::WifiNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## wifi-net-device.h: bool ns3::WifiNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## wifi-net-device.h: bool ns3::WifiNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## wifi-net-device.h: bool ns3::WifiNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## wifi-net-device.h: bool ns3::WifiNetDevice::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_virtual=True) ## wifi-net-device.h: bool ns3::WifiNetDevice::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_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::SetMac(ns3::Ptr<ns3::WifiMac> mac) [member function] cls.add_method('SetMac', 'void', [param('ns3::Ptr< ns3::WifiMac >', 'mac')]) ## wifi-net-device.h: bool ns3::WifiNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::SetPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function] cls.add_method('SetPhy', 'void', [param('ns3::Ptr< ns3::WifiPhy >', 'phy')]) ## wifi-net-device.h: void ns3::WifiNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, 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> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, 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 >', 'cb')], is_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, 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 >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::SetRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> manager) [member function] cls.add_method('SetRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'manager')]) ## wifi-net-device.h: bool ns3::WifiNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## wifi-net-device.h: void ns3::WifiNetDevice::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) return def register_Ns3YansErrorRateModel_methods(root_module, cls): ## yans-error-rate-model.h: ns3::YansErrorRateModel::YansErrorRateModel(ns3::YansErrorRateModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::YansErrorRateModel const &', 'arg0')]) ## yans-error-rate-model.h: ns3::YansErrorRateModel::YansErrorRateModel() [constructor] cls.add_constructor([]) ## yans-error-rate-model.h: double ns3::YansErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function] cls.add_method('GetChunkSuccessRate', 'double', [param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')], is_const=True, is_virtual=True) ## yans-error-rate-model.h: static ns3::TypeId ns3::YansErrorRateModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3YansWifiChannel_methods(root_module, cls): ## yans-wifi-channel.h: ns3::YansWifiChannel::YansWifiChannel(ns3::YansWifiChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::YansWifiChannel const &', 'arg0')]) ## yans-wifi-channel.h: ns3::YansWifiChannel::YansWifiChannel() [constructor] cls.add_constructor([]) ## yans-wifi-channel.h: void ns3::YansWifiChannel::Add(ns3::Ptr<ns3::YansWifiPhy> phy) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::YansWifiPhy >', 'phy')]) ## yans-wifi-channel.h: ns3::Ptr<ns3::NetDevice> ns3::YansWifiChannel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## yans-wifi-channel.h: uint32_t ns3::YansWifiChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## yans-wifi-channel.h: static ns3::TypeId ns3::YansWifiChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## yans-wifi-channel.h: void ns3::YansWifiChannel::Send(ns3::Ptr<ns3::YansWifiPhy> sender, ns3::Ptr<ns3::Packet const> packet, double txPowerDbm, ns3::WifiMode wifiMode, ns3::WifiPreamble preamble) const [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::YansWifiPhy >', 'sender'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'txPowerDbm'), param('ns3::WifiMode', 'wifiMode'), param('ns3::WifiPreamble', 'preamble')], is_const=True) ## yans-wifi-channel.h: void ns3::YansWifiChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function] cls.add_method('SetPropagationDelayModel', 'void', [param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')]) ## yans-wifi-channel.h: void ns3::YansWifiChannel::SetPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function] cls.add_method('SetPropagationLossModel', 'void', [param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')]) return def register_Ns3DcaTxop_methods(root_module, cls): ## dca-txop.h: static ns3::TypeId ns3::DcaTxop::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## dca-txop.h: ns3::DcaTxop::DcaTxop() [constructor] cls.add_constructor([]) ## dca-txop.h: void ns3::DcaTxop::SetLow(ns3::Ptr<ns3::MacLow> low) [member function] cls.add_method('SetLow', 'void', [param('ns3::Ptr< ns3::MacLow >', 'low')]) ## dca-txop.h: void ns3::DcaTxop::SetManager(ns3::DcfManager * manager) [member function] cls.add_method('SetManager', 'void', [param('ns3::DcfManager *', 'manager')]) ## dca-txop.h: void ns3::DcaTxop::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> remoteManager) [member function] cls.add_method('SetWifiRemoteStationManager', 'void', [param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'remoteManager')]) ## dca-txop.h: void ns3::DcaTxop::SetTxOkCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetTxOkCallback', 'void', [param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## dca-txop.h: void ns3::DcaTxop::SetTxFailedCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetTxFailedCallback', 'void', [param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## dca-txop.h: void ns3::DcaTxop::SetMaxQueueSize(uint32_t size) [member function] cls.add_method('SetMaxQueueSize', 'void', [param('uint32_t', 'size')]) ## dca-txop.h: void ns3::DcaTxop::SetMaxQueueDelay(ns3::Time delay) [member function] cls.add_method('SetMaxQueueDelay', 'void', [param('ns3::Time', 'delay')]) ## dca-txop.h: void ns3::DcaTxop::SetMinCw(uint32_t minCw) [member function] cls.add_method('SetMinCw', 'void', [param('uint32_t', 'minCw')], is_virtual=True) ## dca-txop.h: void ns3::DcaTxop::SetMaxCw(uint32_t maxCw) [member function] cls.add_method('SetMaxCw', 'void', [param('uint32_t', 'maxCw')], is_virtual=True) ## dca-txop.h: void ns3::DcaTxop::SetAifsn(uint32_t aifsn) [member function] cls.add_method('SetAifsn', 'void', [param('uint32_t', 'aifsn')], is_virtual=True) ## dca-txop.h: uint32_t ns3::DcaTxop::GetMinCw() const [member function] cls.add_method('GetMinCw', 'uint32_t', [], is_const=True, is_virtual=True) ## dca-txop.h: uint32_t ns3::DcaTxop::GetMaxCw() const [member function] cls.add_method('GetMaxCw', 'uint32_t', [], is_const=True, is_virtual=True) ## dca-txop.h: uint32_t ns3::DcaTxop::GetAifsn() const [member function] cls.add_method('GetAifsn', 'uint32_t', [], is_const=True, is_virtual=True) ## dca-txop.h: void ns3::DcaTxop::Queue(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function] cls.add_method('Queue', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')]) ## dca-txop.h: void ns3::DcaTxop::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='private', is_virtual=True) ## dca-txop.h: void ns3::DcaTxop::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_functions(root_module): module = root_module ## ssid.h: extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeSsidChecker() [free function] module.add_function('MakeSsidChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## wifi-mode.h: extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeWifiModeChecker() [free function] module.add_function('MakeWifiModeChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## qos-utils.h: extern uint8_t ns3::QosUtilsGetTidForPacket(ns3::Ptr<ns3::Packet const> packet) [free function] module.add_function('QosUtilsGetTidForPacket', 'uint8_t', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## qos-utils.h: extern uint32_t ns3::QosUtilsMapSeqControlToUniqueInteger(uint16_t seqControl, uint16_t endSequence) [free function] module.add_function('QosUtilsMapSeqControlToUniqueInteger', 'uint32_t', [param('uint16_t', 'seqControl'), param('uint16_t', 'endSequence')]) ## qos-utils.h: extern ns3::AcIndex ns3::QosUtilsMapTidToAc(uint8_t tid) [free function] module.add_function('QosUtilsMapTidToAc', 'ns3::AcIndex', [param('uint8_t', 'tid')]) register_functions_ns3_Config(module.get_submodule('Config'), root_module) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module) register_functions_ns3_aodv(module.get_submodule('aodv'), root_module) register_functions_ns3_dot11s(module.get_submodule('dot11s'), root_module) register_functions_ns3_flame(module.get_submodule('flame'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) register_functions_ns3_olsr(module.get_submodule('olsr'), root_module) return def register_functions_ns3_Config(module, root_module): return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_addressUtils(module, root_module): return def register_functions_ns3_aodv(module, root_module): return def register_functions_ns3_dot11s(module, root_module): return def register_functions_ns3_flame(module, root_module): return def register_functions_ns3_internal(module, root_module): return def register_functions_ns3_olsr(module, root_module): return
gpl-2.0
figue/android_kernel_samsung_p5
Documentation/target/tcm_mod_builder.py
3119
42754
#!/usr/bin/python # The TCM v4 multi-protocol fabric module generation script for drivers/target/$NEW_MOD # # Copyright (c) 2010 Rising Tide Systems # Copyright (c) 2010 Linux-iSCSI.org # # Author: nab@kernel.org # import os, sys import subprocess as sub import string import re import optparse tcm_dir = "" fabric_ops = [] fabric_mod_dir = "" fabric_mod_port = "" fabric_mod_init_port = "" def tcm_mod_err(msg): print msg sys.exit(1) def tcm_mod_create_module_subdir(fabric_mod_dir_var): if os.path.isdir(fabric_mod_dir_var) == True: return 1 print "Creating fabric_mod_dir: " + fabric_mod_dir_var ret = os.mkdir(fabric_mod_dir_var) if ret: tcm_mod_err("Unable to mkdir " + fabric_mod_dir_var) return def tcm_mod_build_FC_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* Binary World Wide unique Port Name for FC Initiator Nport */\n" buf += " u64 nport_wwpn;\n" buf += " /* ASCII formatted WWPN for FC Initiator Nport */\n" buf += " char nport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n" buf += "\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* FC lport target portal group tag for TCM */\n" buf += " u16 lport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_lport */\n" buf += " struct " + fabric_mod_name + "_lport *lport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n" buf += "\n" buf += "struct " + fabric_mod_name + "_lport {\n" buf += " /* SCSI protocol the lport is providing */\n" buf += " u8 lport_proto_id;\n" buf += " /* Binary World Wide unique Port Name for FC Target Lport */\n" buf += " u64 lport_wwpn;\n" buf += " /* ASCII formatted WWPN for FC Target Lport */\n" buf += " char lport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_lport() */\n" buf += " struct se_wwn lport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "lport" fabric_mod_init_port = "nport" return def tcm_mod_build_SAS_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* Binary World Wide unique Port Name for SAS Initiator port */\n" buf += " u64 iport_wwpn;\n" buf += " /* ASCII formatted WWPN for Sas Initiator port */\n" buf += " char iport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* SAS port target portal group tag for TCM */\n" buf += " u16 tport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_tport */\n" buf += " struct " + fabric_mod_name + "_tport *tport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tport {\n" buf += " /* SCSI protocol the tport is providing */\n" buf += " u8 tport_proto_id;\n" buf += " /* Binary World Wide unique Port Name for SAS Target port */\n" buf += " u64 tport_wwpn;\n" buf += " /* ASCII formatted WWPN for SAS Target port */\n" buf += " char tport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_tport() */\n" buf += " struct se_wwn tport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "tport" fabric_mod_init_port = "iport" return def tcm_mod_build_iSCSI_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* ASCII formatted InitiatorName */\n" buf += " char iport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* iSCSI target portal group tag for TCM */\n" buf += " u16 tport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_tport */\n" buf += " struct " + fabric_mod_name + "_tport *tport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tport {\n" buf += " /* SCSI protocol the tport is providing */\n" buf += " u8 tport_proto_id;\n" buf += " /* ASCII formatted TargetName for IQN */\n" buf += " char tport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_tport() */\n" buf += " struct se_wwn tport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "tport" fabric_mod_init_port = "iport" return def tcm_mod_build_base_includes(proto_ident, fabric_mod_dir_val, fabric_mod_name): if proto_ident == "FC": tcm_mod_build_FC_include(fabric_mod_dir_val, fabric_mod_name) elif proto_ident == "SAS": tcm_mod_build_SAS_include(fabric_mod_dir_val, fabric_mod_name) elif proto_ident == "iSCSI": tcm_mod_build_iSCSI_include(fabric_mod_dir_val, fabric_mod_name) else: print "Unsupported proto_ident: " + proto_ident sys.exit(1) return def tcm_mod_build_configfs(proto_ident, fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_configfs.c" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#include <linux/module.h>\n" buf += "#include <linux/moduleparam.h>\n" buf += "#include <linux/version.h>\n" buf += "#include <generated/utsrelease.h>\n" buf += "#include <linux/utsname.h>\n" buf += "#include <linux/init.h>\n" buf += "#include <linux/slab.h>\n" buf += "#include <linux/kthread.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/string.h>\n" buf += "#include <linux/configfs.h>\n" buf += "#include <linux/ctype.h>\n" buf += "#include <asm/unaligned.h>\n\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/target_core_transport.h>\n" buf += "#include <target/target_core_fabric_ops.h>\n" buf += "#include <target/target_core_fabric_configfs.h>\n" buf += "#include <target/target_core_fabric_lib.h>\n" buf += "#include <target/target_core_device.h>\n" buf += "#include <target/target_core_tpg.h>\n" buf += "#include <target/target_core_configfs.h>\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/configfs_macros.h>\n\n" buf += "#include \"" + fabric_mod_name + "_base.h\"\n" buf += "#include \"" + fabric_mod_name + "_fabric.h\"\n\n" buf += "/* Local pointer to allocated TCM configfs fabric module */\n" buf += "struct target_fabric_configfs *" + fabric_mod_name + "_fabric_configfs;\n\n" buf += "static struct se_node_acl *" + fabric_mod_name + "_make_nodeacl(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct se_node_acl *se_nacl, *se_nacl_new;\n" buf += " struct " + fabric_mod_name + "_nacl *nacl;\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " u64 wwpn = 0;\n" buf += " u32 nexus_depth;\n\n" buf += " /* " + fabric_mod_name + "_parse_wwn(name, &wwpn, 1) < 0)\n" buf += " return ERR_PTR(-EINVAL); */\n" buf += " se_nacl_new = " + fabric_mod_name + "_alloc_fabric_acl(se_tpg);\n" buf += " if (!(se_nacl_new))\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += "//#warning FIXME: Hardcoded nexus depth in " + fabric_mod_name + "_make_nodeacl()\n" buf += " nexus_depth = 1;\n" buf += " /*\n" buf += " * se_nacl_new may be released by core_tpg_add_initiator_node_acl()\n" buf += " * when converting a NodeACL from demo mode -> explict\n" buf += " */\n" buf += " se_nacl = core_tpg_add_initiator_node_acl(se_tpg, se_nacl_new,\n" buf += " name, nexus_depth);\n" buf += " if (IS_ERR(se_nacl)) {\n" buf += " " + fabric_mod_name + "_release_fabric_acl(se_tpg, se_nacl_new);\n" buf += " return se_nacl;\n" buf += " }\n" buf += " /*\n" buf += " * Locate our struct " + fabric_mod_name + "_nacl and set the FC Nport WWPN\n" buf += " */\n" buf += " nacl = container_of(se_nacl, struct " + fabric_mod_name + "_nacl, se_node_acl);\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " nacl->" + fabric_mod_init_port + "_wwpn = wwpn;\n" buf += " /* " + fabric_mod_name + "_format_wwn(&nacl->" + fabric_mod_init_port + "_name[0], " + fabric_mod_name.upper() + "_NAMELEN, wwpn); */\n\n" buf += " return se_nacl;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_nodeacl(struct se_node_acl *se_acl)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl = container_of(se_acl,\n" buf += " struct " + fabric_mod_name + "_nacl, se_node_acl);\n" buf += " core_tpg_del_initiator_node_acl(se_acl->se_tpg, se_acl, 1);\n" buf += " kfree(nacl);\n" buf += "}\n\n" buf += "static struct se_portal_group *" + fabric_mod_name + "_make_tpg(\n" buf += " struct se_wwn *wwn,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + "*" + fabric_mod_port + " = container_of(wwn,\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + ", " + fabric_mod_port + "_wwn);\n\n" buf += " struct " + fabric_mod_name + "_tpg *tpg;\n" buf += " unsigned long tpgt;\n" buf += " int ret;\n\n" buf += " if (strstr(name, \"tpgt_\") != name)\n" buf += " return ERR_PTR(-EINVAL);\n" buf += " if (strict_strtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)\n" buf += " return ERR_PTR(-EINVAL);\n\n" buf += " tpg = kzalloc(sizeof(struct " + fabric_mod_name + "_tpg), GFP_KERNEL);\n" buf += " if (!(tpg)) {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_tpg\");\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += " }\n" buf += " tpg->" + fabric_mod_port + " = " + fabric_mod_port + ";\n" buf += " tpg->" + fabric_mod_port + "_tpgt = tpgt;\n\n" buf += " ret = core_tpg_register(&" + fabric_mod_name + "_fabric_configfs->tf_ops, wwn,\n" buf += " &tpg->se_tpg, (void *)tpg,\n" buf += " TRANSPORT_TPG_TYPE_NORMAL);\n" buf += " if (ret < 0) {\n" buf += " kfree(tpg);\n" buf += " return NULL;\n" buf += " }\n" buf += " return &tpg->se_tpg;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_tpg(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n\n" buf += " core_tpg_deregister(se_tpg);\n" buf += " kfree(tpg);\n" buf += "}\n\n" buf += "static struct se_wwn *" + fabric_mod_name + "_make_" + fabric_mod_port + "(\n" buf += " struct target_fabric_configfs *tf,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + ";\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " u64 wwpn = 0;\n\n" buf += " /* if (" + fabric_mod_name + "_parse_wwn(name, &wwpn, 1) < 0)\n" buf += " return ERR_PTR(-EINVAL); */\n\n" buf += " " + fabric_mod_port + " = kzalloc(sizeof(struct " + fabric_mod_name + "_" + fabric_mod_port + "), GFP_KERNEL);\n" buf += " if (!(" + fabric_mod_port + ")) {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_" + fabric_mod_port + "\");\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += " }\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " " + fabric_mod_port + "->" + fabric_mod_port + "_wwpn = wwpn;\n" buf += " /* " + fabric_mod_name + "_format_wwn(&" + fabric_mod_port + "->" + fabric_mod_port + "_name[0], " + fabric_mod_name.upper() + "__NAMELEN, wwpn); */\n\n" buf += " return &" + fabric_mod_port + "->" + fabric_mod_port + "_wwn;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_" + fabric_mod_port + "(struct se_wwn *wwn)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = container_of(wwn,\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + ", " + fabric_mod_port + "_wwn);\n" buf += " kfree(" + fabric_mod_port + ");\n" buf += "}\n\n" buf += "static ssize_t " + fabric_mod_name + "_wwn_show_attr_version(\n" buf += " struct target_fabric_configfs *tf,\n" buf += " char *page)\n" buf += "{\n" buf += " return sprintf(page, \"" + fabric_mod_name.upper() + " fabric module %s on %s/%s\"\n" buf += " \"on \"UTS_RELEASE\"\\n\", " + fabric_mod_name.upper() + "_VERSION, utsname()->sysname,\n" buf += " utsname()->machine);\n" buf += "}\n\n" buf += "TF_WWN_ATTR_RO(" + fabric_mod_name + ", version);\n\n" buf += "static struct configfs_attribute *" + fabric_mod_name + "_wwn_attrs[] = {\n" buf += " &" + fabric_mod_name + "_wwn_version.attr,\n" buf += " NULL,\n" buf += "};\n\n" buf += "static struct target_core_fabric_ops " + fabric_mod_name + "_ops = {\n" buf += " .get_fabric_name = " + fabric_mod_name + "_get_fabric_name,\n" buf += " .get_fabric_proto_ident = " + fabric_mod_name + "_get_fabric_proto_ident,\n" buf += " .tpg_get_wwn = " + fabric_mod_name + "_get_fabric_wwn,\n" buf += " .tpg_get_tag = " + fabric_mod_name + "_get_tag,\n" buf += " .tpg_get_default_depth = " + fabric_mod_name + "_get_default_depth,\n" buf += " .tpg_get_pr_transport_id = " + fabric_mod_name + "_get_pr_transport_id,\n" buf += " .tpg_get_pr_transport_id_len = " + fabric_mod_name + "_get_pr_transport_id_len,\n" buf += " .tpg_parse_pr_out_transport_id = " + fabric_mod_name + "_parse_pr_out_transport_id,\n" buf += " .tpg_check_demo_mode = " + fabric_mod_name + "_check_false,\n" buf += " .tpg_check_demo_mode_cache = " + fabric_mod_name + "_check_true,\n" buf += " .tpg_check_demo_mode_write_protect = " + fabric_mod_name + "_check_true,\n" buf += " .tpg_check_prod_mode_write_protect = " + fabric_mod_name + "_check_false,\n" buf += " .tpg_alloc_fabric_acl = " + fabric_mod_name + "_alloc_fabric_acl,\n" buf += " .tpg_release_fabric_acl = " + fabric_mod_name + "_release_fabric_acl,\n" buf += " .tpg_get_inst_index = " + fabric_mod_name + "_tpg_get_inst_index,\n" buf += " .release_cmd_to_pool = " + fabric_mod_name + "_release_cmd,\n" buf += " .release_cmd_direct = " + fabric_mod_name + "_release_cmd,\n" buf += " .shutdown_session = " + fabric_mod_name + "_shutdown_session,\n" buf += " .close_session = " + fabric_mod_name + "_close_session,\n" buf += " .stop_session = " + fabric_mod_name + "_stop_session,\n" buf += " .fall_back_to_erl0 = " + fabric_mod_name + "_reset_nexus,\n" buf += " .sess_logged_in = " + fabric_mod_name + "_sess_logged_in,\n" buf += " .sess_get_index = " + fabric_mod_name + "_sess_get_index,\n" buf += " .sess_get_initiator_sid = NULL,\n" buf += " .write_pending = " + fabric_mod_name + "_write_pending,\n" buf += " .write_pending_status = " + fabric_mod_name + "_write_pending_status,\n" buf += " .set_default_node_attributes = " + fabric_mod_name + "_set_default_node_attrs,\n" buf += " .get_task_tag = " + fabric_mod_name + "_get_task_tag,\n" buf += " .get_cmd_state = " + fabric_mod_name + "_get_cmd_state,\n" buf += " .new_cmd_failure = " + fabric_mod_name + "_new_cmd_failure,\n" buf += " .queue_data_in = " + fabric_mod_name + "_queue_data_in,\n" buf += " .queue_status = " + fabric_mod_name + "_queue_status,\n" buf += " .queue_tm_rsp = " + fabric_mod_name + "_queue_tm_rsp,\n" buf += " .get_fabric_sense_len = " + fabric_mod_name + "_get_fabric_sense_len,\n" buf += " .set_fabric_sense_len = " + fabric_mod_name + "_set_fabric_sense_len,\n" buf += " .is_state_remove = " + fabric_mod_name + "_is_state_remove,\n" buf += " .pack_lun = " + fabric_mod_name + "_pack_lun,\n" buf += " /*\n" buf += " * Setup function pointers for generic logic in target_core_fabric_configfs.c\n" buf += " */\n" buf += " .fabric_make_wwn = " + fabric_mod_name + "_make_" + fabric_mod_port + ",\n" buf += " .fabric_drop_wwn = " + fabric_mod_name + "_drop_" + fabric_mod_port + ",\n" buf += " .fabric_make_tpg = " + fabric_mod_name + "_make_tpg,\n" buf += " .fabric_drop_tpg = " + fabric_mod_name + "_drop_tpg,\n" buf += " .fabric_post_link = NULL,\n" buf += " .fabric_pre_unlink = NULL,\n" buf += " .fabric_make_np = NULL,\n" buf += " .fabric_drop_np = NULL,\n" buf += " .fabric_make_nodeacl = " + fabric_mod_name + "_make_nodeacl,\n" buf += " .fabric_drop_nodeacl = " + fabric_mod_name + "_drop_nodeacl,\n" buf += "};\n\n" buf += "static int " + fabric_mod_name + "_register_configfs(void)\n" buf += "{\n" buf += " struct target_fabric_configfs *fabric;\n" buf += " int ret;\n\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + " fabric module %s on %s/%s\"\n" buf += " \" on \"UTS_RELEASE\"\\n\"," + fabric_mod_name.upper() + "_VERSION, utsname()->sysname,\n" buf += " utsname()->machine);\n" buf += " /*\n" buf += " * Register the top level struct config_item_type with TCM core\n" buf += " */\n" buf += " fabric = target_fabric_configfs_init(THIS_MODULE, \"" + fabric_mod_name[4:] + "\");\n" buf += " if (!(fabric)) {\n" buf += " printk(KERN_ERR \"target_fabric_configfs_init() failed\\n\");\n" buf += " return -ENOMEM;\n" buf += " }\n" buf += " /*\n" buf += " * Setup fabric->tf_ops from our local " + fabric_mod_name + "_ops\n" buf += " */\n" buf += " fabric->tf_ops = " + fabric_mod_name + "_ops;\n" buf += " /*\n" buf += " * Setup default attribute lists for various fabric->tf_cit_tmpl\n" buf += " */\n" buf += " TF_CIT_TMPL(fabric)->tfc_wwn_cit.ct_attrs = " + fabric_mod_name + "_wwn_attrs;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_attrib_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_param_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_np_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_auth_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_param_cit.ct_attrs = NULL;\n" buf += " /*\n" buf += " * Register the fabric for use within TCM\n" buf += " */\n" buf += " ret = target_fabric_configfs_register(fabric);\n" buf += " if (ret < 0) {\n" buf += " printk(KERN_ERR \"target_fabric_configfs_register() failed\"\n" buf += " \" for " + fabric_mod_name.upper() + "\\n\");\n" buf += " return ret;\n" buf += " }\n" buf += " /*\n" buf += " * Setup our local pointer to *fabric\n" buf += " */\n" buf += " " + fabric_mod_name + "_fabric_configfs = fabric;\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + "[0] - Set fabric -> " + fabric_mod_name + "_fabric_configfs\\n\");\n" buf += " return 0;\n" buf += "};\n\n" buf += "static void " + fabric_mod_name + "_deregister_configfs(void)\n" buf += "{\n" buf += " if (!(" + fabric_mod_name + "_fabric_configfs))\n" buf += " return;\n\n" buf += " target_fabric_configfs_deregister(" + fabric_mod_name + "_fabric_configfs);\n" buf += " " + fabric_mod_name + "_fabric_configfs = NULL;\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + "[0] - Cleared " + fabric_mod_name + "_fabric_configfs\\n\");\n" buf += "};\n\n" buf += "static int __init " + fabric_mod_name + "_init(void)\n" buf += "{\n" buf += " int ret;\n\n" buf += " ret = " + fabric_mod_name + "_register_configfs();\n" buf += " if (ret < 0)\n" buf += " return ret;\n\n" buf += " return 0;\n" buf += "};\n\n" buf += "static void " + fabric_mod_name + "_exit(void)\n" buf += "{\n" buf += " " + fabric_mod_name + "_deregister_configfs();\n" buf += "};\n\n" buf += "#ifdef MODULE\n" buf += "MODULE_DESCRIPTION(\"" + fabric_mod_name.upper() + " series fabric driver\");\n" buf += "MODULE_LICENSE(\"GPL\");\n" buf += "module_init(" + fabric_mod_name + "_init);\n" buf += "module_exit(" + fabric_mod_name + "_exit);\n" buf += "#endif\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_scan_fabric_ops(tcm_dir): fabric_ops_api = tcm_dir + "include/target/target_core_fabric_ops.h" print "Using tcm_mod_scan_fabric_ops: " + fabric_ops_api process_fo = 0; p = open(fabric_ops_api, 'r') line = p.readline() while line: if process_fo == 0 and re.search('struct target_core_fabric_ops {', line): line = p.readline() continue if process_fo == 0: process_fo = 1; line = p.readline() # Search for function pointer if not re.search('\(\*', line): continue fabric_ops.append(line.rstrip()) continue line = p.readline() # Search for function pointer if not re.search('\(\*', line): continue fabric_ops.append(line.rstrip()) p.close() return def tcm_mod_dump_fabric_ops(proto_ident, fabric_mod_dir_var, fabric_mod_name): buf = "" bufi = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_fabric.c" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) fi = fabric_mod_dir_var + "/" + fabric_mod_name + "_fabric.h" print "Writing file: " + fi pi = open(fi, 'w') if not pi: tcm_mod_err("Unable to open file: " + fi) buf = "#include <linux/slab.h>\n" buf += "#include <linux/kthread.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/list.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/string.h>\n" buf += "#include <linux/ctype.h>\n" buf += "#include <asm/unaligned.h>\n" buf += "#include <scsi/scsi.h>\n" buf += "#include <scsi/scsi_host.h>\n" buf += "#include <scsi/scsi_device.h>\n" buf += "#include <scsi/scsi_cmnd.h>\n" buf += "#include <scsi/libfc.h>\n\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/target_core_transport.h>\n" buf += "#include <target/target_core_fabric_ops.h>\n" buf += "#include <target/target_core_fabric_lib.h>\n" buf += "#include <target/target_core_device.h>\n" buf += "#include <target/target_core_tpg.h>\n" buf += "#include <target/target_core_configfs.h>\n\n" buf += "#include \"" + fabric_mod_name + "_base.h\"\n" buf += "#include \"" + fabric_mod_name + "_fabric.h\"\n\n" buf += "int " + fabric_mod_name + "_check_true(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_check_true(struct se_portal_group *);\n" buf += "int " + fabric_mod_name + "_check_false(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_check_false(struct se_portal_group *);\n" total_fabric_ops = len(fabric_ops) i = 0 while i < total_fabric_ops: fo = fabric_ops[i] i += 1 # print "fabric_ops: " + fo if re.search('get_fabric_name', fo): buf += "char *" + fabric_mod_name + "_get_fabric_name(void)\n" buf += "{\n" buf += " return \"" + fabric_mod_name[4:] + "\";\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_get_fabric_name(void);\n" continue if re.search('get_fabric_proto_ident', fo): buf += "u8 " + fabric_mod_name + "_get_fabric_proto_ident(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " u8 proto_id;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " proto_id = fc_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " proto_id = sas_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " proto_id = iscsi_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" buf += " }\n\n" buf += " return proto_id;\n" buf += "}\n\n" bufi += "u8 " + fabric_mod_name + "_get_fabric_proto_ident(struct se_portal_group *);\n" if re.search('get_wwn', fo): buf += "char *" + fabric_mod_name + "_get_fabric_wwn(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n\n" buf += " return &" + fabric_mod_port + "->" + fabric_mod_port + "_name[0];\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_get_fabric_wwn(struct se_portal_group *);\n" if re.search('get_tag', fo): buf += "u16 " + fabric_mod_name + "_get_tag(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " return tpg->" + fabric_mod_port + "_tpgt;\n" buf += "}\n\n" bufi += "u16 " + fabric_mod_name + "_get_tag(struct se_portal_group *);\n" if re.search('get_default_depth', fo): buf += "u32 " + fabric_mod_name + "_get_default_depth(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_default_depth(struct se_portal_group *);\n" if re.search('get_pr_transport_id\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_pr_transport_id(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl,\n" buf += " struct t10_pr_registration *pr_reg,\n" buf += " int *format_code,\n" buf += " unsigned char *buf)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " int ret = 0;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " ret = fc_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " ret = sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " ret = iscsi_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" buf += " }\n\n" buf += " return ret;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_pr_transport_id(struct se_portal_group *,\n" bufi += " struct se_node_acl *, struct t10_pr_registration *,\n" bufi += " int *, unsigned char *);\n" if re.search('get_pr_transport_id_len\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_pr_transport_id_len(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl,\n" buf += " struct t10_pr_registration *pr_reg,\n" buf += " int *format_code)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " int ret = 0;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " ret = fc_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " ret = sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " ret = iscsi_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" buf += " }\n\n" buf += " return ret;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_pr_transport_id_len(struct se_portal_group *,\n" bufi += " struct se_node_acl *, struct t10_pr_registration *,\n" bufi += " int *);\n" if re.search('parse_pr_out_transport_id\)\(', fo): buf += "char *" + fabric_mod_name + "_parse_pr_out_transport_id(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " const char *buf,\n" buf += " u32 *out_tid_len,\n" buf += " char **port_nexus_ptr)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " char *tid = NULL;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " tid = fc_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " tid = sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " tid = iscsi_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" buf += " }\n\n" buf += " return tid;\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_parse_pr_out_transport_id(struct se_portal_group *,\n" bufi += " const char *, u32 *, char **);\n" if re.search('alloc_fabric_acl\)\(', fo): buf += "struct se_node_acl *" + fabric_mod_name + "_alloc_fabric_acl(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl;\n\n" buf += " nacl = kzalloc(sizeof(struct " + fabric_mod_name + "_nacl), GFP_KERNEL);\n" buf += " if (!(nacl)) {\n" buf += " printk(KERN_ERR \"Unable to alocate struct " + fabric_mod_name + "_nacl\\n\");\n" buf += " return NULL;\n" buf += " }\n\n" buf += " return &nacl->se_node_acl;\n" buf += "}\n\n" bufi += "struct se_node_acl *" + fabric_mod_name + "_alloc_fabric_acl(struct se_portal_group *);\n" if re.search('release_fabric_acl\)\(', fo): buf += "void " + fabric_mod_name + "_release_fabric_acl(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl = container_of(se_nacl,\n" buf += " struct " + fabric_mod_name + "_nacl, se_node_acl);\n" buf += " kfree(nacl);\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_release_fabric_acl(struct se_portal_group *,\n" bufi += " struct se_node_acl *);\n" if re.search('tpg_get_inst_index\)\(', fo): buf += "u32 " + fabric_mod_name + "_tpg_get_inst_index(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_tpg_get_inst_index(struct se_portal_group *);\n" if re.search('release_cmd_to_pool', fo): buf += "void " + fabric_mod_name + "_release_cmd(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_release_cmd(struct se_cmd *);\n" if re.search('shutdown_session\)\(', fo): buf += "int " + fabric_mod_name + "_shutdown_session(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_shutdown_session(struct se_session *);\n" if re.search('close_session\)\(', fo): buf += "void " + fabric_mod_name + "_close_session(struct se_session *se_sess)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_close_session(struct se_session *);\n" if re.search('stop_session\)\(', fo): buf += "void " + fabric_mod_name + "_stop_session(struct se_session *se_sess, int sess_sleep , int conn_sleep)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_stop_session(struct se_session *, int, int);\n" if re.search('fall_back_to_erl0\)\(', fo): buf += "void " + fabric_mod_name + "_reset_nexus(struct se_session *se_sess)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_reset_nexus(struct se_session *);\n" if re.search('sess_logged_in\)\(', fo): buf += "int " + fabric_mod_name + "_sess_logged_in(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_sess_logged_in(struct se_session *);\n" if re.search('sess_get_index\)\(', fo): buf += "u32 " + fabric_mod_name + "_sess_get_index(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_sess_get_index(struct se_session *);\n" if re.search('write_pending\)\(', fo): buf += "int " + fabric_mod_name + "_write_pending(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_write_pending(struct se_cmd *);\n" if re.search('write_pending_status\)\(', fo): buf += "int " + fabric_mod_name + "_write_pending_status(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_write_pending_status(struct se_cmd *);\n" if re.search('set_default_node_attributes\)\(', fo): buf += "void " + fabric_mod_name + "_set_default_node_attrs(struct se_node_acl *nacl)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_set_default_node_attrs(struct se_node_acl *);\n" if re.search('get_task_tag\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_task_tag(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_task_tag(struct se_cmd *);\n" if re.search('get_cmd_state\)\(', fo): buf += "int " + fabric_mod_name + "_get_cmd_state(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_get_cmd_state(struct se_cmd *);\n" if re.search('new_cmd_failure\)\(', fo): buf += "void " + fabric_mod_name + "_new_cmd_failure(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_new_cmd_failure(struct se_cmd *);\n" if re.search('queue_data_in\)\(', fo): buf += "int " + fabric_mod_name + "_queue_data_in(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_data_in(struct se_cmd *);\n" if re.search('queue_status\)\(', fo): buf += "int " + fabric_mod_name + "_queue_status(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_status(struct se_cmd *);\n" if re.search('queue_tm_rsp\)\(', fo): buf += "int " + fabric_mod_name + "_queue_tm_rsp(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_tm_rsp(struct se_cmd *);\n" if re.search('get_fabric_sense_len\)\(', fo): buf += "u16 " + fabric_mod_name + "_get_fabric_sense_len(void)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u16 " + fabric_mod_name + "_get_fabric_sense_len(void);\n" if re.search('set_fabric_sense_len\)\(', fo): buf += "u16 " + fabric_mod_name + "_set_fabric_sense_len(struct se_cmd *se_cmd, u32 sense_length)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u16 " + fabric_mod_name + "_set_fabric_sense_len(struct se_cmd *, u32);\n" if re.search('is_state_remove\)\(', fo): buf += "int " + fabric_mod_name + "_is_state_remove(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_is_state_remove(struct se_cmd *);\n" if re.search('pack_lun\)\(', fo): buf += "u64 " + fabric_mod_name + "_pack_lun(unsigned int lun)\n" buf += "{\n" buf += " WARN_ON(lun >= 256);\n" buf += " /* Caller wants this byte-swapped */\n" buf += " return cpu_to_le64((lun & 0xff) << 8);\n" buf += "}\n\n" bufi += "u64 " + fabric_mod_name + "_pack_lun(unsigned int);\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() ret = pi.write(bufi) if ret: tcm_mod_err("Unable to write fi: " + fi) pi.close() return def tcm_mod_build_kbuild(fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/Makefile" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) buf += fabric_mod_name + "-objs := " + fabric_mod_name + "_fabric.o \\\n" buf += " " + fabric_mod_name + "_configfs.o\n" buf += "obj-$(CONFIG_" + fabric_mod_name.upper() + ") += " + fabric_mod_name + ".o\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_build_kconfig(fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/Kconfig" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) buf = "config " + fabric_mod_name.upper() + "\n" buf += " tristate \"" + fabric_mod_name.upper() + " fabric module\"\n" buf += " depends on TARGET_CORE && CONFIGFS_FS\n" buf += " default n\n" buf += " ---help---\n" buf += " Say Y here to enable the " + fabric_mod_name.upper() + " fabric module\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_add_kbuild(tcm_dir, fabric_mod_name): buf = "obj-$(CONFIG_" + fabric_mod_name.upper() + ") += " + fabric_mod_name.lower() + "/\n" kbuild = tcm_dir + "/drivers/target/Makefile" f = open(kbuild, 'a') f.write(buf) f.close() return def tcm_mod_add_kconfig(tcm_dir, fabric_mod_name): buf = "source \"drivers/target/" + fabric_mod_name.lower() + "/Kconfig\"\n" kconfig = tcm_dir + "/drivers/target/Kconfig" f = open(kconfig, 'a') f.write(buf) f.close() return def main(modname, proto_ident): # proto_ident = "FC" # proto_ident = "SAS" # proto_ident = "iSCSI" tcm_dir = os.getcwd(); tcm_dir += "/../../" print "tcm_dir: " + tcm_dir fabric_mod_name = modname fabric_mod_dir = tcm_dir + "drivers/target/" + fabric_mod_name print "Set fabric_mod_name: " + fabric_mod_name print "Set fabric_mod_dir: " + fabric_mod_dir print "Using proto_ident: " + proto_ident if proto_ident != "FC" and proto_ident != "SAS" and proto_ident != "iSCSI": print "Unsupported proto_ident: " + proto_ident sys.exit(1) ret = tcm_mod_create_module_subdir(fabric_mod_dir) if ret: print "tcm_mod_create_module_subdir() failed because module already exists!" sys.exit(1) tcm_mod_build_base_includes(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_scan_fabric_ops(tcm_dir) tcm_mod_dump_fabric_ops(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_build_configfs(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_build_kbuild(fabric_mod_dir, fabric_mod_name) tcm_mod_build_kconfig(fabric_mod_dir, fabric_mod_name) input = raw_input("Would you like to add " + fabric_mod_name + "to drivers/target/Makefile..? [yes,no]: ") if input == "yes" or input == "y": tcm_mod_add_kbuild(tcm_dir, fabric_mod_name) input = raw_input("Would you like to add " + fabric_mod_name + "to drivers/target/Kconfig..? [yes,no]: ") if input == "yes" or input == "y": tcm_mod_add_kconfig(tcm_dir, fabric_mod_name) return parser = optparse.OptionParser() parser.add_option('-m', '--modulename', help='Module name', dest='modname', action='store', nargs=1, type='string') parser.add_option('-p', '--protoident', help='Protocol Ident', dest='protoident', action='store', nargs=1, type='string') (opts, args) = parser.parse_args() mandatories = ['modname', 'protoident'] for m in mandatories: if not opts.__dict__[m]: print "mandatory option is missing\n" parser.print_help() exit(-1) if __name__ == "__main__": main(str(opts.modname), opts.protoident)
gpl-2.0
onshape/jenkins-job-builder
jenkins_jobs/modules/builders.py
1
171629
# Copyright 2012 Hewlett-Packard Development Company, L.P. # Copyright 2012 Varnish Software AS # # 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. """ Builders define actions that the Jenkins job should execute. Examples include shell scripts or maven targets. The ``builders`` attribute in the :ref:`Job` definition accepts a list of builders to invoke. They may be components defined below, locally defined macros (using the top level definition of ``builder:``, or locally defined components found via the ``jenkins_jobs.builders`` entry point. **Component**: builders :Macro: builder :Entry Point: jenkins_jobs.builders Example:: job: name: test_job builders: - shell: "make test" """ import logging import xml.etree.ElementTree as XML from jenkins_jobs.errors import is_sequence from jenkins_jobs.errors import InvalidAttributeError from jenkins_jobs.errors import JenkinsJobsException from jenkins_jobs.errors import MissingAttributeError import jenkins_jobs.modules.base import jenkins_jobs.modules.helpers as helpers from jenkins_jobs.modules.helpers import append_git_revision_config import pkg_resources from jenkins_jobs.modules.helpers import cloudformation_init from jenkins_jobs.modules.helpers import cloudformation_region_dict from jenkins_jobs.modules.helpers import cloudformation_stack from jenkins_jobs.modules.helpers import config_file_provider_builder from jenkins_jobs.modules.helpers import config_file_provider_settings from jenkins_jobs.modules.helpers import convert_mapping_to_xml from jenkins_jobs.modules.helpers import copyartifact_build_selector from jenkins_jobs.modules import hudson_model from jenkins_jobs.modules.publishers import ssh logger = logging.getLogger(__name__) def shell(registry, xml_parent, data): """yaml: shell Execute a shell command. :arg str parameter: the shell command to execute Example: .. literalinclude:: /../../tests/builders/fixtures/shell.yaml :language: yaml """ shell = XML.SubElement(xml_parent, 'hudson.tasks.Shell') XML.SubElement(shell, 'command').text = data def python(registry, xml_parent, data): """yaml: python Execute a python command. Requires the Jenkins :jenkins-wiki:`Python plugin <Python+Plugin>`. :arg str parameter: the python command to execute Example: .. literalinclude:: /../../tests/builders/fixtures/python.yaml :language: yaml """ python = XML.SubElement(xml_parent, 'hudson.plugins.python.Python') XML.SubElement(python, 'command').text = data def copyartifact(registry, xml_parent, data): """yaml: copyartifact Copy artifact from another project. Requires the :jenkins-wiki:`Copy Artifact plugin <Copy+Artifact+Plugin>`. Please note using the multijob-build for which-build argument requires the :jenkins-wiki:`Multijob plugin <Multijob+Plugin>` :arg str project: Project to copy from :arg str filter: what files to copy :arg str target: Target base directory for copy, blank means use workspace :arg bool flatten: Flatten directories (default false) :arg bool optional: If the artifact is missing (for any reason) and optional is true, the build won't fail because of this builder (default false) :arg bool do-not-fingerprint: Disable automatic fingerprinting of copied artifacts (default false) :arg str which-build: which build to get artifacts from (optional, default last-successful) :which-build values: * **last-successful** * **last-completed** * **specific-build** * **last-saved** * **upstream-build** * **permalink** * **workspace-latest** * **build-param** * **downstream-build** * **multijob-build** :arg str build-number: specifies the build number to get when when specific-build is specified as which-build :arg str permalink: specifies the permalink to get when permalink is specified as which-build :permalink values: * **last** * **last-stable** * **last-successful** * **last-failed** * **last-unstable** * **last-unsuccessful** :arg bool stable: specifies to get only last stable build when last-successful is specified as which-build :arg bool fallback-to-last-successful: specifies to fallback to last successful build when upstream-build is specified as which-build :arg string param: specifies to use a build parameter to get the build when build-param is specified as which-build :arg str upstream-project-name: specifies the project name of downstream when downstream-build is specified as which-build :arg str upstream-build-number: specifies the number of the build to find its downstream build when downstream-build is specified as which-build :arg string parameter-filters: Filter matching jobs based on these parameters (optional) Example: .. literalinclude:: ../../tests/builders/fixtures/copy-artifact001.yaml :language: yaml Multijob Example: .. literalinclude:: ../../tests/builders/fixtures/copy-artifact004.yaml :language: yaml """ t = XML.SubElement(xml_parent, 'hudson.plugins.copyartifact.CopyArtifact') mappings = [ # Warning: this only works with copy artifact version 1.26+, # for copy artifact version 1.25- the 'projectName' element needs # to be used instead of 'project' ('project', 'project', None), ('filter', 'filter', ''), ('target', 'target', ''), ('flatten', 'flatten', False), ('optional', 'optional', False), ('do-not-fingerprint', 'doNotFingerprintArtifacts', False), ('parameter-filters', 'parameters', '') ] convert_mapping_to_xml(t, data, mappings, fail_required=True) copyartifact_build_selector(t, data) def change_assembly_version(registry, xml_parent, data): """yaml: change-assembly-version Change the assembly version. Requires the Jenkins :jenkins-wiki:`Change Assembly Version <Change+Assembly+Version>`. :arg str version: Set the new version number for replace (default 1.0.0) :arg str assemblyFile: The file name to search (default AssemblyInfo.cs) Minimal Example: .. literalinclude:: /../../tests/builders/fixtures/changeassemblyversion-minimal.yaml :language: yaml Full Example: .. literalinclude:: /../../tests/builders/fixtures/changeassemblyversion-full.yaml :language: yaml """ cav_builder_tag = ('org.jenkinsci.plugins.changeassemblyversion.' 'ChangeAssemblyVersion') cav = XML.SubElement(xml_parent, cav_builder_tag) mappings = [ ('version', 'task', '1.0.0'), ('assembly-file', 'assemblyFile', 'AssemblyInfo.cs'), ] convert_mapping_to_xml(cav, data, mappings, fail_required=True) def fingerprint(registry, xml_parent, data): """yaml: fingerprint Adds the ability to generate fingerprints as build steps instead of waiting for a build to complete. Requires the Jenkins :jenkins-wiki:`Fingerprint Plugin <Fingerprint+Plugin>`. :arg str targets: Files to fingerprint (default '') Full Example: .. literalinclude:: /../../tests/builders/fixtures/fingerprint-full.yaml :language: yaml Minimal Example: .. literalinclude:: /../../tests/builders/fixtures/fingerprint-minimal.yaml :language: yaml """ fingerprint = XML.SubElement( xml_parent, 'hudson.plugins.createfingerprint.CreateFingerprint') fingerprint.set('plugin', 'create-fingerprint') mapping = [('targets', 'targets', '')] convert_mapping_to_xml(fingerprint, data, mapping, fail_required=True) def ant(registry, xml_parent, data): """yaml: ant Execute an ant target. Requires the Jenkins :jenkins-wiki:`Ant Plugin <Ant+Plugin>`. To setup this builder you can either reference the list of targets or use named parameters. Below is a description of both forms: *1) Listing targets:* After the ant directive, simply pass as argument a space separated list of targets to build. :Parameter: space separated list of Ant targets Example to call two Ant targets: .. literalinclude:: ../../tests/builders/fixtures/ant001.yaml :language: yaml The build file would be whatever the Jenkins Ant Plugin is set to use per default (i.e build.xml in the workspace root). *2) Using named parameters:* :arg str targets: the space separated list of ANT targets. :arg str buildfile: the path to the ANT build file. :arg list properties: Passed to ant script using -Dkey=value (optional) :arg str ant-name: the name of the ant installation, (default 'default') (optional) :arg str java-opts: java options for ant, can have multiples, must be in quotes (optional) Example specifying the build file too and several targets: .. literalinclude:: ../../tests/builders/fixtures/ant002.yaml :language: yaml """ ant = XML.SubElement(xml_parent, 'hudson.tasks.Ant') if type(data) is str: # Support for short form: -ant: "target" data = {'targets': data} for setting, value in sorted(data.items()): if setting == 'targets': targets = XML.SubElement(ant, 'targets') targets.text = value if setting == 'buildfile': buildfile = XML.SubElement(ant, 'buildFile') buildfile.text = value if setting == 'properties': properties = data['properties'] prop_string = '' for prop, val in properties.items(): prop_string += "%s=%s\n" % (prop, val) prop_element = XML.SubElement(ant, 'properties') prop_element.text = prop_string if setting == 'java-opts': javaopts = data['java-opts'] jopt_string = ' '.join(javaopts) jopt_element = XML.SubElement(ant, 'antOpts') jopt_element.text = jopt_string XML.SubElement(ant, 'antName').text = data.get('ant-name', 'default') def trigger_remote(registry, xml_parent, data): """yaml: trigger-remote Trigger build of job on remote Jenkins instance. :jenkins-wiki:`Parameterized Remote Trigger Plugin <Parameterized+Remote+Trigger+Plugin>` Please note that this plugin requires system configuration on the Jenkins Master that is unavailable from individual job views; specifically, one must add remote jenkins servers whose 'Display Name' field are what make up valid fields on the `remote-jenkins-name` attribute below. :arg str remote-jenkins-name: the remote Jenkins server (required) :arg str job: the Jenkins project to trigger on the remote Jenkins server (required) :arg bool should-not-fail-build: if true, remote job failure will not lead current job to fail (default false) :arg bool prevent-remote-build-queue: if true, wait to trigger remote builds until no other builds (default false) :arg bool block: whether to wait for the trigger jobs to finish or not (default true) :arg str poll-interval: polling interval in seconds for checking statues of triggered remote job, only necessary if current job is configured to block (default 10) :arg str connection-retry-limit: number of connection attempts to remote Jenkins server before giving up. (default 5) :arg str predefined-parameters: predefined parameters to send to the remote job when triggering it (optional) :arg str property-file: file in workspace of current job containing additional parameters to be set on remote job (optional) Example: .. literalinclude:: /../../tests/builders/fixtures/trigger-remote/trigger-remote001.yaml :language: yaml """ triggerr = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.' 'ParameterizedRemoteTrigger.' 'RemoteBuildConfiguration') XML.SubElement(triggerr, 'remoteJenkinsName').text = data.get('remote-jenkins-name') XML.SubElement(triggerr, 'token').text = data.get('token', '') for attribute in ['job', 'remote-jenkins-name']: if attribute not in data: raise MissingAttributeError(attribute, "builders.trigger-remote") if data[attribute] == '': raise InvalidAttributeError(attribute, data[attribute], "builders.trigger-remote") XML.SubElement(triggerr, 'job').text = data.get('job') XML.SubElement(triggerr, 'shouldNotFailBuild').text = str( data.get('should-not-fail-build', False)).lower() XML.SubElement(triggerr, 'pollInterval').text = str(data.get('poll-interval', 10)) XML.SubElement(triggerr, 'connectionRetryLimit').text = str( data.get('connection-retry-limit', 5)) XML.SubElement(triggerr, 'preventRemoteBuildQueue').text = str( data.get('prevent-remote-build-queue', False)).lower() XML.SubElement(triggerr, 'blockBuildUntilComplete').text = str( data.get('block', True)).lower() if 'predefined-parameters' in data: parameters = XML.SubElement(triggerr, 'parameters') parameters.text = data.get('predefined-parameters', '') params_list = parameters.text.split("\n") parameter_list = XML.SubElement(triggerr, 'parameterList') for param in params_list: if param == '': continue tmp = XML.SubElement(parameter_list, 'string') tmp.text = param if 'property-file' in data and data['property-file'] != '': XML.SubElement(triggerr, 'loadParamsFromFile').text = 'true' XML.SubElement(triggerr, 'parameterFile').text = data.get('property-file') else: XML.SubElement(triggerr, 'loadParamsFromFile').text = 'false' XML.SubElement(triggerr, 'overrideAuth').text = "false" def trigger_builds(registry, xml_parent, data): """yaml: trigger-builds Trigger builds of other jobs. Requires the Jenkins :jenkins-wiki:`Parameterized Trigger Plugin <Parameterized+Trigger+Plugin>`. :arg list project: the Jenkins project to trigger :arg str predefined-parameters: key/value pairs to be passed to the job (optional) :arg list bool-parameters: :Bool: * **name** (`str`) -- Parameter name * **value** (`bool`) -- Value to set (default false) :arg str property-file: Pass properties from file to the other job (optional) :arg bool property-file-fail-on-missing: Don't trigger if any files are missing (default true) :arg bool current-parameters: Whether to include the parameters passed to the current build to the triggered job. :arg str node-label-name: Define a name for the NodeLabel parameter to be set. Used in conjunction with node-label. Requires NodeLabel Parameter Plugin (optional) :arg str node-label: Label of the nodes where build should be triggered. Used in conjunction with node-label-name. Requires NodeLabel Parameter Plugin (optional) :arg str restrict-matrix-project: Filter that restricts the subset of the combinations that the triggered job will run (optional) :arg bool svn-revision: Whether to pass the svn revision to the triggered job (optional) :arg dict git-revision: Passes git revision to the triggered job (optional). * **combine-queued-commits** (bool): Whether to combine queued git hashes or not (default false) :arg bool block: whether to wait for the triggered jobs to finish or not (default false) :arg dict block-thresholds: Fail builds and/or mark as failed or unstable based on thresholds. Only apply if block parameter is true (optional) :block-thresholds: * **build-step-failure-threshold** (`str`) - build step failure threshold, valid values are 'never', 'SUCCESS', 'UNSTABLE', or 'FAILURE'. (default 'FAILURE') * **unstable-threshold** (`str`) - unstable threshold, valid values are 'never', 'SUCCESS', 'UNSTABLE', or 'FAILURE'. (default 'UNSTABLE') * **failure-threshold** (`str`) - overall failure threshold, valid values are 'never', 'SUCCESS', 'UNSTABLE', or 'FAILURE'. (default 'FAILURE') :arg bool same-node: Use the same node for the triggered builds that was used for this build (optional) :arg list parameter-factories: list of parameter factories :Factory: * **factory** (`str`) **filebuild** -- For every property file, invoke one build * **file-pattern** (`str`) -- File wildcard pattern * **no-files-found-action** (`str`) -- Action to perform when no files found. Valid values 'FAIL', 'SKIP', or 'NOPARMS'. (default 'SKIP') :Factory: * **factory** (`str`) **binaryfile** -- For every matching file, invoke one build * **file-pattern** (`str`) -- Artifact ID of the artifact * **no-files-found-action** (`str`) -- Action to perform when no files found. Valid values 'FAIL', 'SKIP', or 'NOPARMS'. (default 'SKIP') :Factory: * **factory** (`str`) **counterbuild** -- Invoke i=0...N builds * **from** (`int`) -- Artifact ID of the artifact * **to** (`int`) -- Version of the artifact * **step** (`int`) -- Classifier of the artifact * **parameters** (`str`) -- KEY=value pairs, one per line (default '') * **validation-fail** (`str`) -- Action to perform when stepping validation fails. Valid values 'FAIL', 'SKIP', or 'NOPARMS'. (default 'FAIL') :Factory: * **factory** (`str`) **allnodesforlabel** -- Trigger a build on all nodes having specific label. Requires NodeLabel Parameter Plugin (optional) * **name** (`str`) -- Name of the parameter to set (optional) * **node-label** (`str`) -- Label of the nodes where build should be triggered * **ignore-offline-nodes** (`bool`) -- Don't trigger build on offline nodes (default true) :Factory: * **factory** (`str`) **allonlinenodes** -- Trigger a build on every online node. Requires NodeLabel Parameter Plugin (optional) Examples: Basic usage with yaml list of projects. .. literalinclude:: /../../tests/builders/fixtures/trigger-builds/project-list.yaml :language: yaml Basic usage with passing svn revision through. .. literalinclude:: /../../tests/builders/fixtures/trigger-builds001.yaml :language: yaml Basic usage with passing git revision through. .. literalinclude:: /../../tests/builders/fixtures/trigger-builds006.yaml :language: yaml Example with all supported parameter factories. .. literalinclude:: /../../tests/builders/fixtures/trigger-builds-configfactory-multi.yaml :language: yaml """ tbuilder = XML.SubElement(xml_parent, 'hudson.plugins.parameterizedtrigger.' 'TriggerBuilder') configs = XML.SubElement(tbuilder, 'configs') for project_def in data: if 'project' not in project_def or project_def['project'] == '': logger.debug("No project specified - skipping trigger-build") continue tconfig = XML.SubElement(configs, 'hudson.plugins.parameterizedtrigger.' 'BlockableBuildTriggerConfig') tconfigs = XML.SubElement(tconfig, 'configs') if(project_def.get('current-parameters')): XML.SubElement(tconfigs, 'hudson.plugins.parameterizedtrigger.' 'CurrentBuildParameters') if(project_def.get('svn-revision')): XML.SubElement(tconfigs, 'hudson.plugins.parameterizedtrigger.' 'SubversionRevisionBuildParameters') if(project_def.get('git-revision')): append_git_revision_config(tconfigs, project_def['git-revision']) if(project_def.get('same-node')): XML.SubElement(tconfigs, 'hudson.plugins.parameterizedtrigger.' 'NodeParameters') if 'property-file' in project_def: params = XML.SubElement(tconfigs, 'hudson.plugins.parameterizedtrigger.' 'FileBuildParameters') propertiesFile = XML.SubElement(params, 'propertiesFile') propertiesFile.text = project_def['property-file'] failTriggerOnMissing = XML.SubElement(params, 'failTriggerOnMissing') failTriggerOnMissing.text = str(project_def.get( 'property-file-fail-on-missing', True)).lower() if 'predefined-parameters' in project_def: params = XML.SubElement(tconfigs, 'hudson.plugins.parameterizedtrigger.' 'PredefinedBuildParameters') properties = XML.SubElement(params, 'properties') properties.text = project_def['predefined-parameters'] if 'bool-parameters' in project_def: params = XML.SubElement(tconfigs, 'hudson.plugins.parameterizedtrigger.' 'BooleanParameters') configs = XML.SubElement(params, 'configs') for bool_param in project_def['bool-parameters']: param = XML.SubElement(configs, 'hudson.plugins.parameterizedtrigger.' 'BooleanParameterConfig') XML.SubElement(param, 'name').text = str(bool_param['name']) XML.SubElement(param, 'value').text = str( bool_param.get('value', False)).lower() if 'node-label-name' in project_def and 'node-label' in project_def: node = XML.SubElement(tconfigs, 'org.jvnet.jenkins.plugins.' 'nodelabelparameter.parameterizedtrigger.' 'NodeLabelBuildParameter') XML.SubElement(node, 'name').text = project_def['node-label-name'] XML.SubElement(node, 'nodeLabel').text = project_def['node-label'] if 'restrict-matrix-project' in project_def: params = XML.SubElement(tconfigs, 'hudson.plugins.parameterizedtrigger.' 'matrix.MatrixSubsetBuildParameters') XML.SubElement(params, 'filter').text = project_def[ 'restrict-matrix-project'] if(len(list(tconfigs)) == 0): tconfigs.set('class', 'java.util.Collections$EmptyList') if 'parameter-factories' in project_def: fconfigs = XML.SubElement(tconfig, 'configFactories') supported_factories = ['filebuild', 'binaryfile', 'counterbuild', 'allnodesforlabel', 'allonlinenodes'] supported_actions = ['SKIP', 'NOPARMS', 'FAIL'] for factory in project_def['parameter-factories']: if factory['factory'] not in supported_factories: raise InvalidAttributeError('factory', factory['factory'], supported_factories) if factory['factory'] == 'filebuild': params = XML.SubElement( fconfigs, 'hudson.plugins.parameterizedtrigger.' 'FileBuildParameterFactory') if factory['factory'] == 'binaryfile': params = XML.SubElement( fconfigs, 'hudson.plugins.parameterizedtrigger.' 'BinaryFileParameterFactory') parameterName = XML.SubElement(params, 'parameterName') parameterName.text = factory['parameter-name'] if (factory['factory'] == 'filebuild' or factory['factory'] == 'binaryfile'): filePattern = XML.SubElement(params, 'filePattern') filePattern.text = factory['file-pattern'] noFilesFoundAction = XML.SubElement( params, 'noFilesFoundAction') noFilesFoundActionValue = str(factory.get( 'no-files-found-action', 'SKIP')) if noFilesFoundActionValue not in supported_actions: raise InvalidAttributeError('no-files-found-action', noFilesFoundActionValue, supported_actions) noFilesFoundAction.text = noFilesFoundActionValue if factory['factory'] == 'counterbuild': params = XML.SubElement( fconfigs, 'hudson.plugins.parameterizedtrigger.' 'CounterBuildParameterFactory') fromProperty = XML.SubElement(params, 'from') fromProperty.text = str(factory['from']) toProperty = XML.SubElement(params, 'to') toProperty.text = str(factory['to']) stepProperty = XML.SubElement(params, 'step') stepProperty.text = str(factory['step']) paramExpr = XML.SubElement(params, 'paramExpr') paramExpr.text = str(factory.get( 'parameters', '')) validationFail = XML.SubElement(params, 'validationFail') validationFailValue = str(factory.get( 'validation-fail', 'FAIL')) if validationFailValue not in supported_actions: raise InvalidAttributeError('validation-fail', validationFailValue, supported_actions) validationFail.text = validationFailValue if factory['factory'] == 'allnodesforlabel': params = XML.SubElement( fconfigs, 'org.jvnet.jenkins.plugins.nodelabelparameter.' 'parameterizedtrigger.' 'AllNodesForLabelBuildParameterFactory') nameProperty = XML.SubElement(params, 'name') nameProperty.text = str(factory.get( 'name', '')) nodeLabel = XML.SubElement(params, 'nodeLabel') nodeLabel.text = str(factory['node-label']) ignoreOfflineNodes = XML.SubElement( params, 'ignoreOfflineNodes') ignoreOfflineNodes.text = str(factory.get( 'ignore-offline-nodes', True)).lower() if factory['factory'] == 'allonlinenodes': params = XML.SubElement( fconfigs, 'org.jvnet.jenkins.plugins.nodelabelparameter.' 'parameterizedtrigger.' 'AllNodesBuildParameterFactory') projects = XML.SubElement(tconfig, 'projects') if isinstance(project_def['project'], list): projects.text = ",".join(project_def['project']) else: projects.text = project_def['project'] condition = XML.SubElement(tconfig, 'condition') condition.text = 'ALWAYS' trigger_with_no_params = XML.SubElement(tconfig, 'triggerWithNoParameters') trigger_with_no_params.text = 'false' build_all_nodes_with_label = XML.SubElement(tconfig, 'buildAllNodesWithLabel') build_all_nodes_with_label.text = 'false' block = project_def.get('block', False) if block: block = XML.SubElement(tconfig, 'block') supported_thresholds = [['build-step-failure-threshold', 'buildStepFailureThreshold', 'FAILURE'], ['unstable-threshold', 'unstableThreshold', 'UNSTABLE'], ['failure-threshold', 'failureThreshold', 'FAILURE']] supported_threshold_values = ['never', hudson_model.SUCCESS['name'], hudson_model.UNSTABLE['name'], hudson_model.FAILURE['name']] thrsh = project_def.get('block-thresholds', False) for toptname, txmltag, tvalue in supported_thresholds: if thrsh: tvalue = thrsh.get(toptname, tvalue) if tvalue.lower() == supported_threshold_values[0]: continue if tvalue.upper() not in supported_threshold_values: raise InvalidAttributeError(toptname, tvalue, supported_threshold_values) th = XML.SubElement(block, txmltag) XML.SubElement(th, 'name').text = hudson_model.THRESHOLDS[ tvalue.upper()]['name'] XML.SubElement(th, 'ordinal').text = hudson_model.THRESHOLDS[ tvalue.upper()]['ordinal'] XML.SubElement(th, 'color').text = hudson_model.THRESHOLDS[ tvalue.upper()]['color'] XML.SubElement(th, 'completeBuild').text = "true" # If configs is empty, remove the entire tbuilder tree. if(len(configs) == 0): logger.debug("Pruning empty TriggerBuilder tree.") xml_parent.remove(tbuilder) def builders_from(registry, xml_parent, data): """yaml: builders-from Use builders from another project. Requires the Jenkins :jenkins-wiki:`Template Project Plugin <Template+Project+Plugin>`. :arg str projectName: the name of the other project Example: .. literalinclude:: ../../tests/builders/fixtures/builders-from.yaml :language: yaml """ pbs = XML.SubElement(xml_parent, 'hudson.plugins.templateproject.ProxyBuilder') XML.SubElement(pbs, 'projectName').text = data def http_request(registry, xml_parent, data): """yaml: http-request This plugin sends a http request to an url with some parameters. Requires the Jenkins :jenkins-wiki:`HTTP Request Plugin <HTTP+Request+Plugin>`. :arg str url: Specify an URL to be requested (required) :arg str mode: The http mode of the request (default GET) :mode values: * **GET** * **POST** * **PUT** * **DELETE** * **HEAD** :arg str content-type: Add 'Content-type: foo' HTTP request headers where foo is the http content-type the request is using. (default NOT_SET) :arg str accept-type: Add 'Accept: foo' HTTP request headers where foo is the http content-type to accept (default NOT_SET) :content-type and accept-type values: * **NOT_SET** * **TEXT_HTML** * **APPLICATION_JSON** * **APPLICATION_TAR** * **APPLICATION_ZIP** * **APPLICATION_OCTETSTREAM** :arg str output-file: Name of the file in which to write response data (default '') :arg int time-out: Specify a timeout value in seconds (default 0) :arg bool console-log: This allows you to turn off writing the response body to the log (default false) :arg bool pass-build: Should build parameters be passed to the URL being called (default false) :arg str valid-response-codes: Configure response code to mark an execution as success. You can configure simple code such as "200" or multiple codes separeted by comma(',') e.g. "200,404,500" Interval of codes should be in format From:To e.g. "100:399". The default (as if empty) is to fail to 4xx and 5xx. That means success from 100 to 399 "100:399" To ignore any response code use "100:599". (default '') :arg str valid-response-content: If set response must contain this string to mark an execution as success (default '') :arg str authentication-key: Authentication that will be used before this request. Authentications are created in global configuration under a key name that is selected here. :arg list custom-headers: list of header parameters :custom-header: * **name** (`str`) -- Name of the header * **value** (`str`) -- Value of the header Example: .. literalinclude:: ../../tests/builders/fixtures/http-request-minimal.yaml :language: yaml .. literalinclude:: ../../tests/builders/fixtures/http-request-full.yaml :language: yaml """ http_request = XML.SubElement(xml_parent, 'jenkins.plugins.http__request.HttpRequest') http_request.set('plugin', 'http_request') valid_modes = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD'] valid_types = ['NOT_SET', 'TEXT_HTML', 'APPLICATION_JSON', 'APPLICATION_TAR', 'APPLICATION_ZIP', 'APPLICATION_OCTETSTREAM'] mappings = [ ('url', 'url', None), ('mode', 'httpMode', 'GET', valid_modes), ('content-type', 'contentType', 'NOT_SET', valid_types), ('accept-type', 'acceptType', 'NOT_SET', valid_types), ('output-file', 'outputFile', ''), ('console-log', 'consoleLogResponseBody', False), ('pass-build', 'passBuildParameters', False), ('time-out', 'timeout', 0), ('valid-response-codes', 'validResponseCodes', ''), ('valid-response-content', 'validResponseContent', '')] convert_mapping_to_xml(http_request, data, mappings, fail_required=True) if 'authentication-key' in data: XML.SubElement( http_request, 'authentication').text = data['authentication-key'] if 'custom-headers' in data: customHeader = XML.SubElement(http_request, 'customHeaders') header_mappings = [ ('name', 'name', None), ('value', 'value', None) ] for customhead in data['custom-headers']: pair = XML.SubElement(customHeader, 'pair') convert_mapping_to_xml(pair, customhead, header_mappings, fail_required=True) def inject(registry, xml_parent, data): """yaml: inject Inject an environment for the job. Requires the Jenkins :jenkins-wiki:`EnvInject Plugin <EnvInject+Plugin>`. :arg str properties-file: the name of the property file (optional) :arg str properties-content: the properties content (optional) :arg str script-file: the name of a script file to run (optional) :arg str script-content: the script content (optional) Example: .. literalinclude:: ../../tests/builders/fixtures/inject.yaml :language: yaml """ eib = XML.SubElement(xml_parent, 'EnvInjectBuilder') info = XML.SubElement(eib, 'info') mapping = [ ('properties-file', 'propertiesFilePath', None), ('properties-content', 'propertiesContent', None), ('script-file', 'scriptFilePath', None), ('script-content', 'scriptContent', None), ] convert_mapping_to_xml(info, data, mapping, fail_required=False) def kmap(registry, xml_parent, data): """yaml: kmap Publish mobile applications to your Keivox KMAP Private Mobile App Store. Requires the Jenkins :jenkins-wiki:`Keivox KMAP Private Mobile App Store Plugin <Keivox+KMAP+Private+Mobile+App+Store+Plugin>`. :arg str username: KMAP's user email with permissions to upload/publish applications to KMAP (required) :arg str password: Password for the KMAP user uploading/publishing applications (required) :arg str url: KMAP's url. This url must always end with "/kmap-client/". For example: http://testing.keivox.com/kmap-client/ (required) :arg str categories: Categories' names. If you want to add the application to more than one category, write the categories between commas. (required) :arg str file-path: Path to the application's file (required) :arg str app-name: KMAP's application name (required) :arg str bundle: Bundle indentifier (default '') :arg str version: Application's version (required) :arg str description: Application's description (default '') :arg str icon-path: Path to the application's icon (default '') :arg bool publish-optional: Publish application after it has been uploaded to KMAP (default false) :publish-optional: * **groups** ('str') -- groups' names to publish the application (default '') * **users** ('str') -- users' names to publish the application (default '') * **notify-users** ('bool') -- Send notifications to the users and groups when publishing the application (default false) Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/kmap-minimal.yaml :language: yaml Full Example: .. literalinclude:: ../../tests/builders/fixtures/kmap-full.yaml :language: yaml """ kmap = XML.SubElement( xml_parent, 'org.jenkinsci.plugins.KmapJenkinsBuilder') kmap.set('plugin', 'kmap-jenkins') publish = data.get('publish-optional', False) mapping = [ ('username', 'username', None), ('password', 'password', None), ('url', 'kmapClient', None), ('categories', 'categories', None), ('file-path', 'filePath', None), ('app-name', 'appName', None), ('bundle', 'bundle', ''), ('version', 'version', None), ('description', 'description', ''), ('icon-path', 'iconPath', ''), ] convert_mapping_to_xml(kmap, data, mapping, fail_required=True) if publish is True: publish_optional = XML.SubElement(kmap, 'publishOptional') publish_mapping = [ ('groups', 'teams', ''), ('users', 'users', ''), ('notify-users', 'sendNotifications', False), ] convert_mapping_to_xml( publish_optional, data, publish_mapping, fail_required=True) def artifact_resolver(registry, xml_parent, data): """yaml: artifact-resolver Allows one to resolve artifacts from a maven repository like nexus (without having maven installed) Requires the Jenkins :jenkins-wiki:`Repository Connector Plugin <Repository+Connector+Plugin>`. :arg bool fail-on-error: Whether to fail the build on error (default false) :arg bool repository-logging: Enable repository logging (default false) :arg str target-directory: Where to resolve artifacts to :arg list artifacts: list of artifacts to resolve :Artifact: * **group-id** (`str`) -- Group ID of the artifact * **artifact-id** (`str`) -- Artifact ID of the artifact * **version** (`str`) -- Version of the artifact * **classifier** (`str`) -- Classifier of the artifact (default '') * **extension** (`str`) -- Extension of the artifact (default 'jar') * **target-file-name** (`str`) -- What to name the artifact (default '') Example: .. literalinclude:: ../../tests/builders/fixtures/artifact-resolver.yaml :language: yaml """ ar = XML.SubElement(xml_parent, 'org.jvnet.hudson.plugins.repositoryconnector.' 'ArtifactResolver') XML.SubElement(ar, 'targetDirectory').text = data['target-directory'] artifacttop = XML.SubElement(ar, 'artifacts') artifacts = data['artifacts'] for artifact in artifacts: rcartifact = XML.SubElement(artifacttop, 'org.jvnet.hudson.plugins.' 'repositoryconnector.Artifact') XML.SubElement(rcartifact, 'groupId').text = artifact['group-id'] XML.SubElement(rcartifact, 'artifactId').text = artifact['artifact-id'] XML.SubElement(rcartifact, 'classifier').text = artifact.get( 'classifier', '') XML.SubElement(rcartifact, 'version').text = artifact['version'] XML.SubElement(rcartifact, 'extension').text = artifact.get( 'extension', 'jar') XML.SubElement(rcartifact, 'targetFileName').text = artifact.get( 'target-file-name', '') XML.SubElement(ar, 'failOnError').text = str(data.get( 'fail-on-error', False)).lower() XML.SubElement(ar, 'enableRepoLogging').text = str(data.get( 'repository-logging', False)).lower() XML.SubElement(ar, 'snapshotUpdatePolicy').text = 'never' XML.SubElement(ar, 'releaseUpdatePolicy').text = 'never' XML.SubElement(ar, 'snapshotChecksumPolicy').text = 'warn' XML.SubElement(ar, 'releaseChecksumPolicy').text = 'warn' def doxygen(registry, xml_parent, data): """yaml: doxygen Builds doxygen HTML documentation. Requires the Jenkins :jenkins-wiki:`Doxygen plugin <Doxygen+Plugin>`. :arg str doxyfile: The doxyfile path (required) :arg str install: The doxygen installation to use (required) :arg bool ignore-failure: Keep executing build even on doxygen generation failure (default false) :arg bool unstable-warning: Mark the build as unstable if warnings are generated (default false) Example: .. literalinclude:: /../../tests/builders/fixtures/doxygen001.yaml :language: yaml """ doxygen = XML.SubElement(xml_parent, 'hudson.plugins.doxygen.DoxygenBuilder') mappings = [ ('doxyfile', 'doxyfilePath', None), ('install', 'installationName', None), ('ignore-failure', 'continueOnBuildFailure', False), ('unstable-warning', 'unstableIfWarnings', False) ] convert_mapping_to_xml(doxygen, data, mappings, fail_required=True) def gradle(registry, xml_parent, data): """yaml: gradle Execute gradle tasks. Requires the Jenkins :jenkins-wiki:`Gradle Plugin <Gradle+Plugin>`. :arg str tasks: List of tasks to execute :arg str gradle-name: Use a custom gradle name (default '') :arg bool wrapper: use gradle wrapper (default false) :arg bool executable: make gradlew executable (default false) :arg list switches: Switches for gradle, can have multiples :arg bool use-root-dir: Whether to run the gradle script from the top level directory or from a different location (default false) :arg str root-build-script-dir: If your workspace has the top-level build.gradle in somewhere other than the module root directory, specify the path (relative to the module root) here, such as ${workspace}/parent/ instead of just ${workspace}. :arg str build-file: name of gradle build script (default 'build.gradle') Example: .. literalinclude:: ../../tests/builders/fixtures/gradle.yaml :language: yaml """ gradle = XML.SubElement(xml_parent, 'hudson.plugins.gradle.Gradle') XML.SubElement(gradle, 'description').text = '' mappings = [ ('build-file', 'buildFile', 'build.gradle'), ('tasks', 'tasks', None), ('root-build-script-dir', 'rootBuildScriptDir', ''), ('gradle-name', 'gradleName', ''), ('wrapper', 'useWrapper', False), ('executable', 'makeExecutable', False), ('use-root-dir', 'fromRootBuildScriptDir', False), ] convert_mapping_to_xml(gradle, data, mappings, fail_required=True) XML.SubElement(gradle, 'switches').text = '\n'.join( data.get('switches', [])) def _groovy_common_scriptSource(data): """Helper function to generate the XML element common to groovy builders """ scriptSource = XML.Element("scriptSource") if 'command' in data and 'file' in data: raise JenkinsJobsException("Use just one of 'command' or 'file'") if 'command' in data: command = XML.SubElement(scriptSource, 'command') command.text = str(data['command']) scriptSource.set('class', 'hudson.plugins.groovy.StringScriptSource') elif 'file' in data: scriptFile = XML.SubElement(scriptSource, 'scriptFile') scriptFile.text = str(data['file']) scriptSource.set('class', 'hudson.plugins.groovy.FileScriptSource') else: raise JenkinsJobsException("A groovy command or file is required") return scriptSource def groovy(registry, xml_parent, data): """yaml: groovy Execute a groovy script or command. Requires the Jenkins :jenkins-wiki:`Groovy Plugin <Groovy+plugin>`. :arg str file: Groovy file to run. (Alternative: you can chose a command instead) :arg str command: Groovy command to run. (Alternative: you can chose a script file instead) :arg str version: Groovy version to use. (default '(Default)') :arg str parameters: Parameters for the Groovy executable. (default '') :arg str script-parameters: These parameters will be passed to the script. (default '') :arg str properties: Instead of passing properties using the -D parameter you can define them here. (default '') :arg str java-opts: Direct access to JAVA_OPTS. Properties allows only -D properties, while sometimes also other properties like -XX need to be setup. It can be done here. This line is appended at the end of JAVA_OPTS string. (default '') :arg str class-path: Specify script classpath here. Each line is one class path item. (default '') Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/groovy-minimal.yaml :language: yaml Full Example: .. literalinclude:: ../../tests/builders/fixtures/groovy-full.yaml :language: yaml """ root_tag = 'hudson.plugins.groovy.Groovy' groovy = XML.SubElement(xml_parent, root_tag) groovy.append(_groovy_common_scriptSource(data)) mappings = [ ('version', 'groovyName', '(Default)'), ('parameters', 'parameters', ''), ('script-parameters', 'scriptParameters', ''), ('properties', 'properties', ''), ('java-opts', 'javaOpts', ''), ('class-path', 'classPath', '') ] convert_mapping_to_xml(groovy, data, mappings, fail_required=True) def system_groovy(registry, xml_parent, data): """yaml: system-groovy Execute a system groovy script or command. Requires the Jenkins :jenkins-wiki:`Groovy Plugin <Groovy+plugin>`. :arg str file: Groovy file to run. (Alternative: you can chose a command instead) :arg str command: Groovy command to run. (Alternative: you can chose a script file instead) :arg str bindings: Define variable bindings (in the properties file format). Specified variables can be addressed from the script. (optional) :arg str class-path: Specify script classpath here. Each line is one class path item. (optional) Examples: .. literalinclude:: ../../tests/builders/fixtures/system-groovy001.yaml :language: yaml .. literalinclude:: ../../tests/builders/fixtures/system-groovy002.yaml :language: yaml """ root_tag = 'hudson.plugins.groovy.SystemGroovy' sysgroovy = XML.SubElement(xml_parent, root_tag) sysgroovy.append(_groovy_common_scriptSource(data)) mapping = [ ('bindings', 'bindings', ''), ('class-path', 'classpath', ''), ] convert_mapping_to_xml(sysgroovy, data, mapping, fail_required=True) def batch(registry, xml_parent, data): """yaml: batch Execute a batch command. :Parameter: the batch command to execute Example: .. literalinclude:: ../../tests/builders/fixtures/batch.yaml :language: yaml """ batch = XML.SubElement(xml_parent, 'hudson.tasks.BatchFile') XML.SubElement(batch, 'command').text = data def powershell(registry, xml_parent, data): """yaml: powershell Execute a powershell command. Requires the :jenkins-wiki:`Powershell Plugin <PowerShell+Plugin>`. :Parameter: the powershell command to execute Example: .. literalinclude:: ../../tests/builders/fixtures/powershell.yaml :language: yaml """ ps = XML.SubElement(xml_parent, 'hudson.plugins.powershell.PowerShell') XML.SubElement(ps, 'command').text = data def msbuild(registry, xml_parent, data): """yaml: msbuild Build .NET project using msbuild. Requires the :jenkins-wiki:`Jenkins MSBuild Plugin <MSBuild+Plugin>`. :arg str msbuild-version: which msbuild configured in Jenkins to use (default '(Default)') :arg str solution-file: location of the solution file to build (required) :arg str extra-parameters: extra parameters to pass to msbuild (default '') :arg bool pass-build-variables: should build variables be passed to msbuild (default true) :arg bool continue-on-build-failure: should the build continue if msbuild returns an error (default false) :arg bool unstable-if-warnings: If set to true and warnings on compilation, the build will be unstable (>=1.20) (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/msbuild-full.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/msbuild-minimal.yaml :language: yaml """ msbuilder = XML.SubElement(xml_parent, 'hudson.plugins.msbuild.MsBuildBuilder') msbuilder.set('plugin', 'msbuild') mapping = [ ('msbuild-version', 'msBuildName', '(Default)'), ('solution-file', 'msBuildFile', None), ('extra-parameters', 'cmdLineArgs', ''), ('pass-build-variables', 'buildVariablesAsProperties', True), ('continue-on-build-failure', 'continueOnBuildFailure', False), ('unstable-if-warnings', 'unstableIfWarnings', False) ] convert_mapping_to_xml(msbuilder, data, mapping, fail_required=True) def create_builders(registry, step): dummy_parent = XML.Element("dummy") registry.dispatch('builder', dummy_parent, step) return list(dummy_parent) def conditional_step(registry, xml_parent, data): """yaml: conditional-step Conditionally execute some build steps. Requires the Jenkins :jenkins-wiki:`Conditional BuildStep Plugin <Conditional+BuildStep+Plugin>`. Depending on the number of declared steps, a `Conditional step (single)` or a `Conditional steps (multiple)` is created in Jenkins. :arg str condition-kind: Condition kind that must be verified before the steps are executed. Valid values and their additional attributes are described in the conditions_ table. :arg str on-evaluation-failure: What should be the outcome of the build if the evaluation of the condition fails. Possible values are `fail`, `mark-unstable`, `run-and-mark-unstable`, `run` and `dont-run`. (default 'fail'). :arg list steps: List of steps to run if the condition is verified. Items in the list can be any builder known by Jenkins Job Builder. .. _conditions: ================== ==================================================== Condition kind Description ================== ==================================================== always Condition is always verified never Condition is never verified boolean-expression Run the step if the expression expends to a representation of true :condition-expression: Expression to expand (required) build-cause Run if the current build has a specific cause :cause: The cause why the build was triggered. Following causes are supported - :USER_CAUSE: build was triggered by a manual interaction. (default) :SCM_CAUSE: build was triggered by a SCM change. :TIMER_CAUSE: build was triggered by a timer. :CLI_CAUSE: build was triggered by via CLI interface :REMOTE_CAUSE: build was triggered via remote interface. :UPSTREAM_CAUSE: build was triggered by an upstream project. Following supported if XTrigger plugin installed: :FS_CAUSE: build was triggered by a file system change (FSTrigger Plugin). :URL_CAUSE: build was triggered by a URL change (URLTrigger Plugin) :IVY_CAUSE: build triggered by an Ivy dependency version has change (IvyTrigger Plugin) :SCRIPT_CAUSE: build was triggered by a script (ScriptTrigger Plugin) :BUILDRESULT_CAUSE: build was triggered by a result of an other job (BuildResultTrigger Plugin) :exclusive-cause: (bool) There might by multiple casues causing a build to be triggered, with this true, the cause must be the only one causing this build this build to be triggered. (default false) day-of-week Only run on specific days of the week. :day-selector: Days you want the build to run on. Following values are supported - :weekend: Saturday and Sunday (default). :weekday: Monday - Friday. :select-days: Selected days, defined by 'days' below. :days: True for days for which the build should run. Definition needed only for 'select-days' day-selector, at the same level as day-selector. Define the days to run under this. :SUN: Run on Sunday (default false) :MON: Run on Monday (default false) :TUES: Run on Tuesday (default false) :WED: Run on Wednesday (default false) :THURS: Run on Thursday (default false) :FRI: Run on Friday (default false) :SAT: Run on Saturday (default false) :use-build-time: (bool) Use the build time instead of the the time that the condition is evaluated. (default false) execution-node Run only on selected nodes. :nodes: (list) List of nodes to execute on. (required) strings-match Run the step if two strings match :condition-string1: First string (optional) :condition-string2: Second string (optional) :condition-case-insensitive: Case insensitive (default false) current-status Run the build step if the current build status is within the configured range :condition-worst: Accepted values are SUCCESS, UNSTABLE, FAILURE, NOT_BUILD, ABORTED (default SUCCESS) :condition-best: Accepted values are SUCCESS, UNSTABLE, FAILURE, NOT_BUILD, ABORTED (default SUCCESS) shell Run the step if the shell command succeed :condition-command: Shell command to execute (optional) windows-shell Similar to shell, except that commands will be executed by cmd, under Windows :condition-command: Command to execute (optional) file-exists Run the step if a file exists :condition-filename: Check existence of this file (required) :condition-basedir: If condition-filename is relative, it will be considered relative to either `workspace`, `artifact-directory`, or `jenkins-home`. (default 'workspace') files-match Run if one or more files match the selectors. :include-pattern: (list str) List of Includes Patterns. Since the separator in the patterns is hardcoded as ',', any use of ',' would need escaping. (optional) :exclude-pattern: (list str) List of Excludes Patterns. Since the separator in the patterns is hardcoded as ',', any use of ',' would need escaping. (optional) :condition-basedir: Accepted values are `workspace`, `artifact-directory`, or `jenkins-home`. (default 'workspace') num-comp Run if the numerical comparison is true. :lhs: Left Hand Side. Must evaluate to a number. (required) :rhs: Right Hand Side. Must evaluate to a number. (required) :comparator: Accepted values are `less-than`, `greater-than`, `equal`, `not-equal`, `less-than-equal`, `greater-than-equal`. (default 'less-than') regex-match Run if the Expression matches the Label. :regex: The regular expression used to match the label (optional) :label: The label that will be tested by the regular expression. (optional) time Only run during a certain period of the day. :earliest-hour: Starting hour (default "09") :earliest-min: Starting min (default "00") :latest-hour: Ending hour (default "17") :latest-min: Ending min (default "30") :use-build-time: (bool) Use the build time instead of the the time that the condition is evaluated. (default false) not Run the step if the inverse of the condition-operand is true :condition-operand: Condition to evaluate. Can be any supported conditional-step condition. (required) and Run the step if logical and of all conditional-operands is true :condition-operands: (list) Conditions to evaluate. Can be any supported conditional-step condition. (required) or Run the step if logical or of all conditional-operands is true :condition-operands: (list) Conditions to evaluate. Can be any supported conditional-step condition. (required) ================== ==================================================== Examples: .. literalinclude:: /../../tests/builders/fixtures/conditional-step-multiple-steps.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/conditional-step-success-failure.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/conditional-step-not-file-exists.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/conditional-step-day-of-week001.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/conditional-step-day-of-week003.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/conditional-step-time.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/conditional-step-regex-match.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/conditional-step-or.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/conditional-step-and.yaml :language: yaml """ def build_condition(cdata, cond_root_tag, condition_tag): kind = cdata['condition-kind'] ctag = XML.SubElement(cond_root_tag, condition_tag) core_prefix = 'org.jenkins_ci.plugins.run_condition.core.' logic_prefix = 'org.jenkins_ci.plugins.run_condition.logic.' if kind == "always": ctag.set('class', core_prefix + 'AlwaysRun') elif kind == "never": ctag.set('class', core_prefix + 'NeverRun') elif kind == "boolean-expression": ctag.set('class', core_prefix + 'BooleanCondition') try: XML.SubElement(ctag, "token").text = ( cdata['condition-expression']) except KeyError: raise MissingAttributeError('condition-expression') elif kind == "build-cause": ctag.set('class', core_prefix + 'CauseCondition') cause_list = ('USER_CAUSE', 'SCM_CAUSE', 'TIMER_CAUSE', 'CLI_CAUSE', 'REMOTE_CAUSE', 'UPSTREAM_CAUSE', 'FS_CAUSE', 'URL_CAUSE', 'IVY_CAUSE', 'SCRIPT_CAUSE', 'BUILDRESULT_CAUSE') cause_name = cdata.get('cause', 'USER_CAUSE') if cause_name not in cause_list: raise InvalidAttributeError('cause', cause_name, cause_list) XML.SubElement(ctag, "buildCause").text = cause_name XML.SubElement(ctag, "exclusiveCause").text = str(cdata.get( 'exclusive-cause', False)).lower() elif kind == "day-of-week": ctag.set('class', core_prefix + 'DayCondition') day_selector_class_prefix = core_prefix + 'DayCondition$' day_selector_classes = { 'weekend': day_selector_class_prefix + 'Weekend', 'weekday': day_selector_class_prefix + 'Weekday', 'select-days': day_selector_class_prefix + 'SelectDays', } day_selector = cdata.get('day-selector', 'weekend') if day_selector not in day_selector_classes: raise InvalidAttributeError('day-selector', day_selector, day_selector_classes) day_selector_tag = XML.SubElement(ctag, "daySelector") day_selector_tag.set('class', day_selector_classes[day_selector]) if day_selector == "select-days": days_tag = XML.SubElement(day_selector_tag, "days") day_tag_text = ('org.jenkins__ci.plugins.run__condition.' 'core.DayCondition_-Day') inp_days = cdata.get('days') if cdata.get('days') else {} days = ['SUN', 'MON', 'TUES', 'WED', 'THURS', 'FRI', 'SAT'] for day_no, day in enumerate(days, 1): day_tag = XML.SubElement(days_tag, day_tag_text) XML.SubElement(day_tag, "day").text = str(day_no) XML.SubElement(day_tag, "selected").text = str( inp_days.get(day, False)).lower() XML.SubElement(ctag, "useBuildTime").text = str(cdata.get( 'use-build-time', False)).lower() elif kind == "execution-node": ctag.set('class', core_prefix + 'NodeCondition') allowed_nodes_tag = XML.SubElement(ctag, "allowedNodes") try: nodes_list = cdata['nodes'] except KeyError: raise MissingAttributeError('nodes') for node in nodes_list: node_tag = XML.SubElement(allowed_nodes_tag, "string") node_tag.text = node elif kind == "strings-match": ctag.set('class', core_prefix + 'StringsMatchCondition') XML.SubElement(ctag, "arg1").text = cdata.get( 'condition-string1', '') XML.SubElement(ctag, "arg2").text = cdata.get( 'condition-string2', '') XML.SubElement(ctag, "ignoreCase").text = str(cdata.get( 'condition-case-insensitive', False)).lower() elif kind == "current-status": ctag.set('class', core_prefix + 'StatusCondition') wr = XML.SubElement(ctag, 'worstResult') wr_name = cdata.get('condition-worst', 'SUCCESS') if wr_name not in hudson_model.THRESHOLDS: raise InvalidAttributeError('condition-worst', wr_name, hudson_model.THRESHOLDS.keys()) wr_threshold = hudson_model.THRESHOLDS[wr_name] XML.SubElement(wr, "name").text = wr_threshold['name'] XML.SubElement(wr, "ordinal").text = wr_threshold['ordinal'] XML.SubElement(wr, "color").text = wr_threshold['color'] XML.SubElement(wr, "completeBuild").text = str( wr_threshold['complete']).lower() br = XML.SubElement(ctag, 'bestResult') br_name = cdata.get('condition-best', 'SUCCESS') if br_name not in hudson_model.THRESHOLDS: raise InvalidAttributeError('condition-best', br_name, hudson_model.THRESHOLDS.keys()) br_threshold = hudson_model.THRESHOLDS[br_name] XML.SubElement(br, "name").text = br_threshold['name'] XML.SubElement(br, "ordinal").text = br_threshold['ordinal'] XML.SubElement(br, "color").text = br_threshold['color'] XML.SubElement(br, "completeBuild").text = str( wr_threshold['complete']).lower() elif kind == "shell": ctag.set('class', 'org.jenkins_ci.plugins.run_condition.contributed.' 'ShellCondition') XML.SubElement(ctag, "command").text = cdata.get( 'condition-command', '') elif kind == "windows-shell": ctag.set('class', 'org.jenkins_ci.plugins.run_condition.contributed.' 'BatchFileCondition') XML.SubElement(ctag, "command").text = cdata.get( 'condition-command', '') elif kind == "file-exists" or kind == "files-match": if kind == "file-exists": ctag.set('class', core_prefix + 'FileExistsCondition') try: XML.SubElement(ctag, "file").text = ( cdata['condition-filename']) except KeyError: raise MissingAttributeError('condition-filename') else: ctag.set('class', core_prefix + 'FilesMatchCondition') XML.SubElement(ctag, "includes").text = ",".join(cdata.get( 'include-pattern', '')) XML.SubElement(ctag, "excludes").text = ",".join(cdata.get( 'exclude-pattern', '')) basedir_class_prefix = ('org.jenkins_ci.plugins.run_condition.' 'common.BaseDirectory$') basedir_classes = { 'workspace': basedir_class_prefix + 'Workspace', 'artifact-directory': basedir_class_prefix + 'ArtifactsDir', 'jenkins-home': basedir_class_prefix + 'JenkinsHome' } basedir = cdata.get('condition-basedir', 'workspace') if basedir not in basedir_classes: raise InvalidAttributeError('condition-basedir', basedir, basedir_classes) XML.SubElement(ctag, "baseDir").set('class', basedir_classes[basedir]) elif kind == "num-comp": ctag.set('class', core_prefix + 'NumericalComparisonCondition') try: XML.SubElement(ctag, "lhs").text = cdata['lhs'] XML.SubElement(ctag, "rhs").text = cdata['rhs'] except KeyError as e: raise MissingAttributeError(e.args[0]) comp_class_prefix = core_prefix + 'NumericalComparisonCondition$' comp_classes = { 'less-than': comp_class_prefix + 'LessThan', 'greater-than': comp_class_prefix + 'GreaterThan', 'equal': comp_class_prefix + 'EqualTo', 'not-equal': comp_class_prefix + 'NotEqualTo', 'less-than-equal': comp_class_prefix + 'LessThanOrEqualTo', 'greater-than-equal': comp_class_prefix + 'GreaterThanOrEqualTo' } comp = cdata.get('comparator', 'less-than') if comp not in comp_classes: raise InvalidAttributeError('comparator', comp, comp_classes) XML.SubElement(ctag, "comparator").set('class', comp_classes[comp]) elif kind == "regex-match": ctag.set('class', core_prefix + 'ExpressionCondition') XML.SubElement(ctag, "expression").text = cdata.get('regex', '') XML.SubElement(ctag, "label").text = cdata.get('label', '') elif kind == "time": ctag.set('class', core_prefix + 'TimeCondition') XML.SubElement(ctag, "earliestHours").text = cdata.get( 'earliest-hour', '09') XML.SubElement(ctag, "earliestMinutes").text = cdata.get( 'earliest-min', '00') XML.SubElement(ctag, "latestHours").text = cdata.get( 'latest-hour', '17') XML.SubElement(ctag, "latestMinutes").text = cdata.get( 'latest-min', '30') XML.SubElement(ctag, "useBuildTime").text = str(cdata.get( 'use-build-time', False)).lower() elif kind == "not": ctag.set('class', logic_prefix + 'Not') try: notcondition = cdata['condition-operand'] except KeyError: raise MissingAttributeError('condition-operand') build_condition(notcondition, ctag, "condition") elif kind == "and" or "or": if kind == "and": ctag.set('class', logic_prefix + 'And') else: ctag.set('class', logic_prefix + 'Or') conditions_tag = XML.SubElement(ctag, "conditions") container_tag_text = ('org.jenkins__ci.plugins.run__condition.' 'logic.ConditionContainer') try: conditions_list = cdata['condition-operands'] except KeyError: raise MissingAttributeError('condition-operands') for condition in conditions_list: conditions_container_tag = XML.SubElement(conditions_tag, container_tag_text) build_condition(condition, conditions_container_tag, "condition") def build_step(parent, step): for edited_node in create_builders(registry, step): if not has_multiple_steps: edited_node.set('class', edited_node.tag) edited_node.tag = 'buildStep' parent.append(edited_node) cond_builder_tag = ('org.jenkinsci.plugins.conditionalbuildstep.' 'singlestep.SingleConditionalBuilder') cond_builders_tag = ('org.jenkinsci.plugins.conditionalbuildstep.' 'ConditionalBuilder') steps = data['steps'] has_multiple_steps = len(steps) > 1 if has_multiple_steps: root_tag = XML.SubElement(xml_parent, cond_builders_tag) steps_parent = XML.SubElement(root_tag, "conditionalbuilders") condition_tag = "runCondition" else: root_tag = XML.SubElement(xml_parent, cond_builder_tag) steps_parent = root_tag condition_tag = "condition" build_condition(data, root_tag, condition_tag) evaluation_classes_pkg = 'org.jenkins_ci.plugins.run_condition' evaluation_classes = { 'fail': evaluation_classes_pkg + '.BuildStepRunner$Fail', 'mark-unstable': evaluation_classes_pkg + '.BuildStepRunner$Unstable', 'run-and-mark-unstable': evaluation_classes_pkg + '.BuildStepRunner$RunUnstable', 'run': evaluation_classes_pkg + '.BuildStepRunner$Run', 'dont-run': evaluation_classes_pkg + '.BuildStepRunner$DontRun', } evaluation_class = evaluation_classes[data.get('on-evaluation-failure', 'fail')] XML.SubElement(root_tag, "runner").set('class', evaluation_class) for step in steps: build_step(steps_parent, step) def maven_builder(registry, xml_parent, data): """yaml: maven-builder Execute Maven3 builder Allows your build jobs to deploy artifacts automatically to Artifactory. Requires the Jenkins :jenkins-wiki:`Artifactory Plugin <Artifactory+Plugin>`. :arg str name: Name of maven installation from the configuration (required) :arg str pom: Location of pom.xml (default 'pom.xml') :arg str goals: Goals to execute (required) :arg str maven-opts: Additional options for maven (default '') Example: .. literalinclude:: /../../tests/builders/fixtures/maven-builder001.yaml :language: yaml """ maven = XML.SubElement(xml_parent, 'org.jfrog.hudson.maven3.Maven3Builder') mapping = [ ('name', 'mavenName', None), ('goals', 'goals', None), ('pom', 'rootPom', 'pom.xml'), ('maven-opts', 'mavenOpts', ''), ] convert_mapping_to_xml(maven, data, mapping, fail_required=True) def maven_target(registry, xml_parent, data): """yaml: maven-target Execute top-level Maven targets. Requires the Jenkins :jenkins-wiki:`Config File Provider Plugin <Config+File+Provider+Plugin>` for the Config File Provider "settings" and "global-settings" config. :arg str goals: Goals to execute :arg str properties: Properties for maven, can have multiples :arg str pom: Location of pom.xml (default 'pom.xml') :arg bool private-repository: Use private maven repository for this job (default false) :arg str maven-version: Installation of maven which should be used (optional) :arg str java-opts: java options for maven, can have multiples, must be in quotes (optional) :arg str settings: Path to use as user settings.xml It is possible to provide a ConfigFileProvider settings file, such as see CFP Example below. (optional) :arg str settings-type: Type of settings file file|cfp. (default file) :arg str global-settings: Path to use as global settings.xml It is possible to provide a ConfigFileProvider settings file, such as see CFP Example below. (optional) :arg str global-settings-type: Type of settings file file|cfp. (default file) Example: .. literalinclude:: /../../tests/builders/fixtures/maven-target-doc.yaml :language: yaml CFP Example: .. literalinclude:: /../../tests/builders/fixtures/maven-target002.yaml :language: yaml """ maven = XML.SubElement(xml_parent, 'hudson.tasks.Maven') XML.SubElement(maven, 'targets').text = data['goals'] prop_string = '\n'.join(data.get('properties', [])) XML.SubElement(maven, 'properties').text = prop_string if 'maven-version' in data: XML.SubElement(maven, 'mavenName').text = str(data['maven-version']) if 'pom' in data: XML.SubElement(maven, 'pom').text = str(data['pom']) use_private = str(data.get('private-repository', False)).lower() XML.SubElement(maven, 'usePrivateRepository').text = use_private if 'java-opts' in data: javaoptions = ' '.join(data.get('java-opts', [])) XML.SubElement(maven, 'jvmOptions').text = javaoptions config_file_provider_settings(maven, data) def multijob(registry, xml_parent, data): """yaml: multijob Define a multijob phase. Requires the Jenkins :jenkins-wiki:`Multijob Plugin <Multijob+Plugin>`. This builder may only be used in :py:class:`jenkins_jobs.modules.project_multijob.MultiJob` projects. :arg str name: MultiJob phase name :arg str condition: when to trigger the other job. Can be: 'SUCCESSFUL', 'UNSTABLE', 'COMPLETED', 'FAILURE', 'ALWAYS'. (default 'SUCCESSFUL') :arg list projects: list of projects to include in the MultiJob phase :Project: * **name** (`str`) -- Project name * **current-parameters** (`bool`) -- Pass current build parameters to the other job (default false) * **node-label-name** (`str`) -- Define a list of nodes on which the job should be allowed to be executed on. Requires NodeLabel Parameter Plugin (optional) * **node-label** (`str`) -- Define a label of 'Restrict where this project can be run' on the fly. Requires NodeLabel Parameter Plugin (optional) * **node-parameters** (`bool`) -- Use the same Node for the triggered builds that was used for this build. (optional) * **git-revision** (`bool`) -- Pass current git-revision to the other job (default false) * **property-file** (`str`) -- Pass properties from file to the other job (optional) * **predefined-parameters** (`str`) -- Pass predefined parameters to the other job (optional) * **abort-all-job** (`bool`) -- Kill allsubs job and the phase job, if this subjob is killed (default false) * **enable-condition** (`str`) -- Condition to run the job in groovy script format (optional) * **kill-phase-on** (`str`) -- Stop the phase execution on specific job status. Can be 'FAILURE', 'UNSTABLE', 'NEVER'. (optional) * **restrict-matrix-project** (`str`) -- Filter that restricts the subset of the combinations that the downstream project will run (optional) * **retry** (`dict`): Enable retry strategy (optional) :retry: * **max-retry** (`int`) -- Max number of retries (default 0) * **strategy-path** (`str`) -- Parsing rules path (required) Example: .. literalinclude:: /../../tests/builders/fixtures/multibuild.yaml :language: yaml """ builder = XML.SubElement(xml_parent, 'com.tikal.jenkins.plugins.multijob.' 'MultiJobBuilder') XML.SubElement(builder, 'phaseName').text = data['name'] condition = data.get('condition', 'SUCCESSFUL') conditions_available = ('SUCCESSFUL', 'UNSTABLE', 'COMPLETED', 'FAILURE', 'ALWAYS') if condition not in conditions_available: raise JenkinsJobsException('Multijob condition must be one of: %s.' % ', '.join(conditions_available)) XML.SubElement(builder, 'continuationCondition').text = condition phaseJobs = XML.SubElement(builder, 'phaseJobs') kill_status_list = ('FAILURE', 'UNSTABLE', 'NEVER') for project in data.get('projects', []): phaseJob = XML.SubElement(phaseJobs, 'com.tikal.jenkins.plugins.' 'multijob.PhaseJobsConfig') XML.SubElement(phaseJob, 'jobName').text = project['name'] # Pass through the current build params currParams = str(project.get('current-parameters', False)).lower() XML.SubElement(phaseJob, 'currParams').text = currParams # Pass through other params configs = XML.SubElement(phaseJob, 'configs') nodeLabelName = project.get('node-label-name') nodeLabel = project.get('node-label') if (nodeLabelName and nodeLabel): node = XML.SubElement( configs, 'org.jvnet.jenkins.plugins.nodelabelparameter.' 'parameterizedtrigger.NodeLabelBuildParameter') XML.SubElement(node, 'name').text = nodeLabelName XML.SubElement(node, 'nodeLabel').text = nodeLabel # Node parameter if project.get('node-parameters', False): XML.SubElement(configs, 'hudson.plugins.parameterizedtrigger.' 'NodeParameters') # Git Revision if project.get('git-revision', False): param = XML.SubElement(configs, 'hudson.plugins.git.' 'GitRevisionBuildParameters') combine = XML.SubElement(param, 'combineQueuedCommits') combine.text = 'false' # Properties File properties_file = project.get('property-file', False) if properties_file: param = XML.SubElement(configs, 'hudson.plugins.parameterizedtrigger.' 'FileBuildParameters') propertiesFile = XML.SubElement(param, 'propertiesFile') propertiesFile.text = properties_file failOnMissing = XML.SubElement(param, 'failTriggerOnMissing') failOnMissing.text = 'true' # Predefined Parameters predefined_parameters = project.get('predefined-parameters', False) if predefined_parameters: param = XML.SubElement(configs, 'hudson.plugins.parameterizedtrigger.' 'PredefinedBuildParameters') properties = XML.SubElement(param, 'properties') properties.text = predefined_parameters # Abort all other job abortAllJob = str(project.get('abort-all-job', False)).lower() XML.SubElement(phaseJob, 'abortAllJob').text = abortAllJob # Retry job retry = project.get('retry', False) if retry: try: rules_path = str(retry['strategy-path']) XML.SubElement(phaseJob, 'parsingRulesPath').text = rules_path except KeyError: raise MissingAttributeError('strategy-path') max_retry = retry.get('max-retry', 0) XML.SubElement(phaseJob, 'maxRetries').text = str(int(max_retry)) XML.SubElement(phaseJob, 'enableRetryStrategy').text = 'true' else: XML.SubElement(phaseJob, 'enableRetryStrategy').text = 'false' # Restrict matrix jobs to a subset if project.get('restrict-matrix-project') is not None: subset = XML.SubElement( configs, 'hudson.plugins.parameterizedtrigger.' 'matrix.MatrixSubsetBuildParameters') XML.SubElement( subset, 'filter').text = project['restrict-matrix-project'] # Enable Condition enable_condition = project.get('enable-condition') if enable_condition is not None: XML.SubElement( phaseJob, 'enableCondition' ).text = 'true' XML.SubElement( phaseJob, 'condition' ).text = enable_condition # Kill phase on job status kill_status = project.get('kill-phase-on') if kill_status is not None: kill_status = kill_status.upper() if kill_status not in kill_status_list: raise JenkinsJobsException( 'multijob kill-phase-on must be one of: %s' + ','.join(kill_status_list)) XML.SubElement( phaseJob, 'killPhaseOnJobResultCondition' ).text = kill_status def config_file_provider(registry, xml_parent, data): """yaml: config-file-provider Provide configuration files (i.e., settings.xml for maven etc.) which will be copied to the job's workspace. Requires the Jenkins :jenkins-wiki:`Config File Provider Plugin <Config+File+Provider+Plugin>`. :arg list files: List of managed config files made up of three parameters :files: * **file-id** (`str`) -- The identifier for the managed config file * **target** (`str`) -- Define where the file should be created (default '') * **variable** (`str`) -- Define an environment variable to be used (default '') Example: .. literalinclude:: ../../tests/builders/fixtures/config-file-provider01.yaml :language: yaml """ cfp = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.configfiles.builder.' 'ConfigFileBuildStep') cfp.set('plugin', 'config-file-provider') config_file_provider_builder(cfp, data) def grails(registry, xml_parent, data): """yaml: grails Execute a grails build step. Requires the :jenkins-wiki:`Jenkins Grails Plugin <Grails+Plugin>`. :arg bool use-wrapper: Use a grails wrapper (default false) :arg str name: Select a grails installation to use (default '(Default)') :arg bool force-upgrade: Run 'grails upgrade --non-interactive' first (default false) :arg bool non-interactive: append --non-interactive to all build targets (default false) :arg str targets: Specify target(s) to run separated by spaces (required) :arg str server-port: Specify a value for the server.port system property (default '') :arg str work-dir: Specify a value for the grails.work.dir system property (default '') :arg str project-dir: Specify a value for the grails.project.work.dir system property (default '') :arg str base-dir: Specify a path to the root of the Grails project (default '') :arg str properties: Additional system properties to set (default '') :arg bool plain-output: append --plain-output to all build targets (default false) :arg bool stack-trace: append --stack-trace to all build targets (default false) :arg bool verbose: append --verbose to all build targets (default false) :arg bool refresh-dependencies: append --refresh-dependencies to all build targets (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/grails-full.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/grails-minimal.yaml :language: yaml """ grails = XML.SubElement(xml_parent, 'com.g2one.hudson.grails.' 'GrailsBuilder') grails.set('plugin', 'grails') mappings = [ ('targets', 'targets', None), ('name', 'name', '(Default)'), ('work-dir', 'grailsWorkDir', ''), ('project-dir', 'projectWorkDir', ''), ('base-dir', 'projectBaseDir', ''), ('server-port', 'serverPort', ''), ('properties', 'properties', ''), ('force-upgrade', 'forceUpgrade', False), ('non-interactive', 'nonInteractive', False), ('use-wrapper', 'useWrapper', False), ('plain-output', 'plainOutput', False), ('stack-trace', 'stackTrace', False), ('verbose', 'verbose', False), ('refresh-dependencies', 'refreshDependencies', False), ] convert_mapping_to_xml(grails, data, mappings, fail_required=True) def sbt(registry, xml_parent, data): """yaml: sbt Execute a sbt build step. Requires the Jenkins :jenkins-wiki:`Sbt Plugin <sbt+plugin>`. :arg str name: Select a sbt installation to use. If no name is provided, the first in the list of defined SBT builders will be used. (default to first in list) :arg str jvm-flags: Parameters to pass to the JVM (default '') :arg str actions: Select the sbt tasks to execute (default '') :arg str sbt-flags: Add flags to SBT launcher (default '-Dsbt.log.noformat=true') :arg str subdir-path: Path relative to workspace to run sbt in (default '') Example: .. literalinclude:: ../../tests/builders/fixtures/sbt.yaml :language: yaml """ sbt = XML.SubElement(xml_parent, 'org.jvnet.hudson.plugins.' 'SbtPluginBuilder') mappings = [ ('name', 'name', ''), ('jvm-flags', 'jvmFlags', ''), ('sbt-flags', 'sbtFlags', '-Dsbt.log.noformat=true'), ('actions', 'actions', ''), ('subdir-path', 'subdirPath', ''), ] convert_mapping_to_xml(sbt, data, mappings, fail_required=True) def critical_block_start(registry, xml_parent, data): """yaml: critical-block-start Designate the start of a critical block. Must be used in conjuction with critical-block-end. Must also add a build wrapper (exclusion), specifying the resources that control the critical block. Otherwise, this will have no effect. Requires Jenkins :jenkins-wiki:`Exclusion Plugin <Exclusion-Plugin>`. Example: .. literalinclude:: ../../tests/yamlparser/fixtures/critical_block_complete001.yaml :language: yaml """ cbs = XML.SubElement( xml_parent, 'org.jvnet.hudson.plugins.exclusion.CriticalBlockStart') cbs.set('plugin', 'Exclusion') def critical_block_end(registry, xml_parent, data): """yaml: critical-block-end Designate the end of a critical block. Must be used in conjuction with critical-block-start. Must also add a build wrapper (exclusion), specifying the resources that control the critical block. Otherwise, this will have no effect. Requires Jenkins :jenkins-wiki:`Exclusion Plugin <Exclusion-Plugin>`. Example: .. literalinclude:: ../../tests/yamlparser/fixtures/critical_block_complete001.yaml :language: yaml """ cbs = XML.SubElement( xml_parent, 'org.jvnet.hudson.plugins.exclusion.CriticalBlockEnd') cbs.set('plugin', 'Exclusion') def publish_over_ssh(registry, xml_parent, data): """yaml: publish-over-ssh Send files or execute commands over SSH. Requires the Jenkins :jenkins-wiki:`Publish over SSH Plugin <Publish+Over+SSH+Plugin>`. :arg str site: name of the ssh site :arg str target: destination directory :arg bool target-is-date-format: whether target is a date format. If true, raw text should be quoted (default false) :arg bool clean-remote: should the remote directory be deleted before transferring files (default false) :arg str source: source path specifier :arg str command: a command to execute on the remote server (optional) :arg int timeout: timeout in milliseconds for the Exec command (optional) :arg bool use-pty: run the exec command in pseudo TTY (default false) :arg str excludes: excluded file pattern (optional) :arg str remove-prefix: prefix to remove from uploaded file paths (optional) :arg bool fail-on-error: fail the build if an error occurs (default false) Example: .. literalinclude:: /../../tests/builders/fixtures/publish-over-ssh.yaml :language: yaml """ ssh(registry, xml_parent, data) def saltstack(parser, xml_parent, data): """yaml: saltstack Send a message to Salt API. Requires the :jenkins-wiki:`saltstack plugin <saltstack-plugin>`. :arg str servername: Salt master server name (required) :arg str authtype: Authentication type ('pam' or 'ldap', default 'pam') :arg str credentials: Credentials ID for which to authenticate to Salt master (required) :arg str target: Target minions (default '') :arg str targettype: Target type ('glob', 'pcre', 'list', 'grain', 'pillar', 'nodegroup', 'range', or 'compound', default 'glob') :arg str function: Function to execute (default '') :arg str arguments: Salt function arguments (default '') :arg str kwarguments: Salt keyword arguments (default '') :arg bool saveoutput: Save Salt return data into environment variable (default false) :arg str clientinterface: Client interface type ('local', 'local-batch', or 'runner', default 'local') :arg bool wait: Wait for completion of command (default false) :arg str polltime: Number of seconds to wait before polling job completion status (default '') :arg str batchsize: Salt batch size, absolute value or %-age (default 100%) :arg str mods: Mods to runner (default '') :arg bool setpillardata: Set Pillar data (default false) :arg str pillarkey: Pillar key (default '') :arg str pillarvalue: Pillar value (default '') Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/saltstack-minimal.yaml :language: yaml Full Example: .. literalinclude:: ../../tests/builders/fixtures/saltstack-full.yaml :language: yaml """ saltstack = XML.SubElement(xml_parent, 'com.waytta.SaltAPIBuilder') supported_auth_types = ['pam', 'ldap'] supported_target_types = ['glob', 'pcre', 'list', 'grain', 'pillar', 'nodegroup', 'range', 'compound'] supported_client_interfaces = ['local', 'local-batch', 'runner'] mapping = [ ('servername', 'servername', None), ('credentials', 'credentialsId', None), ('authtype', 'authtype', 'pam', supported_auth_types), ('target', 'target', ''), ('targettype', 'targettype', 'glob', supported_target_types), ('clientinterface', 'clientInterface', 'local', supported_client_interfaces), ('function', 'function', ''), ('arguments', 'arguments', ''), ('kwarguments', 'kwarguments', ''), ('setpillardata', 'usePillar', False), ('pillarkey', 'pillarkey', ''), ('pillarvalue', 'pillarvalue', ''), ('wait', 'blockbuild', False), ('polltime', 'jobPollTime', ''), ('batchsize', 'batchSize', '100%'), ('mods', 'mods', ''), ('saveoutput', 'saveEnvVar', False) ] helpers.convert_mapping_to_xml(saltstack, data, mapping, fail_required=True) clientInterface = data.get('clientinterface', 'local') blockbuild = str(data.get('wait', False)).lower() jobPollTime = str(data.get('polltime', '')) batchSize = data.get('batchsize', '100%') mods = data.get('mods', '') usePillar = str(data.get('setpillardata', False)).lower() # Build the clientInterfaces structure, based on the # clientinterface setting clientInterfaces = XML.SubElement(saltstack, 'clientInterfaces') XML.SubElement(clientInterfaces, 'nullObject').text = 'false' ci_attrib = { 'class': 'org.apache.commons.collections.map.ListOrderedMap', 'serialization': 'custom' } properties = XML.SubElement(clientInterfaces, 'properties', ci_attrib) lomElement = 'org.apache.commons.collections.map.ListOrderedMap' listOrderedMap = XML.SubElement(properties, lomElement) default = XML.SubElement(listOrderedMap, 'default') ordered_map = XML.SubElement(listOrderedMap, 'map') insertOrder = XML.SubElement(default, 'insertOrder') ci_config = [] if clientInterface == 'local': ci_config = [ ('blockbuild', blockbuild), ('jobPollTime', jobPollTime), ('clientInterface', clientInterface) ] elif clientInterface == 'local-batch': ci_config = [ ('batchSize', batchSize), ('clientInterface', clientInterface) ] elif clientInterface == 'runner': ci_config = [ ('mods', mods), ('clientInterface', clientInterface) ] if usePillar == 'true': ci_config.append(('usePillar', usePillar)) pillar_cfg = [ ('pillarkey', data.get('pillarkey')), ('pillarvalue', data.get('pillarvalue')) ] for emt, value in ci_config: XML.SubElement(insertOrder, 'string').text = emt entry = XML.SubElement(ordered_map, 'entry') XML.SubElement(entry, 'string').text = emt # Special handling when usePillar == true, requires additional # structure in the builder XML if emt != 'usePillar': XML.SubElement(entry, 'string').text = value else: jsonobj = XML.SubElement(entry, 'net.sf.json.JSONObject') XML.SubElement(jsonobj, 'nullObject').text = 'false' pillarProps = XML.SubElement(jsonobj, 'properties', ci_attrib) XML.SubElement(pillarProps, 'unserializable-parents') pillarLom = XML.SubElement(pillarProps, lomElement) pillarDefault = XML.SubElement(pillarLom, 'default') pillarMap = XML.SubElement(pillarLom, 'map') pillarInsertOrder = XML.SubElement(pillarDefault, 'insertOrder') for pemt, value in pillar_cfg: XML.SubElement(pillarInsertOrder, 'string').text = pemt pillarEntry = XML.SubElement(pillarMap, 'entry') XML.SubElement(pillarEntry, 'string').text = pemt XML.SubElement(pillarEntry, 'string').text = value class Builders(jenkins_jobs.modules.base.Base): sequence = 60 component_type = 'builder' component_list_type = 'builders' def gen_xml(self, xml_parent, data): for alias in ['prebuilders', 'builders', 'postbuilders']: if alias in data: builders = XML.SubElement(xml_parent, alias) for builder in data[alias]: self.registry.dispatch('builder', builders, builder) # Make sure freestyle projects always have a <builders> entry # or Jenkins v1.472 (at least) will NPE. project_type = data.get('project-type', 'freestyle') if project_type in ('freestyle', 'matrix') and 'builders' not in data: XML.SubElement(xml_parent, 'builders') def shining_panda(registry, xml_parent, data): """yaml: shining-panda Execute a command inside various python environments. Requires the Jenkins :jenkins-wiki:`ShiningPanda plugin <ShiningPanda+Plugin>`. :arg str build-environment: Building environment to set up (required). :build-environment values: * **python**: Use a python installation configured in Jenkins. * **custom**: Use a manually installed python. * **virtualenv**: Create a virtualenv For the **python** environment :arg str python-version: Name of the python installation to use. Must match one of the configured installations on server configuration (default 'System-CPython-2.7') For the **custom** environment: :arg str home: path to the home folder of the custom installation (required) For the **virtualenv** environment: :arg str python-version: Name of the python installation to use. Must match one of the configured installations on server configuration (default 'System-CPython-2.7') :arg str name: Name of this virtualenv. Two virtualenv builders with the same name will use the same virtualenv installation (optional) :arg bool clear: If true, delete and recreate virtualenv on each build. (default false) :arg bool use-distribute: if true use distribute, if false use setuptools. (default true) :arg bool system-site-packages: if true, give access to the global site-packages directory to the virtualenv. (default false) Common to all environments: :arg str nature: Nature of the command field. (default shell) :nature values: * **shell**: execute the Command contents with default shell * **xshell**: like **shell** but performs platform conversion first * **python**: execute the Command contents with the Python executable :arg str command: The command to execute :arg bool ignore-exit-code: mark the build as failure if any of the commands exits with a non-zero exit code. (default false) Examples: .. literalinclude:: /../../tests/builders/fixtures/shining-panda-pythonenv.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/shining-panda-customenv.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/shining-panda-virtualenv.yaml :language: yaml """ pluginelementpart = 'jenkins.plugins.shiningpanda.builders.' buildenvdict = {'custom': 'CustomPythonBuilder', 'virtualenv': 'VirtualenvBuilder', 'python': 'PythonBuilder'} envs = (buildenvdict.keys()) try: buildenv = data['build-environment'] except KeyError: raise MissingAttributeError('build-environment') if buildenv not in envs: raise InvalidAttributeError('build-environment', buildenv, envs) t = XML.SubElement(xml_parent, '%s%s' % (pluginelementpart, buildenvdict[buildenv])) if buildenv in ('python', 'virtualenv'): XML.SubElement(t, 'pythonName').text = data.get("python-version", "System-CPython-2.7") if buildenv in ('custom'): try: homevalue = data["home"] except KeyError: raise JenkinsJobsException("'home' argument is required for the" " 'custom' environment") XML.SubElement(t, 'home').text = homevalue if buildenv in ('virtualenv'): XML.SubElement(t, 'home').text = data.get("name", "") clear = data.get("clear", False) XML.SubElement(t, 'clear').text = str(clear).lower() use_distribute = data.get('use-distribute', False) XML.SubElement(t, 'useDistribute').text = str(use_distribute).lower() system_site_packages = data.get('system-site-packages', False) XML.SubElement(t, 'systemSitePackages').text = str( system_site_packages).lower() # Common arguments nature = data.get('nature', 'shell') naturetuple = ('shell', 'xshell', 'python') if nature not in naturetuple: raise InvalidAttributeError('nature', nature, naturetuple) XML.SubElement(t, 'nature').text = nature XML.SubElement(t, 'command').text = data.get("command", "") ignore_exit_code = data.get('ignore-exit-code', False) XML.SubElement(t, 'ignoreExitCode').text = str(ignore_exit_code).lower() def tox(registry, xml_parent, data): """yaml: tox Use tox to build a multi-configuration project. Requires the Jenkins :jenkins-wiki:`ShiningPanda plugin <ShiningPanda+Plugin>`. :arg str ini: The TOX configuration file path (default tox.ini) :arg bool recreate: If true, create a new environment each time (default false) :arg str toxenv-pattern: The pattern used to build the TOXENV environment variable. (optional) Example: .. literalinclude:: /../../tests/builders/fixtures/tox001.yaml :language: yaml """ pluginelement = 'jenkins.plugins.shiningpanda.builders.ToxBuilder' t = XML.SubElement(xml_parent, pluginelement) mappings = [ ('ini', 'toxIni', 'tox.ini'), ('recreate', 'recreate', False), ] convert_mapping_to_xml(t, data, mappings, fail_required=True) pattern = data.get('toxenv-pattern') if pattern: XML.SubElement(t, 'toxenvPattern').text = pattern def managed_script(registry, xml_parent, data): """yaml: managed-script This step allows to reference and execute a centrally managed script within your build. Requires the Jenkins :jenkins-wiki:`Managed Script Plugin <Managed+Script+Plugin>`. :arg str script-id: Id of script to execute (required) :arg str type: Type of managed file (default script) :type values: * **batch**: Execute managed windows batch * **script**: Execute managed script :arg list args: Arguments to be passed to referenced script Example: .. literalinclude:: /../../tests/builders/fixtures/managed-script.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/managed-winbatch.yaml :language: yaml """ step_type = data.get('type', 'script').lower() if step_type == 'script': step = 'ScriptBuildStep' script_tag = 'buildStepId' elif step_type == 'batch': step = 'WinBatchBuildStep' script_tag = 'command' else: raise InvalidAttributeError('type', step_type, ['script', 'batch']) ms = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.managedscripts.' + step) try: script_id = data['script-id'] except KeyError: raise MissingAttributeError('script-id') XML.SubElement(ms, script_tag).text = script_id args = XML.SubElement(ms, 'buildStepArgs') for arg in data.get('args', []): XML.SubElement(args, 'string').text = arg def cmake(registry, xml_parent, data): """yaml: cmake Execute a CMake target. Requires the Jenkins :jenkins-wiki:`CMake Plugin <CMake+Plugin>`. This builder is compatible with both versions 2.x and 1.x of the plugin. When specifying paramenters from both versions only the ones from the installed version in Jenkins will be used, and the rest will be ignored. :arg str source-dir: the source code directory relative to the workspace directory. (required) :arg str build-type: Sets the "build type" option for CMake (default "Debug"). :arg str preload-script: Path to a CMake preload script file. (optional) :arg str other-arguments: Other arguments to be added to the CMake call. (optional) :arg bool clean-build-dir: If true, delete the build directory before each build (default false). :arg list generator: The makefile generator (default "Unix Makefiles"). :type Possible generators: * **Borland Makefiles** * **CodeBlocks - MinGW Makefiles** * **CodeBlocks - Unix Makefiles** * **Eclipse CDT4 - MinGW Makefiles** * **Eclipse CDT4 - NMake Makefiles** * **Eclipse CDT4 - Unix Makefiles** * **MSYS Makefiles** * **MinGW Makefiles** * **NMake Makefiles** * **Unix Makefiles** * **Visual Studio 6** * **Visual Studio 7 .NET 2003** * **Visual Studio 8 2005** * **Visual Studio 8 2005 Win64** * **Visual Studio 9 2008** * **Visual Studio 9 2008 Win64** * **Watcom WMake** :Version 2.x: Parameters that available only to versions 2.x of the plugin * **working-dir** (`str`): The directory where the project will be built in. Relative to the workspace directory. (optional) * **installation-name** (`str`): The CMake installation to be used on this builder. Use one defined in your Jenkins global configuration page (default "InSearchPath"). * **build-tool-invocations** (`list`): list of build tool invocations that will happen during the build: :Build tool invocations: * **use-cmake** (`str`) -- Whether to run the actual build tool directly (by expanding ``$CMAKE_BUILD_TOOL``) or to have cmake run the build tool (by invoking ``cmake --build <dir>``) (default false). * **arguments** (`str`) -- Specify arguments to pass to the build tool or cmake (separated by spaces). Arguments may contain spaces if they are enclosed in double quotes. (optional) * **environment-variables** (`str`) -- Specify extra environment variables to pass to the build tool as key-value pairs here. Each entry must be on its own line, for example: ``DESTDIR=${WORKSPACE}/artifacts/dir`` ``KEY=VALUE`` :Version 1.x: Parameters available only to versions 1.x of the plugin * **build-dir** (`str`): The directory where the project will be built in. Relative to the workspace directory. (optional) * **install-dir** (`str`): The directory where the project will be installed in, relative to the workspace directory. (optional) * **build-type** (`list`): Sets the "build type" option. A custom type different than the default ones specified on the CMake plugin can also be set, which will be automatically used in the "Other Build Type" option of the plugin. (default "Debug") :Default types present in the CMake plugin: * **Debug** * **Release** * **RelWithDebInfo** * **MinSizeRel** * **make-command** (`str`): The make command (default "make"). * **install-command** (`arg`): The install command (default "make install"). * **custom-cmake-path** (`str`): Path to cmake executable. (optional) * **clean-install-dir** (`bool`): If true, delete the install dir before each build (default false). Example (Versions 2.x): .. literalinclude:: ../../tests/builders/fixtures/cmake/version-2.0/complete-2.x.yaml :language: yaml Example (Versions 1.x): .. literalinclude:: ../../tests/builders/fixtures/cmake/version-1.10/complete-1.x.yaml :language: yaml """ BUILD_TYPES = ['Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel'] cmake = XML.SubElement(xml_parent, 'hudson.plugins.cmake.CmakeBuilder') source_dir = XML.SubElement(cmake, 'sourceDir') try: source_dir.text = data['source-dir'] except KeyError: raise MissingAttributeError('source-dir') XML.SubElement(cmake, 'generator').text = str( data.get('generator', "Unix Makefiles")) XML.SubElement(cmake, 'cleanBuild').text = str( data.get('clean-build-dir', False)).lower() plugin_info = registry.get_plugin_info("CMake plugin") version = pkg_resources.parse_version(plugin_info.get("version", "1.0")) # Version 2.x breaks compatibility. So parse the input data differently # based on it: if version >= pkg_resources.parse_version("2.0"): if data.get('preload-script'): XML.SubElement(cmake, 'preloadScript').text = str( data.get('preload-script', '')) XML.SubElement(cmake, 'workingDir').text = str( data.get('working-dir', '')) XML.SubElement(cmake, 'buildType').text = str( data.get('build-type', 'Debug')) XML.SubElement(cmake, 'installationName').text = str( data.get('installation-name', 'InSearchPath')) XML.SubElement(cmake, 'toolArgs').text = str( data.get('other-arguments', '')) tool_steps = XML.SubElement(cmake, 'toolSteps') for step_data in data.get('build-tool-invocations', []): tagname = 'hudson.plugins.cmake.BuildToolStep' step = XML.SubElement(tool_steps, tagname) XML.SubElement(step, 'withCmake').text = str( step_data.get('use-cmake', False)).lower() XML.SubElement(step, 'args').text = str( step_data.get('arguments', '')) XML.SubElement(step, 'vars').text = str( step_data.get('environment-variables', '')) else: XML.SubElement(cmake, 'preloadScript').text = str( data.get('preload-script', '')) build_dir = XML.SubElement(cmake, 'buildDir') build_dir.text = data.get('build-dir', '') install_dir = XML.SubElement(cmake, 'installDir') install_dir.text = data.get('install-dir', '') # The options buildType and otherBuildType work together on the CMake # plugin: # * If the passed value is one of the predefined values, set buildType # to it and otherBuildType to blank; # * Otherwise, set otherBuildType to the value, and buildType to # "Debug". The CMake plugin will ignore the buildType option. # # It is strange and confusing that the plugin author chose to do # something like that instead of simply passing a string "buildType" # option, so this was done to simplify it for the JJB user. build_type = XML.SubElement(cmake, 'buildType') build_type.text = data.get('build-type', BUILD_TYPES[0]) other_build_type = XML.SubElement(cmake, 'otherBuildType') if(build_type.text not in BUILD_TYPES): other_build_type.text = build_type.text build_type.text = BUILD_TYPES[0] else: other_build_type.text = '' make_command = XML.SubElement(cmake, 'makeCommand') make_command.text = data.get('make-command', 'make') install_command = XML.SubElement(cmake, 'installCommand') install_command.text = data.get('install-command', 'make install') other_cmake_args = XML.SubElement(cmake, 'cmakeArgs') other_cmake_args.text = data.get('other-arguments', '') custom_cmake_path = XML.SubElement(cmake, 'projectCmakePath') custom_cmake_path.text = data.get('custom-cmake-path', '') clean_install_dir = XML.SubElement(cmake, 'cleanInstallDir') clean_install_dir.text = str(data.get('clean-install-dir', False)).lower() # The plugin generates this tag, but there doesn't seem to be anything # that can be configurable by it. Let's keep it to maintain # compatibility: XML.SubElement(cmake, 'builderImpl') def dsl(registry, xml_parent, data): """yaml: dsl Process Job DSL Requires the Jenkins :jenkins-wiki:`Job DSL plugin <Job+DSL+Plugin>`. :arg str script-text: dsl script which is Groovy code (Required if targets is not specified) :arg str targets: Newline separated list of DSL scripts, located in the Workspace. Can use wildcards like 'jobs/\*/\*/\*.groovy' (Required if script-text is not specified) :arg str ignore-existing: Ignore previously generated jobs and views :arg str removed-job-action: Specifies what to do when a previously generated job is not referenced anymore, can be 'IGNORE', 'DISABLE', or 'DELETE' (default 'IGNORE') :arg str removed-view-action: Specifies what to do when a previously generated view is not referenced anymore, can be 'IGNORE' or 'DELETE'. (default 'IGNORE') :arg str lookup-strategy: Determines how relative job names in DSL scripts are interpreted, can be 'JENKINS_ROOT' or 'SEED_JOB'. (default 'JENKINS_ROOT') :arg str additional-classpath: Newline separated list of additional classpath entries for the Job DSL scripts. All entries must be relative to the workspace root, e.g. build/classes/main. (optional) Example: .. literalinclude:: /../../tests/builders/fixtures/dsl001.yaml :language: yaml .. literalinclude:: /../../tests/builders/fixtures/dsl002.yaml :language: yaml """ dsl = XML.SubElement(xml_parent, 'javaposse.jobdsl.plugin.ExecuteDslScripts') if 'target' in data: if 'targets' not in data: logger.warning("Converting from old format of 'target' to new " "name 'targets', please update your job " "definitions.") data['targets'] = data['target'] else: logger.warning("Ignoring old argument 'target' in favour of new " "format argument 'targets', please remove old " "format.") if data.get('script-text'): XML.SubElement(dsl, 'scriptText').text = data.get('script-text') XML.SubElement(dsl, 'usingScriptText').text = 'true' elif data.get('targets'): XML.SubElement(dsl, 'targets').text = data.get('targets') XML.SubElement(dsl, 'usingScriptText').text = 'false' else: raise MissingAttributeError(['script-text', 'target']) XML.SubElement(dsl, 'ignoreExisting').text = str(data.get( 'ignore-existing', False)).lower() supportedJobActions = ['IGNORE', 'DISABLE', 'DELETE'] removedJobAction = data.get('removed-job-action', supportedJobActions[0]) if removedJobAction not in supportedJobActions: raise InvalidAttributeError('removed-job-action', removedJobAction, supportedJobActions) XML.SubElement(dsl, 'removedJobAction').text = removedJobAction supportedViewActions = ['IGNORE', 'DELETE'] removedViewAction = data.get('removed-view-action', supportedViewActions[0]) if removedViewAction not in supportedViewActions: raise InvalidAttributeError('removed-view-action', removedViewAction, supportedViewActions) XML.SubElement(dsl, 'removedViewAction').text = removedViewAction supportedLookupActions = ['JENKINS_ROOT', 'SEED_JOB'] lookupStrategy = data.get('lookup-strategy', supportedLookupActions[0]) if lookupStrategy not in supportedLookupActions: raise InvalidAttributeError('lookup-strategy', lookupStrategy, supportedLookupActions) XML.SubElement(dsl, 'lookupStrategy').text = lookupStrategy XML.SubElement(dsl, 'additionalClasspath').text = data.get( 'additional-classpath') def github_notifier(registry, xml_parent, data): """yaml: github-notifier Set pending build status on Github commit. Requires the Jenkins :jenkins-wiki:`Github Plugin <GitHub+Plugin>`. Example: .. literalinclude:: /../../tests/builders/fixtures/github-notifier.yaml :language: yaml """ XML.SubElement(xml_parent, 'com.cloudbees.jenkins.GitHubSetCommitStatusBuilder') def scan_build(registry, xml_parent, data): """yaml: scan-build This plugin allows you configure a build step that will execute the Clang scan-build static analysis tool against an XCode project. The scan-build report has to be generated in the directory ``${WORKSPACE}/clangScanBuildReports`` for the publisher to find it. Requires the Jenkins :jenkins-wiki:`Clang Scan-Build Plugin <Clang+Scan-Build+Plugin>`. :arg str target: Provide the exact name of the XCode target you wish to have compiled and analyzed (required) :arg str target-sdk: Set the simulator version of a currently installed SDK (default iphonesimulator) :arg str config: Provide the XCode config you wish to execute scan-build against (default Debug) :arg str clang-install-name: Name of clang static analyzer to use (default '') :arg str xcode-sub-path: Path of XCode project relative to the workspace (default '') :arg str workspace: Name of workspace (default '') :arg str scheme: Name of scheme (default '') :arg str scan-build-args: Additional arguments to clang scan-build (default --use-analyzer Xcode) :arg str xcode-build-args: Additional arguments to XCode (default -derivedDataPath $WORKSPACE/build) :arg str report-folder: Folder where generated reports are located (>=1.7) (default clangScanBuildReports) Full Example: .. literalinclude:: /../../tests/builders/fixtures/scan-build-full.yaml :language: yaml Minimal Example: .. literalinclude:: /../../tests/builders/fixtures/scan-build-minimal.yaml :language: yaml """ p = XML.SubElement( xml_parent, 'jenkins.plugins.clangscanbuild.ClangScanBuildBuilder') p.set('plugin', 'clang-scanbuild') mappings = [ ('target', 'target', None), ('target-sdk', 'targetSdk', 'iphonesimulator'), ('config', 'config', 'Debug'), ('clang-install-name', 'clangInstallationName', ''), ('xcode-sub-path', 'xcodeProjectSubPath', 'myProj/subfolder'), ('workspace', 'workspace', ''), ('scheme', 'scheme', ''), ('scan-build-args', 'scanbuildargs', '--use-analyzer Xcode'), ('xcode-build-args', 'xcodebuildargs', '-derivedDataPath $WORKSPACE/build'), ('report-folder', 'outputFolderName', 'clangScanBuildReports'), ] convert_mapping_to_xml(p, data, mappings, fail_required=True) def ssh_builder(registry, xml_parent, data): """yaml: ssh-builder Executes command on remote host Requires the Jenkins :jenkins-wiki:`SSH plugin <SSH+plugin>`. :arg str ssh-user-ip: user@ip:ssh_port of machine that was defined in jenkins according to SSH plugin instructions :arg str command: command to run on remote server Example: .. literalinclude:: /../../tests/builders/fixtures/ssh-builder.yaml :language: yaml """ builder = XML.SubElement( xml_parent, 'org.jvnet.hudson.plugins.SSHBuilder') mapping = [ ('ssh-user-ip', 'siteName', None), ('command', 'command', None), ] convert_mapping_to_xml(builder, data, mapping, fail_required=True) def sonar(registry, xml_parent, data): """yaml: sonar Invoke standalone Sonar analysis. Requires the Jenkins `Sonar Plugin. <http://docs.sonarqube.org/display/SCAN/\ Analyzing+with+SonarQube+Scanner+for+Jenkins\ #AnalyzingwithSonarQubeScannerforJenkins-\ AnalyzingwiththeSonarQubeScanner>`_ :arg str sonar-name: Name of the Sonar installation. :arg str task: Task to run. (default '') :arg str project: Path to Sonar project properties file. (default '') :arg str properties: Sonar configuration properties. (default '') :arg str java-opts: Java options for Sonnar Runner. (default '') :arg str additional-arguments: additional command line arguments (default '') :arg str jdk: JDK to use (inherited from the job if omitted). (optional) Example: .. literalinclude:: /../../tests/builders/fixtures/sonar.yaml :language: yaml """ sonar = XML.SubElement(xml_parent, 'hudson.plugins.sonar.SonarRunnerBuilder') sonar.set('plugin', 'sonar') XML.SubElement(sonar, 'installationName').text = data['sonar-name'] mappings = [ ('task', 'task', ''), ('project', 'project', ''), ('properties', 'properties', ''), ('java-opts', 'javaOpts', ''), ('additional-arguments', 'additionalArguments', ''), ] convert_mapping_to_xml(sonar, data, mappings, fail_required=True) if 'jdk' in data: XML.SubElement(sonar, 'jdk').text = data['jdk'] def xcode(registry, xml_parent, data): """yaml: xcode This step allows to execute an xcode build step. Requires the Jenkins :jenkins-wiki:`Xcode Plugin <Xcode+Plugin>`. :arg str developer-profile: the jenkins credential id for a ios developer profile. (optional) :arg bool clean-build: if true will delete the build directories before invoking the build. (default false) :arg bool clean-test-reports: UNKNOWN. (default false) :arg bool archive: if true will generate an xcarchive of the specified scheme. A workspace and scheme are are also needed for archives. (default false) :arg str configuration: This is the name of the configuration as defined in the Xcode project. (default 'Release') :arg str configuration-directory: The value to use for CONFIGURATION_BUILD_DIR setting. (default '') :arg str target: Leave empty for all targets. (default '') :arg str sdk: Leave empty for default SDK. (default '') :arg str symroot: Leave empty for default SYMROOT. (default '') :arg str project-path: Relative path within the workspace that contains the xcode project file(s). (default '') :arg str project-file: Only needed if there is more than one project file in the Xcode Project Directory. (default '') :arg str build-arguments: Extra commandline arguments provided to the xcode builder. (default '') :arg str schema: Only needed if you want to compile for a specific schema instead of a target. (default '') :arg str workspace: Only needed if you want to compile a workspace instead of a project. (default '') :arg str profile: The relative path to the mobileprovision to embed, leave blank for no embedded profile. (default '') :arg str codesign-id: Override the code signing identity specified in the project. (default '') :arg bool allow-failing: if true will prevent this build step from failing if xcodebuild exits with a non-zero return code. (default false) :arg str version-technical: The value to use for CFBundleVersion. Leave blank to use project's technical number. (default '') :arg str version-marketing: The value to use for CFBundleShortVersionString. Leave blank to use project's marketing number. (default '') :arg str ipa-version: A pattern for the ipa file name. You may use ${VERSION} and ${BUILD_DATE} (yyyy.MM.dd) in this string. (default '') :arg str ipa-output: The output directory for the .ipa file, relative to the build directory. (default '') :arg str keychain-name: The globally configured keychain to unlock for this build. (default '') :arg str keychain-path: The path of the keychain to use to sign the IPA. (default '') :arg str keychain-password: The password to use to unlock the keychain. (default '') :arg str keychain-unlock: Unlocks the keychain during use. (default false) Example: .. literalinclude:: /../../tests/builders/fixtures/xcode.yaml :language: yaml """ if data.get('developer-profile'): profile = XML.SubElement(xml_parent, 'au.com.rayh.' 'DeveloperProfileLoader') mapping = [('developer-profile', 'id', None)] convert_mapping_to_xml(profile, data, mapping, fail_required=False) xcode = XML.SubElement(xml_parent, 'au.com.rayh.XCodeBuilder') mappings = [ ('clean-build', 'cleanBeforeBuild', False), ('clean-test-reports', 'cleanTestReports', False), ('archive', 'generateArchive', False), ('configuration', 'configuration', 'Release'), ('configuration-directory', 'configurationBuildDir', ''), ('target', 'target', ''), ('sdk', 'sdk', ''), ('symroot', 'symRoot', ''), ('project-path', 'xcodeProjectPath', ''), ('project-file', 'xcodeProjectFile', ''), ('build-arguments', 'xcodebuildArguments', ''), ('schema', 'xcodeSchema', ''), ('workspace', 'xcodeWorkspaceFile', ''), ('profile', 'embeddedProfileFile', ''), ('codesign-id', 'codeSigningIdentity', ''), ('allow-failing', 'allowFailingBuildResults', False), ] convert_mapping_to_xml(xcode, data, mappings, fail_required=True) version = XML.SubElement(xcode, 'provideApplicationVersion') version_technical = XML.SubElement(xcode, 'cfBundleVersionValue') version_marketing = XML.SubElement(xcode, 'cfBundleShortVersionStringValue') if data.get('version-technical') or data.get('version-marketing'): version.text = 'true' version_technical.text = data.get('version-technical', '') version_marketing.text = data.get('version-marketing', '') else: version.text = 'false' XML.SubElement(xcode, 'buildIpa').text = str( bool(data.get('ipa-version')) or False).lower() mapping = [ ('ipa-version', 'ipaName', ''), ('ipa-output', 'ipaOutputDirectory', ''), ('keychain-name', 'keychainName', ''), ('keychain-path', 'keychainPath', ''), ('keychain-password', 'keychainPwd', ''), ('keychain-unlock', 'unlockKeychain', False), ] convert_mapping_to_xml(xcode, data, mapping, fail_required=True) def sonatype_clm(registry, xml_parent, data): """yaml: sonatype-clm Requires the Jenkins :jenkins-wiki:`Sonatype CLM Plugin <Sonatype+CLM+%28formerly+Insight+for+CI%29>`. :arg str value: Select CLM application from a list of available CLM applications or specify CLM Application ID (default list) :arg str application-name: Determines the policy elements to associate with this build. (required) :arg str username: Username on the Sonatype CLM server. Leave empty to use the username configured at global level. (default '') :arg str password: Password on the Sonatype CLM server. Leave empty to use the password configured at global level. (default '') :arg bool fail-on-clm-server-failure: Controls the build outcome if there is a failure in communicating with the CLM server. (default false) :arg str stage: Controls the stage the policy evaluation will be run against on the CLM server. Valid stages: build, stage-release, release, operate. (default 'build') :arg str scan-targets: Pattern of files to include for scanning. (default '') :arg str module-excludes: Pattern of files to exclude. (default '') :arg str advanced-options: Options to be set on a case-by-case basis as advised by Sonatype Support. (default '') Minimal Example: .. literalinclude:: /../../tests/builders/fixtures/sonatype-clm-minimal.yaml :language: yaml Full Example: .. literalinclude:: /../../tests/builders/fixtures/sonatype-clm-full.yaml :language: yaml """ clm = XML.SubElement(xml_parent, 'com.sonatype.insight.ci.hudson.PreBuildScan') clm.set('plugin', 'sonatype-clm-ci') SUPPORTED_VALUES = ['list', 'manual'] SUPPORTED_STAGES = ['build', 'stage-release', 'release', 'operate'] application_select = XML.SubElement(clm, 'applicationSelectType') application_mappings = [ ('value', 'value', 'list', SUPPORTED_VALUES), ('application-name', 'applicationId', None), ] convert_mapping_to_xml( application_select, data, application_mappings, fail_required=True) path = XML.SubElement(clm, 'pathConfig') path_mappings = [ ('scan-targets', 'scanTargets', ''), ('module-excludes', 'moduleExcludes', ''), ('advanced-options', 'scanProperties', ''), ] convert_mapping_to_xml(path, data, path_mappings, fail_required=True) mappings = [ ('fail-on-clm-server-failure', 'failOnClmServerFailures', False), ('stage', 'stageId', 'build', SUPPORTED_STAGES), ('username', 'username', ''), ('password', 'password', ''), ] convert_mapping_to_xml(clm, data, mappings, fail_required=True) def beaker(registry, xml_parent, data): """yaml: beaker Execute a beaker build step. Requires the Jenkins :jenkins-wiki:`Beaker Builder Plugin <Beaker+Builder+Plugin>`. :arg str content: Run job from string (Alternative: you can choose a path instead) :arg str path: Run job from file (Alternative: you can choose a content instead) :arg bool download-logs: Download Beaker log files (default false) Example: .. literalinclude:: ../../tests/builders/fixtures/beaker-path.yaml :language: yaml .. literalinclude:: ../../tests/builders/fixtures/beaker-content.yaml :language: yaml """ beaker = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.beakerbuilder.' 'BeakerBuilder') jobSource = XML.SubElement(beaker, 'jobSource') if 'content' in data and 'path' in data: raise JenkinsJobsException("Use just one of 'content' or 'path'") elif 'content' in data: jobSourceClass = "org.jenkinsci.plugins.beakerbuilder.StringJobSource" jobSource.set('class', jobSourceClass) XML.SubElement(jobSource, 'jobContent').text = data['content'] elif 'path' in data: jobSourceClass = "org.jenkinsci.plugins.beakerbuilder.FileJobSource" jobSource.set('class', jobSourceClass) XML.SubElement(jobSource, 'jobPath').text = data['path'] else: raise JenkinsJobsException("Use one of 'content' or 'path'") XML.SubElement(beaker, 'downloadFiles').text = str(data.get( 'download-logs', False)).lower() def cloudformation(registry, xml_parent, data): """yaml: cloudformation Create cloudformation stacks before running a build and optionally delete them at the end. Requires the Jenkins :jenkins-wiki:`AWS Cloudformation Plugin <AWS+Cloudformation+Plugin>`. :arg list name: The names of the stacks to create (required) :arg str description: Description of the stack (optional) :arg str recipe: The cloudformation recipe file (required) :arg list parameters: List of key/value pairs to pass into the recipe, will be joined together into a comma separated string (optional) :arg int timeout: Number of seconds to wait before giving up creating a stack (default 0) :arg str access-key: The Amazon API Access Key (required) :arg str secret-key: The Amazon API Secret Key (required) :arg int sleep: Number of seconds to wait before continuing to the next step (default 0) :arg array region: The region to run cloudformation in (required) :region values: * **us-east-1** * **us-west-1** * **us-west-2** * **eu-central-1** * **eu-west-1** * **ap-southeast-1** * **ap-southeast-2** * **ap-northeast-1** * **sa-east-1** Example: .. literalinclude:: ../../tests/builders/fixtures/cloudformation.yaml :language: yaml """ region_dict = cloudformation_region_dict() stacks = cloudformation_init(xml_parent, data, 'CloudFormationBuildStep') for stack in data: cloudformation_stack(xml_parent, stack, 'PostBuildStackBean', stacks, region_dict) def jms_messaging(registry, xml_parent, data): """yaml: jms-messaging The JMS Messaging Plugin provides the following functionality: - A build trigger to submit jenkins jobs upon receipt of a matching message. - A builder that may be used to submit a message to the topic upon the completion of a job - A post-build action that may be used to submit a message to the topic upon the completion of a job JMS Messaging provider types supported: - ActiveMQ - FedMsg Requires the Jenkins :jenkins-wiki:`JMS Messaging Plugin Pipeline Plugin <JMS+Messaging+Plugin>`. :arg str override-topic: If you need to override the default topic. (default '') :arg str provider-name: Name of message provider setup in the global config. (default '') :arg str msg-type: A message type (default 'CodeQualityChecksDone') :arg str msg-props: Message header to publish. (default '') :arg str msg-content: Message body to publish. (default '') Full Example: .. literalinclude:: ../../tests/builders/fixtures/jms-messaging-full.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/jms-messaging-minimal.yaml :language: yaml """ helpers.jms_messaging_common(xml_parent, 'com.redhat.jenkins.plugins.ci.' 'CIMessageBuilder', data) def openshift_build_verify(registry, xml_parent, data): """yaml: openshift-build-verify Performs the equivalent of an 'oc get builds` command invocation for the provided buildConfig key provided; once the list of builds are obtained, the state of the latest build is inspected for up to a minute to see if it has completed successfully. Requires the Jenkins :jenkins-wiki:`OpenShift Pipeline Plugin <OpenShift+Pipeline+Plugin>`. :arg str api-url: this would be the value you specify if you leverage the --server option on the OpenShift `oc` command. (default '\https://openshift.default.svc.cluster.local') :arg str bld-cfg: The value here should be whatever was the output form `oc project` when you created the BuildConfig you want to run a Build on (default 'frontend') :arg str namespace: If you run `oc get bc` for the project listed in "namespace", that is the value you want to put here. (default 'test') :arg str auth-token: The value here is what you supply with the --token option when invoking the OpenShift `oc` command. (default '') :arg bool verbose: This flag is the toggle for turning on or off detailed logging in this plug-in. (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-build-verify001.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-build-verify002.yaml :language: yaml """ osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.' 'OpenShiftBuildVerifier') mapping = [ # option, xml name, default value ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'), ("bld-cfg", 'bldCfg', 'frontend'), ("namespace", 'namespace', 'test'), ("auth-token", 'authToken', ''), ("verbose", 'verbose', False), ] convert_mapping_to_xml(osb, data, mapping, fail_required=True) def openshift_builder(registry, xml_parent, data): """yaml: openshift-builder Perform builds in OpenShift for the job. Requires the Jenkins :jenkins-wiki:`OpenShift Pipeline Plugin <OpenShift+Pipeline+Plugin>`. :arg str api-url: this would be the value you specify if you leverage the --server option on the OpenShift `oc` command. (default '\https://openshift.default.svc.cluster.local') :arg str bld-cfg: The value here should be whatever was the output form `oc project` when you created the BuildConfig you want to run a Build on (default 'frontend') :arg str namespace: If you run `oc get bc` for the project listed in "namespace", that is the value you want to put here. (default 'test') :arg str auth-token: The value here is what you supply with the --token option when invoking the OpenShift `oc` command. (default '') :arg str commit-ID: The value here is what you supply with the --commit option when invoking the OpenShift `oc start-build` command. (default '') :arg bool verbose: This flag is the toggle for turning on or off detailed logging in this plug-in. (default false) :arg str build-name: TThe value here is what you supply with the --from-build option when invoking the OpenShift `oc start-build` command. (default '') :arg bool show-build-logs: Indicates whether the build logs get dumped to the console of the Jenkins build. (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-builder001.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-builder002.yaml :language: yaml """ osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.' 'OpenShiftBuilder') mapping = [ # option, xml name, default value ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'), ("bld-cfg", 'bldCfg', 'frontend'), ("namespace", 'namespace', 'test'), ("auth-token", 'authToken', ''), ("commit-ID", 'commitID', ''), ("verbose", 'verbose', False), ("build-name", 'buildName', ''), ("show-build-logs", 'showBuildLogs', False), ] convert_mapping_to_xml(osb, data, mapping, fail_required=True) def openshift_creator(registry, xml_parent, data): """yaml: openshift-creator Performs the equivalent of an oc create command invocation; this build step takes in the provided JSON or YAML text, and if it conforms to OpenShift schema, creates whichever OpenShift resources are specified. Requires the Jenkins :jenkins-wiki:`OpenShift Pipeline Plugin <OpenShift+Pipeline+Plugin>`. :arg str api-url: this would be the value you specify if you leverage the --server option on the OpenShift `oc` command. (default '\https://openshift.default.svc.cluster.local') :arg str jsonyaml: The JSON or YAML formatted text that conforms to the schema for defining the various OpenShift resources. (default '') :arg str namespace: If you run `oc get bc` for the project listed in "namespace", that is the value you want to put here. (default 'test') :arg str auth-token: The value here is what you supply with the --token option when invoking the OpenShift `oc` command. (default '') :arg bool verbose: This flag is the toggle for turning on or off detailed logging in this plug-in. (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-creator001.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-creator002.yaml :language: yaml """ osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.' 'OpenShiftCreator') mapping = [ # option, xml name, default value ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'), ("jsonyaml", 'jsonyaml', ''), ("namespace", 'namespace', 'test'), ("auth-token", 'authToken', ''), ("verbose", 'verbose', False), ] convert_mapping_to_xml(osb, data, mapping, fail_required=True) def openshift_dep_verify(registry, xml_parent, data): """yaml: openshift-dep-verify Determines whether the expected set of DeploymentConfig's, ReplicationController's, and active replicas are present based on prior use of the scaler (2) and deployer (3) steps Requires the Jenkins :jenkins-wiki:`OpenShift Pipeline Plugin <OpenShift+Pipeline+Plugin>`._ :arg str api-url: this would be the value you specify if you leverage the --server option on the OpenShift `oc` command. (default \https://openshift.default.svc.cluster.local\) :arg str dep-cfg: The value here should be whatever was the output form `oc project` when you created the BuildConfig you want to run a Build on (default frontend) :arg str namespace: If you run `oc get bc` for the project listed in "namespace", that is the value you want to put here. (default test) :arg int replica-count: The value here should be whatever the number of pods you want started for the deployment. (default 0) :arg str auth-token: The value here is what you supply with the --token option when invoking the OpenShift `oc` command. (default '') :arg bool verbose: This flag is the toggle for turning on or off detailed logging in this plug-in. (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-dep-verify001.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-dep-verify002.yaml :language: yaml """ osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.' 'OpenShiftDeploymentVerifier') mapping = [ # option, xml name, default value ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'), ("dep-cfg", 'depCfg', 'frontend'), ("namespace", 'namespace', 'test'), ("replica-count", 'replicaCount', 0), ("auth-token", 'authToken', ''), ("verbose", 'verbose', False), ] convert_mapping_to_xml(osb, data, mapping, fail_required=True) def openshift_deployer(registry, xml_parent, data): """yaml: openshift-deployer Start a deployment in OpenShift for the job. Requires the Jenkins :jenkins-wiki:`OpenShift Pipeline Plugin <OpenShift+Pipeline+Plugin>`. :arg str api-url: this would be the value you specify if you leverage the --server option on the OpenShift `oc` command. (default '\https://openshift.default.svc.cluster.local') :arg str dep-cfg: The value here should be whatever was the output form `oc project` when you created the BuildConfig you want to run a Build on (default 'frontend') :arg str namespace: If you run `oc get bc` for the project listed in "namespace", that is the value you want to put here. (default 'test') :arg str auth-token: The value here is what you supply with the --token option when invoking the OpenShift `oc` command. (default '') :arg bool verbose: This flag is the toggle for turning on or off detailed logging in this plug-in. (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-deployer001.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-deployer002.yaml :language: yaml """ osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.' 'OpenShiftDeployer') mapping = [ # option, xml name, default value ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'), ("dep-cfg", 'depCfg', 'frontend'), ("namespace", 'namespace', 'test'), ("auth-token", 'authToken', ''), ("verbose", 'verbose', False), ] convert_mapping_to_xml(osb, data, mapping, fail_required=True) def openshift_img_tagger(registry, xml_parent, data): """yaml: openshift-img-tagger Performs the equivalent of an oc tag command invocation in order to manipulate tags for images in OpenShift ImageStream's Requires the Jenkins :jenkins-wiki:`OpenShift Pipeline Plugin <OpenShift+Pipeline+Plugin>`. :arg str api-url: this would be the value you specify if you leverage the --server option on the OpenShift `oc` command. (default '\https://openshift.default.svc.cluster.local') :arg str test-tag: The equivalent to the name supplied to a `oc get service` command line invocation. (default 'origin-nodejs-sample:latest') :arg str prod-tag: The equivalent to the name supplied to a `oc get service` command line invocation. (default 'origin-nodejs-sample:prod') :arg str namespace: If you run `oc get bc` for the project listed in "namespace", that is the value you want to put here. (default 'test') :arg str auth-token: The value here is what you supply with the --token option when invoking the OpenShift `oc` command. (default '') :arg bool verbose: This flag is the toggle for turning on or off detailed logging in this plug-in. (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-img-tagger001.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-img-tagger002.yaml :language: yaml """ osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.' 'OpenShiftImageTagger') mapping = [ # option, xml name, default value ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'), ("test-tag", 'testTag', 'origin-nodejs-sample:latest'), ("prod-tag", 'prodTag', 'origin-nodejs-sample:prod'), ("namespace", 'namespace', 'test'), ("auth-token", 'authToken', ''), ("verbose", 'verbose', False), ] convert_mapping_to_xml(osb, data, mapping, fail_required=True) def openshift_scaler(registry, xml_parent, data): """yaml: openshift-scaler Scale deployments in OpenShift for the job. Requires the Jenkins :jenkins-wiki:`OpenShift Pipeline Plugin <OpenShift+Pipeline+Plugin>`. :arg str api-url: this would be the value you specify if you leverage the --server option on the OpenShift `oc` command. (default '\https://openshift.default.svc.cluster.local') :arg str dep-cfg: The value here should be whatever was the output form `oc project` when you created the BuildConfig you want to run a Build on (default 'frontend') :arg str namespace: If you run `oc get bc` for the project listed in "namespace", that is the value you want to put here. (default 'test') :arg int replica-count: The value here should be whatever the number of pods you want started for the deployment. (default 0) :arg str auth-token: The value here is what you supply with the --token option when invoking the OpenShift `oc` command. (default '') :arg bool verbose: This flag is the toggle for turning on or off detailed logging in this plug-in. (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-scaler001.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-scaler002.yaml :language: yaml """ osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.' 'OpenShiftScaler') mapping = [ # option, xml name, default value ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'), ("dep-cfg", 'depCfg', 'frontend'), ("namespace", 'namespace', 'test'), ("replica-count", 'replicaCount', 0), ("auth-token", 'authToken', ''), ("verbose", 'verbose', False), ] convert_mapping_to_xml(osb, data, mapping, fail_required=True) def openshift_svc_verify(registry, xml_parent, data): """yaml: openshift-svc-verify Verify a service is up in OpenShift for the job. Requires the Jenkins :jenkins-wiki:`OpenShift Pipeline Plugin <OpenShift+Pipeline+Plugin>`. :arg str api-url: this would be the value you specify if you leverage the --server option on the OpenShift `oc` command. (default '\https://openshift.default.svc.cluster.local') :arg str svc-name: The equivalent to the name supplied to a `oc get service` command line invocation. (default 'frontend') :arg str namespace: If you run `oc get bc` for the project listed in "namespace", that is the value you want to put here. (default 'test') :arg str auth-token: The value here is what you supply with the --token option when invoking the OpenShift `oc` command. (default '') :arg bool verbose: This flag is the toggle for turning on or off detailed logging in this plug-in. (default false) Full Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-svc-verify001.yaml :language: yaml Minimal Example: .. literalinclude:: ../../tests/builders/fixtures/openshift-svc-verify002.yaml :language: yaml """ osb = XML.SubElement(xml_parent, 'com.openshift.jenkins.plugins.pipeline.' 'OpenShiftServiceVerifier') mapping = [ # option, xml name, default value ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'), ("svc-name", 'svcName', 'frontend'), ("namespace", 'namespace', 'test'), ("auth-token", 'authToken', ''), ("verbose", 'verbose', False), ] convert_mapping_to_xml(osb, data, mapping, fail_required=True) def runscope(registry, xml_parent, data): """yaml: runscope Execute a Runscope test. Requires the Jenkins :jenkins-wiki:`Runscope Plugin <Runscope+Plugin>`. :arg str test-trigger-url: Trigger URL for test. (required) :arg str access-token: OAuth Personal Access token. (required) :arg int timeout: Timeout for test duration in seconds. (default 60) Minimal Example: .. literalinclude:: /../../tests/builders/fixtures/runscope-minimal.yaml :language: yaml Full Example: .. literalinclude:: /../../tests/builders/fixtures/runscope-full.yaml :language: yaml """ runscope = XML.SubElement(xml_parent, 'com.runscope.jenkins.Runscope.RunscopeBuilder') runscope.set('plugin', 'runscope') mapping = [ ('test-trigger-url', 'triggerEndPoint', None), ('access-token', 'accessToken', None), ('timeout', 'timeout', 60), ] convert_mapping_to_xml(runscope, data, mapping, fail_required=True) def description_setter(registry, xml_parent, data): """yaml: description-setter This plugin sets the description for each build, based upon a RegEx test of the build log file. Requires the Jenkins :jenkins-wiki:`Description Setter Plugin <Description+Setter+Plugin>`. :arg str regexp: A RegEx which is used to scan the build log file (default '') :arg str description: The description to set on the build (optional) Example: .. literalinclude:: /../../tests/builders/fixtures/description-setter001.yaml :language: yaml """ descriptionsetter = XML.SubElement( xml_parent, 'hudson.plugins.descriptionsetter.DescriptionSetterBuilder') XML.SubElement(descriptionsetter, 'regexp').text = data.get('regexp', '') if 'description' in data: XML.SubElement(descriptionsetter, 'description').text = data[ 'description'] def docker_build_publish(parse, xml_parent, data): """yaml: docker-build-publish Requires the Jenkins :jenkins-wiki:`Docker build publish Plugin <Docker+build+publish+Plugin>`. :arg str repo-name: Name of repository to push to. :arg str repo-tag: Tag for image. (default '') :arg dict server: The docker daemon (optional) * **uri** (str): Define the docker server to use. (optional) * **credentials-id** (str): ID of credentials to use to connect (optional) :arg dict registry: Registry to push to * **url** (str) repository url to use (optional) * **credentials-id** (str): ID of credentials to use to connect (optional) :arg bool no-cache: If build should be cached. (default false) :arg bool no-force-pull: Don't update the source image before building when it exists locally. (default false) :arg bool skip-build: Do not build the image. (default false) :arg bool skip-decorate: Do not decorate the build name. (default false) :arg bool skip-tag-latest: Do not tag this build as latest. (default false) :arg bool skip-push: Do not push. (default false) :arg str file-path: Path of the Dockerfile. (default '') :arg str build-context: Project root path for the build, defaults to the workspace if not specified. (default '') Minimal example: .. literalinclude:: /../../tests/builders/fixtures/docker-builder001.yaml Full example: .. literalinclude:: /../../tests/builders/fixtures/docker-builder002.yaml """ db = XML.SubElement(xml_parent, 'com.cloudbees.dockerpublish.DockerBuilder') db.set('plugin', 'docker-build-publish') mapping = [ ('repo-name', 'repoName', None), ('repo-tag', 'repoTag', ''), ('no-cache', 'noCache', False), ('no-force-pull', 'noForcePull', False), ('skip-build', 'skipBuild', False), ('skip-decorate', 'skipDecorate', False), ('skip-tag-latest', 'skipTagLatest', False), ('skip-push', 'skipPush', False), ('file-path', 'dockerfilePath', ''), ('build-context', 'buildContext', ''), ] convert_mapping_to_xml(db, data, mapping, fail_required=True) mapping = [] if 'server' in data: server = XML.SubElement(db, 'server') server.set('plugin', 'docker-commons') server_data = data['server'] if 'credentials-id' in server_data: mapping.append(('credentials-id', 'credentialsId', None)) if 'uri' in server_data: mapping.append(('uri', 'uri', None)) convert_mapping_to_xml( server, server_data, mapping, fail_required=True) mappings = [] if 'registry' in data: registry = XML.SubElement(db, 'registry') registry.set('plugin', 'docker-commons') registry_data = data['registry'] if 'credentials-id' in registry_data: mappings.append(('credentials-id', 'credentialsId', None)) if 'url' in registry_data: mappings.append(('url', 'url', None)) convert_mapping_to_xml( registry, registry_data, mappings, fail_required=True) def build_name_setter(registry, xml_parent, data): """yaml: build-name-setter Define Build Name Setter options which allows your build name to be updated during the build process. Requires the Jenkins :jenkins-wiki:`Build Name Setter Plugin <Build+Name+Setter+Plugin>`. :arg str name: Filename to use for Build Name Setter, only used if file bool is true. (default 'version.txt') :arg str template: Macro Template string, only used if macro bool is true. (default '#${BUILD_NUMBER}') :arg bool file: Read from named file (default false) :arg bool macro: Read from macro template (default false) :arg bool macro-first: Insert macro first (default false) File Example: .. literalinclude:: /../../tests/builders/fixtures/build-name-setter001.yaml :language: yaml Macro Example: .. literalinclude:: /../../tests/builders/fixtures/build-name-setter002.yaml :language: yaml """ build_name_setter = XML.SubElement( xml_parent, 'org.jenkinsci.plugins.buildnameupdater.BuildNameUpdater') mapping = [ ('name', 'buildName', 'version.txt'), ('template', 'macroTemplate', '#${BUILD_NUMBER}'), ('file', 'fromFile', False), ('macro', 'fromMacro', False), ('macro-first', 'macroFirst', False), ] convert_mapping_to_xml( build_name_setter, data, mapping, fail_required=True) def nexus_artifact_uploader(registry, xml_parent, data): """yaml: nexus-artifact-uploader To upload result of a build as an artifact in Nexus without the need of Maven. Requires the Jenkins :nexus-artifact-uploader: `Nexus Artifact Uploader Plugin <Nexus+Artifact+Uploader>`. :arg str protocol: Protocol to use to connect to Nexus (default https) :arg str nexus_url: Nexus url (without protocol) (default '') :arg str nexus_user: Username to upload artifact to Nexus (default '') :arg str nexus_password: Password to upload artifact to Nexus (default '') :arg str group_id: GroupId to set for the artifact to upload (default '') :arg str artifact_id: ArtifactId to set for the artifact to upload (default '') :arg str version: Version to set for the artifact to upload (default '') :arg str packaging: Packaging to set for the artifact to upload (default '') :arg str type: Type to set for the artifact to upload (default '') :arg str classifier: Classifier to set for the artifact to upload (default '') :arg str repository: In which repository to upload the artifact (default '') :arg str file: File which will be the uploaded artifact (default '') :arg str credentials_id: Credentials to use (instead of password) (default '') File Example: .. literalinclude:: /../../tests/builders/fixtures/nexus-artifact-uploader.yaml :language: yaml """ nexus_artifact_uploader = XML.SubElement( xml_parent, 'sp.sd.nexusartifactuploader.NexusArtifactUploader') mapping = [ ('protocol', 'protocol', 'https'), ('nexus_url', 'nexusUrl', ''), ('nexus_user', 'nexusUser', ''), ('nexus_password', 'nexusPassword', ''), ('group_id', 'groupId', ''), ('artifact_id', 'artifactId', ''), ('version', 'version', ''), ('packaging', 'packaging', ''), ('type', 'type', ''), ('classifier', 'classifier', ''), ('repository', 'repository', ''), ('file', 'file', ''), ('credentials_id', 'credentialsId', ''), ] convert_mapping_to_xml( nexus_artifact_uploader, data, mapping, fail_required=True) def ansible_playbook(parser, xml_parent, data): """yaml: ansible-playbook This plugin allows to execute Ansible tasks as a job build step. Requires the Jenkins :jenkins-wiki:`Ansible Plugin <Ansible+Plugin>`. :arg str playbook: Path to the ansible playbook file. The path can be absolute or relative to the job workspace. (required) :arg str inventory-type: The inventory file form (default `path`) :inventory-type values: * **path** * **content** :arg dict inventory: Inventory data, depends on inventory-type :inventory-type == path: * **path** (`str`) -- Path to inventory file. :inventory-type == content: * **content** (`str`) -- Content of inventory file. * **dynamic** (`bool`) -- Dynamic inventory is used (default false) :arg str hosts: Further limit selected hosts to an additional pattern (default '') :arg str tags-to-run: Only run plays and tasks tagged with these values (default '') :arg str tags-to-skip: Only run plays and tasks whose tags do not match these values (default '') :arg str task-to-start-at: Start the playbook at the task matching this name (default '') :arg int workers: Specify number of parallel processes to use (default 5) :arg str credentials-id: The ID of credentials for the SSH connections. Only private key authentication is supported (default '') :arg bool sudo: Run operations with sudo. It works only when the remote user is sudoer with nopasswd option (default false) :arg str sudo-user: Desired sudo user. "root" is used when this field is empty. (default '') :arg bool unbuffered-output: Skip standard output buffering for the ansible process. The ansible output is directly rendered into the Jenkins console. This option can be usefull for long running operations. (default true) :arg bool colorized-output: Check this box to allow ansible to render ANSI color codes in the Jenkins console. (default false) :arg bool host-key-checking: Check this box to enforce the validation of the hosts SSH server keys. (default false) :arg str additional-parameters: Any additional parameters to pass to the ansible command. (default '') :arg list variables: List of extra variables to be passed to ansible. (optional) :variable item: * **name** (`str`) -- Name of variable (required) * **value** (`str`) -- Desired value (default '') * **hidden** (`bool`) -- Hide variable in build log (default false) Example: .. literalinclude:: /../../tests/builders/fixtures/ansible-playbook001.yaml :language: yaml OR .. literalinclude:: /../../tests/builders/fixtures/ansible-playbook002.yaml :language: yaml """ plugin = XML.SubElement( xml_parent, 'org.jenkinsci.plugins.ansible.AnsiblePlaybookBuilder') try: XML.SubElement(plugin, 'playbook').text = str(data['playbook']) except KeyError as ex: raise MissingAttributeError(ex) inventory_types = ('path', 'content') inventory_type = str( data.get('inventory-type', inventory_types[0])).lower() inventory = XML.SubElement(plugin, 'inventory') inv_data = data.get('inventory', {}) if inventory_type == 'path': inventory.set( 'class', 'org.jenkinsci.plugins.ansible.InventoryPath') try: path = inv_data['path'] except KeyError: raise MissingAttributeError('inventory[\'path\']') XML.SubElement(inventory, 'path').text = path elif inventory_type == 'content': inventory.set( 'class', 'org.jenkinsci.plugins.ansible.InventoryContent') try: content = inv_data['content'] except KeyError: raise MissingAttributeError('inventory[\'content\']') XML.SubElement(inventory, 'content').text = content XML.SubElement(inventory, 'dynamic').text = str( inv_data.get('dynamic', False)).lower() else: raise InvalidAttributeError( 'inventory-type', inventory_type, inventory_types) XML.SubElement(plugin, 'limit').text = data.get('hosts', '') XML.SubElement(plugin, 'tags').text = data.get('tags-to-run', '') XML.SubElement(plugin, 'skippedTags').text = data.get('tags-to-skip', '') XML.SubElement(plugin, 'startAtTask').text = data.get( 'task-to-start-at', '') XML.SubElement(plugin, 'credentialsId').text = data.get( 'credentials-id', '') if data.get('sudo', False): XML.SubElement(plugin, 'sudo').text = 'true' XML.SubElement(plugin, 'sudoUser').text = data.get('sudo-user', '') else: XML.SubElement(plugin, 'sudo').text = 'false' XML.SubElement(plugin, 'forks').text = str(data.get('workers', '5')) XML.SubElement(plugin, 'unbufferedOutput').text = str( data.get('unbuffered-output', True)).lower() XML.SubElement(plugin, 'colorizedOutput').text = str( data.get('colorized-output', False)).lower() XML.SubElement(plugin, 'hostKeyChecking').text = str( data.get('host-key-checking', False)).lower() XML.SubElement(plugin, 'additionalParameters').text = str( data.get('additional-parameters', '')) # Following option is not available from UI XML.SubElement(plugin, 'copyCredentialsInWorkspace').text = 'false' variables = data.get('variables', []) if variables: if not is_sequence(variables): raise InvalidAttributeError( 'variables', variables, 'list(dict(name, value, hidden))') variables_elm = XML.SubElement(plugin, 'extraVars') for idx, values in enumerate(variables): if not hasattr(values, 'keys'): raise InvalidAttributeError( 'variables[%s]' % idx, values, 'dict(name, value, hidden)') try: var_name = values['name'] except KeyError: raise MissingAttributeError('variables[%s][\'name\']' % idx) value_elm = XML.SubElement( variables_elm, 'org.jenkinsci.plugins.ansible.ExtraVar') XML.SubElement(value_elm, 'key').text = var_name XML.SubElement(value_elm, 'value').text = values.get('value', '') XML.SubElement(value_elm, 'hidden').text = str( values.get('hidden', False)).lower()
apache-2.0
jason-z-hang/airflow
airflow/macros/hive.py
43
3615
import datetime def max_partition( table, schema="default", field=None, filter=None, metastore_conn_id='metastore_default'): ''' Gets the max partition for a table. :param schema: The hive schema the table lives in :type schema: string :param table: The hive table you are interested in, supports the dot notation as in "my_database.my_table", if a dot is found, the schema param is disregarded :type table: string :param hive_conn_id: The hive connection you are interested in. If your default is set you don't need to use this parameter. :type hive_conn_id: string :param filter: filter on a subset of partition as in `sub_part='specific_value'` :type filter: string :param field: the field to get the max value from. If there's only one partition field, this will be inferred >>> max_partition('airflow.static_babynames_partitioned') '2015-01-01' ''' from airflow.hooks import HiveMetastoreHook if '.' in table: schema, table = table.split('.') hh = HiveMetastoreHook(metastore_conn_id=metastore_conn_id) return hh.max_partition( schema=schema, table_name=table, field=field, filter=filter) def _closest_date(target_dt, date_list, before_target=None): ''' This function finds the date in a list closest to the target date. An optional parameter can be given to get the closest before or after. :param target_dt: The target date :type target_dt: datetime.date :param date_list: The list of dates to search :type date_list: datetime.date list :param before_target: closest before or after the target :type before_target: bool or None :returns: The closest date :rtype: datetime.date or None ''' fb = lambda d: d - target_dt if d >= target_dt else datetime.timedelta.max fa = lambda d: d - target_dt if d <= target_dt else datetime.timedelta.min fnone = lambda d: target_dt - d if d < target_dt else d - target_dt if before_target is None: return min(date_list, key=fnone).date() if before_target: return min(date_list, key=fb).date() else: return min(date_list, key=fa).date() def closest_ds_partition( table, ds, before=True, schema="default", metastore_conn_id='metastore_default'): ''' This function finds the date in a list closest to the target date. An optional parameter can be given to get the closest before or after. :param table: A hive table name :type table: str :param ds: A datestamp ``%Y-%m-%d`` e.g. ``yyyy-mm-dd`` :type ds: datetime.date list :param before: closest before (True), after (False) or either side of ds :type before: bool or None :returns: The closest date :rtype: str or None >>> tbl = 'airflow.static_babynames_partitioned' >>> closest_ds_partition(tbl, '2015-01-02') '2015-01-01' ''' from airflow.hooks import HiveMetastoreHook if '.' in table: schema, table = table.split('.') hh = HiveMetastoreHook(metastore_conn_id=metastore_conn_id) partitions = hh.get_partitions(schema=schema, table_name=table) if not partitions: return None part_vals = [list(p.values())[0] for p in partitions] if ds in part_vals: return ds else: parts = [datetime.datetime.strptime(pv, '%Y-%m-%d') for pv in part_vals] target_dt = datetime.datetime.strptime(ds, '%Y-%m-%d') closest_ds = _closest_date(target_dt, parts, before_target=before) return closest_ds.isoformat()
apache-2.0
duncant/stupid_python_tricks
decorator_decorator.py
1
1795
# This file is part of stupid_python_tricks written by Duncan Townsend. # # stupid_python_tricks 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 3 of the License, or (at your # option) any later version. # # stupid_python_tricks 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 stupid_python_tricks. If not, see <http://www.gnu.org/licenses/>. import decorator from collections import Callable def decorator_apply(dec, func, args, kwargs): """ Decorate a function by preserving the signature even if dec is not a signature-preserving decorator. """ return decorator.FunctionMaker.create( func, 'return decorated(%(signature)s)', dict(decorated=dec(func, *args, **kwargs)), __wrapped__=func, addsource=True) @decorator.decorator def decorator_decorator(dec, func, *args, **kwargs): """Decorator for decorators""" if isinstance(func, Callable): return decorator_apply(dec, func, args, kwargs) else: return dec(func, *args, **kwargs) def decorates(dec, func=None): if not isinstance(func, Callable): def decorates_with_func(new_dec): return decorates(new_dec, dec) return decorates_with_func return decorator.FunctionMaker.create( func, 'return decorated(%(signature)s)', dict(decorated=dec, __wrapped__=func)) __all__ = ['decorator_decorator', 'decorates']
lgpl-3.0
justacec/bokeh
bokeh/charts/tests/test_builder.py
3
3097
"""This is the Bokeh charts testing interface. """ #----------------------------------------------------------------------------- # Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import absolute_import from mock import Mock import pytest from bokeh.charts.builder import Builder from bokeh.charts.properties import Dimension from bokeh.charts.attributes import ColorAttr, DEFAULT_PALETTE #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- CUSTOM_PALETTE = ['Red', 'Green', 'Blue'] @pytest.fixture def test_builder(): class TestBuilder(Builder): default_attributes = {'color': ColorAttr()} x = Dimension('x') y = Dimension('y') dimensions = ['x', 'y'] return TestBuilder @pytest.fixture def simple_builder(test_builder, test_data): return test_builder(test_data.pd_data) @pytest.fixture def custom_palette_builder(test_builder, test_data): return test_builder(test_data.pd_data, palette=CUSTOM_PALETTE) def test_empty_builder_labels(test_builder): builder = test_builder() assert builder.xlabel is None assert builder.ylabel is None def test_default_color(simple_builder): assert simple_builder.attributes['color'].iterable == DEFAULT_PALETTE def test_custom_color(custom_palette_builder): assert custom_palette_builder.attributes['color'].iterable == CUSTOM_PALETTE def test_legend_sort(test_data): sort_legend = [('color', False)] col1, col2, col3 = Mock(), Mock(), Mock() legends = [('col1', col1), ('col3', col3), ('col2', col2)] items = [('col1', Mock()), ('col2', Mock()), ('col3', Mock())] attributes = { 'color': Mock(columns=['series'], items=items), 'dash': Mock(columns=['series'], items=items), 'marker': Mock(columns=['series'], items=items) } # assert we don't change anything if sort_legend is not specified assert Builder._sort_legend(None, None, legends, attributes) == legends # assert we sort asc if specified so assert Builder._sort_legend('color', 'ascending', legends, attributes) == \ [('col1', col1), ('col2', col2), ('col3', col3)] # assert we sort desc if specified so assert Builder._sort_legend('color', 'descending', legends, attributes) == \ [('col3', col3), ('col2', col2), ('col1', col1)] def test_sort_legend(test_builder, test_data): test_builder = test_builder(test_data.pd_data, sort_legend=[('color', 'ascending')]) assert test_builder.legend_sort_field == 'color' assert test_builder.legend_sort_direction == 'ascending'
bsd-3-clause
revmischa/boto
boto/glacier/__init__.py
145
1685
# Copyright (c) 2011 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2011 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 boto.regioninfo import RegionInfo, get_regions def regions(): """ Get all available regions for the Amazon Glacier service. :rtype: list :return: A list of :class:`boto.regioninfo.RegionInfo` """ from boto.glacier.layer2 import Layer2 return get_regions('glacier', connection_cls=Layer2) def connect_to_region(region_name, **kw_params): for region in regions(): if region.name == region_name: return region.connect(**kw_params) return None
mit
direvus/ansible
lib/ansible/modules/cloud/cloudstack/cs_instancegroup.py
37
5335
#!/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/>. ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cs_instancegroup short_description: Manages instance groups on Apache CloudStack based clouds. description: - Create and remove instance groups. version_added: '2.0' author: "René Moser (@resmo)" options: name: description: - Name of the instance group. required: true domain: description: - Domain the instance group is related to. account: description: - Account the instance group is related to. project: description: - Project the instance group is related to. state: description: - State of the instance group. default: 'present' choices: [ 'present', 'absent' ] extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' # Create an instance group - local_action: module: cs_instancegroup name: loadbalancers # Remove an instance group - local_action: module: cs_instancegroup name: loadbalancers state: absent ''' RETURN = ''' --- id: description: UUID of the instance group. returned: success type: string sample: 04589590-ac63-4ffc-93f5-b698b8ac38b6 name: description: Name of the instance group. returned: success type: string sample: webservers created: description: Date when the instance group was created. returned: success type: string sample: 2015-05-03T15:05:51+0200 domain: description: Domain the instance group is related to. returned: success type: string sample: example domain account: description: Account the instance group is related to. returned: success type: string sample: example account project: description: Project the instance group is related to. returned: success type: string sample: example project ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, cs_argument_spec, cs_required_together ) class AnsibleCloudStackInstanceGroup(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackInstanceGroup, self).__init__(module) self.instance_group = None def get_instance_group(self): if self.instance_group: return self.instance_group name = self.module.params.get('name') args = { 'account': self.get_account('name'), 'domainid': self.get_domain('id'), 'projectid': self.get_project('id'), 'fetch_list': True, } instance_groups = self.query_api('listInstanceGroups', **args) if instance_groups: for g in instance_groups: if name in [g['name'], g['id']]: self.instance_group = g break return self.instance_group def present_instance_group(self): instance_group = self.get_instance_group() if not instance_group: self.result['changed'] = True args = { 'name': self.module.params.get('name'), 'account': self.get_account('name'), 'domainid': self.get_domain('id'), 'projectid': self.get_project('id'), } if not self.module.check_mode: res = self.query_api('createInstanceGroup', **args) instance_group = res['instancegroup'] return instance_group def absent_instance_group(self): instance_group = self.get_instance_group() if instance_group: self.result['changed'] = True if not self.module.check_mode: self.query_api('deleteInstanceGroup', id=instance_group['id']) return instance_group def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name=dict(required=True), state=dict(default='present', choices=['present', 'absent']), domain=dict(), account=dict(), project=dict(), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True ) acs_ig = AnsibleCloudStackInstanceGroup(module) state = module.params.get('state') if state in ['absent']: instance_group = acs_ig.absent_instance_group() else: instance_group = acs_ig.present_instance_group() result = acs_ig.get_result(instance_group) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
Spiderlover/Toontown
toontown/battle/MoviePetSOS.py
3
4398
from direct.directnotify import DirectNotifyGlobal from direct.interval.IntervalGlobal import * import random import BattleParticles from BattleProps import * from BattleSounds import * import HealJokes import MovieCamera import MovieUtil from toontown.chat.ChatGlobals import * from toontown.pets import Pet, PetTricks from toontown.toonbase import TTLocalizer from toontown.toonbase import ToontownBattleGlobals notify = DirectNotifyGlobal.directNotify.newCategory('MoviePetSOS') soundFiles = ('AA_heal_tickle.ogg', 'AA_heal_telljoke.ogg', 'AA_heal_smooch.ogg', 'AA_heal_happydance.ogg', 'AA_heal_pixiedust.ogg', 'AA_heal_juggle.ogg') offset = Point3(0, 4.0, 0) def doPetSOSs(PetSOSs): if len(PetSOSs) == 0: return (None, None) track = Sequence() textTrack = Sequence() for p in PetSOSs: ival = __doPetSOS(p) if ival: track.append(ival) camDuration = track.getDuration() camTrack = MovieCamera.chooseHealShot(PetSOSs, camDuration) return (track, camTrack) def __doPetSOS(sos): return __healJuggle(sos) def __healToon(toon, hp, gender, callerToonId, ineffective = 0): notify.debug('healToon() - toon: %d hp: %d ineffective: %d' % (toon.doId, hp, ineffective)) nolaughter = 0 if ineffective == 1: if callerToonId == toon.doId: laughter = TTLocalizer.MoviePetSOSTrickFail else: nolaughter = 1 else: maxDam = ToontownBattleGlobals.AvPropDamage[0][1][0][1] if callerToonId == toon.doId: if gender == 1: laughter = TTLocalizer.MoviePetSOSTrickSucceedBoy else: laughter = TTLocalizer.MoviePetSOSTrickSucceedGirl elif hp >= maxDam - 1: laughter = random.choice(TTLocalizer.MovieHealLaughterHits2) else: laughter = random.choice(TTLocalizer.MovieHealLaughterHits1) if nolaughter == 0: toon.setChatAbsolute(laughter, CFSpeech | CFTimeout) if hp > 0 and toon.hp != None: toon.toonUp(hp) else: notify.debug('__healToon() - toon: %d hp: %d' % (toon.doId, hp)) return def __teleportIn(attack, pet, pos = Point3(0, 0, 0), hpr = Vec3(180.0, 0.0, 0.0)): a = Func(pet.reparentTo, attack['battle']) b = Func(pet.setPos, pos) c = Func(pet.setHpr, hpr) d = Func(pet.pose, 'reappear', 0) e = pet.getTeleportInTrack() g = Func(pet.loop, 'neutral') return Sequence(a, b, c, d, e, g) def __teleportOut(attack, pet): a = pet.getTeleportOutTrack() c = Func(pet.detachNode) d = Func(pet.delete) return Sequence(a, c) def __doPet(attack, level, hp): track = __doSprinkle(attack, 'suits', hp) pbpText = attack['playByPlayText'] pbpTrack = pbpText.getShowInterval(TTLocalizer.MovieNPCSOSCogsMiss, track.getDuration()) return (track, pbpTrack) def __healJuggle(heal): petProxyId = heal['petId'] pet = Pet.Pet() gender = 0 if petProxyId in base.cr.doId2do: petProxy = base.cr.doId2do[petProxyId] if petProxy == None: return pet.setDNA(petProxy.style) pet.setName(petProxy.petName) gender = petProxy.gender else: pet.setDNA([-1, 0, 0, -1, 2, 0, 4, 0, 1]) pet.setName('Smiley') targets = heal['target'] ineffective = heal['sidestep'] level = heal['level'] track = Sequence(__teleportIn(heal, pet)) if ineffective: trickTrack = Parallel(Wait(1.0), Func(pet.loop, 'neutralSad'), Func(pet.showMood, 'confusion')) else: trickTrack = PetTricks.getTrickIval(pet, level) track.append(trickTrack) delay = 4.0 first = 1 targetTrack = Sequence() for target in targets: targetToon = target['toon'] hp = target['hp'] callerToonId = heal['toonId'] reactIval = Func(__healToon, targetToon, hp, gender, callerToonId, ineffective) if first == 1: first = 0 targetTrack.append(reactIval) mtrack = Parallel(Wait(2.0), targetTrack) track.append(mtrack) track.append(Sequence(Func(pet.clearMood))) track.append(__teleportOut(heal, pet)) for target in targets: targetToon = target['toon'] track.append(Func(targetToon.clearChat)) track.append(Func(pet.delete)) return track
mit
rghe/ansible
lib/ansible/modules/cloud/profitbricks/profitbricks_datacenter.py
36
7523
#!/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: profitbricks_datacenter short_description: Create or destroy a ProfitBricks Virtual Datacenter. description: - This is a simple module that supports creating or removing vDCs. A vDC is required before you can create servers. This module has a dependency on profitbricks >= 1.0.0 version_added: "2.0" options: name: description: - The name of the virtual datacenter. required: true description: description: - The description of the virtual datacenter. required: false location: description: - The datacenter location. required: false default: us/las choices: [ "us/las", "de/fra", "de/fkb" ] subscription_user: description: - The ProfitBricks username. Overrides the PB_SUBSCRIPTION_ID environment variable. required: false subscription_password: description: - THe ProfitBricks password. Overrides the PB_PASSWORD environment variable. required: false wait: description: - wait for the datacenter to be created before returning required: false default: "yes" type: bool wait_timeout: description: - how long before wait gives up, in seconds default: 600 state: description: - create or terminate datacenters required: false default: 'present' choices: [ "present", "absent" ] requirements: [ "profitbricks" ] author: Matt Baldwin (baldwin@stackpointcloud.com) ''' EXAMPLES = ''' # Create a Datacenter - profitbricks_datacenter: datacenter: Tardis One wait_timeout: 500 # Destroy a Datacenter. This will remove all servers, volumes, and other objects in the datacenter. - profitbricks_datacenter: datacenter: Tardis One wait_timeout: 500 state: absent ''' import re import time HAS_PB_SDK = True try: from profitbricks.client import ProfitBricksService, Datacenter except ImportError: HAS_PB_SDK = False from ansible.module_utils.basic import AnsibleModule LOCATIONS = ['us/las', 'de/fra', 'de/fkb'] uuid_match = re.compile( r'[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}', re.I) def _wait_for_completion(profitbricks, promise, wait_timeout, msg): if not promise: return wait_timeout = time.time() + wait_timeout while wait_timeout > time.time(): time.sleep(5) operation_result = profitbricks.get_request( request_id=promise['requestId'], status=True) if operation_result['metadata']['status'] == "DONE": return elif operation_result['metadata']['status'] == "FAILED": raise Exception( 'Request failed to complete ' + msg + ' "' + str( promise['requestId']) + '" to complete.') raise Exception( 'Timed out waiting for async operation ' + msg + ' "' + str( promise['requestId'] ) + '" to complete.') def _remove_datacenter(module, profitbricks, datacenter): try: profitbricks.delete_datacenter(datacenter) except Exception as e: module.fail_json(msg="failed to remove the datacenter: %s" % str(e)) def create_datacenter(module, profitbricks): """ Creates a Datacenter This will create a new Datacenter in the specified location. module : AnsibleModule object profitbricks: authenticated profitbricks object. Returns: True if a new datacenter was created, false otherwise """ name = module.params.get('name') location = module.params.get('location') description = module.params.get('description') wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) i = Datacenter( name=name, location=location, description=description ) try: datacenter_response = profitbricks.create_datacenter(datacenter=i) if wait: _wait_for_completion(profitbricks, datacenter_response, wait_timeout, "_create_datacenter") results = { 'datacenter_id': datacenter_response['id'] } return results except Exception as e: module.fail_json(msg="failed to create the new datacenter: %s" % str(e)) def remove_datacenter(module, profitbricks): """ Removes a Datacenter. This will remove a datacenter. module : AnsibleModule object profitbricks: authenticated profitbricks object. Returns: True if the datacenter was deleted, false otherwise """ name = module.params.get('name') changed = False if(uuid_match.match(name)): _remove_datacenter(module, profitbricks, name) changed = True else: datacenters = profitbricks.list_datacenters() for d in datacenters['items']: vdc = profitbricks.get_datacenter(d['id']) if name == vdc['properties']['name']: name = d['id'] _remove_datacenter(module, profitbricks, name) changed = True return changed def main(): module = AnsibleModule( argument_spec=dict( name=dict(), description=dict(), location=dict(choices=LOCATIONS, default='us/las'), subscription_user=dict(), subscription_password=dict(no_log=True), wait=dict(type='bool', default=True), wait_timeout=dict(default=600), state=dict(default='present'), ) ) if not HAS_PB_SDK: module.fail_json(msg='profitbricks required for this module') if not module.params.get('subscription_user'): module.fail_json(msg='subscription_user parameter is required') if not module.params.get('subscription_password'): module.fail_json(msg='subscription_password parameter is required') subscription_user = module.params.get('subscription_user') subscription_password = module.params.get('subscription_password') profitbricks = ProfitBricksService( username=subscription_user, password=subscription_password) state = module.params.get('state') if state == 'absent': if not module.params.get('name'): module.fail_json(msg='name parameter is required deleting a virtual datacenter.') try: (changed) = remove_datacenter(module, profitbricks) module.exit_json( changed=changed) except Exception as e: module.fail_json(msg='failed to set datacenter state: %s' % str(e)) elif state == 'present': if not module.params.get('name'): module.fail_json(msg='name parameter is required for a new datacenter') if not module.params.get('location'): module.fail_json(msg='location parameter is required for a new datacenter') try: (datacenter_dict_array) = create_datacenter(module, profitbricks) module.exit_json(**datacenter_dict_array) except Exception as e: module.fail_json(msg='failed to set datacenter state: %s' % str(e)) if __name__ == '__main__': main()
gpl-3.0
maxalbert/tohu
tohu/v4/base.py
1
4952
import hashlib from abc import ABCMeta, abstractmethod from itertools import islice from random import Random from tqdm import tqdm from .item_list import ItemList from .logging import logger __all__ = ['SeedGenerator', 'TohuBaseGenerator'] class TohuBaseGenerator(metaclass=ABCMeta): """ Base class for all of tohu's generators. """ def __init__(self): self._clones = [] self.tohu_name = None def __repr__(self): clsname = self.__class__.__name__ name = '' if self.tohu_name is None else f'{self.tohu_name}: ' return f'<{name}{clsname} (id={self.tohu_id})>' def __format__(self, fmt): return self.__repr__() def set_tohu_name(self, tohu_name): """ Set this generator's `tohu_name` attribute. This is mainly useful for debugging where one can temporarily use this at the end of generator definitions to set a name that will be displayed in debugging messages. For example: g1 = SomeGeneratorClass().set_tohu_name('g1') g2 = SomeGeneratorClass().set_tohu_name('g2') """ self.tohu_name = tohu_name return self @property def tohu_id(self): """ Return (truncated) md5 hash representing this generator. We truncate the hash simply for readability, as this is purely intended for debugging purposes and the risk of any collisions will be negligible. """ myhash = hashlib.md5(str(id(self)).encode()).hexdigest() return myhash[:12] def __iter__(self): return self def register_clone(self, clone): self._clones.append(clone) # If possible, set the clone's tohu_name for easier debugging if self.tohu_name is not None: clone.set_tohu_name(f"{self.tohu_name} (clone #{len(self._clones)})") if len(self._clones) != len(set(self._clones)): raise RuntimeError(f"Duplicate clone added: {self} --> {clone}") @abstractmethod def __next__(self): raise NotImplementedError("Class {} does not implement method '__next__'.".format(self.__class__.__name__)) @abstractmethod def reset(self, seed): logger.debug(f'Resetting {self} (seed={seed})') # Print debugging messages in bulk before actually # resetting clones because it makes them easier to # read in the debugging output. if self._clones != []: logger.debug(' Will also reset the following clones:') for c in self._clones: logger.debug(f' - {c}') for c in self._clones: c.reset(seed) @abstractmethod def _set_random_state_from(self, other): """ This helper method sets the internal random state of `self` to the same state that `other` is in. This ensures that afterwards any the two generators `self` and `other` produce the same elements in the same order (even though otherwise they remain independent). This is used internally when spawning generators. """ raise NotImplementedError("Class {} does not implement method 'spawn'.".format(self.__class__.__name__)) @abstractmethod def spawn(self): raise NotImplementedError("Class {} does not implement method 'spawn'.".format(self.__class__.__name__)) def clone(self): c = self.spawn() self.register_clone(c) return c def generate(self, num, *, seed=None, progressbar=False): """ Return sequence of `num` elements. If `seed` is not None, the generator is reset using this seed before generating the elements. """ if seed is not None: self.reset(seed) items = islice(self, num) if progressbar: items = tqdm(items, total=num) item_list = [x for x in items] #logger.warning("TODO: initialise ItemList with random seed!") return ItemList(item_list, num) class SeedGenerator: """ This class is used in custom generators to create a collection of seeds when reset() is called, so that each of the constituent generators can be re-initialised with a different seed in a reproducible way. Note: This is almost identical to the `tohu.Integer` generator, but we need a version which does *not* inherit from `TohuUltraBaseGenerator`, otherwise the automatic item class creation in `CustomGeneratorMeta` gets confused. """ def __init__(self): self.randgen = Random() self.minval = 0 self.maxval = 2**32 - 1 def reset(self, seed): self.randgen.seed(seed) def __iter__(self): return self def __next__(self): return self.randgen.randint(self.minval, self.maxval) def _set_random_state_from(self, other): self.randgen.setstate(other.randgen.getstate())
mit
blueburningcoder/nupic
examples/prediction/experiments/confidenceTest/base/description.py
39
13873
# ---------------------------------------------------------------------- # 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/ # ---------------------------------------------------------------------- import os import imp from nupic.encoders import (LogEncoder, DateEncoder, MultiEncoder, CategoryEncoder, SDRCategoryEncoder, ScalarEncoder) from nupic.data.file_record_stream import FileRecordStream from nupic.frameworks.prediction.callbacks import (printSPCoincidences, printTPCells, printTPTiming, displaySPCoincidences, setAttribute, sensorRewind, sensorOpen) from nupic.frameworks.prediction.helpers import updateConfigFromSubConfig # ---------------------------------------------------------------------- # Define this experiment's base configuration, and adjust for any modifications # if imported from a sub-experiment. config = dict( sensorVerbosity = 0, spVerbosity = 0, tpVerbosity = 0, ppVerbosity = 0, dataSetPackage = None, # This can be specified in place of the next 6: filenameTrain = 'confidence/confidence1.csv', filenameTest = 'confidence/confidence1.csv', filenameCategory = None, dataGenScript = None, dataDesc = None, dataGenNumCategories = None, dataGenNumTraining = None, dataGenNumTesting = None, noiseAmts = [], iterationCountTrain = None, iterationCountTest = None, evalTrainingSetNumIterations = 10000, # Set to 0 to disable completely trainSP = True, trainTP = True, trainTPRepeats = 1, computeTopDown = 1, # Encoder overlappingPatterns = 0, # SP params disableSpatial = 1, spPrintPeriodicStats = 0, # An integer N: print stats every N iterations spCoincCount = 200, spNumActivePerInhArea = 3, # TP params tpNCellsPerCol = 20, tpInitialPerm = 0.6, tpPermanenceInc = 0.1, tpPermanenceDec = 0.000, tpGlobalDecay = 0.0, tpPAMLength = 1, tpMaxSeqLength = 0, tpMaxAge = 1, tpTimingEvery = 0, temporalImp = 'cpp', ) updateConfigFromSubConfig(config) # ========================================================================== # Was a complete dataset package specified? This is an alternate way to # specify a bunch of dataset related config parameters at once. They are # especially helpful when running permutations - it keeps the permutations # directory names shorter. if config['dataSetPackage'] is not None: assert (config['filenameTrain'] == 'confidence/confidence1.csv') assert (config['filenameTest'] == 'confidence/confidence1.csv') assert (config['filenameCategory'] == None) assert (config['dataGenScript'] == None) assert (config['dataDesc'] == None) assert (config['dataGenNumCategories'] == None) assert (config['dataGenNumTraining'] == None) assert (config['dataGenNumTesting'] == None) if config['dataSetPackage'] == 'firstOrder': config['filenameTrain'] = 'extra/firstOrder/fo_1000_10_train_resets.csv' config['filenameTest'] = 'extra/firstOrder/fo_10000_10_test_resets.csv' config['filenameCategory'] = 'extra/firstOrder/categories.txt' elif config['dataSetPackage'] == 'secondOrder0': config['filenameTrain'] = None config['filenameTest'] = None config['filenameCategory'] = None config['dataGenScript'] = 'extra/secondOrder/makeDataset.py' config['dataDesc'] = 'model0' config['dataGenNumCategories'] = 20 config['dataGenNumTraining'] = 5000 config['dataGenNumTesting'] = 1000 elif config['dataSetPackage'] == 'secondOrder1': config['filenameTrain'] = None config['filenameTest'] = None config['filenameCategory'] = None config['dataGenScript'] = 'extra/secondOrder/makeDataset.py' config['dataDesc'] = 'model1' config['dataGenNumCategories'] = 25 config['dataGenNumTraining'] = 5000 config['dataGenNumTesting'] = 1000 elif config['dataSetPackage'] == 'secondOrder2': config['filenameTrain'] = None config['filenameTest'] = None config['filenameCategory'] = None config['dataGenScript'] = 'extra/secondOrder/makeDataset.py' config['dataDesc'] = 'model2' config['dataGenNumCategories'] = 5 config['dataGenNumTraining'] = 5000 config['dataGenNumTesting'] = 1000 else: assert False def getBaseDatasets(): datasets = dict() for name in ['filenameTrain', 'filenameTest', 'filenameCategory', 'dataGenScript']: if config[name] is not None: datasets[name] = config[name] return datasets def getDatasets(baseDatasets, generate=False): # nothing to generate if no script if not 'dataGenScript' in baseDatasets: return baseDatasets # ------------------------------------------------------------------- # Form the path to each dataset datasets = dict(baseDatasets) dataPath = os.path.dirname(baseDatasets['dataGenScript']) # At some point, this prefix will be modified to be unique for each # possible variation of parameters into the data generation script. prefix = '%s' % (config['dataDesc']) datasets['filenameTrain'] = os.path.join(dataPath, '%s_train.csv' % prefix) datasets['filenameTest'] = os.path.join(dataPath, '%s_test.csv' % prefix) datasets['filenameCategory'] = os.path.join(dataPath, '%s_categories.txt' % prefix) if not generate: return datasets # ------------------------------------------------------------------- # Generate our data makeDataset = imp.load_source('makeDataset', baseDatasets['dataGenScript']) makeDataset.generate(model = config['dataDesc'], filenameTrain = datasets['filenameTrain'], filenameTest = datasets['filenameTest'], filenameCategory = datasets['filenameCategory'], numCategories=config['dataGenNumCategories'], numTrainingRecords=config['dataGenNumTraining'], numTestingRecords=config['dataGenNumTesting'], numNoise=0, resetsEvery=None) return datasets def getDescription(datasets): # ======================================================================== # Network definition # Encoder for the sensor encoder = MultiEncoder() if 'filenameCategory' in datasets: categories = [x.strip() for x in open(datasets['filenameCategory']).xreadlines()] else: categories = [chr(x+ord('a')) for x in range(26)] if config['overlappingPatterns']: encoder.addEncoder("name", SDRCategoryEncoder(n=200, w=config['spNumActivePerInhArea'], categoryList=categories, name="name")) else: encoder.addEncoder("name", CategoryEncoder(w=config['spNumActivePerInhArea'], categoryList=categories, name="name")) # ------------------------------------------------------------------ # Node params # The inputs are long, horizontal vectors inputDimensions = (1, encoder.getWidth()) # Layout the coincidences vertically stacked on top of each other, each # looking at the entire input field. columnDimensions = (config['spCoincCount'], 1) # If we have disableSpatial, then set the number of "coincidences" to be the # same as the encoder width if config['disableSpatial']: columnDimensions = (encoder.getWidth(), 1) config['trainSP'] = 0 sensorParams = dict( # encoder/datasource are not parameters so don't include here verbosity=config['sensorVerbosity'] ) CLAParams = dict( # SP params disableSpatial = config['disableSpatial'], inputDimensions = inputDimensions, columnDimensions = columnDimensions, potentialRadius = inputDimensions[1]/2, potentialPct = 1.00, gaussianDist = 0, commonDistributions = 0, # should be False if possibly not training localAreaDensity = -1, #0.05, numActiveColumnsPerInhArea = config['spNumActivePerInhArea'], dutyCyclePeriod = 1000, stimulusThreshold = 1, synPermInactiveDec=0.11, synPermActiveInc=0.11, synPermActiveSharedDec=0.0, synPermOrphanDec = 0.0, minPctDutyCycleBeforeInh = 0.001, minPctDutyCycleAfterInh = 0.001, spVerbosity = config['spVerbosity'], spSeed = 1, printPeriodicStats = int(config['spPrintPeriodicStats']), # TP params tpSeed = 1, disableTemporal = 0 if config['trainTP'] else 1, temporalImp = config['temporalImp'], nCellsPerCol = config['tpNCellsPerCol'] if config['trainTP'] else 1, collectStats = 1, burnIn = 2, verbosity = config['tpVerbosity'], newSynapseCount = config['spNumActivePerInhArea'], minThreshold = config['spNumActivePerInhArea'], activationThreshold = config['spNumActivePerInhArea'], initialPerm = config['tpInitialPerm'], connectedPerm = 0.5, permanenceInc = config['tpPermanenceInc'], permanenceDec = config['tpPermanenceDec'], # perhaps tune this globalDecay = config['tpGlobalDecay'], pamLength = config['tpPAMLength'], maxSeqLength = config['tpMaxSeqLength'], maxAge = config['tpMaxAge'], # General params computeTopDown = config['computeTopDown'], trainingStep = 'spatial', ) dataSource = FileRecordStream(datasets['filenameTrain']) description = dict( options = dict( logOutputsDuringInference = False, ), network = dict( sensorDataSource = dataSource, sensorEncoder = encoder, sensorParams = sensorParams, CLAType = 'py.CLARegion', CLAParams = CLAParams, classifierType = None, classifierParams = None), ) if config['trainSP']: description['spTrain'] = dict( iterationCount=config['iterationCountTrain'], #iter=displaySPCoincidences(50), #finish=printSPCoincidences() ), else: description['spTrain'] = dict( # need to train with one iteration just to initialize data structures iterationCount=1) if config['trainTP']: description['tpTrain'] = [] for i in xrange(config['trainTPRepeats']): stepDict = dict(name='step_%d' % (i), setup=sensorRewind, iterationCount=config['iterationCountTrain'], ) if config['tpTimingEvery'] > 0: stepDict['iter'] = printTPTiming(config['tpTimingEvery']) stepDict['finish'] = [printTPTiming(), printTPCells] description['tpTrain'].append(stepDict) # ---------------------------------------------------------------------------- # Inference tests inferSteps = [] if config['evalTrainingSetNumIterations'] > 0: # The training set. Used to train the n-grams. inferSteps.append( dict(name = 'confidenceTrain_baseline', iterationCount = min(config['evalTrainingSetNumIterations'], config['iterationCountTrain']), ppOptions = dict(verbosity=config['ppVerbosity'], printLearnedCoincidences=True, nGrams='train', #ipsDetailsFor = "name,None,2", ), #finish=printTPCells, ) ) # Testing the training set on both the TP and n-grams. inferSteps.append( dict(name = 'confidenceTrain_nonoise', iterationCount = min(config['evalTrainingSetNumIterations'], config['iterationCountTrain']), setup = [sensorOpen(datasets['filenameTrain'])], ppOptions = dict(verbosity=config['ppVerbosity'], printLearnedCoincidences=False, nGrams='test', burnIns = [1,2,3,4], #ipsDetailsFor = "name,None,2", #ipsAt = [1,2,3,4], ), ) ) # The test set if True: if datasets['filenameTest'] != datasets['filenameTrain']: inferSteps.append( dict(name = 'confidenceTest_baseline', iterationCount = config['iterationCountTest'], setup = [sensorOpen(datasets['filenameTest'])], ppOptions = dict(verbosity=config['ppVerbosity'], printLearnedCoincidences=False, nGrams='test', burnIns = [1,2,3,4], #ipsAt = [1,2,3,4], ipsDetailsFor = "name,None,2", ), ) ) description['infer'] = inferSteps return description
agpl-3.0
noif/locust
locust/main.py
31
14285
import locust import runners import gevent import sys import os import signal import inspect import logging import socket from optparse import OptionParser import web from log import setup_logging, console_logger from stats import stats_printer, print_percentile_stats, print_error_report, print_stats from inspectlocust import print_task_ratio, get_task_ratio_dict from core import Locust, HttpLocust from runners import MasterLocustRunner, SlaveLocustRunner, LocalLocustRunner import events _internals = [Locust, HttpLocust] version = locust.version def parse_options(): """ Handle command-line options with optparse.OptionParser. Return list of arguments, largely for use in `parse_arguments`. """ # Initialize parser = OptionParser(usage="locust [options] [LocustClass [LocustClass2 ... ]]") parser.add_option( '-H', '--host', dest="host", default=None, help="Host to load test in the following format: http://10.21.32.33" ) parser.add_option( '--web-host', dest="web_host", default="", help="Host to bind the web interface to. Defaults to '' (all interfaces)" ) parser.add_option( '-P', '--port', '--web-port', type="int", dest="port", default=8089, help="Port on which to run web host" ) parser.add_option( '-f', '--locustfile', dest='locustfile', default='locustfile', help="Python module file to import, e.g. '../other.py'. Default: locustfile" ) # if locust should be run in distributed mode as master parser.add_option( '--master', action='store_true', dest='master', default=False, help="Set locust to run in distributed mode with this process as master" ) # if locust should be run in distributed mode as slave parser.add_option( '--slave', action='store_true', dest='slave', default=False, help="Set locust to run in distributed mode with this process as slave" ) # master host options parser.add_option( '--master-host', action='store', type='str', dest='master_host', default="127.0.0.1", help="Host or IP address of locust master for distributed load testing. Only used when running with --slave. Defaults to 127.0.0.1." ) parser.add_option( '--master-port', action='store', type='int', dest='master_port', default=5557, help="The port to connect to that is used by the locust master for distributed load testing. Only used when running with --slave. Defaults to 5557. Note that slaves will also connect to the master node on this port + 1." ) parser.add_option( '--master-bind-host', action='store', type='str', dest='master_bind_host', default="*", help="Interfaces (hostname, ip) that locust master should bind to. Only used when running with --master. Defaults to * (all available interfaces)." ) parser.add_option( '--master-bind-port', action='store', type='int', dest='master_bind_port', default=5557, help="Port that locust master should bind to. Only used when running with --master. Defaults to 5557. Note that Locust will also use this port + 1, so by default the master node will bind to 5557 and 5558." ) # if we should print stats in the console parser.add_option( '--no-web', action='store_true', dest='no_web', default=False, help="Disable the web interface, and instead start running the test immediately. Requires -c and -r to be specified." ) # Number of clients parser.add_option( '-c', '--clients', action='store', type='int', dest='num_clients', default=1, help="Number of concurrent clients. Only used together with --no-web" ) # Client hatch rate parser.add_option( '-r', '--hatch-rate', action='store', type='float', dest='hatch_rate', default=1, help="The rate per second in which clients are spawned. Only used together with --no-web" ) # Number of requests parser.add_option( '-n', '--num-request', action='store', type='int', dest='num_requests', default=None, help="Number of requests to perform. Only used together with --no-web" ) # log level parser.add_option( '--loglevel', '-L', action='store', type='str', dest='loglevel', default='INFO', help="Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL. Default is INFO.", ) # log file parser.add_option( '--logfile', action='store', type='str', dest='logfile', default=None, help="Path to log file. If not set, log will go to stdout/stderr", ) # if we should print stats in the console parser.add_option( '--print-stats', action='store_true', dest='print_stats', default=False, help="Print stats in the console" ) # only print summary stats parser.add_option( '--only-summary', action='store_true', dest='only_summary', default=False, help='Only print the summary stats' ) # List locust commands found in loaded locust files/source files parser.add_option( '-l', '--list', action='store_true', dest='list_commands', default=False, help="Show list of possible locust classes and exit" ) # Display ratio table of all tasks parser.add_option( '--show-task-ratio', action='store_true', dest='show_task_ratio', default=False, help="print table of the locust classes' task execution ratio" ) # Display ratio table of all tasks in JSON format parser.add_option( '--show-task-ratio-json', action='store_true', dest='show_task_ratio_json', default=False, help="print json data of the locust classes' task execution ratio" ) # Version number (optparse gives you --version but we have to do it # ourselves to get -V too. sigh) parser.add_option( '-V', '--version', action='store_true', dest='show_version', default=False, help="show program's version number and exit" ) # Finalize # Return three-tuple of parser + the output from parse_args (opt obj, args) opts, args = parser.parse_args() return parser, opts, args def _is_package(path): """ Is the given path a Python package? """ return ( os.path.isdir(path) and os.path.exists(os.path.join(path, '__init__.py')) ) def find_locustfile(locustfile): """ Attempt to locate a locustfile, either explicitly or by searching parent dirs. """ # Obtain env value names = [locustfile] # Create .py version if necessary if not names[0].endswith('.py'): names += [names[0] + '.py'] # Does the name contain path elements? if os.path.dirname(names[0]): # If so, expand home-directory markers and test for existence for name in names: expanded = os.path.expanduser(name) if os.path.exists(expanded): if name.endswith('.py') or _is_package(expanded): return os.path.abspath(expanded) else: # Otherwise, start in cwd and work downwards towards filesystem root path = '.' # Stop before falling off root of filesystem (should be platform # agnostic) while os.path.split(os.path.abspath(path))[1]: for name in names: joined = os.path.join(path, name) if os.path.exists(joined): if name.endswith('.py') or _is_package(joined): return os.path.abspath(joined) path = os.path.join('..', path) # Implicit 'return None' if nothing was found def is_locust(tup): """ Takes (name, object) tuple, returns True if it's a public Locust subclass. """ name, item = tup return bool( inspect.isclass(item) and issubclass(item, Locust) and hasattr(item, "task_set") and getattr(item, "task_set") and not name.startswith('_') ) def load_locustfile(path): """ Import given locustfile path and return (docstring, callables). Specifically, the locustfile's ``__doc__`` attribute (a string) and a dictionary of ``{'name': callable}`` containing all callables which pass the "is a Locust" test. """ # Get directory and locustfile name directory, locustfile = os.path.split(path) # If the directory isn't in the PYTHONPATH, add it so our import will work added_to_path = False index = None if directory not in sys.path: sys.path.insert(0, directory) added_to_path = True # If the directory IS in the PYTHONPATH, move it to the front temporarily, # otherwise other locustfiles -- like Locusts's own -- may scoop the intended # one. else: i = sys.path.index(directory) if i != 0: # Store index for later restoration index = i # Add to front, then remove from original position sys.path.insert(0, directory) del sys.path[i + 1] # Perform the import (trimming off the .py) imported = __import__(os.path.splitext(locustfile)[0]) # Remove directory from path if we added it ourselves (just to be neat) if added_to_path: del sys.path[0] # Put back in original index if we moved it if index is not None: sys.path.insert(index + 1, directory) del sys.path[0] # Return our two-tuple locusts = dict(filter(is_locust, vars(imported).items())) return imported.__doc__, locusts def main(): parser, options, arguments = parse_options() # setup logging setup_logging(options.loglevel, options.logfile) logger = logging.getLogger(__name__) if options.show_version: print "Locust %s" % (version,) sys.exit(0) locustfile = find_locustfile(options.locustfile) if not locustfile: logger.error("Could not find any locustfile! Ensure file ends in '.py' and see --help for available options.") sys.exit(1) docstring, locusts = load_locustfile(locustfile) if options.list_commands: console_logger.info("Available Locusts:") for name in locusts: console_logger.info(" " + name) sys.exit(0) if not locusts: logger.error("No Locust class found!") sys.exit(1) # make sure specified Locust exists if arguments: missing = set(arguments) - set(locusts.keys()) if missing: logger.error("Unknown Locust(s): %s\n" % (", ".join(missing))) sys.exit(1) else: names = set(arguments) & set(locusts.keys()) locust_classes = [locusts[n] for n in names] else: locust_classes = locusts.values() if options.show_task_ratio: console_logger.info("\n Task ratio per locust class") console_logger.info( "-" * 80) print_task_ratio(locust_classes) console_logger.info("\n Total task ratio") console_logger.info("-" * 80) print_task_ratio(locust_classes, total=True) sys.exit(0) if options.show_task_ratio_json: from json import dumps task_data = { "per_class": get_task_ratio_dict(locust_classes), "total": get_task_ratio_dict(locust_classes, total=True) } console_logger.info(dumps(task_data)) sys.exit(0) # if --master is set, make sure --no-web isn't set if options.master and options.no_web: logger.error("Locust can not run distributed with the web interface disabled (do not use --no-web and --master together)") sys.exit(0) if not options.no_web and not options.slave: # spawn web greenlet logger.info("Starting web monitor at %s:%s" % (options.web_host or "*", options.port)) main_greenlet = gevent.spawn(web.start, locust_classes, options) if not options.master and not options.slave: runners.locust_runner = LocalLocustRunner(locust_classes, options) # spawn client spawning/hatching greenlet if options.no_web: runners.locust_runner.start_hatching(wait=True) main_greenlet = runners.locust_runner.greenlet elif options.master: runners.locust_runner = MasterLocustRunner(locust_classes, options) elif options.slave: try: runners.locust_runner = SlaveLocustRunner(locust_classes, options) main_greenlet = runners.locust_runner.greenlet except socket.error, e: logger.error("Failed to connect to the Locust master: %s", e) sys.exit(-1) if not options.only_summary and (options.print_stats or (options.no_web and not options.slave)): # spawn stats printing greenlet gevent.spawn(stats_printer) def shutdown(code=0): """ Shut down locust by firing quitting event, printing stats and exiting """ logger.info("Shutting down (exit code %s), bye." % code) events.quitting.fire() print_stats(runners.locust_runner.request_stats) print_percentile_stats(runners.locust_runner.request_stats) print_error_report() sys.exit(code) # install SIGTERM handler def sig_term_handler(): logger.info("Got SIGTERM signal") shutdown(0) gevent.signal(signal.SIGTERM, sig_term_handler) try: logger.info("Starting Locust %s" % version) main_greenlet.join() code = 0 if len(runners.locust_runner.errors): code = 1 shutdown(code=code) except KeyboardInterrupt as e: shutdown(0) if __name__ == '__main__': main()
mit
sysadminmatmoz/ingadhoc
account_journal_payment_subtype/__openerp__.py
5
1647
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015, Eska Yazılım ve Danışmanlık A.Ş. # http://www.eskayazilim.com.tr # # 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/>. # ############################################################################## { 'name': 'Journal Payment Subtype', 'version': '1.0', 'category': 'Account', 'summary': 'Adds payment subtype field to cash and bank journals', 'description': """ Journal Payment Subtype ======================= Adds payment subtype field to cash and bank journals. This addon is used by addons that implement different payment subtypes such as check, credit card, promissory notes etc.. """, 'author': 'Eska Yazılım ve Danışmanlık A.Ş.', 'website': 'http://www.eskayazilim.com.tr', 'license': 'AGPL-3', 'depends': ['account_voucher'], 'data': ['views/account_journal_payment_subtype_view.xml'], 'installable': True, }
agpl-3.0
peterbraden/tensorflow
tensorflow/python/kernel_tests/sparse_tensor_dense_matmul_grad_test.py
13
2971
# Copyright 2016 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. # ============================================================================== """Tests for the gradient of `tf.sparse_tensor_dense_matmul()`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class SparseTensorDenseMatMulGradientTest(tf.test.TestCase): def _sparsify(self, x): x[x < 0.5] = 0 non_zero = np.where(x) x_indices = np.vstack(non_zero).astype(np.int64).T x_values = x[non_zero] x_shape = x.shape return tf.SparseTensor( indices=x_indices, values=x_values, shape=x_shape), len(x_values) def _randomTensor(self, size, np_dtype, adjoint=False, sparse=False): n, m = size x = np.random.randn(n, m).astype(np_dtype) if adjoint: x = x.transpose() if sparse: return self._sparsify(x) else: return tf.constant(x, dtype=np_dtype) def _testGradients(self, adjoint_a, adjoint_b, name, np_dtype, use_gpu=False): n, k, m = np.random.randint(1, 10, size=3) sp_t, nnz = self._randomTensor( [n, k], np_dtype, adjoint=adjoint_a, sparse=True) dense_t = self._randomTensor([k, m], np_dtype, adjoint=adjoint_b) matmul = tf.sparse_tensor_dense_matmul( sp_t, dense_t, adjoint_a=adjoint_a, adjoint_b=adjoint_b, name=name) with self.test_session(use_gpu=use_gpu): dense_t_shape = [m, k] if adjoint_b else [k, m] sp_t_val_shape = [nnz] err = tf.test.compute_gradient_error([dense_t, sp_t.values], [dense_t_shape, sp_t_val_shape], matmul, [n, m]) print("%s gradient err = %s" % (name, err)) self.assertLess(err, 1e-3) def _testGradientsType(self, np_dtype, use_gpu=False): for adjoint_a in [True, False]: for adjoint_b in [True, False]: name = "sparse_tensor_dense_matmul_%s_%s_%s" % (adjoint_a, adjoint_b, np_dtype.__name__) self._testGradients(adjoint_a, adjoint_b, name, np_dtype, use_gpu) def testGradients(self): np.random.seed(5) # Fix seed to avoid flakiness for use_gpu in [True, False]: self._testGradientsType(np.float32, use_gpu) self._testGradientsType(np.float64, use_gpu) if __name__ == "__main__": tf.test.main()
apache-2.0
rhertzog/django
tests/datetimes/tests.py
16
6327
from __future__ import unicode_literals import datetime from unittest import skipIf from django.test import TestCase, override_settings from django.utils import timezone from .models import Article, Category, Comment try: import pytz except ImportError: pytz = None class DateTimesTests(TestCase): def test_related_model_traverse(self): a1 = Article.objects.create( title="First one", pub_date=datetime.datetime(2005, 7, 28, 9, 0, 0), ) a2 = Article.objects.create( title="Another one", pub_date=datetime.datetime(2010, 7, 28, 10, 0, 0), ) a3 = Article.objects.create( title="Third one, in the first day", pub_date=datetime.datetime(2005, 7, 28, 17, 0, 0), ) a1.comments.create( text="Im the HULK!", pub_date=datetime.datetime(2005, 7, 28, 9, 30, 0), ) a1.comments.create( text="HULK SMASH!", pub_date=datetime.datetime(2005, 7, 29, 1, 30, 0), ) a2.comments.create( text="LMAO", pub_date=datetime.datetime(2010, 7, 28, 10, 10, 10), ) a3.comments.create( text="+1", pub_date=datetime.datetime(2005, 8, 29, 10, 10, 10), ) c = Category.objects.create(name="serious-news") c.articles.add(a1, a3) self.assertQuerysetEqual( Comment.objects.datetimes("article__pub_date", "year"), [ datetime.datetime(2005, 1, 1), datetime.datetime(2010, 1, 1), ], lambda d: d, ) self.assertQuerysetEqual( Comment.objects.datetimes("article__pub_date", "month"), [ datetime.datetime(2005, 7, 1), datetime.datetime(2010, 7, 1), ], lambda d: d ) self.assertQuerysetEqual( Comment.objects.datetimes("article__pub_date", "day"), [ datetime.datetime(2005, 7, 28), datetime.datetime(2010, 7, 28), ], lambda d: d ) self.assertQuerysetEqual( Article.objects.datetimes("comments__pub_date", "day"), [ datetime.datetime(2005, 7, 28), datetime.datetime(2005, 7, 29), datetime.datetime(2005, 8, 29), datetime.datetime(2010, 7, 28), ], lambda d: d ) self.assertQuerysetEqual( Article.objects.datetimes("comments__approval_date", "day"), [] ) self.assertQuerysetEqual( Category.objects.datetimes("articles__pub_date", "day"), [ datetime.datetime(2005, 7, 28), ], lambda d: d, ) @skipIf(pytz is None, "this test requires pytz") @override_settings(USE_TZ=True) def test_21432(self): now = timezone.localtime(timezone.now().replace(microsecond=0)) Article.objects.create(title="First one", pub_date=now) qs = Article.objects.datetimes('pub_date', 'second') self.assertEqual(qs[0], now) def test_datetimes_returns_available_dates_for_given_scope_and_given_field(self): pub_dates = [ datetime.datetime(2005, 7, 28, 12, 15), datetime.datetime(2005, 7, 29, 2, 15), datetime.datetime(2005, 7, 30, 5, 15), datetime.datetime(2005, 7, 31, 19, 15)] for i, pub_date in enumerate(pub_dates): Article(pub_date=pub_date, title='title #{}'.format(i)).save() self.assertQuerysetEqual( Article.objects.datetimes('pub_date', 'year'), ["datetime.datetime(2005, 1, 1, 0, 0)"]) self.assertQuerysetEqual( Article.objects.datetimes('pub_date', 'month'), ["datetime.datetime(2005, 7, 1, 0, 0)"]) self.assertQuerysetEqual( Article.objects.datetimes('pub_date', 'day'), ["datetime.datetime(2005, 7, 28, 0, 0)", "datetime.datetime(2005, 7, 29, 0, 0)", "datetime.datetime(2005, 7, 30, 0, 0)", "datetime.datetime(2005, 7, 31, 0, 0)"]) self.assertQuerysetEqual( Article.objects.datetimes('pub_date', 'day', order='ASC'), ["datetime.datetime(2005, 7, 28, 0, 0)", "datetime.datetime(2005, 7, 29, 0, 0)", "datetime.datetime(2005, 7, 30, 0, 0)", "datetime.datetime(2005, 7, 31, 0, 0)"]) self.assertQuerysetEqual( Article.objects.datetimes('pub_date', 'day', order='DESC'), ["datetime.datetime(2005, 7, 31, 0, 0)", "datetime.datetime(2005, 7, 30, 0, 0)", "datetime.datetime(2005, 7, 29, 0, 0)", "datetime.datetime(2005, 7, 28, 0, 0)"]) def test_datetimes_has_lazy_iterator(self): pub_dates = [ datetime.datetime(2005, 7, 28, 12, 15), datetime.datetime(2005, 7, 29, 2, 15), datetime.datetime(2005, 7, 30, 5, 15), datetime.datetime(2005, 7, 31, 19, 15)] for i, pub_date in enumerate(pub_dates): Article(pub_date=pub_date, title='title #{}'.format(i)).save() # Use iterator() with datetimes() to return a generator that lazily # requests each result one at a time, to save memory. dates = [] with self.assertNumQueries(0): article_datetimes_iterator = Article.objects.datetimes('pub_date', 'day', order='DESC').iterator() with self.assertNumQueries(1): for article in article_datetimes_iterator: dates.append(article) self.assertEqual(dates, [ datetime.datetime(2005, 7, 31, 0, 0), datetime.datetime(2005, 7, 30, 0, 0), datetime.datetime(2005, 7, 29, 0, 0), datetime.datetime(2005, 7, 28, 0, 0)]) def test_datetimes_disallows_date_fields(self): dt = datetime.datetime(2005, 7, 28, 12, 15) Article.objects.create(pub_date=dt, published_on=dt.date(), title="Don't put dates into datetime functions!") with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'published_on' to DateTimeField"): list(Article.objects.datetimes('published_on', 'second'))
bsd-3-clause
gisce/OCB
addons/l10n_be_hr_payroll/l10n_be_hr_payroll.py
51
3144
#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 OpenERP SA (<http://openerp.com>). All Rights Reserved # # 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 import openerp.addons.decimal_precision as dp class hr_contract_be(osv.osv): _inherit = 'hr.contract' _columns = { 'travel_reimbursement_amount': fields.float('Reimbursement of travel expenses', digits_compute=dp.get_precision('Payroll')), 'car_company_amount': fields.float('Company car employer', digits_compute=dp.get_precision('Payroll')), 'car_employee_deduction': fields.float('Company Car Deduction for Worker', digits_compute=dp.get_precision('Payroll')), 'misc_onss_deduction': fields.float('Miscellaneous exempt ONSS ', digits_compute=dp.get_precision('Payroll')), 'meal_voucher_amount': fields.float('Check Value Meal ', digits_compute=dp.get_precision('Payroll')), 'meal_voucher_employee_deduction': fields.float('Check Value Meal - by worker ', digits_compute=dp.get_precision('Payroll')), 'insurance_employee_deduction': fields.float('Insurance Group - by worker ', digits_compute=dp.get_precision('Payroll')), 'misc_advantage_amount': fields.float('Benefits of various nature ', digits_compute=dp.get_precision('Payroll')), 'additional_net_amount': fields.float('Net supplements', digits_compute=dp.get_precision('Payroll')), 'retained_net_amount': fields.float('Net retained ', digits_compute=dp.get_precision('Payroll')), } hr_contract_be() class hr_employee_be(osv.osv): _inherit = 'hr.employee' _columns = { 'spouse_fiscal_status': fields.selection([('without income','Without Income'),('with income','With Income')], 'Tax status for spouse'), 'disabled_spouse_bool': fields.boolean('Disabled Spouse', help="if recipient spouse is declared disabled by law"), 'disabled_children_bool': fields.boolean('Disabled Children', help="if recipient children is/are declared disabled by law"), 'resident_bool': fields.boolean('Nonresident', help="if recipient lives in a foreign country"), 'disabled_children_number': fields.integer('Number of disabled children'), } hr_employee_be() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
beauraines/fail2ban
fail2ban/client/filterreader.py
18
3049
# 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" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" import os import shlex from .configreader import DefinitionInitConfigReader from ..server.action import CommandAction from ..helpers import getLogger # Gets the instance of the logger. logSys = getLogger(__name__) class FilterReader(DefinitionInitConfigReader): _configOpts = [ ["string", "ignoreregex", None], ["string", "failregex", ""], ] def setFile(self, fileName): self.__file = fileName DefinitionInitConfigReader.setFile(self, os.path.join("filter.d", fileName)) def getFile(self): return self.__file def getCombined(self): combinedopts = dict(list(self._opts.items()) + list(self._initOpts.items())) if not len(combinedopts): return {} opts = CommandAction.substituteRecursiveTags(combinedopts) if not opts: raise ValueError('recursive tag definitions unable to be resolved') return opts def convert(self): stream = list() opts = self.getCombined() if not len(opts): return stream for opt, value in opts.iteritems(): if opt == "failregex": for regex in value.split('\n'): # Do not send a command if the rule is empty. if regex != '': stream.append(["set", self._jailName, "addfailregex", regex]) elif opt == "ignoreregex": for regex in value.split('\n'): # Do not send a command if the rule is empty. if regex != '': stream.append(["set", self._jailName, "addignoreregex", regex]) if self._initOpts: if 'maxlines' in self._initOpts: # We warn when multiline regex is used without maxlines > 1 # therefore keep sure we set this option first. stream.insert(0, ["set", self._jailName, "maxlines", self._initOpts["maxlines"]]) if 'datepattern' in self._initOpts: stream.append(["set", self._jailName, "datepattern", self._initOpts["datepattern"]]) # Do not send a command if the match is empty. if self._initOpts.get("journalmatch", '') != '': for match in self._initOpts["journalmatch"].split("\n"): stream.append( ["set", self._jailName, "addjournalmatch"] + shlex.split(match)) return stream
gpl-2.0
gtrensch/nest-simulator
pynest/nest/tests/test_helper_functions.py
21
1675
# -*- coding: utf-8 -*- # # test_helper_functions.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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. # # NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. import unittest import nest class TestHelperFunctions(unittest.TestCase): def test_get_verbosity(self): verbosity = nest.get_verbosity() self.assertTrue(isinstance(verbosity, int)) def test_set_verbosity(self): levels = [('M_ALL', 0), ('M_DEBUG', 5), ('M_STATUS', 7), ('M_INFO', 10), ('M_DEPRECATED', 18), ('M_WARNING', 20), ('M_ERROR', 30), ('M_FATAL', 40), ('M_QUIET', 100) ] for level, code in levels: nest.set_verbosity(level) verbosity = nest.get_verbosity() self.assertEqual(verbosity, code) def suite(): suite = unittest.makeSuite(TestHelperFunctions, 'test') return suite if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) runner.run(suite())
gpl-2.0
dalegregory/odoo
addons/account/report/account_partner_ledger.py
236
13439
# -*- 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 time from openerp.osv import osv from openerp.tools.translate import _ from openerp.report import report_sxw from common_report_header import common_report_header from openerp import SUPERUSER_ID class third_party_ledger(report_sxw.rml_parse, common_report_header): def __init__(self, cr, uid, name, context=None): super(third_party_ledger, self).__init__(cr, uid, name, context=context) self.init_bal_sum = 0.0 self.amount_currency = {} self.localcontext.update({ 'time': time, 'lines': self.lines, 'sum_debit_partner': self._sum_debit_partner, 'sum_credit_partner': self._sum_credit_partner, 'get_currency': self._get_currency, 'get_start_period': self.get_start_period, 'get_end_period': self.get_end_period, 'get_account': self._get_account, 'get_filter': self._get_filter, 'get_start_date': self._get_start_date, 'get_end_date': self._get_end_date, 'get_fiscalyear': self._get_fiscalyear, 'get_journal': self._get_journal, 'get_partners':self._get_partners, 'get_intial_balance':self._get_intial_balance, 'display_initial_balance':self._display_initial_balance, 'display_currency':self._display_currency, 'get_target_move': self._get_target_move, 'amount_currency': self.amount_currency, }) def _get_filter(self, data): if data['form']['filter'] == 'unreconciled': return _('Unreconciled Entries') return super(third_party_ledger, self)._get_filter(data) def set_context(self, objects, data, ids, report_type=None): obj_move = self.pool.get('account.move.line') obj_partner = self.pool.get('res.partner') self.query = obj_move._query_get(self.cr, self.uid, obj='l', context=data['form'].get('used_context', {})) ctx2 = data['form'].get('used_context',{}).copy() self.initial_balance = data['form'].get('initial_balance', True) if self.initial_balance: ctx2.update({'initial_bal': True}) self.init_query = obj_move._query_get(self.cr, self.uid, obj='l', context=ctx2) self.reconcil = True if data['form']['filter'] == 'unreconciled': self.reconcil = False self.result_selection = data['form'].get('result_selection', 'customer') if data['form'].get('amount_currency'): self.amount_currency['currency'] = True else: self.amount_currency.pop('currency', False) self.target_move = data['form'].get('target_move', 'all') PARTNER_REQUEST = '' move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] if self.result_selection == 'supplier': self.ACCOUNT_TYPE = ['payable'] elif self.result_selection == 'customer': self.ACCOUNT_TYPE = ['receivable'] else: self.ACCOUNT_TYPE = ['payable','receivable'] self.cr.execute( "SELECT a.id " \ "FROM account_account a " \ "LEFT JOIN account_account_type t " \ "ON (a.type=t.code) " \ 'WHERE a.type IN %s' \ "AND a.active", (tuple(self.ACCOUNT_TYPE), )) self.account_ids = [a for (a,) in self.cr.fetchall()] params = [tuple(move_state), tuple(self.account_ids)] #if we print from the partners, add a clause on active_ids if (data['model'] == 'res.partner') and ids: PARTNER_REQUEST = "AND l.partner_id IN %s" params += [tuple(ids)] reconcile = "" if self.reconcil else "AND l.reconcile_id IS NULL " self.cr.execute( "SELECT DISTINCT l.partner_id " \ "FROM account_move_line AS l, account_account AS account, " \ " account_move AS am " \ "WHERE l.partner_id IS NOT NULL " \ "AND l.account_id = account.id " \ "AND am.id = l.move_id " \ "AND am.state IN %s" "AND " + self.query +" " \ "AND l.account_id IN %s " \ " " + PARTNER_REQUEST + " " \ "AND account.active " + reconcile + " ", params) self.partner_ids = [res['partner_id'] for res in self.cr.dictfetchall()] objects = obj_partner.browse(self.cr, SUPERUSER_ID, self.partner_ids) objects = sorted(objects, key=lambda x: (x.ref, x.name)) return super(third_party_ledger, self).set_context(objects, data, self.partner_ids, report_type) def lines(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] full_account = [] if self.reconcil: RECONCILE_TAG = " " else: RECONCILE_TAG = "AND l.reconcile_id IS NULL" self.cr.execute( "SELECT l.id, l.date, j.code, acc.code as a_code, acc.name as a_name, l.ref, m.name as move_name, l.name, l.debit, l.credit, l.amount_currency,l.currency_id, c.symbol AS currency_code " \ "FROM account_move_line l " \ "LEFT JOIN account_journal j " \ "ON (l.journal_id = j.id) " \ "LEFT JOIN account_account acc " \ "ON (l.account_id = acc.id) " \ "LEFT JOIN res_currency c ON (l.currency_id=c.id)" \ "LEFT JOIN account_move m ON (m.id=l.move_id)" \ "WHERE l.partner_id = %s " \ "AND l.account_id IN %s AND " + self.query +" " \ "AND m.state IN %s " \ " " + RECONCILE_TAG + " "\ "ORDER BY l.date", (partner.id, tuple(self.account_ids), tuple(move_state))) res = self.cr.dictfetchall() sum = 0.0 if self.initial_balance: sum = self.init_bal_sum for r in res: sum += r['debit'] - r['credit'] r['progress'] = sum full_account.append(r) return full_account def _get_intial_balance(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] if self.reconcil: RECONCILE_TAG = " " else: RECONCILE_TAG = "AND l.reconcile_id IS NULL" self.cr.execute( "SELECT COALESCE(SUM(l.debit),0.0), COALESCE(SUM(l.credit),0.0), COALESCE(sum(debit-credit), 0.0) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE l.partner_id = %s " \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ " " + RECONCILE_TAG + " "\ "AND " + self.init_query + " ", (partner.id, tuple(move_state), tuple(self.account_ids))) res = self.cr.fetchall() self.init_bal_sum = res[0][2] return res def _sum_debit_partner(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] result_tmp = 0.0 result_init = 0.0 if self.reconcil: RECONCILE_TAG = " " else: RECONCILE_TAG = "AND reconcile_id IS NULL" if self.initial_balance: self.cr.execute( "SELECT sum(debit) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE l.partner_id = %s" \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ " " + RECONCILE_TAG + " " \ "AND " + self.init_query + " ", (partner.id, tuple(move_state), tuple(self.account_ids))) contemp = self.cr.fetchone() if contemp != None: result_init = contemp[0] or 0.0 else: result_init = result_tmp + 0.0 self.cr.execute( "SELECT sum(debit) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE l.partner_id = %s " \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ " " + RECONCILE_TAG + " " \ "AND " + self.query + " ", (partner.id, tuple(move_state), tuple(self.account_ids),)) contemp = self.cr.fetchone() if contemp != None: result_tmp = contemp[0] or 0.0 else: result_tmp = result_tmp + 0.0 return result_tmp + result_init def _sum_credit_partner(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] result_tmp = 0.0 result_init = 0.0 if self.reconcil: RECONCILE_TAG = " " else: RECONCILE_TAG = "AND reconcile_id IS NULL" if self.initial_balance: self.cr.execute( "SELECT sum(credit) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE l.partner_id = %s" \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ " " + RECONCILE_TAG + " " \ "AND " + self.init_query + " ", (partner.id, tuple(move_state), tuple(self.account_ids))) contemp = self.cr.fetchone() if contemp != None: result_init = contemp[0] or 0.0 else: result_init = result_tmp + 0.0 self.cr.execute( "SELECT sum(credit) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE l.partner_id=%s " \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ " " + RECONCILE_TAG + " " \ "AND " + self.query + " ", (partner.id, tuple(move_state), tuple(self.account_ids),)) contemp = self.cr.fetchone() if contemp != None: result_tmp = contemp[0] or 0.0 else: result_tmp = result_tmp + 0.0 return result_tmp + result_init def _get_partners(self): # TODO: deprecated, to remove in trunk if self.result_selection == 'customer': return _('Receivable Accounts') elif self.result_selection == 'supplier': return _('Payable Accounts') elif self.result_selection == 'customer_supplier': return _('Receivable and Payable Accounts') return '' def _sum_currency_amount_account(self, account, form): self._set_get_account_currency_code(account.id) self.cr.execute("SELECT sum(aml.amount_currency) FROM account_move_line as aml,res_currency as rc WHERE aml.currency_id = rc.id AND aml.account_id= %s ", (account.id,)) total = self.cr.fetchone() if self.account_currency: return_field = str(total[0]) + self.account_currency return return_field else: currency_total = self.tot_currency = 0.0 return currency_total def _display_initial_balance(self, data): if self.initial_balance: return True return False def _display_currency(self, data): if self.amount_currency: return True return False class report_partnerledger(osv.AbstractModel): _name = 'report.account.report_partnerledger' _inherit = 'report.abstract_report' _template = 'account.report_partnerledger' _wrapped_report_class = third_party_ledger class report_partnerledgerother(osv.AbstractModel): _name = 'report.account.report_partnerledgerother' _inherit = 'report.abstract_report' _template = 'account.report_partnerledgerother' _wrapped_report_class = third_party_ledger # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
eformat/vertx-web
vertx-web/src/test/sockjs-protocol/venv/lib/python2.7/site-packages/pip/_vendor/requests/compat.py
571
2556
# -*- coding: utf-8 -*- """ pythoncompat """ from .packages import chardet import sys # ------- # Pythons # ------- # Syntax sugar. _ver = sys.version_info #: Python 2.x? is_py2 = (_ver[0] == 2) #: Python 3.x? is_py3 = (_ver[0] == 3) #: Python 3.0.x is_py30 = (is_py3 and _ver[1] == 0) #: Python 3.1.x is_py31 = (is_py3 and _ver[1] == 1) #: Python 3.2.x is_py32 = (is_py3 and _ver[1] == 2) #: Python 3.3.x is_py33 = (is_py3 and _ver[1] == 3) #: Python 3.4.x is_py34 = (is_py3 and _ver[1] == 4) #: Python 2.7.x is_py27 = (is_py2 and _ver[1] == 7) #: Python 2.6.x is_py26 = (is_py2 and _ver[1] == 6) #: Python 2.5.x is_py25 = (is_py2 and _ver[1] == 5) #: Python 2.4.x is_py24 = (is_py2 and _ver[1] == 4) # I'm assuming this is not by choice. # --------- # Platforms # --------- # Syntax sugar. _ver = sys.version.lower() is_pypy = ('pypy' in _ver) is_jython = ('jython' in _ver) is_ironpython = ('iron' in _ver) # Assume CPython, if nothing else. is_cpython = not any((is_pypy, is_jython, is_ironpython)) # Windows-based system. is_windows = 'win32' in str(sys.platform).lower() # Standard Linux 2+ system. is_linux = ('linux' in str(sys.platform).lower()) is_osx = ('darwin' in str(sys.platform).lower()) is_hpux = ('hpux' in str(sys.platform).lower()) # Complete guess. is_solaris = ('solar==' in str(sys.platform).lower()) # Complete guess. try: import simplejson as json except ImportError: import json # --------- # Specifics # --------- if is_py2: from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag from urllib2 import parse_http_list import cookielib from Cookie import Morsel from StringIO import StringIO from .packages.urllib3.packages.ordered_dict import OrderedDict from httplib import IncompleteRead builtin_str = str bytes = str str = unicode basestring = basestring numeric_types = (int, long, float) elif is_py3: from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag from urllib.request import parse_http_list, getproxies, proxy_bypass from http import cookiejar as cookielib from http.cookies import Morsel from io import StringIO from collections import OrderedDict from http.client import IncompleteRead builtin_str = str str = str bytes = bytes basestring = (str, bytes) numeric_types = (int, float)
apache-2.0
avistous/QSTK
epydoc-3.0.1/epydoc/test/__init__.py
24
3198
# epydoc -- Regression testing # # Copyright (C) 2005 Edward Loper # Author: Edward Loper <edloper@loper.org> # URL: <http://epydoc.sf.net> # # $Id: __init__.py 1502 2007-02-14 08:38:44Z edloper $ """ Regression testing. """ __docformat__ = 'epytext en' import unittest, doctest, epydoc, os, os.path, re, sys def main(): try: doctest.register_optionflag except: print ("\n" "The regression test suite requires a more recent version of\n" "doctest (e.g., the version that ships with Python 2.4 or 2.5).\n" "Please place a new version of doctest on your path before \n" "running the test suite.\n") return PY24 = doctest.register_optionflag('PYTHON2.4') """Flag indicating that a doctest example requires Python 2.4+""" PY25 = doctest.register_optionflag('PYTHON2.5') """Flag indicating that a doctest example requires Python 2.5+""" class DocTestParser(doctest.DocTestParser): """ Custom doctest parser that adds support for two new flags +PYTHON2.4 and +PYTHON2.5. """ def parse(self, string, name='<string>'): pieces = doctest.DocTestParser.parse(self, string, name) for i, val in enumerate(pieces): if (isinstance(val, doctest.Example) and ((val.options.get(PY24, False) and sys.version[:2] < (2,4)) or (val.options.get(PY25, False) and sys.version[:2] < (2,5)))): pieces[i] = doctest.Example('1', '1') return pieces # Turn on debugging. epydoc.DEBUG = True # Options for doctest: options = doctest.ELLIPSIS doctest.set_unittest_reportflags(doctest.REPORT_UDIFF) # Use a custom parser parser = DocTestParser() # Find all test cases. tests = [] testdir = os.path.join(os.path.split(__file__)[0]) if testdir == '': testdir = '.' for filename in os.listdir(testdir): if (filename.endswith('.doctest') and check_requirements(os.path.join(testdir, filename))): tests.append(doctest.DocFileSuite(filename, optionflags=options, parser=parser)) # Run all test cases. unittest.TextTestRunner(verbosity=2).run(unittest.TestSuite(tests)) def check_requirements(filename): """ Search for strings of the form:: [Require: <module>] If any are found, then try importing the module named <module>. If the import fails, then return False. If all required modules are found, return True. (This includes the case where no requirements are listed.) """ s = open(filename).read() for m in re.finditer('(?mi)^[ ]*\:RequireModule:(.*)$', s): module = m.group(1).strip() try: __import__(module) except ImportError: print ('Skipping %r (required module %r not found)' % (os.path.split(filename)[-1], module)) return False return True if __name__=='__main__': main()
bsd-3-clause
bobeirasa/virtualenvs
pygeckozabbix/lib/python2.7/site-packages/setuptools/tests/test_packageindex.py
377
7625
"""Package Index Tests """ import sys import os import unittest import pkg_resources from setuptools.compat import urllib2, httplib, HTTPError, unicode, pathname2url import distutils.errors import setuptools.package_index from setuptools.tests.server import IndexServer class TestPackageIndex(unittest.TestCase): def test_bad_url_bad_port(self): index = setuptools.package_index.PackageIndex() url = 'http://127.0.0.1:0/nonesuch/test_package_index' try: v = index.open_url(url) except Exception: v = sys.exc_info()[1] self.assertTrue(url in str(v)) else: self.assertTrue(isinstance(v, HTTPError)) def test_bad_url_typo(self): # issue 16 # easy_install inquant.contentmirror.plone breaks because of a typo # in its home URL index = setuptools.package_index.PackageIndex( hosts=('www.example.com',) ) url = 'url:%20https://svn.plone.org/svn/collective/inquant.contentmirror.plone/trunk' try: v = index.open_url(url) except Exception: v = sys.exc_info()[1] self.assertTrue(url in str(v)) else: self.assertTrue(isinstance(v, HTTPError)) def test_bad_url_bad_status_line(self): index = setuptools.package_index.PackageIndex( hosts=('www.example.com',) ) def _urlopen(*args): raise httplib.BadStatusLine('line') index.opener = _urlopen url = 'http://example.com' try: v = index.open_url(url) except Exception: v = sys.exc_info()[1] self.assertTrue('line' in str(v)) else: raise AssertionError('Should have raise here!') def test_bad_url_double_scheme(self): """ A bad URL with a double scheme should raise a DistutilsError. """ index = setuptools.package_index.PackageIndex( hosts=('www.example.com',) ) # issue 20 url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk' try: index.open_url(url) except distutils.errors.DistutilsError: error = sys.exc_info()[1] msg = unicode(error) assert 'nonnumeric port' in msg or 'getaddrinfo failed' in msg or 'Name or service not known' in msg return raise RuntimeError("Did not raise") def test_bad_url_screwy_href(self): index = setuptools.package_index.PackageIndex( hosts=('www.example.com',) ) # issue #160 if sys.version_info[0] == 2 and sys.version_info[1] == 7: # this should not fail url = 'http://example.com' page = ('<a href="http://www.famfamfam.com](' 'http://www.famfamfam.com/">') index.process_index(url, page) def test_url_ok(self): index = setuptools.package_index.PackageIndex( hosts=('www.example.com',) ) url = 'file:///tmp/test_package_index' self.assertTrue(index.url_ok(url, True)) def test_links_priority(self): """ Download links from the pypi simple index should be used before external download links. https://bitbucket.org/tarek/distribute/issue/163 Usecase : - someone uploads a package on pypi, a md5 is generated - someone manually copies this link (with the md5 in the url) onto an external page accessible from the package page. - someone reuploads the package (with a different md5) - while easy_installing, an MD5 error occurs because the external link is used -> Setuptools should use the link from pypi, not the external one. """ if sys.platform.startswith('java'): # Skip this test on jython because binding to :0 fails return # start an index server server = IndexServer() server.start() index_url = server.base_url() + 'test_links_priority/simple/' # scan a test index pi = setuptools.package_index.PackageIndex(index_url) requirement = pkg_resources.Requirement.parse('foobar') pi.find_packages(requirement) server.stop() # the distribution has been found self.assertTrue('foobar' in pi) # we have only one link, because links are compared without md5 self.assertTrue(len(pi['foobar'])==1) # the link should be from the index self.assertTrue('correct_md5' in pi['foobar'][0].location) def test_parse_bdist_wininst(self): self.assertEqual(setuptools.package_index.parse_bdist_wininst( 'reportlab-2.5.win32-py2.4.exe'), ('reportlab-2.5', '2.4', 'win32')) self.assertEqual(setuptools.package_index.parse_bdist_wininst( 'reportlab-2.5.win32.exe'), ('reportlab-2.5', None, 'win32')) self.assertEqual(setuptools.package_index.parse_bdist_wininst( 'reportlab-2.5.win-amd64-py2.7.exe'), ('reportlab-2.5', '2.7', 'win-amd64')) self.assertEqual(setuptools.package_index.parse_bdist_wininst( 'reportlab-2.5.win-amd64.exe'), ('reportlab-2.5', None, 'win-amd64')) def test__vcs_split_rev_from_url(self): """ Test the basic usage of _vcs_split_rev_from_url """ vsrfu = setuptools.package_index.PackageIndex._vcs_split_rev_from_url url, rev = vsrfu('https://example.com/bar@2995') self.assertEqual(url, 'https://example.com/bar') self.assertEqual(rev, '2995') def test_local_index(self): """ local_open should be able to read an index from the file system. """ f = open('index.html', 'w') f.write('<div>content</div>') f.close() try: url = 'file:' + pathname2url(os.getcwd()) + '/' res = setuptools.package_index.local_open(url) finally: os.remove('index.html') assert 'content' in res.read() class TestContentCheckers(unittest.TestCase): def test_md5(self): checker = setuptools.package_index.HashChecker.from_url( 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478') checker.feed('You should probably not be using MD5'.encode('ascii')) self.assertEqual(checker.hash.hexdigest(), 'f12895fdffbd45007040d2e44df98478') self.assertTrue(checker.is_valid()) def test_other_fragment(self): "Content checks should succeed silently if no hash is present" checker = setuptools.package_index.HashChecker.from_url( 'http://foo/bar#something%20completely%20different') checker.feed('anything'.encode('ascii')) self.assertTrue(checker.is_valid()) def test_blank_md5(self): "Content checks should succeed if a hash is empty" checker = setuptools.package_index.HashChecker.from_url( 'http://foo/bar#md5=') checker.feed('anything'.encode('ascii')) self.assertTrue(checker.is_valid()) def test_get_hash_name_md5(self): checker = setuptools.package_index.HashChecker.from_url( 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478') self.assertEqual(checker.hash_name, 'md5') def test_report(self): checker = setuptools.package_index.HashChecker.from_url( 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478') rep = checker.report(lambda x: x, 'My message about %s') self.assertEqual(rep, 'My message about md5')
mit
metaml/nupic
src/nupic/research/spatial_pooler.py
6
76590
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013-2014, 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/ # ---------------------------------------------------------------------- import itertools import numpy from nupic.bindings.math import (SM32 as SparseMatrix, SM_01_32_32 as SparseBinaryMatrix, GetNTAReal, Random as NupicRandom) realDType = GetNTAReal() uintType = "uint32" VERSION = 2 class InvalidSPParamValueError(ValueError): """The user passed an invalid value for a SpatialPooler parameter """ pass class _SparseMatrixCorticalColumnAdapter(object): """ Many functions in SpatialPooler operate on a columnIndex but use an underlying storage implementation based on a Sparse Matrix in which cortical columns are represented as rows. This can be confusing to someone trying to follow the algorithm, confusing terminology between matrix math and cortical columns. This class is provided to abstract away some of the details of the underlying implementation, providing a cleaner API that isn't specific to sparse matrices. """ def __getitem__(self, columnIndex): """ Wraps getRow() such that instances may be indexed by columnIndex. """ return super(_SparseMatrixCorticalColumnAdapter, self).getRow(columnIndex) def replace(self, columnIndex, bitmap): """ Wraps replaceSparseRow() """ return super(_SparseMatrixCorticalColumnAdapter, self).replaceSparseRow( columnIndex, bitmap ) def update(self, columnIndex, vector): """ Wraps setRowFromDense() """ return super(_SparseMatrixCorticalColumnAdapter, self).setRowFromDense( columnIndex, vector ) class CorticalColumns(_SparseMatrixCorticalColumnAdapter, SparseMatrix): """ SparseMatrix variant of _SparseMatrixCorticalColumnAdapter. Use in cases where column connections are represented as float values, such as permanence values """ pass class BinaryCorticalColumns(_SparseMatrixCorticalColumnAdapter, SparseBinaryMatrix): """ SparseBinaryMatrix variant of _SparseMatrixCorticalColumnAdapter. Use in cases where column connections are represented as bitmaps. """ pass class SpatialPooler(object): """ This class implements the spatial pooler. It is in charge of handling the relationships between the columns of a region and the inputs bits. The primary public interface to this function is the "compute" method, which takes in an input vector and returns a list of activeColumns columns. Example Usage: > > sp = SpatialPooler(...) > for line in file: > inputVector = numpy.array(line) > sp.compute(inputVector) > ... """ def __init__(self, inputDimensions=(32, 32), columnDimensions=(64, 64), potentialRadius=16, potentialPct=0.5, globalInhibition=False, localAreaDensity=-1.0, numActiveColumnsPerInhArea=10.0, stimulusThreshold=0, synPermInactiveDec=0.008, synPermActiveInc=0.05, synPermConnected=0.10, minPctOverlapDutyCycle=0.001, minPctActiveDutyCycle=0.001, dutyCyclePeriod=1000, maxBoost=10.0, seed=-1, spVerbosity=0, wrapAround=True ): """ Parameters: ---------------------------- @param inputDimensions: A sequence representing the dimensions of the input vector. Format is (height, width, depth, ...), where each value represents the size of the dimension. For a topology of one dimension with 100 inputs use 100, or (100,). For a two dimensional topology of 10x5 use (10,5). @param columnDimensions: A sequence representing the dimensions of the columns in the region. Format is (height, width, depth, ...), where each value represents the size of the dimension. For a topology of one dimension with 2000 columns use 2000, or (2000,). For a three dimensional topology of 32x64x16 use (32, 64, 16). @param potentialRadius: This parameter determines the extent of the input that each column can potentially be connected to. This can be thought of as the input bits that are visible to each column, or a 'receptiveField' of the field of vision. A large enough value will result in 'global coverage', meaning that each column can potentially be connected to every input bit. This parameter defines a square (or hyper square) area: a column will have a max square potential pool with sides of length 2 * potentialRadius + 1. @param potentialPct: The percent of the inputs, within a column's potential radius, that a column can be connected to. If set to 1, the column will be connected to every input within its potential radius. This parameter is used to give each column a unique potential pool when a large potentialRadius causes overlap between the columns. At initialization time we choose ((2*potentialRadius + 1)^(# inputDimensions) * potentialPct) input bits to comprise the column's potential pool. @param globalInhibition: If true, then during inhibition phase the winning columns are selected as the most active columns from the region as a whole. Otherwise, the winning columns are selected with respect to their local neighborhoods. Using global inhibition boosts performance x60. @param localAreaDensity: The desired density of active columns within a local inhibition area (the size of which is set by the internally calculated inhibitionRadius, which is in turn determined from the average size of the connected potential pools of all columns). The inhibition logic will insure that at most N columns remain ON within a local inhibition area, where N = localAreaDensity * (total number of columns in inhibition area). @param numActiveColumnsPerInhArea: An alternate way to control the density of the active columns. If numActiveColumnsPerInhArea is specified then localAreaDensity must be less than 0, and vice versa. When using numActiveColumnsPerInhArea, the inhibition logic will insure that at most 'numActiveColumnsPerInhArea' columns remain ON within a local inhibition area (the size of which is set by the internally calculated inhibitionRadius, which is in turn determined from the average size of the connected receptive fields of all columns). When using this method, as columns learn and grow their effective receptive fields, the inhibitionRadius will grow, and hence the net density of the active columns will *decrease*. This is in contrast to the localAreaDensity method, which keeps the density of active columns the same regardless of the size of their receptive fields. @param stimulusThreshold: This is a number specifying the minimum number of synapses that must be on in order for a columns to turn ON. The purpose of this is to prevent noise input from activating columns. Specified as a percent of a fully grown synapse. @param synPermInactiveDec: The amount by which an inactive synapse is decremented in each round. Specified as a percent of a fully grown synapse. @param synPermActiveInc: The amount by which an active synapse is incremented in each round. Specified as a percent of a fully grown synapse. @param synPermConnected: The default connected threshold. Any synapse whose permanence value is above the connected threshold is a "connected synapse", meaning it can contribute to the cell's firing. @param minPctOverlapDutyCycle: A number between 0 and 1.0, used to set a floor on how often a column should have at least stimulusThreshold active inputs. Periodically, each column looks at the overlap duty cycle of all other columns within its inhibition radius and sets its own internal minimal acceptable duty cycle to: minPctDutyCycleBeforeInh * max(other columns' duty cycles). On each iteration, any column whose overlap duty cycle falls below this computed value will get all of its permanence values boosted up by synPermActiveInc. Raising all permanences in response to a sub-par duty cycle before inhibition allows a cell to search for new inputs when either its previously learned inputs are no longer ever active, or when the vast majority of them have been "hijacked" by other columns. @param minPctActiveDutyCycle: A number between 0 and 1.0, used to set a floor on how often a column should be activate. Periodically, each column looks at the activity duty cycle of all other columns within its inhibition radius and sets its own internal minimal acceptable duty cycle to: minPctDutyCycleAfterInh * max(other columns' duty cycles). On each iteration, any column whose duty cycle after inhibition falls below this computed value will get its internal boost factor increased. @param dutyCyclePeriod: The period used to calculate duty cycles. Higher values make it take longer to respond to changes in boost or synPerConnectedCell. Shorter values make it more unstable and likely to oscillate. @param maxBoost: The maximum overlap boost factor. Each column's overlap gets multiplied by a boost factor before it gets considered for inhibition. The actual boost factor for a column is number between 1.0 and maxBoost. A boost factor of 1.0 is used if the duty cycle is >= minOverlapDutyCycle, maxBoost is used if the duty cycle is 0, and any duty cycle in between is linearly extrapolated from these 2 endpoints. @param seed: Seed for our own pseudo-random number generator. @param spVerbosity: spVerbosity level: 0, 1, 2, or 3 @param wrapAround: Determines if inputs at the beginning and end of an input dimension should be considered neighbors when mapping columns to inputs. """ if (numActiveColumnsPerInhArea == 0 and (localAreaDensity == 0 or localAreaDensity > 0.5)): raise InvalidSPParamValueError("Inhibition parameters are invalid") columnDimensions = numpy.array(columnDimensions, ndmin=1) numColumns = columnDimensions.prod() if not isinstance(numColumns, (int, long)) or numColumns <= 0: raise InvalidSPParamValueError("Invalid number of columns ({})" .format(repr(numColumns))) inputDimensions = numpy.array(inputDimensions, ndmin=1) numInputs = inputDimensions.prod() if not isinstance(numInputs, (int, long)) or numInputs <= 0: raise InvalidSPParamValueError("Invalid number of inputs ({}" .format(repr(numInputs))) if inputDimensions.size != columnDimensions.size: raise InvalidSPParamValueError( "Input dimensions must match column dimensions") self._seed(seed) self._numInputs = int(numInputs) self._numColumns = int(numColumns) self._columnDimensions = columnDimensions self._inputDimensions = inputDimensions self._potentialRadius = int(min(potentialRadius, numInputs)) self._potentialPct = potentialPct self._globalInhibition = globalInhibition self._numActiveColumnsPerInhArea = int(numActiveColumnsPerInhArea) self._localAreaDensity = localAreaDensity self._stimulusThreshold = stimulusThreshold self._synPermInactiveDec = synPermInactiveDec self._synPermActiveInc = synPermActiveInc self._synPermBelowStimulusInc = synPermConnected / 10.0 self._synPermConnected = synPermConnected self._minPctOverlapDutyCycles = minPctOverlapDutyCycle self._minPctActiveDutyCycles = minPctActiveDutyCycle self._dutyCyclePeriod = dutyCyclePeriod self._maxBoost = maxBoost self._spVerbosity = spVerbosity self._wrapAround = wrapAround self._synPermMin = 0.0 self._synPermMax = 1.0 self._synPermTrimThreshold = synPermActiveInc / 2.0 if self._synPermTrimThreshold >= self._synPermConnected: raise InvalidSPParamValueError( "synPermTrimThreshold ({}) must be less than synPermConnected ({})" .format(repr(self._synPermTrimThreshold), repr(self._synPermConnected))) self._updatePeriod = 50 initConnectedPct = 0.5 self._version = VERSION self._iterationNum = 0 self._iterationLearnNum = 0 # Store the set of all inputs within each columns potential pool as a # single adjacency matrix such that matrix rows map to cortical columns, # and matrix columns map to input buts. If potentialPools[i][j] == 1, # then input bit 'j' is in column 'i's potential pool. A column can only be # connected to inputs in its potential pool. Here, BinaryCorticalColumns # is used to provide cortical column-centric semantics for what is # otherwise a sparse binary matrix implementation. Sparse binary matrix is # used as an optimization since a column will only be connected to a small # fraction of input bits. self._potentialPools = BinaryCorticalColumns(numInputs) self._potentialPools.resize(numColumns, numInputs) # Initialize the permanences for each column. Similar to the # 'self._potentialPools', the permanences are stored in a matrix whose rows # represent the cortical columns, and whose columns represent the input # bits. If self._permanences[i][j] = 0.2, then the synapse connecting # cortical column 'i' to input bit 'j' has a permanence of 0.2. Here, # CorticalColumns is used to provide cortical column-centric semantics for # what is otherwise a sparse matrix implementation. Sparse matrix is used # as an optimization to improve computation time of alforithms that # require iterating over the data structure. This permanence matrix is # only allowed to have non-zero elements where the potential pool is # non-zero. self._permanences = CorticalColumns(numColumns, numInputs) # Initialize a tiny random tie breaker. This is used to determine winning # columns where the overlaps are identical. self._tieBreaker = 0.01*numpy.array([self._random.getReal64() for i in xrange(self._numColumns)]) # 'self._connectedSynapses' is a similar matrix to 'self._permanences' # (rows represent cortical columns, columns represent input bits) whose # entries represent whether the cortical column is connected to the input # bit, i.e. its permanence value is greater than 'synPermConnected'. While # this information is readily available from the 'self._permanence' matrix, # it is stored separately for efficiency purposes. self._connectedSynapses = BinaryCorticalColumns(numInputs) self._connectedSynapses.resize(numColumns, numInputs) # Stores the number of connected synapses for each column. This is simply # a sum of each row of 'self._connectedSynapses'. again, while this # information is readily available from 'self._connectedSynapses', it is # stored separately for efficiency purposes. self._connectedCounts = numpy.zeros(numColumns, dtype=realDType) # Initialize the set of permanence values for each column. Ensure that # each column is connected to enough input bits to allow it to be # activated. for columnIndex in xrange(numColumns): potential = self._mapPotential(columnIndex, wrapAround=self._wrapAround) self._potentialPools.replace(columnIndex, potential.nonzero()[0]) perm = self._initPermanence(potential, initConnectedPct) self._updatePermanencesForColumn(perm, columnIndex, raisePerm=True) self._overlapDutyCycles = numpy.zeros(numColumns, dtype=realDType) self._activeDutyCycles = numpy.zeros(numColumns, dtype=realDType) self._minOverlapDutyCycles = numpy.zeros(numColumns, dtype=realDType) self._minActiveDutyCycles = numpy.zeros(numColumns, dtype=realDType) self._boostFactors = numpy.ones(numColumns, dtype=realDType) # The inhibition radius determines the size of a column's local # neighborhood. A cortical column must overcome the overlap score of # columns in its neighborhood in order to become active. This radius is # updated every learning round. It grows and shrinks with the average # number of connected synapses per column. self._inhibitionRadius = 0 self._updateInhibitionRadius() if self._spVerbosity > 0: self.printParameters() def getColumnDimensions(self): """Returns the dimensions of the columns in the region""" return self._columnDimensions def getInputDimensions(self): """Returns the dimensions of the input vector""" return self._inputDimensions def getNumColumns(self): """Returns the total number of columns""" return self._numColumns def getNumInputs(self): """Returns the total number of inputs""" return self._numInputs def getPotentialRadius(self): """Returns the potential radius""" return self._potentialRadius def setPotentialRadius(self, potentialRadius): """Sets the potential radius""" self._potentialRadius = potentialRadius def getPotentialPct(self): """Returns the potential percent""" return self._potentialPct def setPotentialPct(self, potentialPct): """Sets the potential percent""" self._potentialPct = potentialPct def getGlobalInhibition(self): """Returns whether global inhibition is enabled""" return self._globalInhibition def setGlobalInhibition(self, globalInhibition): """Sets global inhibition""" self._globalInhibition = globalInhibition def getNumActiveColumnsPerInhArea(self): """Returns the number of active columns per inhibition area. Returns a value less than 0 if parameter is unused""" return self._numActiveColumnsPerInhArea def setNumActiveColumnsPerInhArea(self, numActiveColumnsPerInhArea): """Sets the number of active columns per inhibition area. Invalidates the 'localAreaDensity' parameter""" assert(numActiveColumnsPerInhArea > 0) self._numActiveColumnsPerInhArea = numActiveColumnsPerInhArea self._localAreaDensity = 0 def getLocalAreaDensity(self): """Returns the local area density. Returns a value less than 0 if parameter is unused""" return self._localAreaDensity def setLocalAreaDensity(self, localAreaDensity): """Sets the local area density. Invalidates the 'numActiveColumnsPerInhArea' parameter""" assert(localAreaDensity > 0 and localAreaDensity <= 1) self._localAreaDensity = localAreaDensity self._numActiveColumnsPerInhArea = 0 def getStimulusThreshold(self): """Returns the stimulus threshold""" return self._stimulusThreshold def setStimulusThreshold(self, stimulusThreshold): """Sets the stimulus threshold""" self._stimulusThreshold = stimulusThreshold def getInhibitionRadius(self): """Returns the inhibition radius""" return self._inhibitionRadius def setInhibitionRadius(self, inhibitionRadius): """Sets the inhibition radius""" self._inhibitionRadius = inhibitionRadius def getDutyCyclePeriod(self): """Returns the duty cycle period""" return self._dutyCyclePeriod def setDutyCyclePeriod(self, dutyCyclePeriod): """Sets the duty cycle period""" self._dutyCyclePeriod = dutyCyclePeriod def getMaxBoost(self): """Returns the maximum boost value""" return self._maxBoost def setMaxBoost(self, maxBoost): """Sets the maximum boost value""" self._maxBoost = maxBoost def getIterationNum(self): """Returns the iteration number""" return self._iterationNum def setIterationNum(self, iterationNum): """Sets the iteration number""" self._iterationNum = iterationNum def getIterationLearnNum(self): """Returns the learning iteration number""" return self._iterationLearnNum def setIterationLearnNum(self, iterationLearnNum): """Sets the learning iteration number""" self._iterationLearnNum = iterationLearnNum def getSpVerbosity(self): """Returns the verbosity level""" return self._spVerbosity def setSpVerbosity(self, spVerbosity): """Sets the verbosity level""" self._spVerbosity = spVerbosity def getUpdatePeriod(self): """Returns the update period""" return self._updatePeriod def setUpdatePeriod(self, updatePeriod): """Sets the update period""" self._updatePeriod = updatePeriod def getSynPermTrimThreshold(self): """Returns the permanence trim threshold""" return self._synPermTrimThreshold def setSynPermTrimThreshold(self, synPermTrimThreshold): """Sets the permanence trim threshold""" self._synPermTrimThreshold = synPermTrimThreshold def getSynPermActiveInc(self): """Returns the permanence increment amount for active synapses inputs""" return self._synPermActiveInc def setSynPermActiveInc(self, synPermActiveInc): """Sets the permanence increment amount for active synapses""" self._synPermActiveInc = synPermActiveInc def getSynPermInactiveDec(self): """Returns the permanence decrement amount for inactive synapses""" return self._synPermInactiveDec def setSynPermInactiveDec(self, synPermInactiveDec): """Sets the permanence decrement amount for inactive synapses""" self._synPermInactiveDec = synPermInactiveDec def getSynPermBelowStimulusInc(self): """Returns the permanence increment amount for columns that have not been recently active """ return self._synPermBelowStimulusInc def setSynPermBelowStimulusInc(self, synPermBelowStimulusInc): """Sets the permanence increment amount for columns that have not been recently active """ self._synPermBelowStimulusInc = synPermBelowStimulusInc def getSynPermConnected(self): """Returns the permanence amount that qualifies a synapse as being connected""" return self._synPermConnected def setSynPermConnected(self, synPermConnected): """Sets the permanence amount that qualifies a synapse as being connected""" self._synPermConnected = synPermConnected def getMinPctOverlapDutyCycles(self): """Returns the minimum tolerated overlaps, given as percent of neighbors overlap score""" return self._minPctOverlapDutyCycles def setMinPctOverlapDutyCycles(self, minPctOverlapDutyCycles): """Sets the minimum tolerated activity duty cycle, given as percent of neighbors' activity duty cycle""" self._minPctOverlapDutyCycles = minPctOverlapDutyCycles def getMinPctActiveDutyCycles(self): """Returns the minimum tolerated activity duty cycle, given as percent of neighbors' activity duty cycle""" return self._minPctActiveDutyCycles def setMinPctActiveDutyCycles(self, minPctActiveDutyCycles): """Sets the minimum tolerated activity duty, given as percent of neighbors' activity duty cycle""" self._minPctActiveDutyCycles = minPctActiveDutyCycles def getBoostFactors(self, boostFactors): """Returns the boost factors for all columns. 'boostFactors' size must match the number of columns""" boostFactors[:] = self._boostFactors[:] def setBoostFactors(self, boostFactors): """Sets the boost factors for all columns. 'boostFactors' size must match the number of columns""" self._boostFactors[:] = boostFactors[:] def getOverlapDutyCycles(self, overlapDutyCycles): """Returns the overlap duty cycles for all columns. 'overlapDutyCycles' size must match the number of columns""" overlapDutyCycles[:] = self._overlapDutyCycles[:] def setOverlapDutyCycles(self, overlapDutyCycles): """Sets the overlap duty cycles for all columns. 'overlapDutyCycles' size must match the number of columns""" self._overlapDutyCycles[:] = overlapDutyCycles def getActiveDutyCycles(self, activeDutyCycles): """Returns the activity duty cycles for all columns. 'activeDutyCycles' size must match the number of columns""" activeDutyCycles[:] = self._activeDutyCycles[:] def setActiveDutyCycles(self, activeDutyCycles): """Sets the activity duty cycles for all columns. 'activeDutyCycles' size must match the number of columns""" self._activeDutyCycles[:] = activeDutyCycles def getMinOverlapDutyCycles(self, minOverlapDutyCycles): """Returns the minimum overlap duty cycles for all columns. '_minOverlapDutyCycles' size must match the number of columns""" minOverlapDutyCycles[:] = self._minOverlapDutyCycles[:] def setMinOverlapDutyCycles(self, minOverlapDutyCycles): """Sets the minimum overlap duty cycles for all columns. '_minOverlapDutyCycles' size must match the number of columns""" self._minOverlapDutyCycles[:] = minOverlapDutyCycles[:] def getMinActiveDutyCycles(self, minActiveDutyCycles): """Returns the minimum activity duty cycles for all columns. '_minActiveDutyCycles' size must match the number of columns""" minActiveDutyCycles[:] = self._minActiveDutyCycles[:] def setMinActiveDutyCycles(self, minActiveDutyCycles): """Sets the minimum activity duty cycles for all columns. '_minActiveDutyCycles' size must match the number of columns""" self._minActiveDutyCycles = minActiveDutyCycles def getPotential(self, columnIndex, potential): """Returns the potential mapping for a given column. 'potential' size must match the number of inputs""" assert(columnIndex < self._numColumns) potential[:] = self._potentialPools[columnIndex] def setPotential(self, columnIndex, potential): """Sets the potential mapping for a given column. 'potential' size must match the number of inputs, and must be greater than _stimulusThreshold """ assert(column < self._numColumns) potentialSparse = numpy.where(potential > 0)[0] if len(potentialSparse) < self._stimulusThreshold: raise Exception("This is likely due to a " + "value of stimulusThreshold that is too large relative " + "to the input size.") self._potentialPools.replace(columnIndex, potentialSparse) def getPermanence(self, columnIndex, permanence): """Returns the permanence values for a given column. 'permanence' size must match the number of inputs""" assert(columnIndex < self._numColumns) permanence[:] = self._permanences[columnIndex] def setPermanence(self, columnIndex, permanence): """Sets the permanence values for a given column. 'permanence' size must match the number of inputs""" assert(columnIndex < self._numColumns) self._updatePermanencesForColumn(permanence, columnIndex, raisePerm=False) def getConnectedSynapses(self, columnIndex, connectedSynapses): """Returns the connected synapses for a given column. 'connectedSynapses' size must match the number of inputs""" assert(columnIndex < self._numColumns) connectedSynapses[:] = self._connectedSynapses[columnIndex] def getConnectedCounts(self, connectedCounts): """Returns the number of connected synapses for all columns. 'connectedCounts' size must match the number of columns""" connectedCounts[:] = self._connectedCounts[:] def compute(self, inputVector, learn, activeArray): """ This is the primary public method of the SpatialPooler class. This function takes a input vector and outputs the indices of the active columns. If 'learn' is set to True, this method also updates the permanences of the columns. @param inputVector: A numpy array of 0's and 1's that comprises the input to the spatial pooler. The array will be treated as a one dimensional array, therefore the dimensions of the array do not have to match the exact dimensions specified in the class constructor. In fact, even a list would suffice. The number of input bits in the vector must, however, match the number of bits specified by the call to the constructor. Therefore there must be a '0' or '1' in the array for every input bit. @param learn: A boolean value indicating whether learning should be performed. Learning entails updating the permanence values of the synapses, and hence modifying the 'state' of the model. Setting learning to 'off' freezes the SP and has many uses. For example, you might want to feed in various inputs and examine the resulting SDR's. @param activeArray: An array whose size is equal to the number of columns. Before the function returns this array will be populated with 1's at the indices of the active columns, and 0's everywhere else. """ if not isinstance(inputVector, numpy.ndarray): raise TypeError("Input vector must be a numpy array, not %s" % str(type(inputVector))) if inputVector.size != self._numInputs: raise ValueError( "Input vector dimensions don't match. Expecting %s but got %s" % ( inputVector.size, self._numInputs)) self._updateBookeepingVars(learn) inputVector = numpy.array(inputVector, dtype=realDType) inputVector.reshape(-1) overlaps = self._calculateOverlap(inputVector) # Apply boosting when learning is on if learn: boostedOverlaps = self._boostFactors * overlaps else: boostedOverlaps = overlaps # Apply inhibition to determine the winning columns activeColumns = self._inhibitColumns(boostedOverlaps) if learn: self._adaptSynapses(inputVector, activeColumns) self._updateDutyCycles(overlaps, activeColumns) self._bumpUpWeakColumns() self._updateBoostFactors() if self._isUpdateRound(): self._updateInhibitionRadius() self._updateMinDutyCycles() activeArray.fill(0) if activeColumns.size > 0: activeArray[activeColumns] = 1 def stripUnlearnedColumns(self, activeArray): """Removes the set of columns who have never been active from the set of active columns selected in the inhibition round. Such columns cannot represent learned pattern and are therefore meaningless if only inference is required. This should not be done when using a random, unlearned SP since you would end up with no active columns. @param activeArray: An array whose size is equal to the number of columns. Any columns marked as active with an activeDutyCycle of 0 have never been activated before and therefore are not active due to learning. Any of these (unlearned) columns will be disabled (set to 0). """ neverLearned = numpy.where(self._activeDutyCycles == 0)[0] activeArray[neverLearned] = 0 def _updateMinDutyCycles(self): """ Updates the minimum duty cycles defining normal activity for a column. A column with activity duty cycle below this minimum threshold is boosted. """ if self._globalInhibition or self._inhibitionRadius > self._numInputs: self._updateMinDutyCyclesGlobal() else: self._updateMinDutyCyclesLocal() def _updateMinDutyCyclesGlobal(self): """ Updates the minimum duty cycles in a global fashion. Sets the minimum duty cycles for the overlap and activation of all columns to be a percent of the maximum in the region, specified by minPctOverlapDutyCycle and minPctActiveDutyCycle respectively. Functionality it is equivalent to _updateMinDutyCyclesLocal, but this function exploits the globality of the computation to perform it in a straightforward, and more efficient manner. """ self._minOverlapDutyCycles.fill( self._minPctOverlapDutyCycles * self._overlapDutyCycles.max() ) self._minActiveDutyCycles.fill( self._minPctActiveDutyCycles * self._activeDutyCycles.max() ) def _updateMinDutyCyclesLocal(self): """ Updates the minimum duty cycles. The minimum duty cycles are determined locally. Each column's minimum duty cycles are set to be a percent of the maximum duty cycles in the column's neighborhood. Unlike _updateMinDutyCyclesGlobal, here the values can be quite different for different columns. """ for i in xrange(self._numColumns): maskNeighbors = numpy.append(i, self._getNeighborsND(i, self._columnDimensions, self._inhibitionRadius)) self._minOverlapDutyCycles[i] = ( self._overlapDutyCycles[maskNeighbors].max() * self._minPctOverlapDutyCycles ) self._minActiveDutyCycles[i] = ( self._activeDutyCycles[maskNeighbors].max() * self._minPctActiveDutyCycles ) def _updateDutyCycles(self, overlaps, activeColumns): """ Updates the duty cycles for each column. The OVERLAP duty cycle is a moving average of the number of inputs which overlapped with the each column. The ACTIVITY duty cycles is a moving average of the frequency of activation for each column. Parameters: ---------------------------- @param overlaps: An array containing the overlap score for each column. The overlap score for a column is defined as the number of synapses in a "connected state" (connected synapses) that are connected to input bits which are turned on. @param activeColumns: An array containing the indices of the active columns, the sparse set of columns which survived inhibition """ overlapArray = numpy.zeros(self._numColumns, dtype=realDType) activeArray = numpy.zeros(self._numColumns, dtype=realDType) overlapArray[overlaps > 0] = 1 if activeColumns.size > 0: activeArray[activeColumns] = 1 period = self._dutyCyclePeriod if (period > self._iterationNum): period = self._iterationNum self._overlapDutyCycles = self._updateDutyCyclesHelper( self._overlapDutyCycles, overlapArray, period ) self._activeDutyCycles = self._updateDutyCyclesHelper( self._activeDutyCycles, activeArray, period ) def _updateInhibitionRadius(self): """ Update the inhibition radius. The inhibition radius is a measure of the square (or hypersquare) of columns that each a column is "connected to" on average. Since columns are are not connected to each other directly, we determine this quantity by first figuring out how many *inputs* a column is connected to, and then multiplying it by the total number of columns that exist for each input. For multiple dimension the aforementioned calculations are averaged over all dimensions of inputs and columns. This value is meaningless if global inhibition is enabled. """ if self._globalInhibition: self._inhibitionRadius = self._columnDimensions.max() return avgConnectedSpan = numpy.average( [self._avgConnectedSpanForColumnND(i) for i in xrange(self._numColumns)] ) columnsPerInput = self._avgColumnsPerInput() diameter = avgConnectedSpan * columnsPerInput radius = (diameter - 1) / 2.0 radius = max(1.0, radius) self._inhibitionRadius = int(round(radius)) def _avgColumnsPerInput(self): """ The average number of columns per input, taking into account the topology of the inputs and columns. This value is used to calculate the inhibition radius. This function supports an arbitrary number of dimensions. If the number of column dimensions does not match the number of input dimensions, we treat the missing, or phantom dimensions as 'ones'. """ #TODO: extend to support different number of dimensions for inputs and # columns numDim = max(self._columnDimensions.size, self._inputDimensions.size) colDim = numpy.ones(numDim) colDim[:self._columnDimensions.size] = self._columnDimensions inputDim = numpy.ones(numDim) inputDim[:self._inputDimensions.size] = self._inputDimensions columnsPerInput = colDim.astype(realDType) / inputDim return numpy.average(columnsPerInput) def _avgConnectedSpanForColumn1D(self, columnIndex): """ The range of connected synapses for column. This is used to calculate the inhibition radius. This variation of the function only supports a 1 dimensional column topology. Parameters: ---------------------------- @param columnIndex: The index identifying a column in the permanence, potential and connectivity matrices """ assert(self._inputDimensions.size == 1) connected = self._connectedSynapses[columnIndex].nonzero()[0] if connected.size == 0: return 0 else: return max(connected) - min(connected) + 1 def _avgConnectedSpanForColumn2D(self, columnIndex): """ The range of connectedSynapses per column, averaged for each dimension. This value is used to calculate the inhibition radius. This variation of the function only supports a 2 dimensional column topology. Parameters: ---------------------------- @param columnIndex: The index identifying a column in the permanence, potential and connectivity matrices """ assert(self._inputDimensions.size == 2) connected = self._connectedSynapses[columnIndex] (rows, cols) = connected.reshape(self._inputDimensions).nonzero() if rows.size == 0 and cols.size == 0: return 0 rowSpan = rows.max() - rows.min() + 1 colSpan = cols.max() - cols.min() + 1 return numpy.average([rowSpan, colSpan]) def _avgConnectedSpanForColumnND(self, columnIndex): """ The range of connectedSynapses per column, averaged for each dimension. This value is used to calculate the inhibition radius. This variation of the function supports arbitrary column dimensions. Parameters: ---------------------------- @param index: The index identifying a column in the permanence, potential and connectivity matrices. """ dimensions = self._inputDimensions connected = self._connectedSynapses[columnIndex].nonzero()[0] if connected.size == 0: return 0 maxCoord = numpy.empty(self._inputDimensions.size) minCoord = numpy.empty(self._inputDimensions.size) maxCoord.fill(-1) minCoord.fill(max(self._inputDimensions)) for i in connected: maxCoord = numpy.maximum(maxCoord, numpy.unravel_index(i, dimensions)) minCoord = numpy.minimum(minCoord, numpy.unravel_index(i, dimensions)) return numpy.average(maxCoord - minCoord + 1) def _adaptSynapses(self, inputVector, activeColumns): """ The primary method in charge of learning. Adapts the permanence values of the synapses based on the input vector, and the chosen columns after inhibition round. Permanence values are increased for synapses connected to input bits that are turned on, and decreased for synapses connected to inputs bits that are turned off. Parameters: ---------------------------- @param inputVector: A numpy array of 0's and 1's that comprises the input to the spatial pooler. There exists an entry in the array for every input bit. @param activeColumns: An array containing the indices of the columns that survived inhibition. """ inputIndices = numpy.where(inputVector > 0)[0] permChanges = numpy.zeros(self._numInputs) permChanges.fill(-1 * self._synPermInactiveDec) permChanges[inputIndices] = self._synPermActiveInc for columnIndex in activeColumns: perm = self._permanences[columnIndex] maskPotential = numpy.where(self._potentialPools[columnIndex] > 0)[0] perm[maskPotential] += permChanges[maskPotential] self._updatePermanencesForColumn(perm, columnIndex, raisePerm=True) def _bumpUpWeakColumns(self): """ This method increases the permanence values of synapses of columns whose activity level has been too low. Such columns are identified by having an overlap duty cycle that drops too much below those of their peers. The permanence values for such columns are increased. """ weakColumns = numpy.where(self._overlapDutyCycles < self._minOverlapDutyCycles)[0] for columnIndex in weakColumns: perm = self._permanences[columnIndex].astype(realDType) maskPotential = numpy.where(self._potentialPools[columnIndex] > 0)[0] perm[maskPotential] += self._synPermBelowStimulusInc self._updatePermanencesForColumn(perm, columnIndex, raisePerm=False) def _raisePermanenceToThreshold(self, perm, mask): """ This method ensures that each column has enough connections to input bits to allow it to become active. Since a column must have at least 'self._stimulusThreshold' overlaps in order to be considered during the inhibition phase, columns without such minimal number of connections, even if all the input bits they are connected to turn on, have no chance of obtaining the minimum threshold. For such columns, the permanence values are increased until the minimum number of connections are formed. Parameters: ---------------------------- @param perm: An array of permanence values for a column. The array is "dense", i.e. it contains an entry for each input bit, even if the permanence value is 0. @param mask: the indices of the columns whose permanences need to be raised. """ if len(mask) < self._stimulusThreshold: raise Exception("This is likely due to a " + "value of stimulusThreshold that is too large relative " + "to the input size. [len(mask) < self._stimulusThreshold]") numpy.clip(perm, self._synPermMin, self._synPermMax, out=perm) while True: numConnected = numpy.nonzero(perm > self._synPermConnected)[0].size if numConnected >= self._stimulusThreshold: return perm[mask] += self._synPermBelowStimulusInc def _updatePermanencesForColumn(self, perm, columnIndex, raisePerm=True): """ This method updates the permanence matrix with a column's new permanence values. The column is identified by its index, which reflects the row in the matrix, and the permanence is given in 'dense' form, i.e. a full array containing all the zeros as well as the non-zero values. It is in charge of implementing 'clipping' - ensuring that the permanence values are always between 0 and 1 - and 'trimming' - enforcing sparsity by zeroing out all permanence values below '_synPermTrimThreshold'. It also maintains the consistency between 'self._permanences' (the matrix storing the permanence values), 'self._connectedSynapses', (the matrix storing the bits each column is connected to), and 'self._connectedCounts' (an array storing the number of input bits each column is connected to). Every method wishing to modify the permanence matrix should do so through this method. Parameters: ---------------------------- @param perm: An array of permanence values for a column. The array is "dense", i.e. it contains an entry for each input bit, even if the permanence value is 0. @param index: The index identifying a column in the permanence, potential and connectivity matrices @param raisePerm: A boolean value indicating whether the permanence values should be raised until a minimum number are synapses are in a connected state. Should be set to 'false' when a direct assignment is required. """ maskPotential = numpy.where(self._potentialPools[columnIndex] > 0)[0] if raisePerm: self._raisePermanenceToThreshold(perm, maskPotential) perm[perm < self._synPermTrimThreshold] = 0 numpy.clip(perm, self._synPermMin, self._synPermMax, out=perm) newConnected = numpy.where(perm >= self._synPermConnected)[0] self._permanences.update(columnIndex, perm) self._connectedSynapses.replace(columnIndex, newConnected) self._connectedCounts[columnIndex] = newConnected.size def _initPermConnected(self): """ Returns a randomly generated permanence value for a synapses that is initialized in a connected state. The basic idea here is to initialize permanence values very close to synPermConnected so that a small number of learning steps could make it disconnected or connected. Note: experimentation was done a long time ago on the best way to initialize permanence values, but the history for this particular scheme has been lost. """ p = self._synPermConnected + ( self._synPermMax - self._synPermConnected)*self._random.getReal64() # Ensure we don't have too much unnecessary precision. A full 64 bits of # precision causes numerical stability issues across platforms and across # implementations p = int(p*100000) / 100000.0 return p def _initPermNonConnected(self): """ Returns a randomly generated permanence value for a synapses that is to be initialized in a non-connected state. """ p = self._synPermConnected * self._random.getReal64() # Ensure we don't have too much unnecessary precision. A full 64 bits of # precision causes numerical stability issues across platforms and across # implementations p = int(p*100000) / 100000.0 return p def _initPermanence(self, potential, connectedPct): """ Initializes the permanences of a column. The method returns a 1-D array the size of the input, where each entry in the array represents the initial permanence value between the input bit at the particular index in the array, and the column represented by the 'index' parameter. Parameters: ---------------------------- @param potential: A numpy array specifying the potential pool of the column. Permanence values will only be generated for input bits corresponding to indices for which the mask value is 1. @param connectedPct: A value between 0 or 1 governing the chance, for each permanence, that the initial permanence value will be a value that is considered connected. """ # Determine which inputs bits will start out as connected # to the inputs. Initially a subset of the input bits in a # column's potential pool will be connected. This number is # given by the parameter "connectedPct" perm = numpy.zeros(self._numInputs) for i in xrange(self._numInputs): if (potential[i] < 1): continue if (self._random.getReal64() <= connectedPct): perm[i] = self._initPermConnected() else: perm[i] = self._initPermNonConnected() # Clip off low values. Since we use a sparse representation # to store the permanence values this helps reduce memory # requirements. perm[perm < self._synPermTrimThreshold] = 0 return perm def _mapColumn(self, index): """ Maps a column to its respective input index, keeping to the topology of the region. It takes the index of the column as an argument and determines what is the index of the flattened input vector that is to be the center of the column's potential pool. It distributes the columns over the inputs uniformly. The return value is an integer representing the index of the input bit. Examples of the expected output of this method: * If the topology is one dimensional, and the column index is 0, this method will return the input index 0. If the column index is 1, and there are 3 columns over 7 inputs, this method will return the input index 3. * If the topology is two dimensional, with column dimensions [3, 5] and input dimensions [7, 11], and the column index is 3, the method returns input index 8. Parameters: ---------------------------- @param index: The index identifying a column in the permanence, potential and connectivity matrices. @param wrapAround: A boolean value indicating that boundaries should be ignored. """ columnCoords = numpy.unravel_index(index, self._columnDimensions) columnCoords = numpy.array(columnCoords, dtype=realDType) ratios = columnCoords / self._columnDimensions inputCoords = self._inputDimensions * ratios inputCoords += 0.5 * self._inputDimensions / self._columnDimensions inputCoords = inputCoords.astype(int) inputIndex = numpy.ravel_multi_index(inputCoords, self._inputDimensions) return inputIndex def _mapPotential(self, index, wrapAround=False): """ Maps a column to its input bits. This method encapsulates the topology of the region. It takes the index of the column as an argument and determines what are the indices of the input vector that are located within the column's potential pool. The return value is a list containing the indices of the input bits. The current implementation of the base class only supports a 1 dimensional topology of columns with a 1 dimensional topology of inputs. To extend this class to support 2-D topology you will need to override this method. Examples of the expected output of this method: * If the potentialRadius is greater than or equal to the largest input dimension then each column connects to all of the inputs. * If the topology is one dimensional, the input space is divided up evenly among the columns and each column is centered over its share of the inputs. If the potentialRadius is 5, then each column connects to the input it is centered above as well as the 5 inputs to the left of that input and the five inputs to the right of that input, wrapping around if wrapAround=True. * If the topology is two dimensional, the input space is again divided up evenly among the columns and each column is centered above its share of the inputs. If the potentialRadius is 5, the column connects to a square that has 11 inputs on a side and is centered on the input that the column is centered above. Parameters: ---------------------------- @param index: The index identifying a column in the permanence, potential and connectivity matrices. @param wrapAround: A boolean value indicating that boundaries should be fignored. """ index = self._mapColumn(index) indices = self._getNeighborsND(index, self._inputDimensions, self._potentialRadius, wrapAround=wrapAround) indices.append(index) indices = numpy.array(indices, dtype=uintType) # TODO: See https://github.com/numenta/nupic.core/issues/128 indices.sort() # Select a subset of the receptive field to serve as the # the potential pool numPotential = int(round(indices.size * self._potentialPct)) selectedIndices = numpy.empty(numPotential, dtype=uintType) self._random.sample(indices, selectedIndices) potential = numpy.zeros(self._numInputs, dtype=uintType) potential[selectedIndices] = 1 return potential @staticmethod def _updateDutyCyclesHelper(dutyCycles, newInput, period): """ Updates a duty cycle estimate with a new value. This is a helper function that is used to update several duty cycle variables in the Column class, such as: overlapDutyCucle, activeDutyCycle, minPctDutyCycleBeforeInh, minPctDutyCycleAfterInh, etc. returns the updated duty cycle. Duty cycles are updated according to the following formula: (period - 1)*dutyCycle + newValue dutyCycle := ---------------------------------- period Parameters: ---------------------------- @param dutyCycles: An array containing one or more duty cycle values that need to be updated @param newInput: A new numerical value used to update the duty cycle @param period: The period of the duty cycle """ assert(period >= 1) return (dutyCycles * (period -1.0) + newInput) / period def _updateBoostFactors(self): r""" Update the boost factors for all columns. The boost factors are used to increase the overlap of inactive columns to improve their chances of becoming active. and hence encourage participation of more columns in the learning process. This is a line defined as: y = mx + b boost = (1-maxBoost)/minDuty * dutyCycle + maxFiringBoost. Intuitively this means that columns that have been active enough have a boost factor of 1, meaning their overlap is not boosted. Columns whose active duty cycle drops too much below that of their neighbors are boosted depending on how infrequently they have been active. The more infrequent, the more they are boosted. The exact boost factor is linearly interpolated between the points (dutyCycle:0, boost:maxFiringBoost) and (dutyCycle:minDuty, boost:1.0). boostFactor ^ maxBoost _ | |\ | \ 1 _ | \ _ _ _ _ _ _ _ | +--------------------> activeDutyCycle | minActiveDutyCycle """ mask = numpy.where(self._minActiveDutyCycles > 0)[0] self._boostFactors[mask] = ((1 - self._maxBoost) / self._minActiveDutyCycles[mask] * self._activeDutyCycles[mask] ).astype(realDType) + self._maxBoost self._boostFactors[self._activeDutyCycles > self._minActiveDutyCycles] = 1.0 def _updateBookeepingVars(self, learn): """ Updates counter instance variables each round. Parameters: ---------------------------- @param learn: a boolean value indicating whether learning should be performed. Learning entails updating the permanence values of the synapses, and hence modifying the 'state' of the model. setting learning to 'off' might be useful for indicating separate training vs. testing sets. """ self._iterationNum += 1 if learn: self._iterationLearnNum += 1 def _calculateOverlap(self, inputVector): """ This function determines each column's overlap with the current input vector. The overlap of a column is the number of synapses for that column that are connected (permanence value is greater than '_synPermConnected') to input bits which are turned on. Overlap values that are lower than the 'stimulusThreshold' are ignored. The implementation takes advantage of the SparseBinaryMatrix class to perform this calculation efficiently. Parameters: ---------------------------- @param inputVector: a numpy array of 0's and 1's that comprises the input to the spatial pooler. """ overlaps = numpy.zeros(self._numColumns).astype(realDType) self._connectedSynapses.rightVecSumAtNZ_fast(inputVector, overlaps) overlaps[overlaps < self._stimulusThreshold] = 0 return overlaps def _calculateOverlapPct(self, overlaps): return overlaps.astype(realDType) / self._connectedCounts def _inhibitColumns(self, overlaps): """ Performs inhibition. This method calculates the necessary values needed to actually perform inhibition and then delegates the task of picking the active columns to helper functions. Parameters: ---------------------------- @param overlaps: an array containing the overlap score for each column. The overlap score for a column is defined as the number of synapses in a "connected state" (connected synapses) that are connected to input bits which are turned on. """ # determine how many columns should be selected in the inhibition phase. # This can be specified by either setting the 'numActiveColumnsPerInhArea' # parameter or the 'localAreaDensity' parameter when initializing the class overlaps = overlaps.copy() if (self._localAreaDensity > 0): density = self._localAreaDensity else: inhibitionArea = ((2*self._inhibitionRadius + 1) ** self._columnDimensions.size) inhibitionArea = min(self._numColumns, inhibitionArea) density = float(self._numActiveColumnsPerInhArea) / inhibitionArea density = min(density, 0.5) # Add our fixed little bit of random noise to the scores to help break ties. overlaps += self._tieBreaker if self._globalInhibition or \ self._inhibitionRadius > max(self._columnDimensions): return self._inhibitColumnsGlobal(overlaps, density) else: return self._inhibitColumnsLocal(overlaps, density) def _inhibitColumnsGlobal(self, overlaps, density): """ Perform global inhibition. Performing global inhibition entails picking the top 'numActive' columns with the highest overlap score in the entire region. At most half of the columns in a local neighborhood are allowed to be active. Parameters: ---------------------------- @param overlaps: an array containing the overlap score for each column. The overlap score for a column is defined as the number of synapses in a "connected state" (connected synapses) that are connected to input bits which are turned on. @param density: The fraction of columns to survive inhibition. """ #calculate num active per inhibition area numActive = int(density * self._numColumns) activeColumns = numpy.zeros(self._numColumns) winners = sorted(range(overlaps.size), key=lambda k: overlaps[k], reverse=True)[0:numActive] activeColumns[winners] = 1 return numpy.where(activeColumns > 0)[0] def _inhibitColumnsLocal(self, overlaps, density): """ Performs local inhibition. Local inhibition is performed on a column by column basis. Each column observes the overlaps of its neighbors and is selected if its overlap score is within the top 'numActive' in its local neighborhood. At most half of the columns in a local neighborhood are allowed to be active. Parameters: ---------------------------- @param overlaps: an array containing the overlap score for each column. The overlap score for a column is defined as the number of synapses in a "connected state" (connected synapses) that are connected to input bits which are turned on. @param density: The fraction of columns to survive inhibition. This value is only an intended target. Since the surviving columns are picked in a local fashion, the exact fraction of surviving columns is likely to vary. """ activeColumns = numpy.zeros(self._numColumns) addToWinners = max(overlaps)/1000.0 overlaps = numpy.array(overlaps, dtype=realDType) for i in xrange(self._numColumns): maskNeighbors = self._getNeighborsND(i, self._columnDimensions, self._inhibitionRadius) overlapSlice = overlaps[maskNeighbors] numActive = int(0.5 + density * (len(maskNeighbors) + 1)) numBigger = numpy.count_nonzero(overlapSlice > overlaps[i]) if numBigger < numActive: activeColumns[i] = 1 overlaps[i] += addToWinners return numpy.where(activeColumns > 0)[0] @staticmethod def _getNeighbors1D(columnIndex, dimensions, radius, wrapAround=False): """ Returns a list of indices corresponding to the neighbors of a given column. In this variation of the method, which only supports a one dimensional column topology, a column's neighbors are those neighbors who are 'radius' indices away. This information is needed to perform inhibition. This method is a subset of _getNeighborsND and is only included for illustration purposes, and potentially enhanced performance for spatial pooler implementations that only require a one-dimensional topology. Parameters: ---------------------------- @param columnIndex: The index identifying a column in the permanence, potential and connectivity matrices. @param dimensions: An array containing a dimensions for the column space. A 2x3 grid will be represented by [2,3]. @param radius: Indicates how far away from a given column are other columns to be considered its neighbors. In the previous 2x3 example, each column with coordinates: [2+/-radius, 3+/-radius] is considered a neighbor. @param wrapAround: A boolean value indicating whether to consider columns at the border of a dimensions to be adjacent to columns at the other end of the dimension. For example, if the columns are laid out in one dimension, columns 1 and 10 will be considered adjacent if wrapAround is set to true: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ assert(dimensions.size == 1) ncols = dimensions[0] if wrapAround: neighbors = numpy.array( range(columnIndex-radius,columnIndex+radius+1)) % ncols else: neighbors = numpy.array( range(columnIndex-radius,columnIndex+radius+1)) neighbors = neighbors[ numpy.logical_and(neighbors >= 0, neighbors < ncols)] neighbors = list(set(neighbors) - set([columnIndex])) assert(neighbors) return neighbors @staticmethod def _getNeighbors2D(columnIndex, dimensions, radius, wrapAround=False): """ Returns a list of indices corresponding to the neighbors of a given column. Since the permanence values are stored in such a way that information about topology is lost, this method allows for reconstructing the topology of the inputs, which are flattened to one array. Given a column's index, its neighbors are defined as those columns that are 'radius' indices away from it in each dimension. The method returns a list of the flat indices of these columns. This method is a subset of _getNeighborsND and is only included for illustration purposes, and potentially enhanced performance for spatial pooler implementations that only require a two-dimensional topology. Parameters: ---------------------------- @param columnIndex: The index identifying a column in the permanence, potential and connectivity matrices. @param dimensions: An array containing a dimensions for the column space. A 2x3 grid will be represented by [2,3]. @param radius: Indicates how far away from a given column are other columns to be considered its neighbors. In the previous 2x3 example, each column with coordinates: [2+/-radius, 3+/-radius] is considered a neighbor. @param wrapAround: A boolean value indicating whether to consider columns at the border of a dimensions to be adjacent to columns at the other end of the dimension. For example, if the columns are laid out in one dimension, columns 1 and 10 will be considered adjacent if wrapAround is set to true: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ assert(dimensions.size == 2) nrows = dimensions[0] ncols = dimensions[1] toRow = lambda index: index / ncols toCol = lambda index: index % ncols toIndex = lambda row, col: row * ncols + col row = toRow(columnIndex) col = toCol(columnIndex) if wrapAround: colRange = numpy.array(range(col-radius, col+radius+1)) % ncols rowRange = numpy.array(range(row-radius, row+radius+1)) % nrows else: colRange = numpy.array(range(col-radius, col+radius+1)) colRange = colRange[ numpy.logical_and(colRange >= 0, colRange < ncols)] rowRange = numpy.array(range(row-radius, row+radius+1)) rowRange = rowRange[ numpy.logical_and(rowRange >= 0, rowRange < nrows)] neighbors = [toIndex(r, c) for (r, c) in itertools.product(rowRange, colRange)] neighbors = list(set(neighbors) - set([columnIndex])) assert(neighbors) return neighbors @staticmethod def _getNeighborsND(columnIndex, dimensions, radius, wrapAround=False): """ Similar to _getNeighbors1D and _getNeighbors2D, this function Returns a list of indices corresponding to the neighbors of a given column. Since the permanence values are stored in such a way that information about topology is lost. This method allows for reconstructing the topology of the inputs, which are flattened to one array. Given a column's index, its neighbors are defined as those columns that are 'radius' indices away from it in each dimension. The method returns a list of the flat indices of these columns. Parameters: ---------------------------- @param columnIndex: The index identifying a column in the permanence, potential and connectivity matrices. @param dimensions: An array containing a dimensions for the column space. A 2x3 grid will be represented by [2,3]. @param radius: Indicates how far away from a given column are other columns to be considered its neighbors. In the previous 2x3 example, each column with coordinates: [2+/-radius, 3+/-radius] is considered a neighbor. @param wrapAround: A boolean value indicating whether to consider columns at the border of a dimensions to be adjacent to columns at the other end of the dimension. For example, if the columns are laid out in one dimension, columns 1 and 10 will be considered adjacent if wrapAround is set to true: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ assert(dimensions.size > 0) columnCoords = numpy.unravel_index(columnIndex, dimensions) rangeND = [] for i in xrange(dimensions.size): if wrapAround: curRange = numpy.array(range(columnCoords[i]-radius, columnCoords[i]+radius+1)) % dimensions[i] else: curRange = numpy.array(range(columnCoords[i]-radius, columnCoords[i]+radius+1)) curRange = curRange[ numpy.logical_and(curRange >= 0, curRange < dimensions[i])] rangeND.append(numpy.unique(curRange)) neighbors = [numpy.ravel_multi_index(coord, dimensions) for coord in itertools.product(*rangeND)] neighbors.remove(columnIndex) return neighbors def _isUpdateRound(self): """ returns true if enough rounds have passed to warrant updates of duty cycles """ return (self._iterationNum % self._updatePeriod) == 0 def _seed(self, seed=-1): """ Initialize the random seed """ if seed != -1: self._random = NupicRandom(seed) else: self._random = NupicRandom() def __setstate__(self, state): """ Initialize class properties from stored values. """ # original version was a float so check for anything less than 2 if state['_version'] < 2: # the wrapAround property was added in version 2, # in version 1 the wrapAround parameter was True for SP initialization state['_wrapAround'] = True # update version property to current SP version state['_version'] = VERSION self.__dict__.update(state) def write(self, proto): self._random.write(proto.random) proto.numInputs = self._numInputs proto.numColumns = self._numColumns cdimsProto = proto.init("columnDimensions", len(self._columnDimensions)) for i, dim in enumerate(self._columnDimensions): cdimsProto[i] = int(dim) idimsProto = proto.init("inputDimensions", len(self._inputDimensions)) for i, dim in enumerate(self._inputDimensions): idimsProto[i] = int(dim) proto.potentialRadius = self._potentialRadius proto.potentialPct = self._potentialPct proto.inhibitionRadius = self._inhibitionRadius proto.globalInhibition = self._globalInhibition proto.numActiveColumnsPerInhArea = self._numActiveColumnsPerInhArea proto.localAreaDensity = self._localAreaDensity proto.stimulusThreshold = self._stimulusThreshold proto.synPermInactiveDec = self._synPermInactiveDec proto.synPermActiveInc = self._synPermActiveInc proto.synPermBelowStimulusInc = self._synPermBelowStimulusInc proto.synPermConnected = self._synPermConnected proto.minPctOverlapDutyCycles = self._minPctOverlapDutyCycles proto.minPctActiveDutyCycles = self._minPctActiveDutyCycles proto.dutyCyclePeriod = self._dutyCyclePeriod proto.maxBoost = self._maxBoost proto.wrapAround = self._wrapAround proto.spVerbosity = self._spVerbosity proto.synPermMin = self._synPermMin proto.synPermMax = self._synPermMax proto.synPermTrimThreshold = self._synPermTrimThreshold proto.updatePeriod = self._updatePeriod proto.version = self._version proto.iterationNum = self._iterationNum proto.iterationLearnNum = self._iterationLearnNum self._potentialPools.write(proto.potentialPools) self._permanences.write(proto.permanences) tieBreakersProto = proto.init("tieBreaker", len(self._tieBreaker)) for i, v in enumerate(self._tieBreaker): tieBreakersProto[i] = float(v) overlapDutyCyclesProto = proto.init("overlapDutyCycles", len(self._overlapDutyCycles)) for i, v in enumerate(self._overlapDutyCycles): overlapDutyCyclesProto[i] = float(v) activeDutyCyclesProto = proto.init("activeDutyCycles", len(self._activeDutyCycles)) for i, v in enumerate(self._activeDutyCycles): activeDutyCyclesProto[i] = float(v) minOverlapDutyCyclesProto = proto.init("minOverlapDutyCycles", len(self._minOverlapDutyCycles)) for i, v in enumerate(self._minOverlapDutyCycles): minOverlapDutyCyclesProto[i] = float(v) minActiveDutyCyclesProto = proto.init("minActiveDutyCycles", len(self._minActiveDutyCycles)) for i, v in enumerate(self._minActiveDutyCycles): minActiveDutyCyclesProto[i] = float(v) boostFactorsProto = proto.init("boostFactors", len(self._boostFactors)) for i, v in enumerate(self._boostFactors): boostFactorsProto[i] = float(v) def read(self, proto): numInputs = int(proto.numInputs) numColumns = int(proto.numColumns) self._random.read(proto.random) self._numInputs = numInputs self._numColumns = numColumns self._columnDimensions = numpy.array(proto.columnDimensions) self._inputDimensions = numpy.array(proto.inputDimensions) self._potentialRadius = proto.potentialRadius self._potentialPct = proto.potentialPct self._inhibitionRadius = proto.inhibitionRadius self._globalInhibition = proto.globalInhibition self._numActiveColumnsPerInhArea = proto.numActiveColumnsPerInhArea self._localAreaDensity = proto.localAreaDensity self._stimulusThreshold = proto.stimulusThreshold self._synPermInactiveDec = proto.synPermInactiveDec self._synPermActiveInc = proto.synPermActiveInc self._synPermBelowStimulusInc = proto.synPermBelowStimulusInc self._synPermConnected = proto.synPermConnected self._minPctOverlapDutyCycles = proto.minPctOverlapDutyCycles self._minPctActiveDutyCycles = proto.minPctActiveDutyCycles self._dutyCyclePeriod = proto.dutyCyclePeriod self._maxBoost = proto.maxBoost self._wrapAround = proto.wrapAround self._spVerbosity = proto.spVerbosity self._synPermMin = proto.synPermMin self._synPermMax = proto.synPermMax self._synPermTrimThreshold = proto.synPermTrimThreshold self._updatePeriod = proto.updatePeriod self._version = VERSION self._iterationNum = proto.iterationNum self._iterationLearnNum = proto.iterationLearnNum self._potentialPools.read(proto.potentialPools) self._permanences.read(proto.permanences) # Initialize ephemerals and make sure they get updated self._connectedCounts = numpy.zeros(numColumns, dtype=realDType) self._connectedSynapses = BinaryCorticalColumns(numInputs) self._connectedSynapses.resize(numColumns, numInputs) for columnIndex in xrange(proto.numColumns): self._updatePermanencesForColumn( self._permanences[columnIndex], columnIndex, False ) self._tieBreaker = numpy.array(proto.tieBreaker) self._overlapDutyCycles = numpy.array(proto.overlapDutyCycles, dtype=realDType) self._activeDutyCycles = numpy.array(proto.activeDutyCycles, dtype=realDType) self._minOverlapDutyCycles = numpy.array(proto.minOverlapDutyCycles, dtype=realDType) self._minActiveDutyCycles = numpy.array(proto.minActiveDutyCycles, dtype=realDType) self._boostFactors = numpy.array(proto.boostFactors, dtype=realDType) def printParameters(self): """ Useful for debugging. """ print "------------PY SpatialPooler Parameters ------------------" print "numInputs = ", self.getNumInputs() print "numColumns = ", self.getNumColumns() print "columnDimensions = ", self._columnDimensions print "numActiveColumnsPerInhArea = ", self.getNumActiveColumnsPerInhArea() print "potentialPct = ", self.getPotentialPct() print "globalInhibition = ", self.getGlobalInhibition() print "localAreaDensity = ", self.getLocalAreaDensity() print "stimulusThreshold = ", self.getStimulusThreshold() print "synPermActiveInc = ", self.getSynPermActiveInc() print "synPermInactiveDec = ", self.getSynPermInactiveDec() print "synPermConnected = ", self.getSynPermConnected() print "minPctOverlapDutyCycle = ", self.getMinPctOverlapDutyCycles() print "minPctActiveDutyCycle = ", self.getMinPctActiveDutyCycles() print "dutyCyclePeriod = ", self.getDutyCyclePeriod() print "maxBoost = ", self.getMaxBoost() print "spVerbosity = ", self.getSpVerbosity() print "version = ", self._version
agpl-3.0
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/openstackclient/volume/v1/volume.py
1
14040
# Copyright 2012-2013 OpenStack Foundation # # 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. # """Volume v1 Volume action implementations""" import argparse import logging import six from cliff import command from cliff import lister from cliff import show from openstackclient.common import parseractions from openstackclient.common import utils class CreateVolume(show.ShowOne): """Create new volume""" log = logging.getLogger(__name__ + '.CreateVolume') def get_parser(self, prog_name): parser = super(CreateVolume, self).get_parser(prog_name) parser.add_argument( 'name', metavar='<name>', help='New volume name', ) parser.add_argument( '--size', metavar='<size>', required=True, type=int, help='New volume size in GB', ) snapshot_group = parser.add_mutually_exclusive_group() snapshot_group.add_argument( '--snapshot', metavar='<snapshot>', help='Use <snapshot> as source of new volume', ) snapshot_group.add_argument( '--snapshot-id', metavar='<snapshot-id>', help=argparse.SUPPRESS, ) parser.add_argument( '--description', metavar='<description>', help='New volume description', ) parser.add_argument( '--type', metavar='<volume-type>', help='Use <volume-type> as the new volume type', ) parser.add_argument( '--user', metavar='<user>', help='Specify an alternate user (name or ID)', ) parser.add_argument( '--project', metavar='<project>', help='Specify an alternate project (name or ID)', ) parser.add_argument( '--availability-zone', metavar='<availability-zone>', help='Create new volume in <availability-zone>', ) parser.add_argument( '--image', metavar='<image>', help='Use <image> as source of new volume (name or ID)', ) parser.add_argument( '--source', metavar='<volume>', help='Volume to clone (name or ID)', ) parser.add_argument( '--property', metavar='<key=value>', action=parseractions.KeyValueAction, help='Set a property on this volume ' '(repeat option to set multiple properties)', ) return parser @utils.log_method(log) def take_action(self, parsed_args): identity_client = self.app.client_manager.identity image_client = self.app.client_manager.image volume_client = self.app.client_manager.volume source_volume = None if parsed_args.source: source_volume = utils.find_resource( volume_client.volumes, parsed_args.source, ).id project = None if parsed_args.project: project = utils.find_resource( identity_client.tenants, parsed_args.project, ).id user = None if parsed_args.user: user = utils.find_resource( identity_client.users, parsed_args.user, ).id image = None if parsed_args.image: image = utils.find_resource( image_client.images, parsed_args.image, ).id snapshot = parsed_args.snapshot or parsed_args.snapshot_id volume = volume_client.volumes.create( parsed_args.size, snapshot, source_volume, parsed_args.name, parsed_args.description, parsed_args.type, user, project, parsed_args.availability_zone, parsed_args.property, image, ) # Map 'metadata' column to 'properties' volume._info.update( { 'properties': utils.format_dict(volume._info.pop('metadata')), 'type': volume._info.pop('volume_type'), }, ) return zip(*sorted(six.iteritems(volume._info))) class DeleteVolume(command.Command): """Delete volume(s)""" log = logging.getLogger(__name__ + '.DeleteVolume') def get_parser(self, prog_name): parser = super(DeleteVolume, self).get_parser(prog_name) parser.add_argument( 'volumes', metavar='<volume>', nargs="+", help='Volume(s) to delete (name or ID)', ) parser.add_argument( '--force', dest='force', action='store_true', default=False, help='Attempt forced removal of volume(s), regardless of state ' '(defaults to False)', ) return parser @utils.log_method(log) def take_action(self, parsed_args): volume_client = self.app.client_manager.volume for volume in parsed_args.volumes: volume_obj = utils.find_resource( volume_client.volumes, volume) if parsed_args.force: volume_client.volumes.force_delete(volume_obj.id) else: volume_client.volumes.delete(volume_obj.id) return class ListVolume(lister.Lister): """List volumes""" log = logging.getLogger(__name__ + '.ListVolume') def get_parser(self, prog_name): parser = super(ListVolume, self).get_parser(prog_name) parser.add_argument( '--status', metavar='<status>', help='Filter results by status', ) parser.add_argument( '--name', metavar='<name>', help='Filter results by name', ) parser.add_argument( '--all-projects', action='store_true', default=False, help='Include all projects (admin only)', ) parser.add_argument( '--long', action='store_true', default=False, help='List additional fields in output', ) return parser @utils.log_method(log) def take_action(self, parsed_args): volume_client = self.app.client_manager.volume compute_client = self.app.client_manager.compute def _format_attach(attachments): """Return a formatted string of a volume's attached instances :param volume: a volume.attachments field :rtype: a string of formatted instances """ msg = '' for attachment in attachments: server = attachment['server_id'] if server in server_cache.keys(): server = server_cache[server].name device = attachment['device'] msg += 'Attached to %s on %s ' % (server, device) return msg if parsed_args.long: columns = ( 'ID', 'Display Name', 'Status', 'Size', 'Volume Type', 'Bootable', 'Attachments', 'Metadata', ) column_headers = ( 'ID', 'Display Name', 'Status', 'Size', 'Type', 'Bootable', 'Attached to', 'Properties', ) else: columns = ( 'ID', 'Display Name', 'Status', 'Size', 'Attachments', ) column_headers = ( 'ID', 'Display Name', 'Status', 'Size', 'Attached to', ) # Cache the server list server_cache = {} try: for s in compute_client.servers.list(): server_cache[s.id] = s except Exception: # Just forget it if there's any trouble pass search_opts = { 'all_tenants': parsed_args.all_projects, 'display_name': parsed_args.name, 'status': parsed_args.status, } data = volume_client.volumes.list(search_opts=search_opts) return (column_headers, (utils.get_item_properties( s, columns, formatters={'Metadata': utils.format_dict, 'Attachments': _format_attach}, ) for s in data)) class SetVolume(command.Command): """Set volume properties""" log = logging.getLogger(__name__ + '.SetVolume') def get_parser(self, prog_name): parser = super(SetVolume, self).get_parser(prog_name) parser.add_argument( 'volume', metavar='<volume>', help='Volume to change (name or ID)', ) parser.add_argument( '--name', metavar='<name>', help='New volume name', ) parser.add_argument( '--description', metavar='<description>', help='New volume description', ) parser.add_argument( '--size', metavar='<size>', type=int, help='Extend volume size in GB', ) parser.add_argument( '--property', metavar='<key=value>', action=parseractions.KeyValueAction, help='Property to add or modify for this volume ' '(repeat option to set multiple properties)', ) return parser @utils.log_method(log) def take_action(self, parsed_args): volume_client = self.app.client_manager.volume volume = utils.find_resource(volume_client.volumes, parsed_args.volume) if parsed_args.size: if volume.status != 'available': self.app.log.error("Volume is in %s state, it must be " "available before size can be extended" % volume.status) return if parsed_args.size <= volume.size: self.app.log.error("New size must be greater than %s GB" % volume.size) return volume_client.volumes.extend(volume.id, parsed_args.size) if parsed_args.property: volume_client.volumes.set_metadata(volume.id, parsed_args.property) kwargs = {} if parsed_args.name: kwargs['display_name'] = parsed_args.name if parsed_args.description: kwargs['display_description'] = parsed_args.description if kwargs: volume_client.volumes.update(volume.id, **kwargs) if not kwargs and not parsed_args.property and not parsed_args.size: self.app.log.error("No changes requested\n") return class ShowVolume(show.ShowOne): """Show volume details""" log = logging.getLogger(__name__ + '.ShowVolume') def get_parser(self, prog_name): parser = super(ShowVolume, self).get_parser(prog_name) parser.add_argument( 'volume', metavar='<volume>', help='Volume to display (name or ID)', ) return parser @utils.log_method(log) def take_action(self, parsed_args): volume_client = self.app.client_manager.volume volume = utils.find_resource(volume_client.volumes, parsed_args.volume) # Map 'metadata' column to 'properties' volume._info.update( { 'properties': utils.format_dict(volume._info.pop('metadata')), 'type': volume._info.pop('volume_type'), }, ) if 'os-vol-tenant-attr:tenant_id' in volume._info: volume._info.update( {'project_id': volume._info.pop( 'os-vol-tenant-attr:tenant_id')} ) return zip(*sorted(six.iteritems(volume._info))) class UnsetVolume(command.Command): """Unset volume properties""" log = logging.getLogger(__name__ + '.UnsetVolume') def get_parser(self, prog_name): parser = super(UnsetVolume, self).get_parser(prog_name) parser.add_argument( 'volume', metavar='<volume>', help='Volume to modify (name or ID)', ) parser.add_argument( '--property', metavar='<key>', action='append', default=[], help='Property to remove from volume ' '(repeat option to remove multiple properties)', required=True, ) return parser @utils.log_method(log) def take_action(self, parsed_args): volume_client = self.app.client_manager.volume volume = utils.find_resource( volume_client.volumes, parsed_args.volume) if parsed_args.property: volume_client.volumes.delete_metadata( volume.id, parsed_args.property, ) else: self.app.log.error("No changes requested\n") return
mit
onitake/ansible
lib/ansible/plugins/action/uri.py
70
2293
# -*- coding: utf-8 -*- # (c) 2015, Brian Coca <briancoca+dev@gmail.com> # (c) 2018, Matt Martz <matt@sivel.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible.errors import AnsibleError, AnsibleAction, _AnsibleActionDone, AnsibleActionFail from ansible.module_utils._text import to_native from ansible.module_utils.parsing.convert_bool import boolean from ansible.plugins.action import ActionBase class ActionModule(ActionBase): TRANSFERS_FILES = True def run(self, tmp=None, task_vars=None): self._supports_async = True if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect src = self._task.args.get('src', None) remote_src = boolean(self._task.args.get('remote_src', 'no'), strict=False) try: if (src and remote_src) or not src: # everything is remote, so we just execute the module # without changing any of the module arguments raise _AnsibleActionDone(result=self._execute_module(task_vars=task_vars, wrap_async=self._task.async_val)) try: src = self._find_needle('files', src) except AnsibleError as e: raise AnsibleActionFail(to_native(e)) tmp_src = self._connection._shell.join_path(self._connection._shell.tmpdir, os.path.basename(src)) self._transfer_file(src, tmp_src) self._fixup_perms2((self._connection._shell.tmpdir, tmp_src)) new_module_args = self._task.args.copy() new_module_args.update( dict( src=tmp_src, ) ) result.update(self._execute_module('uri', module_args=new_module_args, task_vars=task_vars, wrap_async=self._task.async_val)) except AnsibleAction as e: result.update(e.result) finally: if not self._task.async_val: self._remove_tmp_path(self._connection._shell.tmpdir) return result
gpl-3.0
janssen/kivy
kivy/uix/widget.py
11
46049
''' Widget class ============ The :class:`Widget` class is the base class required for creating Widgets. This widget class was designed with a couple of principles in mind: * *Event Driven* Widget interaction is built on top of events that occur. If a property changes, the widget can respond to the change in the 'on_<propname>' callback. If nothing changes, nothing will be done. That's the main goal of the :class:`~kivy.properties.Property` class. * *Separation Of Concerns (the widget and its graphical representation)* Widgets don't have a `draw()` method. This is done on purpose: The idea is to allow you to create your own graphical representation outside the widget class. Obviously you can still use all the available properties to do that, so that your representation properly reflects the widget's current state. Every widget has its own :class:`~kivy.graphics.Canvas` that you can use to draw. This separation allows Kivy to run your application in a very efficient manner. * *Bounding Box / Collision* Often you want to know if a certain point is within the bounds of your widget. An example would be a button widget where you only want to trigger an action when the button itself is actually touched. For this, you can use the :meth:`~Widget.collide_point` method, which will return True if the point you pass to it is inside the axis-aligned bounding box defined by the widget's position and size. If a simple AABB is not sufficient, you can override the method to perform the collision checks with more complex shapes, e.g. a polygon. You can also check if a widget collides with another widget with :meth:`~Widget.collide_widget`. We also have some default values and behaviors that you should be aware of: * A :class:`Widget` is not a :class:`~kivy.uix.layout.Layout`: it will not change the position or the size of its children. If you want control over positioning or sizing, use a :class:`~kivy.uix.layout.Layout`. * The default size of a widget is (100, 100). This is only changed if the parent is a :class:`~kivy.uix.layout.Layout`. For example, if you add a :class:`Label` inside a :class:`Button`, the label will not inherit the button's size or position because the button is not a *Layout*: it's just another *Widget*. * The default size_hint is (1, 1). If the parent is a :class:`Layout`, then the widget size will be the parent layout's size. * :meth:`~Widget.on_touch_down`, :meth:`~Widget.on_touch_move`, :meth:`~Widget.on_touch_up` don't do any sort of collisions. If you want to know if the touch is inside your widget, use :meth:`~Widget.collide_point`. Using Properties ---------------- When you read the documentation, all properties are described in the format:: <name> is a <property class> and defaults to <default value>. e.g. :attr:`~kivy.uix.label.Label.text` is a :class:`~kivy.properties.StringProperty` and defaults to ''. If you want to be notified when the pos attribute changes, i.e. when the widget moves, you can bind your own callback function like this:: def callback_pos(instance, value): print('The widget', instance, 'moved to', value) wid = Widget() wid.bind(pos=callback_pos) Read more about :doc:`/api-kivy.properties`. Basic drawing ------------- Widgets support a range of drawing instructions that you can use to customize the look of your widgets and layouts. For example, to draw a background image for your widget, you can do the following: .. code-block:: python def redraw(self, args): self.bg_rect.size = self.size self.bg_rect.pos = self.pos widget = Widget() with widget.canvas: widget.bg_rect = Rectangle(source="cover.jpg", pos=self.pos, \ size=self.size) widget.bind(pos=redraw, size=redraw) To draw a background in kv: .. code-block:: kv Widget: canvas: Rectangle: source: "cover.jpg" size: self.size pos: self.pos These examples only scratch the surface. Please see the :mod:`kivy.graphics` documentation for more information. .. _widget-event-bubbling: Widget touch event bubbling --------------------------- When you catch touch events between multiple widgets, you often need to be aware of the order in which these events are propagated. In Kivy, events bubble up from the first child upwards through the other children. If a widget has children, the event is passed through its children before being passed on to the widget after it. As the :meth:`~kivy.uix.widget.Widget.on_touch_up` method inserts widgets at index 0 by default, this means the event goes from the most recently added widget back to the first one added. Consider the following: .. code-block:: python box = BoxLayout() box.add_widget(Label(text="a")) box.add_widget(Label(text="b")) box.add_widget(Label(text="c")) The label with text "c" gets the event first, "b" second and "a" last. You can reverse this order by manually specifying the index: .. code-block:: python box = BoxLayout() box.add_widget(Label(text="a"), index=0) box.add_widget(Label(text="b"), index=1) box.add_widget(Label(text="c"), index=2) Now the order would be "a", "b" then "c". One thing to keep in mind when using kv is that declaring a widget uses the :meth:`~kivy.uix.widget.Widget.add_widget` method for insertion. Hence, using .. code-block:: kv BoxLayout: MyLabel: text: "a" MyLabel: text: "b" MyLabel: text: "c" would result in the event order "c", "b" then "a" as "c" was actually the last added widget. It thus has index 0, "b" index 1 and "a" index 2. Effectively, the child order is the reverse of its listed order. This ordering is the same for the :meth:`~kivy.uix.widget.Widget.on_touch_move` and :meth:`~kivy.uix.widget.Widget.on_touch_up` events. In order to stop this event bubbling, a method can return `True`. This tells Kivy the event has been handled and the event propagation stops. For example: .. code-block:: python class MyWidget(Widget): def on_touch_down(self, touch): If <some_condition>: # Do stuff here and kill the event return True else: return super(MyWidget, self).on_touch_down(touch) This approach gives you good control over exactly how events are dispatched and managed. Sometimes, however, you may wish to let the event be completely propagated before taking action. You can use the :class:`~kivy.clock.Clock` to help you here: .. code-block:: python class MyWidget(Label): def on_touch_down(self, touch, after=False): if after: print "Fired after the event has been dispatched!" else: Clock.schedule_once(lambda dt: self.on_touch_down(touch, True)) return super(MyWidget, self).on_touch_down(touch) Usage of :attr:`Widget.center`, :attr:`Widget.right`, and :attr:`Widget.top` ---------------------------------------------------------------------------- A common mistake when using one of the computed properties such as :attr:`Widget.right` is to use it to make a widget follow its parent with a KV rule such as `right: self.parent.right`. Consider, for example: .. code-block:: kv FloatLayout: id: layout width: 100 Widget: id: wid right: layout.right The (mistaken) expectation is that this rule ensures that wid's right will always be whatever layout's right is - that is wid.right and layout.right will always be identical. In actual fact, this rule only says that "whenever layout's `right` changes, wid's right will be set to that value". The difference being that as long as `layout.right` doesn't change, `wid.right` could be anything, even a value that will make them different. Specifically, for the KV code above, consider the following example:: >>> print(layout.right, wid.right) (100, 100) >>> wid.x = 200 >>> print(layout.right, wid.right) (100, 300) As can be seen, initially they are in sync, however, when we change `wid.x` they go out of sync because `layout.right` is not changed and the rule is not triggered. The proper way to make the widget follow its parent's right is to use :attr:`Widget.pos_hint`. If instead of `right: layout.right` we did `pos_hint: {'right': 1}`, then the widgets right will always be set to be at the parent's right at each layout update. ''' __all__ = ('Widget', 'WidgetException') from kivy.event import EventDispatcher from kivy.factory import Factory from kivy.properties import ( NumericProperty, StringProperty, AliasProperty, ReferenceListProperty, ObjectProperty, ListProperty, DictProperty, BooleanProperty) from kivy.graphics import ( Canvas, Translate, Fbo, ClearColor, ClearBuffers, Scale) from kivy.graphics.transformation import Matrix from kivy.base import EventLoop from kivy.lang import Builder from kivy.context import get_current_context from kivy.weakproxy import WeakProxy from functools import partial from itertools import islice # References to all the widget destructors (partial method with widget uid as # key). _widget_destructors = {} def _widget_destructor(uid, r): # Internal method called when a widget is deleted from memory. the only # thing we remember about it is its uid. Clear all the associated callbacks # created in kv language. del _widget_destructors[uid] Builder.unbind_widget(uid) class WidgetException(Exception): '''Fired when the widget gets an exception. ''' pass class WidgetMetaclass(type): '''Metaclass to automatically register new widgets for the :class:`~kivy.factory.Factory`. .. warning:: This metaclass is used by the Widget. Do not use it directly! ''' def __init__(mcs, name, bases, attrs): super(WidgetMetaclass, mcs).__init__(name, bases, attrs) Factory.register(name, cls=mcs) #: Base class used for Widget, that inherits from :class:`EventDispatcher` WidgetBase = WidgetMetaclass('WidgetBase', (EventDispatcher, ), {}) class Widget(WidgetBase): '''Widget class. See module documentation for more information. :Events: `on_touch_down`: Fired when a new touch event occurs `on_touch_move`: Fired when an existing touch moves `on_touch_up`: Fired when an existing touch disappears .. warning:: Adding a `__del__` method to a class derived from Widget with Python prior to 3.4 will disable automatic garbage collection for instances of that class. This is because the Widget class creates reference cycles, thereby `preventing garbage collection <https://docs.python.org/2/library/gc.html#gc.garbage>`_. .. versionchanged:: 1.0.9 Everything related to event properties has been moved to the :class:`~kivy.event.EventDispatcher`. Event properties can now be used when contructing a simple class without subclassing :class:`Widget`. .. versionchanged:: 1.5.0 The constructor now accepts on_* arguments to automatically bind callbacks to properties or events, as in the Kv language. ''' __metaclass__ = WidgetMetaclass __events__ = ('on_touch_down', 'on_touch_move', 'on_touch_up') _proxy_ref = None def __init__(self, **kwargs): # Before doing anything, ensure the windows exist. EventLoop.ensure_window() # Assign the default context of the widget creation. if not hasattr(self, '_context'): self._context = get_current_context() no_builder = '__no_builder' in kwargs if no_builder: del kwargs['__no_builder'] on_args = {k: v for k, v in kwargs.items() if k[:3] == 'on_'} for key in on_args: del kwargs[key] super(Widget, self).__init__(**kwargs) # Create the default canvas if it does not exist. if self.canvas is None: self.canvas = Canvas(opacity=self.opacity) # Apply all the styles. if not no_builder: Builder.apply(self, ignored_consts=self._kwargs_applied_init) # Bind all the events. if on_args: self.bind(**on_args) @property def proxy_ref(self): '''Return a proxy reference to the widget, i.e. without creating a reference to the widget. See `weakref.proxy <http://docs.python.org/2/library/weakref.html?highlight\ =proxy#weakref.proxy>`_ for more information. .. versionadded:: 1.7.2 ''' _proxy_ref = self._proxy_ref if _proxy_ref is not None: return _proxy_ref f = partial(_widget_destructor, self.uid) self._proxy_ref = _proxy_ref = WeakProxy(self, f) # Only f should be enough here, but it appears that is a very # specific case, the proxy destructor is not called if both f and # _proxy_ref are not together in a tuple. _widget_destructors[self.uid] = (f, _proxy_ref) return _proxy_ref def __hash__(self): return id(self) @property def __self__(self): return self # # Collision # def collide_point(self, x, y): ''' Check if a point (x, y) is inside the widget's axis aligned bounding box. :Parameters: `x`: numeric x position of the point (in parent coordinates) `y`: numeric y position of the point (in parent coordinates) :Returns: A bool. True if the point is inside the bounding box, False otherwise. .. code-block:: python >>> Widget(pos=(10, 10), size=(50, 50)).collide_point(40, 40) True ''' return self.x <= x <= self.right and self.y <= y <= self.top def collide_widget(self, wid): ''' Check if another widget collides with this widget. This function performs an axis-aligned bounding box intersection test by default. :Parameters: `wid`: :class:`Widget` class Widget to test collision with. :Returns: bool. True if the other widget collides with this widget, False otherwise. .. code-block:: python >>> wid = Widget(size=(50, 50)) >>> wid2 = Widget(size=(50, 50), pos=(25, 25)) >>> wid.collide_widget(wid2) True >>> wid2.pos = (55, 55) >>> wid.collide_widget(wid2) False ''' if self.right < wid.x: return False if self.x > wid.right: return False if self.top < wid.y: return False if self.y > wid.top: return False return True # # Default event handlers # def on_touch_down(self, touch): '''Receive a touch down event. :Parameters: `touch`: :class:`~kivy.input.motionevent.MotionEvent` class Touch received. The touch is in parent coordinates. See :mod:`~kivy.uix.relativelayout` for a discussion on coordinate systems. :Returns: bool If True, the dispatching of the touch event will stop. If False, the event will continue to be dispatched to the rest of the widget tree. ''' if self.disabled and self.collide_point(*touch.pos): return True for child in self.children[:]: if child.dispatch('on_touch_down', touch): return True def on_touch_move(self, touch): '''Receive a touch move event. The touch is in parent coordinates. See :meth:`on_touch_down` for more information. ''' if self.disabled: return for child in self.children[:]: if child.dispatch('on_touch_move', touch): return True def on_touch_up(self, touch): '''Receive a touch up event. The touch is in parent coordinates. See :meth:`on_touch_down` for more information. ''' if self.disabled: return for child in self.children[:]: if child.dispatch('on_touch_up', touch): return True def on_disabled(self, instance, value): for child in self.children: child.disabled = value # # Tree management # def add_widget(self, widget, index=0, canvas=None): '''Add a new widget as a child of this widget. :Parameters: `widget`: :class:`Widget` Widget to add to our list of children. `index`: int, defaults to 0 Index to insert the widget in the list. Notice that the default of 0 means the widget is inserted at the beginning of the list and will thus be drawn on top of other sibling widgets. For a full discussion of the index and widget hierarchy, please see the :doc:`Widgets Programming Guide <guide/widgets>`. .. versionadded:: 1.0.5 `canvas`: str, defaults to None Canvas to add widget's canvas to. Can be 'before', 'after' or None for the default canvas. .. versionadded:: 1.9.0 .. code-block:: python >>> from kivy.uix.button import Button >>> from kivy.uix.slider import Slider >>> root = Widget() >>> root.add_widget(Button()) >>> slider = Slider() >>> root.add_widget(slider) ''' if not isinstance(widget, Widget): raise WidgetException( 'add_widget() can be used only with instances' ' of the Widget class.') widget = widget.__self__ if widget is self: raise WidgetException( 'Widget instances cannot be added to themselves.') parent = widget.parent # Check if the widget is already a child of another widget. if parent: raise WidgetException('Cannot add %r, it already has a parent %r' % (widget, parent)) widget.parent = parent = self # Child will be disabled if added to a disabled parent. if parent.disabled: widget.disabled = True canvas = self.canvas.before if canvas == 'before' else \ self.canvas.after if canvas == 'after' else self.canvas if index == 0 or len(self.children) == 0: self.children.insert(0, widget) canvas.add(widget.canvas) else: canvas = self.canvas children = self.children if index >= len(children): index = len(children) next_index = canvas.indexof(children[-1].canvas) else: next_child = children[index] next_index = canvas.indexof(next_child.canvas) if next_index == -1: next_index = canvas.length() else: next_index += 1 children.insert(index, widget) # We never want to insert widget _before_ canvas.before. if next_index == 0 and canvas.has_before: next_index = 1 canvas.insert(next_index, widget.canvas) def remove_widget(self, widget): '''Remove a widget from the children of this widget. :Parameters: `widget`: :class:`Widget` Widget to remove from our children list. .. code-block:: python >>> from kivy.uix.button import Button >>> root = Widget() >>> button = Button() >>> root.add_widget(button) >>> root.remove_widget(button) ''' if widget not in self.children: return self.children.remove(widget) if widget.canvas in self.canvas.children: self.canvas.remove(widget.canvas) elif widget.canvas in self.canvas.after.children: self.canvas.after.remove(widget.canvas) elif widget.canvas in self.canvas.before.children: self.canvas.before.remove(widget.canvas) widget.parent = None def clear_widgets(self, children=None): ''' Remove all (or the specified) :attr:`~Widget.children` of this widget. If the 'children' argument is specified, it should be a list (or filtered list) of children of the current widget. .. versionchanged:: 1.8.0 The `children` argument can be used to specify the children you want to remove. ''' if not children: children = self.children remove_widget = self.remove_widget for child in children[:]: remove_widget(child) def export_to_png(self, filename, *args): '''Saves an image of the widget and its children in png format at the specified filename. Works by removing the widget canvas from its parent, rendering to an :class:`~kivy.graphics.fbo.Fbo`, and calling :meth:`~kivy.graphics.texture.Texture.save`. .. note:: The image includes only this widget and its children. If you want to include widgets elsewhere in the tree, you must call :meth:`~Widget.export_to_png` from their common parent, or use :meth:`~kivy.core.window.WindowBase.screenshot` to capture the whole window. .. note:: The image will be saved in png format, you should include the extension in your filename. .. versionadded:: 1.9.0 ''' if self.parent is not None: canvas_parent_index = self.parent.canvas.indexof(self.canvas) if canvas_parent_index > -1: self.parent.canvas.remove(self.canvas) fbo = Fbo(size=self.size, with_stencilbuffer=True) with fbo: ClearColor(0, 0, 0, 1) ClearBuffers() Scale(1, -1, 1) Translate(-self.x, -self.y - self.height, 0) fbo.add(self.canvas) fbo.draw() fbo.texture.save(filename, flipped=False) fbo.remove(self.canvas) if self.parent is not None and canvas_parent_index > -1: self.parent.canvas.insert(canvas_parent_index, self.canvas) return True def get_root_window(self): '''Return the root window. :Returns: Instance of the root window. Can be a :class:`~kivy.core.window.WindowBase` or :class:`Widget`. ''' if self.parent: return self.parent.get_root_window() def get_parent_window(self): '''Return the parent window. :Returns: Instance of the parent window. Can be a :class:`~kivy.core.window.WindowBase` or :class:`Widget`. ''' if self.parent: return self.parent.get_parent_window() def _walk(self, restrict=False, loopback=False, index=None): # We pass index only when we are going on the parent # so don't yield the parent as well. if index is None: index = len(self.children) yield self for child in reversed(self.children[:index]): for walk_child in child._walk(restrict=True): yield walk_child # If we want to continue with our parent, just do it. if not restrict: parent = self.parent try: if parent is None or not isinstance(parent, Widget): raise ValueError index = parent.children.index(self) except ValueError: # Self is root, if we want to loopback from the first element: if not loopback: return # If we started with root (i.e. index==None), then we have to # start from root again, so we return self again. Otherwise, we # never returned it, so return it now starting with it. parent = self index = None for walk_child in parent._walk(loopback=loopback, index=index): yield walk_child def walk(self, restrict=False, loopback=False): ''' Iterator that walks the widget tree starting with this widget and goes forward returning widgets in the order in which layouts display them. :Parameters: `restrict`: bool, defaults to False If True, it will only iterate through the widget and its children (or children of its children etc.). Defaults to False. `loopback`: bool, defaults to False If True, when the last widget in the tree is reached, it'll loop back to the uppermost root and start walking until we hit this widget again. Naturally, it can only loop back when `restrict` is False. Defaults to False. :return: A generator that walks the tree, returning widgets in the forward layout order. For example, given a tree with the following structure: .. code-block:: kv GridLayout: Button BoxLayout: id: box Widget Button Widget walking this tree: .. code-block:: python >>> # Call walk on box with loopback True, and restrict False >>> [type(widget) for widget in box.walk(loopback=True)] [<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>, <class 'Widget'>, <class 'GridLayout'>, <class 'Button'>] >>> # Now with loopback False, and restrict False >>> [type(widget) for widget in box.walk()] [<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>, <class 'Widget'>] >>> # Now with restrict True >>> [type(widget) for widget in box.walk(restrict=True)] [<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>] .. versionadded:: 1.9.0 ''' gen = self._walk(restrict, loopback) yield next(gen) for node in gen: if node is self: return yield node def _walk_reverse(self, loopback=False, go_up=False): # process is walk up level, walk down its children tree, then walk up # next level etc. # default just walk down the children tree root = self index = 0 # we need to go up a level before walking tree if go_up: root = self.parent try: if root is None or not isinstance(root, Widget): raise ValueError index = root.children.index(self) + 1 except ValueError: if not loopback: return index = 0 go_up = False root = self # now walk children tree starting with last-most child for child in islice(root.children, index, None): for walk_child in child._walk_reverse(loopback=loopback): yield walk_child # we need to return ourself last, in all cases yield root # if going up, continue walking up the parent tree if go_up: for walk_child in root._walk_reverse(loopback=loopback, go_up=go_up): yield walk_child def walk_reverse(self, loopback=False): ''' Iterator that walks the widget tree backwards starting with the widget before this, and going backwards returning widgets in the reverse order in which layouts display them. This walks in the opposite direction of :meth:`walk`, so a list of the tree generated with :meth:`walk` will be in reverse order compared to the list generated with this, provided `loopback` is True. :Parameters: `loopback`: bool, defaults to False If True, when the uppermost root in the tree is reached, it'll loop back to the last widget and start walking back until after we hit widget again. Defaults to False. :return: A generator that walks the tree, returning widgets in the reverse layout order. For example, given a tree with the following structure: .. code-block:: kv GridLayout: Button BoxLayout: id: box Widget Button Widget walking this tree: .. code-block:: python >>> # Call walk on box with loopback True >>> [type(widget) for widget in box.walk_reverse(loopback=True)] [<class 'Button'>, <class 'GridLayout'>, <class 'Widget'>, <class 'Button'>, <class 'Widget'>, <class 'BoxLayout'>] >>> # Now with loopback False >>> [type(widget) for widget in box.walk_reverse()] [<class 'Button'>, <class 'GridLayout'>] >>> forward = [w for w in box.walk(loopback=True)] >>> backward = [w for w in box.walk_reverse(loopback=True)] >>> forward == backward[::-1] True .. versionadded:: 1.9.0 ''' for node in self._walk_reverse(loopback=loopback, go_up=True): yield node if node is self: return def to_widget(self, x, y, relative=False): '''Convert the given coordinate from window to local widget coordinates. See :mod:`~kivy.uix.relativelayout` for details on the coordinate systems. ''' if self.parent: x, y = self.parent.to_widget(x, y) return self.to_local(x, y, relative=relative) def to_window(self, x, y, initial=True, relative=False): '''Transform local coordinates to window coordinates. See :mod:`~kivy.uix.relativelayout` for details on the coordinate systems. ''' if not initial: x, y = self.to_parent(x, y, relative=relative) if self.parent: return self.parent.to_window(x, y, initial=False, relative=relative) return (x, y) def to_parent(self, x, y, relative=False): '''Transform local coordinates to parent coordinates. See :mod:`~kivy.uix.relativelayout` for details on the coordinate systems. :Parameters: `relative`: bool, defaults to False Change to True if you want to translate relative positions from a widget to its parent coordinates. ''' if relative: return (x + self.x, y + self.y) return (x, y) def to_local(self, x, y, relative=False): '''Transform parent coordinates to local coordinates. See :mod:`~kivy.uix.relativelayout` for details on the coordinate systems. :Parameters: `relative`: bool, defaults to False Change to True if you want to translate coordinates to relative widget coordinates. ''' if relative: return (x - self.x, y - self.y) return (x, y) def _apply_transform(self, m, pos=None): if self.parent: x, y = self.parent.to_widget(relative=True, *self.to_window(*(pos or self.pos))) m.translate(x, y, 0) m = self.parent._apply_transform(m) if self.parent else m return m def get_window_matrix(self, x=0, y=0): '''Calculate the transformation matrix to convert between window and widget coordinates. :Parameters: `x`: float, defaults to 0 Translates the matrix on the x axis. `y`: float, defaults to 0 Translates the matrix on the y axis. ''' m = Matrix() m.translate(x, y, 0) m = self._apply_transform(m) return m x = NumericProperty(0) '''X position of the widget. :attr:`x` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. ''' y = NumericProperty(0) '''Y position of the widget. :attr:`y` is a :class:`~kivy.properties.NumericProperty` and defaults to 0. ''' width = NumericProperty(100) '''Width of the widget. :attr:`width` is a :class:`~kivy.properties.NumericProperty` and defaults to 100. .. warning:: Keep in mind that the `width` property is subject to layout logic and that this has not yet happened at the time of the widget's `__init__` method. ''' height = NumericProperty(100) '''Height of the widget. :attr:`height` is a :class:`~kivy.properties.NumericProperty` and defaults to 100. .. warning:: Keep in mind that the `height` property is subject to layout logic and that this has not yet happened at the time of the widget's `__init__` method. ''' pos = ReferenceListProperty(x, y) '''Position of the widget. :attr:`pos` is a :class:`~kivy.properties.ReferenceListProperty` of (:attr:`x`, :attr:`y`) properties. ''' size = ReferenceListProperty(width, height) '''Size of the widget. :attr:`size` is a :class:`~kivy.properties.ReferenceListProperty` of (:attr:`width`, :attr:`height`) properties. ''' def get_right(self): return self.x + self.width def set_right(self, value): self.x = value - self.width right = AliasProperty(get_right, set_right, bind=('x', 'width')) '''Right position of the widget. :attr:`right` is an :class:`~kivy.properties.AliasProperty` of (:attr:`x` + :attr:`width`). ''' def get_top(self): return self.y + self.height def set_top(self, value): self.y = value - self.height top = AliasProperty(get_top, set_top, bind=('y', 'height')) '''Top position of the widget. :attr:`top` is an :class:`~kivy.properties.AliasProperty` of (:attr:`y` + :attr:`height`). ''' def get_center_x(self): return self.x + self.width / 2. def set_center_x(self, value): self.x = value - self.width / 2. center_x = AliasProperty(get_center_x, set_center_x, bind=('x', 'width')) '''X center position of the widget. :attr:`center_x` is an :class:`~kivy.properties.AliasProperty` of (:attr:`x` + :attr:`width` / 2.). ''' def get_center_y(self): return self.y + self.height / 2. def set_center_y(self, value): self.y = value - self.height / 2. center_y = AliasProperty(get_center_y, set_center_y, bind=('y', 'height')) '''Y center position of the widget. :attr:`center_y` is an :class:`~kivy.properties.AliasProperty` of (:attr:`y` + :attr:`height` / 2.). ''' center = ReferenceListProperty(center_x, center_y) '''Center position of the widget. :attr:`center` is a :class:`~kivy.properties.ReferenceListProperty` of (:attr:`center_x`, :attr:`center_y`) properties. ''' cls = ListProperty([]) '''Class of the widget, used for styling. ''' id = StringProperty(None, allownone=True) '''Unique identifier of the widget in the tree. :attr:`id` is a :class:`~kivy.properties.StringProperty` and defaults to None. .. warning:: If the :attr:`id` is already used in the tree, an exception will be raised. ''' children = ListProperty([]) '''List of children of this widget. :attr:`children` is a :class:`~kivy.properties.ListProperty` and defaults to an empty list. Use :meth:`add_widget` and :meth:`remove_widget` for manipulating the children list. Don't manipulate the children list directly unless you know what you are doing. ''' parent = ObjectProperty(None, allownone=True, rebind=True) '''Parent of this widget. The parent of a widget is set when the widget is added to another widget and unset when the widget is removed from its parent. :attr:`parent` is an :class:`~kivy.properties.ObjectProperty` and defaults to None. ''' size_hint_x = NumericProperty(1, allownone=True) '''x size hint. Represents how much space the widget should use in the direction of the x axis relative to its parent's width. Only the :class:`~kivy.uix.layout.Layout` and :class:`~kivy.core.window.Window` classes make use of the hint. The size_hint is used by layouts for two purposes: - When the layout considers widgets on their own rather than in relation to its other children, the size_hint_x is a direct proportion of the parent width, normally between 0.0 and 1.0. For instance, a widget with ``size_hint_x=0.5`` in a vertical BoxLayout will take up half the BoxLayout's width, or a widget in a FloatLayout with ``size_hint_x=0.2`` will take up 20% of the FloatLayout width. If the size_hint is greater than 1, the widget will be wider than the parent. - When multiple widgets can share a row of a layout, such as in a horizontal BoxLayout, their widths will be their size_hint_x as a fraction of the sum of widget size_hints. For instance, if the size_hint_xs are (0.5, 1.0, 0.5), the first widget will have a width of 25% of the parent width. :attr:`size_hint_x` is a :class:`~kivy.properties.NumericProperty` and defaults to 1. ''' size_hint_y = NumericProperty(1, allownone=True) '''y size hint. :attr:`size_hint_y` is a :class:`~kivy.properties.NumericProperty` and defaults to 1. See :attr:`size_hint_x` for more information, but with widths and heights swapped. ''' size_hint = ReferenceListProperty(size_hint_x, size_hint_y) '''Size hint. :attr:`size_hint` is a :class:`~kivy.properties.ReferenceListProperty` of (:attr:`size_hint_x`, :attr:`size_hint_y`) properties. See :attr:`size_hint_x` for more information. ''' pos_hint = ObjectProperty({}) '''Position hint. This property allows you to set the position of the widget inside its parent layout, in percent (similar to size_hint). For example, if you want to set the top of the widget to be at 90% height of its parent layout, you can write:: widget = Widget(pos_hint={'top': 0.9}) The keys 'x', 'right' and 'center_x' will use the parent width. The keys 'y', 'top' and 'center_y' will use the parent height. See :doc:`api-kivy.uix.floatlayout` for further reference. .. note:: :attr:`pos_hint` is not used by all layouts. Check the documentation of the layout in question to see if it supports pos_hint. :attr:`pos_hint` is an :class:`~kivy.properties.ObjectProperty` containing a dict. ''' size_hint_min_x = NumericProperty(None, allownone=True) '''When not None, the x-direction minimum size (in pixels, like :attr:`width`) when :attr:`size_hint_x` is also not None. When :attr:`size_hint_x` is not None, it is the minimum width that the widget will be set due to the :attr:`size_hint_x`. I.e. when a smaller size would be set, :attr:`size_hint_min_x` is the value used instead for the widget width. When None, or when :attr:`size_hint_x` is None, :attr:`size_hint_min_x` doesn't do anything. Only the :class:`~kivy.uix.layout.Layout` and :class:`~kivy.core.window.Window` classes make use of the hint. :attr:`size_hint_min_x` is a :class:`~kivy.properties.NumericProperty` and defaults to None. .. versionadded:: 1.10.0 ''' size_hint_min_y = NumericProperty(None, allownone=True) '''When not None, the y-direction minimum size (in pixels, like :attr:`height`) when :attr:`size_hint_y` is also not None. When :attr:`size_hint_y` is not None, it is the minimum height that the widget will be set due to the :attr:`size_hint_y`. I.e. when a smaller size would be set, :attr:`size_hint_min_y` is the value used instead for the widget height. When None, or when :attr:`size_hint_y` is None, :attr:`size_hint_min_y` doesn't do anything. Only the :class:`~kivy.uix.layout.Layout` and :class:`~kivy.core.window.Window` classes make use of the hint. :attr:`size_hint_min_y` is a :class:`~kivy.properties.NumericProperty` and defaults to None. .. versionadded:: 1.10.0 ''' size_hint_min = ReferenceListProperty(size_hint_min_x, size_hint_min_y) '''Minimum size when using :attr:`size_hint`. :attr:`size_hint_min` is a :class:`~kivy.properties.ReferenceListProperty` of (:attr:`size_hint_min_x`, :attr:`size_hint_min_y`) properties. .. versionadded:: 1.10.0 ''' size_hint_max_x = NumericProperty(None, allownone=True) '''When not None, the x-direction maximum size (in pixels, like :attr:`width`) when :attr:`size_hint_x` is also not None. Similar to :attr:`size_hint_min_x`, except that it sets the maximum width. :attr:`size_hint_max_x` is a :class:`~kivy.properties.NumericProperty` and defaults to None. .. versionadded:: 1.10.0 ''' size_hint_max_y = NumericProperty(None, allownone=True) '''When not None, the y-direction maximum size (in pixels, like :attr:`height`) when :attr:`size_hint_y` is also not None. Similar to :attr:`size_hint_min_y`, except that it sets the maximum height. :attr:`size_hint_max_y` is a :class:`~kivy.properties.NumericProperty` and defaults to None. .. versionadded:: 1.10.0 ''' size_hint_max = ReferenceListProperty(size_hint_max_x, size_hint_max_y) '''Maximum size when using :attr:`size_hint`. :attr:`size_hint_max` is a :class:`~kivy.properties.ReferenceListProperty` of (:attr:`size_hint_max_x`, :attr:`size_hint_max_y`) properties. .. versionadded:: 1.10.0 ''' ids = DictProperty({}) '''This is a dictionary of ids defined in your kv language. This will only be populated if you use ids in your kv language code. .. versionadded:: 1.7.0 :attr:`ids` is a :class:`~kivy.properties.DictProperty` and defaults to an empty dict {}. The :attr:`ids` are populated for each root level widget definition. For example: .. code-block:: kv # in kv <MyWidget@Widget>: id: my_widget Label: id: label_widget Widget: id: inner_widget Label: id: inner_label TextInput: id: text_input OtherWidget: id: other_widget <OtherWidget@Widget> id: other_widget Label: id: other_label TextInput: id: other_textinput Then, in python: .. code-block:: python >>> widget = MyWidget() >>> print(widget.ids) {'other_widget': <weakproxy at 041CFED0 to OtherWidget at 041BEC38>, 'inner_widget': <weakproxy at 04137EA0 to Widget at 04138228>, 'inner_label': <weakproxy at 04143540 to Label at 04138260>, 'label_widget': <weakproxy at 04137B70 to Label at 040F97A0>, 'text_input': <weakproxy at 041BB5D0 to TextInput at 041BEC00>} >>> print(widget.ids['other_widget'].ids) {'other_textinput': <weakproxy at 041DBB40 to TextInput at 041BEF48>, 'other_label': <weakproxy at 041DB570 to Label at 041BEEA0>} >>> print(widget.ids['label_widget'].ids) {} ''' opacity = NumericProperty(1.0) '''Opacity of the widget and all its children. .. versionadded:: 1.4.1 The opacity attribute controls the opacity of the widget and its children. Be careful, it's a cumulative attribute: the value is multiplied by the current global opacity and the result is applied to the current context color. For example, if the parent has an opacity of 0.5 and a child has an opacity of 0.2, the real opacity of the child will be 0.5 * 0.2 = 0.1. Then, the opacity is applied by the shader as: .. code-block:: python frag_color = color * vec4(1.0, 1.0, 1.0, opacity); :attr:`opacity` is a :class:`~kivy.properties.NumericProperty` and defaults to 1.0. ''' def on_opacity(self, instance, value): canvas = self.canvas if canvas is not None: canvas.opacity = value canvas = None '''Canvas of the widget. The canvas is a graphics object that contains all the drawing instructions for the graphical representation of the widget. There are no general properties for the Widget class, such as background color, to keep the design simple and lean. Some derived classes, such as Button, do add such convenience properties but generally the developer is responsible for implementing the graphics representation for a custom widget from the ground up. See the derived widget classes for patterns to follow and extend. See :class:`~kivy.graphics.Canvas` for more information about the usage. ''' disabled = BooleanProperty(False) '''Indicates whether this widget can interact with input or not. .. note:: 1. Child Widgets, when added to a disabled widget, will be disabled automatically. 2. Disabling/enabling a parent disables/enables all of its children. .. versionadded:: 1.8.0 :attr:`disabled` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. '''
mit
yuruofeifei/mxnet
python/mxnet/executor_manager.py
38
17449
# 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. # coding: utf-8 # pylint: disable=invalid-name, protected-access, too-many-locals, too-many-arguments, too-many-statements """Executor manager.""" from __future__ import absolute_import import logging import numpy as np from .base import mx_real_t from . import ndarray as nd from .context import cpu from .io import DataDesc def _split_input_slice(batch_size, work_load_list): """Get input slice from the input shape. Parameters ---------- batch_size : int The number of samples in a mini-batch. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as `ctx`. Returns ------- slices : list of slice The split slices to get a specific slice. Raises ------ ValueError In case of too many splits, leading to some empty slices. """ total_work_load = sum(work_load_list) batch_num_list = [round(work_load * batch_size / total_work_load) for work_load in work_load_list] batch_num_sum = sum(batch_num_list) if batch_num_sum < batch_size: batch_num_list[-1] += batch_size - batch_num_sum slices = [] end = 0 for batch_num in batch_num_list: begin = int(min((end, batch_size))) end = int(min((begin + batch_num, batch_size))) if begin >= end: raise ValueError('Too many slices. Some splits are empty.') slices.append(slice(begin, end)) return slices def _check_arguments(symbol): """Check the argument names of symbol. This function checks the duplication of arguments in Symbol. The check is done for feedforward net for now. Parameters ---------- symbol : Symbol The network configuration. """ arg_set = set() arg_names = symbol.list_arguments() for name in arg_names: if name in arg_set: raise ValueError(('Find duplicated argument name \"%s\", ' + 'please make the weight name non-duplicated(using name arguments), ' + 'arguments are %s') % (name, str(arg_names))) arg_set.add(name) aux_set = set() aux_names = symbol.list_auxiliary_states() for name in aux_names: if name in aux_set: raise ValueError( ('Find duplicated auxiliary param name \"%s\", ' + 'please make the weight name non-duplicated(using name arguments), ' + 'arguments are %s, auxiliary params are %s' ) % (name, str(arg_names), str(aux_names))) aux_set.add(name) def _load_general(data, targets): """Load a list of arrays into a list of arrays specified by slices.""" for d_src, d_targets in zip(data, targets): if isinstance(d_targets, nd.NDArray): d_src.copyto(d_targets) else: assert d_targets[-1][0].stop == d_src.shape[0], \ "Batch size miss match. Expected %d, got %d"%( \ d_targets[-1][0].stop, d_src.shape[0]) for slice_idx, d_dst in d_targets: d_src[slice_idx].copyto(d_dst) def _load_data(batch, targets): """Load data into sliced arrays.""" _load_general(batch.data, targets) def _load_label(batch, targets): """Load label into sliced arrays.""" _load_general(batch.label, targets) # pylint: disable=too-many-branches def _bind_exec(sym, ctx, input_shapes, param_names, need_grad=False, base_exec=None, shared_data_arrays=None, input_types=None, logger=logging): """bind executor for bucketing, potentially sharing data with an existing executor.""" arg_shape, _, aux_shape = sym.infer_shape(**input_shapes) assert(arg_shape is not None) if input_types is None: input_types = {k: mx_real_t for k in input_shapes.keys()} arg_types, _, aux_types = sym.infer_type(**input_types) assert(arg_types is not None) arg_arrays = [] grad_arrays = {} if need_grad != False else None arg_names = sym.list_arguments() if need_grad is False: need_grad = set() elif need_grad is True: need_grad = set(arg_names) - set(input_shapes.keys()) elif isinstance(need_grad, set): pass else: raise AssertionError("need_grad must be boolean or set.") grad_req = {name:('write' if name in need_grad else 'null') for name in arg_names} # create or borrow arguments and gradients for i, name in enumerate(arg_names): if not name in param_names: # data or label if shared_data_arrays is not None and \ name in shared_data_arrays: arg_arr = shared_data_arrays[name] if np.prod(arg_arr.shape) >= np.prod(arg_shape[i]): # good, we can share this memory assert(arg_types[i] == arg_arr.dtype) arg_arr = arg_arr.reshape(arg_shape[i]) else: logger.warning(('bucketing: data "%s" has a shape %s' % (name, arg_shape[i])) + (', which is larger than already allocated ') + ('shape %s' % (arg_arr.shape,)) + ('. Need to re-allocate. Consider putting ') + ('default_bucket_key to be the bucket taking the largest ') + ('input for better memory sharing.')) arg_arr = nd.zeros(arg_shape[i], ctx, dtype=arg_types[i]) # replace existing shared array because the new one is bigger shared_data_arrays[name] = arg_arr else: arg_arr = nd.zeros(arg_shape[i], ctx, dtype=arg_types[i]) if shared_data_arrays is not None: shared_data_arrays[name] = arg_arr arg_arrays.append(arg_arr) else: # model parameter if base_exec is None: arg_arr = nd.zeros(arg_shape[i], ctx, dtype=arg_types[i]) if name in need_grad: grad_arr = nd.zeros(arg_shape[i], ctx, dtype=arg_types[i]) grad_arrays[name] = grad_arr else: arg_arr = base_exec.arg_dict[name] assert arg_arr.shape == arg_shape[i] assert arg_arr.dtype == arg_types[i] if name in need_grad: grad_arrays[name] = base_exec.grad_dict[name] arg_arrays.append(arg_arr) # create or borrow aux variables if base_exec is None: aux_arrays = [nd.zeros(s, ctx, dtype=t) for s, t in zip(aux_shape, aux_types)] else: for i, a in enumerate(base_exec.aux_arrays): assert aux_shape[i] == a.shape assert aux_types[i] == a.dtype aux_arrays = [a for a in base_exec.aux_arrays] executor = sym.bind(ctx=ctx, args=arg_arrays, args_grad=grad_arrays, aux_states=aux_arrays, grad_req=grad_req, shared_exec=base_exec) return executor class DataParallelExecutorGroup(object): """A group of executors living on different devices, for data parallelization. Parameters ---------- sym: Symbol The network configuration. arg_names: list of str Equals `sym.list_arguments()` param_names: list of str List of names of all trainable parameters. ctx: list of Context List of devices for training (data parallelization). slices: list of int Describes how the data parallelization splits data into different devices. train_data: DataIter (or DataBatch) The dataset for training. It could be any object with `provide_data` and `provide_label` properties. Loading of actual data is not necessarily needed at this stage. shared_grop: DataParallelExecutorGroup An existing executor group, if to share parameters with it. """ def __init__(self, sym, arg_names, param_names, ctx, slices, train_data, shared_group=None): # make sure the architecture is valid _check_arguments(sym) if shared_group is None: self.shared_data_arrays = [{} for _ in ctx] else: self.shared_data_arrays = shared_group.shared_data_arrays self.data_names = [x[0] for x in train_data.provide_data] self.label_names = [x[0] for x in train_data.provide_label] self.aux_names = sym.list_auxiliary_states() self.param_idx = [i for i in range(len(arg_names)) if arg_names[i] in param_names] self.param_names = [arg_names[i] for i in self.param_idx] self.train_execs = [] for i, ctxi in enumerate(ctx): data_shapes = {} data_types = {} for x in train_data.provide_data + train_data.provide_label: data_shapes[x[0]] = tuple([slices[i].stop - slices[i].start] + list(x[1][1:])) if isinstance(x, DataDesc): data_types[x.name] = x.dtype else: data_types[x[0]] = mx_real_t shared_exec = None if shared_group is None else shared_group.train_execs[i] train_exec = _bind_exec(sym, ctxi, data_shapes, self.param_names, need_grad=True, base_exec=shared_exec, shared_data_arrays=self.shared_data_arrays[i], input_types=data_types) self.train_execs.append(train_exec) # data structure self.data_arrays = [[(slices[i], e.arg_dict[name]) for i, e in enumerate(self.train_execs)] for name in self.data_names] self.label_arrays = [[(slices[i], e.arg_dict[name]) for i, e in enumerate(self.train_execs)] for name in self.label_names] self.param_arrays = [[e.arg_arrays[i] for e in self.train_execs] for i in self.param_idx] self.grad_arrays = [[e.grad_arrays[i] for e in self.train_execs] for i in self.param_idx] self.aux_arrays = [[e.aux_arrays[i] for e in self.train_execs] for i in range(len(self.aux_names))] self.slices = slices def load_data_batch(self, data_batch): """Load data and labels into arrays.""" _load_data(data_batch, self.data_arrays) _load_label(data_batch, self.label_arrays) def forward(self, is_train=False): """Perform a forward pass on each executor.""" for texec in self.train_execs: texec.forward(is_train=is_train) def backward(self): """Perform a backward pass on each executor.""" for texec in self.train_execs: texec.backward() def update_metric(self, metric, labels): """Update evaluation metric with label and current outputs.""" for texec, islice in zip(self.train_execs, self.slices): labels_slice = [label[islice] for label in labels] metric.update(labels_slice, texec.outputs) class DataParallelExecutorManager(object): """ Helper class to manage multiple executors for data parallelism. Parameters ---------- symbol : Symbol Output symbol. ctx : list of Context Devices to run on. param_names: list of str Name of all trainable parameters of the network. arg_names: list of str Name of all arguments of the network. aux_names: list of str Name of all auxiliary states of the network. train_data : DataIter Training data iterator. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as ctx. logger : logging logger When not specified, default logger will be used. sym_gen : A function that generate new Symbols depending on different input shapes. Used only for bucketing. """ def __init__(self, symbol, ctx, train_data, arg_names, param_names, aux_names, work_load_list=None, logger=None, sym_gen=None): if logger is None: logger = logging # preparation num_device = len(ctx) logger.info('Start training with %s', str(ctx)) if work_load_list is None: work_load_list = [1] * num_device assert isinstance(work_load_list, list) and len(work_load_list) == num_device, \ "Invalid settings for work load. " slices = _split_input_slice(train_data.batch_size, work_load_list) self.slices = slices self.arg_names = arg_names self.param_names = param_names self.aux_names = aux_names self.ctx = ctx self.execgrp = DataParallelExecutorGroup(symbol, self.arg_names, self.param_names, self.ctx, self.slices, train_data) self.symbol = symbol self.sym_gen = sym_gen self.curr_execgrp = None # this is set when data is loaded if self.sym_gen is not None: self.execgrp_bucket = {train_data.default_bucket_key: self.execgrp} def install_monitor(self, monitor): """Install monitor on all executors.""" if self.sym_gen is not None: raise NotImplementedError("Monitoring is not implemented for bucketing") for train_exec in self.execgrp.train_execs: monitor.install(train_exec) def set_params(self, arg_params, aux_params): """Set parameter and aux values. Parameters ---------- arg_params : list of NDArray Source parameter arrays aux_params : list of NDArray Source aux arrays. """ for texec in self.execgrp.train_execs: texec.copy_params_from(arg_params, aux_params) def copy_to(self, arg_params, aux_params): """ Copy data from each executor to ```arg_params`` and ``aux_params``. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ----- - This function will inplace update the NDArrays in arg_params and aux_params. """ for name, block in zip(self.param_names, self.param_arrays): weight = sum(w.copyto(cpu()) for w in block) / len(block) weight.astype(arg_params[name].dtype).copyto(arg_params[name]) for name, block in zip(self.aux_names, self.aux_arrays): weight = sum(w.copyto(cpu()) for w in block) / len(block) weight.astype(aux_params[name].dtype).copyto(aux_params[name]) @property def param_arrays(self): """Shared parameter arrays.""" # param arrays should be shared by all executor groups return self.execgrp.param_arrays @property def grad_arrays(self): """Shared gradient arrays.""" # grad arrays should be shared by all executor groups return self.execgrp.grad_arrays @property def aux_arrays(self): """Shared aux states.""" # aux arrays are also shared by all executor groups return self.execgrp.aux_arrays def load_data_batch(self, data_batch): """Load data and labels into arrays.""" if self.sym_gen is not None: key = data_batch.bucket_key if key not in self.execgrp_bucket: # create new bucket entry symbol = self.sym_gen(key) execgrp = DataParallelExecutorGroup(symbol, self.arg_names, self.param_names, self.ctx, self.slices, data_batch, shared_group=self.execgrp) self.execgrp_bucket[key] = execgrp self.curr_execgrp = self.execgrp_bucket[key] else: self.curr_execgrp = self.execgrp self.curr_execgrp.load_data_batch(data_batch) def forward(self, is_train=False): """Run forward on the current executor.""" self.curr_execgrp.forward(is_train=is_train) def backward(self): """Run backward on the current executor.""" self.curr_execgrp.backward() def update_metric(self, metric, labels): """Update metric with the current executor.""" self.curr_execgrp.update_metric(metric, labels)
apache-2.0
phac-nml/irida-miseq-uploader
Model/SequencingRun.py
1
2879
import os import logging class SequencingRun(object): def __init__(self, metadata = None, sample_list = None, sample_sheet = None): self._sample_list = sample_list self._metadata = metadata if sample_sheet is None: raise ValueError("Sample sheet cannot be None!") self._sample_sheet = sample_sheet self._sample_sheet_dir = os.path.dirname(sample_sheet) self._sample_sheet_name = os.path.basename(self._sample_sheet_dir) for sample in self._sample_list: logging.info("Setting run.") sample.run = self @property def metadata(self): return self._metadata @metadata.setter def metadata(self, metadata_dict): self._metadata = metadata_dict def get_workflow(self): return self._metadata["workflow"] @property def sample_list(self): return self._sample_list @sample_list.setter def sample_list(self, sample_list): self._sample_list = sample_list @property def uploaded_samples(self): return filter(lambda sample: sample.already_uploaded, self.sample_list) @property def samples_to_upload(self): return filter(lambda sample: not sample.already_uploaded, self.sample_list) def get_sample(self, sample_id): for sample in self._sample_list: if sample.get_id() == sample_id: return sample else: raise ValueError("No sample with id {} found!.".format(sample_id)) def set_files(self, sample_id, file_list): for sample in self._sample_list: if sample.get_id() == sample_id: sample.set_files(file_list) break def get_files(self, sample_id): sample = self._get_sample(sample_id) return sample.get_files() @property def sample_sheet(self): return self._sample_sheet @sample_sheet.setter def sample_sheet(self, sample_sheet): self._sample_sheet = sample_sheet @property def sample_sheet_dir(self): return self._sample_sheet_dir @property def sample_sheet_name(self): return self._sample_sheet_name @property def upload_started_topic(self): return self._sample_sheet_name + ".upload_started" @property def upload_progress_topic(self): return self._sample_sheet_name + ".upload_progress" @property def upload_completed_topic(self): return self._sample_sheet_name + ".upload_completed" @property def upload_failed_topic(self): return self._sample_sheet_name + ".upload_failed" @property def offline_validation_topic(self): return self._sample_sheet_name + ".offline_validation" @property def online_validation_topic(self): return self._sample_sheet_name + ".online_validation"
apache-2.0
decause/pyglet-remy
tests/window/EVENT_BUTTON.py
33
1145
#!/usr/bin/env python '''Test that mouse button events work correctly. Expected behaviour: One window will be opened. Click within this window and check the console output for mouse events. - Buttons 1, 2, 4 correspond to left, middle, right, respectively. - No events for scroll wheel - Modifiers are correct Close the window or press ESC to end the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import unittest from pyglet import window from pyglet.window import key class EVENT_BUTTON(unittest.TestCase): def on_mouse_press(self, x, y, button, modifiers): print 'Mouse button %d pressed at %f,%f with %s' % \ (button, x, y, key.modifiers_string(modifiers)) def on_mouse_release(self, x, y, button, modifiers): print 'Mouse button %d released at %f,%f with %s' % \ (button, x, y, key.modifiers_string(modifiers)) def test_button(self): w = window.Window(200, 200) w.push_handlers(self) while not w.has_exit: w.dispatch_events() w.close() if __name__ == '__main__': unittest.main()
bsd-3-clause
brandonshults01/openemr
phpmyadmin/doc/_ext/configext.py
121
6622
from sphinx.domains import Domain, ObjType from sphinx.roles import XRefRole from sphinx.domains.std import GenericObject, StandardDomain from sphinx.directives import ObjectDescription from sphinx.util.nodes import clean_astext, make_refnode from sphinx.util import ws_re from sphinx import addnodes from sphinx.util.docfields import Field from docutils import nodes def get_id_from_cfg(text): ''' Formats anchor ID from config option. ''' if text[:6] == '$cfg[\'': text = text[6:] if text[-2:] == '\']': text = text[:-2] text = text.replace('[$i]', '') parts = text.split("']['") return parts class ConfigOption(ObjectDescription): indextemplate = 'configuration option; %s' parse_node = None has_arguments = True doc_field_types = [ Field('default', label='Default value', has_arg=False, names=('default', )), Field('type', label='Type', has_arg=False, names=('type',)), ] def handle_signature(self, sig, signode): signode.clear() signode += addnodes.desc_name(sig, sig) # normalize whitespace like XRefRole does name = ws_re.sub('', sig) return name def add_target_and_index(self, name, sig, signode): targetparts = get_id_from_cfg(name) targetname = 'cfg_%s' % '_'.join(targetparts) signode['ids'].append(targetname) self.state.document.note_explicit_target(signode) indextype = 'single' # Generic index entries indexentry = self.indextemplate % (name,) self.indexnode['entries'].append((indextype, indexentry, targetname, targetname)) self.indexnode['entries'].append((indextype, name, targetname, targetname)) # Server section if targetparts[0] == 'Servers' and len(targetparts) > 1: indexname = ', '.join(targetparts[1:]) self.indexnode['entries'].append((indextype, 'server configuration; %s' % indexname, targetname, targetname)) self.indexnode['entries'].append((indextype, indexname, targetname, targetname)) else: indexname = ', '.join(targetparts) self.indexnode['entries'].append((indextype, indexname, targetname, targetname)) self.env.domaindata['config']['objects'][self.objtype, name] = \ self.env.docname, targetname class ConfigSectionXRefRole(XRefRole): """ Cross-referencing role for configuration sections (adds an index entry). """ def result_nodes(self, document, env, node, is_ref): if not is_ref: return [node], [] varname = node['reftarget'] tgtid = 'index-%s' % env.new_serialno('index') indexnode = addnodes.index() indexnode['entries'] = [ ('single', varname, tgtid, varname), ('single', 'configuration section; %s' % varname, tgtid, varname) ] targetnode = nodes.target('', '', ids=[tgtid]) document.note_explicit_target(targetnode) return [indexnode, targetnode, node], [] class ConfigSection(ObjectDescription): indextemplate = 'configuration section; %s' parse_node = None def handle_signature(self, sig, signode): if self.parse_node: name = self.parse_node(self.env, sig, signode) else: signode.clear() signode += addnodes.desc_name(sig, sig) # normalize whitespace like XRefRole does name = ws_re.sub('', sig) return name def add_target_and_index(self, name, sig, signode): targetname = '%s-%s' % (self.objtype, name) signode['ids'].append(targetname) self.state.document.note_explicit_target(signode) if self.indextemplate: colon = self.indextemplate.find(':') if colon != -1: indextype = self.indextemplate[:colon].strip() indexentry = self.indextemplate[colon+1:].strip() % (name,) else: indextype = 'single' indexentry = self.indextemplate % (name,) self.indexnode['entries'].append((indextype, indexentry, targetname, targetname)) self.env.domaindata['config']['objects'][self.objtype, name] = \ self.env.docname, targetname class ConfigOptionXRefRole(XRefRole): """ Cross-referencing role for configuration options (adds an index entry). """ def result_nodes(self, document, env, node, is_ref): if not is_ref: return [node], [] varname = node['reftarget'] tgtid = 'index-%s' % env.new_serialno('index') indexnode = addnodes.index() indexnode['entries'] = [ ('single', varname, tgtid, varname), ('single', 'configuration option; %s' % varname, tgtid, varname) ] targetnode = nodes.target('', '', ids=[tgtid]) document.note_explicit_target(targetnode) return [indexnode, targetnode, node], [] class ConfigFileDomain(Domain): name = 'config' label = 'Config' object_types = { 'option': ObjType('config option', 'option'), 'section': ObjType('config section', 'section'), } directives = { 'option': ConfigOption, 'section': ConfigSection, } roles = { 'option': ConfigOptionXRefRole(), 'section': ConfigSectionXRefRole(), } initial_data = { 'objects': {}, # (type, name) -> docname, labelid } def clear_doc(self, docname): for key, (fn, _) in self.data['objects'].items(): if fn == docname: del self.data['objects'][key] def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode): docname, labelid = self.data['objects'].get((typ, target), ('', '')) if not docname: return None else: return make_refnode(builder, fromdocname, docname, labelid, contnode) def get_objects(self): for (type, name), info in self.data['objects'].iteritems(): yield (name, name, type, info[0], info[1], self.object_types[type].attrs['searchprio']) def setup(app): app.add_domain(ConfigFileDomain)
gpl-3.0
Jimmy-Morzaria/scikit-learn
sklearn/feature_selection/from_model.py
224
4316
# Authors: Gilles Louppe, Mathieu Blondel # License: BSD 3 clause import numpy as np from ..base import TransformerMixin from ..externals import six from ..utils import safe_mask, check_array from ..utils.validation import NotFittedError, check_is_fitted class _LearntSelectorMixin(TransformerMixin): # Note because of the extra threshold parameter in transform, this does # not naturally extend from SelectorMixin """Transformer mixin selecting features based on importance weights. This implementation can be mixin on any estimator that exposes a ``feature_importances_`` or ``coef_`` attribute to evaluate the relative importance of individual features for feature selection. """ def transform(self, X, threshold=None): """Reduce X to its most important features. Uses ``coef_`` or ``feature_importances_`` to determine the most important features. For models with a ``coef_`` for each class, the absolute sum over the classes is used. Parameters ---------- X : array or scipy sparse matrix of shape [n_samples, n_features] The input samples. threshold : string, float or None, optional (default=None) The threshold value to use for feature selection. Features whose importance is greater or equal are kept while the others are discarded. If "median" (resp. "mean"), then the threshold value is the median (resp. the mean) of the feature importances. A scaling factor (e.g., "1.25*mean") may also be used. If None and if available, the object attribute ``threshold`` is used. Otherwise, "mean" is used by default. Returns ------- X_r : array of shape [n_samples, n_selected_features] The input samples with only the selected features. """ check_is_fitted(self, ('coef_', 'feature_importances_'), all_or_any=any) X = check_array(X, 'csc') # Retrieve importance vector if hasattr(self, "feature_importances_"): importances = self.feature_importances_ elif hasattr(self, "coef_"): if self.coef_ is None: msg = "This model is not fitted yet. Please call fit() first" raise NotFittedError(msg) if self.coef_.ndim == 1: importances = np.abs(self.coef_) else: importances = np.sum(np.abs(self.coef_), axis=0) if len(importances) != X.shape[1]: raise ValueError("X has different number of features than" " during model fitting.") # Retrieve threshold if threshold is None: if hasattr(self, "penalty") and self.penalty == "l1": # the natural default threshold is 0 when l1 penalty was used threshold = getattr(self, "threshold", 1e-5) else: threshold = getattr(self, "threshold", "mean") if isinstance(threshold, six.string_types): if "*" in threshold: scale, reference = threshold.split("*") scale = float(scale.strip()) reference = reference.strip() if reference == "median": reference = np.median(importances) elif reference == "mean": reference = np.mean(importances) else: raise ValueError("Unknown reference: " + reference) threshold = scale * reference elif threshold == "median": threshold = np.median(importances) elif threshold == "mean": threshold = np.mean(importances) else: threshold = float(threshold) # Selection try: mask = importances >= threshold except TypeError: # Fails in Python 3.x when threshold is str; # result is array of True raise ValueError("Invalid threshold: all features are discarded.") if np.any(mask): mask = safe_mask(X, mask) return X[:, mask] else: raise ValueError("Invalid threshold: all features are discarded.")
bsd-3-clause
allenmodroid/webstack
01_webstack/03Wk04/1_conFusion_http/node_modules/browser-sync/node_modules/socket.io/node_modules/engine.io/node_modules/engine.io-parser/node_modules/utf8/tests/generate-test-data.py
1788
1435
#!/usr/bin/env python import re import json # https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae # http://stackoverflow.com/a/13436167/96656 def unisymbol(codePoint): if codePoint >= 0x0000 and codePoint <= 0xFFFF: return unichr(codePoint) elif codePoint >= 0x010000 and codePoint <= 0x10FFFF: highSurrogate = int((codePoint - 0x10000) / 0x400) + 0xD800 lowSurrogate = int((codePoint - 0x10000) % 0x400) + 0xDC00 return unichr(highSurrogate) + unichr(lowSurrogate) else: return 'Error' def hexify(codePoint): return 'U+' + hex(codePoint)[2:].upper().zfill(6) def writeFile(filename, contents): print filename with open(filename, 'w') as f: f.write(contents.strip() + '\n') data = [] for codePoint in range(0x000000, 0x10FFFF + 1): # Skip non-scalar values. if codePoint >= 0xD800 and codePoint <= 0xDFFF: continue symbol = unisymbol(codePoint) # http://stackoverflow.com/a/17199950/96656 bytes = symbol.encode('utf8').decode('latin1') data.append({ 'codePoint': codePoint, 'decoded': symbol, 'encoded': bytes }); jsonData = json.dumps(data, sort_keys=False, indent=2, separators=(',', ': ')) # Use tabs instead of double spaces for indentation jsonData = jsonData.replace(' ', '\t') # Escape hexadecimal digits in escape sequences jsonData = re.sub( r'\\u([a-fA-F0-9]{4})', lambda match: r'\u{}'.format(match.group(1).upper()), jsonData ) writeFile('data.json', jsonData)
apache-2.0
tuqc/lyman
scripts/run_group.py
1
8643
#! /usr/bin/env python """ Group fMRI analysis frontend for Lyman ecosystem. """ import os import sys import time import shutil import os.path as op from textwrap import dedent import argparse import matplotlib as mpl mpl.use("Agg") import nipype from nipype import Node, MapNode, SelectFiles, DataSink, IdentityInterface import lyman import lyman.workflows as wf from lyman import tools def main(arglist): """Main function for workflow setup and execution.""" args = parse_args(arglist) # Get and process specific information project = lyman.gather_project_info() exp = lyman.gather_experiment_info(args.experiment, args.altmodel) if args.experiment is None: args.experiment = project["default_exp"] if args.altmodel: exp_name = "-".join([args.experiment, args.altmodel]) else: exp_name = args.experiment # Make sure some paths are set properly os.environ["SUBJECTS_DIR"] = project["data_dir"] # Set roots of output storage anal_dir_base = op.join(project["analysis_dir"], exp_name) work_dir_base = op.join(project["working_dir"], exp_name) nipype.config.set("execution", "crashdump_dir", project["crash_dir"]) # Subject source (no iterables here) subject_list = lyman.determine_subjects(args.subjects) subj_source = Node(IdentityInterface(fields=["subject_id"]), name="subj_source") subj_source.inputs.subject_id = subject_list # Set up the regressors and contrasts regressors = dict(group_mean=[1] * len(subject_list)) contrasts = [["group_mean", "T", ["group_mean"], [1]]] # Subject level contrast source contrast_source = Node(IdentityInterface(fields=["l1_contrast"]), iterables=("l1_contrast", exp["contrast_names"]), name="contrast_source") # Group workflow space = args.regspace wf_name = "_".join([space, args.output]) if space == "mni": mfx, mfx_input, mfx_output = wf.create_volume_mixedfx_workflow( wf_name, subject_list, regressors, contrasts, exp) else: mfx, mfx_input, mfx_output = wf.create_surface_ols_workflow( wf_name, subject_list, exp) # Mixed effects inputs ffxspace = "mni" if space == "mni" else "epi" ffxsmooth = "unsmoothed" if args.unsmoothed else "smoothed" mfx_base = op.join("{subject_id}/ffx/%s/%s/{l1_contrast}" % (ffxspace, ffxsmooth)) templates = dict(copes=op.join(mfx_base, "cope1.nii.gz")) if space == "mni": templates.update(dict( varcopes=op.join(mfx_base, "varcope1.nii.gz"), dofs=op.join(mfx_base, "tdof_t1.nii.gz"))) else: templates.update(dict( reg_file=op.join(anal_dir_base, "{subject_id}/preproc/run_1", "func2anat_tkreg.dat"))) # Workflow source node mfx_source = MapNode(SelectFiles(templates, base_directory=anal_dir_base, sort_filelist=True), "subject_id", "mfx_source") # Workflow input connections mfx.connect([ (contrast_source, mfx_source, [("l1_contrast", "l1_contrast")]), (contrast_source, mfx_input, [("l1_contrast", "l1_contrast")]), (subj_source, mfx_source, [("subject_id", "subject_id")]), (mfx_source, mfx_input, [("copes", "copes")]) ]), if space == "mni": mfx.connect([ (mfx_source, mfx_input, [("varcopes", "varcopes"), ("dofs", "dofs")]), ]) else: mfx.connect([ (mfx_source, mfx_input, [("reg_file", "reg_file")]), (subj_source, mfx_input, [("subject_id", "subject_id")]) ]) # Mixed effects outputs mfx_sink = Node(DataSink(base_directory="/".join([anal_dir_base, args.output, space]), substitutions=[("/stats", "/"), ("/_hemi_", "/"), ("_glm_results", "")], parameterization=True), name="mfx_sink") mfx_outwrap = tools.OutputWrapper(mfx, subj_source, mfx_sink, mfx_output) mfx_outwrap.sink_outputs() mfx_outwrap.set_mapnode_substitutions(1) mfx_outwrap.add_regexp_substitutions([ (r"_l1_contrast_[-\w]*/", "/"), (r"_mni_hemi_[lr]h", "") ]) mfx.connect(contrast_source, "l1_contrast", mfx_sink, "container") # Set a few last things mfx.base_dir = work_dir_base # Execute lyman.run_workflow(mfx, args=args) # Clean up if project["rm_working_dir"]: shutil.rmtree(project["working_dir"]) def parse_args(arglist): """Take an arglist and return an argparse Namespace.""" help = dedent(""" Perform a basic group analysis in lyman. This script currently only handles one-sample group mean tests on each of the fixed-effects contrasts. It is possible to run the group model in the volume or on the surface, although the actual model changes depending on this choice. The volume model runs FSL's FLAME mixed effects for hierarchical inference, which uses the lower-level variance estimates, and it applies standard GRF-based correction for multiple comparisons. The details of the model-fitting procedure are set in the experiment file, along with the thresholds used for correction. The surface model uses a standard ordinary least squares fit and does correction with an approach based on a Monte Carlo simulation of the null distribution of cluster sizes for smoothed Gaussian data. Fortunately, the simulations are cached so this runs very quickly. Unfortunately, the cached simulations used a whole-brain search space, so this will be overly conservative for partial-brain acquisitions. Because of how GRF-based correction works, the thresholded volume images only have positive voxels. It is up to you to define "negative" versions of any contrasts where you are interested in relative deactivation. The surface correction does not have this constraint, and the test sign is configurable in the experiment file (and will thus apply to all contrasts). By default the results are written under `group` next to the subject level data in the lyman analysis directory, although the output directory name can be changed. Examples -------- Note that the parameter switches match any unique short version of the full parameter name. run_group.py With no arguments, this will process the default experiment with the subjects defined in $LYMAN_DIR/subjects.txt in the MNI space using the MultiProc plugin with 4 processes. run_group.py -s pilot_subjects -r fsaverage -o pilot -unsmoothed This will processes the subjects defined in a file at $LYMAN_DIR/pilot_subjects.txt as above but with the surface workflow. Unsmoothed fixed effects parameter estimates will be sampled to the surface and smoothed there. The resulting files will be stored under <analysis_dir>/<experiment>/pilot/fsaverage/<contrast>/<hemi> run_group.py -e nback -a parametric -p sge -q batch.q This will process an alternate model for the `nback` experiment using the SGE plugin by submitting jobs to the batch.q queue. Usage Details ------------- """) parser = tools.parser parser.description = help parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.add_argument("-experiment", help="experimental paradigm") parser.add_argument("-altmodel", help="alternate model to fit") parser.add_argument("-regspace", default="mni", choices=["mni", "fsaverage"], help="common space for group analysis") parser.add_argument("-unsmoothed", action="store_true", help="used unsmoothed fixed effects outputs") parser.add_argument("-output", default="group", help="output directory name") return parser.parse_args(arglist) if __name__ == "__main__": main(sys.argv[1:])
bsd-3-clause
pombredanne/voc
voc/__main__.py
6
1261
import voc import argparse from .transpiler import transpile def main(): parser = argparse.ArgumentParser( prog='voc', description='Transpiles Python code to Java class files.' ) parser.add_argument( '-o', '--output', help='The directory where class files should be output.', default='.' ) parser.add_argument( '-p', '--prefix', help='The prefix to strip from all source file paths.', default='.' ) parser.add_argument( '-n', '--namespace', help='The namespace for the generated Java classfiles.', default='python' ) parser.add_argument( '-v', '--verbosity', action='count', default=0 ) parser.add_argument( '--version', action='version', version='voc %s' % voc.__version__, ) parser.add_argument( 'input', metavar='source file', nargs='+', help='The source file or directory to compile' ) args = parser.parse_args() transpile( input=args.input, prefix=args.prefix, outdir=args.output, namespace=args.namespace, verbosity=args.verbosity ) if __name__ == '__main__': main()
bsd-3-clause
dmtucker/keysmith-py
setup.py
2
1218
"""Package Keysmith.""" import codecs import os.path import setuptools # type: ignore import keysmith # This project only depends on the standard library. def read(*parts): """Read a file in this repository.""" here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, *parts), 'r') as file_: return file_.read() ENTRY_POINTS = { 'console_scripts': [ '{name}={module}:{function}'.format( name=keysmith.CONSOLE_SCRIPT, module=keysmith.__name__, function=keysmith.main.__name__, ), ], } if __name__ == '__main__': setuptools.setup( name=keysmith.__name__, version=keysmith.__version__, description='Passphrase Generator', long_description=read('README.rst'), author='David Tucker', author_email='david@tucker.name', license='BSD 3-Clause License', url='https://github.com/dmtucker/keysmith', python_requires='~=3.5', py_modules=[keysmith.__name__], entry_points=ENTRY_POINTS, keywords='diceware generator keygen passphrase password', classifiers=['Development Status :: 7 - Inactive'], )
gpl-3.0
anas-taji/purchase-workflow
product_by_supplier/__init__.py
14
1039
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2010-2013 Elico Corp. # Author: Yannick Gouin <yannick.gouin@elico-corp.com> # # 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 . import models
agpl-3.0
alphafoobar/intellij-community
python/lib/Lib/site-packages/django/contrib/admin/media/js/compress.py
784
1896
#!/usr/bin/env python import os import optparse import subprocess import sys here = os.path.dirname(__file__) def main(): usage = "usage: %prog [file1..fileN]" description = """With no file paths given this script will automatically compress all jQuery-based files of the admin app. Requires the Google Closure Compiler library and Java version 6 or later.""" parser = optparse.OptionParser(usage, description=description) parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar", help="path to Closure Compiler jar file") parser.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "--quiet", action="store_false", dest="verbose") (options, args) = parser.parse_args() compiler = os.path.expanduser(options.compiler) if not os.path.exists(compiler): sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler) if not args: if options.verbose: sys.stdout.write("No filenames given; defaulting to admin scripts\n") args = [os.path.join(here, f) for f in [ "actions.js", "collapse.js", "inlines.js", "prepopulate.js"]] for arg in args: if not arg.endswith(".js"): arg = arg + ".js" to_compress = os.path.expanduser(arg) if os.path.exists(to_compress): to_compress_min = "%s.min.js" % "".join(arg.rsplit(".js")) cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min) if options.verbose: sys.stdout.write("Running: %s\n" % cmd) subprocess.call(cmd.split()) else: sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress) if __name__ == '__main__': main()
apache-2.0
fvant/ansible-modules-core
packaging/os/apt_repository.py
30
17258
#!/usr/bin/python # encoding: utf-8 # (c) 2012, Matt Wright <matt@nobien.net> # (c) 2013, Alexander Saltanov <asd@mokote.com> # (c) 2014, Rutger Spiertz <rutger@kumina.nl> # # 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: apt_repository short_description: Add and remove APT repositories description: - Add or remove an APT repositories in Ubuntu and Debian. notes: - This module works on Debian and Ubuntu and requires C(python-apt). - This module supports Debian Squeeze (version 6) as well as its successors. - This module treats Debian and Ubuntu distributions separately. So PPA could be installed only on Ubuntu machines. options: repo: required: true default: none description: - A source string for the repository. state: required: false choices: [ "absent", "present" ] default: "present" description: - A source string state. mode: required: false default: 0644 description: - The octal mode for newly created files in sources.list.d version_added: "1.6" update_cache: description: - Run the equivalent of C(apt-get update) when a change occurs. Cache updates are run after making changes. required: false default: "yes" choices: [ "yes", "no" ] validate_certs: version_added: '1.8' description: - If C(no), SSL certificates for the target repo will not be validated. This should only be used on personally controlled sites using self-signed certificates. required: false default: 'yes' choices: ['yes', 'no'] author: "Alexander Saltanov (@sashka)" version_added: "0.7" requirements: [ python-apt ] ''' EXAMPLES = ''' # Add specified repository into sources list. apt_repository: repo='deb http://archive.canonical.com/ubuntu hardy partner' state=present # Add source repository into sources list. apt_repository: repo='deb-src http://archive.canonical.com/ubuntu hardy partner' state=present # Remove specified repository from sources list. apt_repository: repo='deb http://archive.canonical.com/ubuntu hardy partner' state=absent # On Ubuntu target: add nginx stable repository from PPA and install its signing key. # On Debian target: adding PPA is not available, so it will fail immediately. apt_repository: repo='ppa:nginx/stable' ''' import glob import os import re import tempfile try: import apt import apt_pkg import aptsources.distro as aptsources_distro distro = aptsources_distro.get_distro() HAVE_PYTHON_APT = True except ImportError: distro = None HAVE_PYTHON_APT = False VALID_SOURCE_TYPES = ('deb', 'deb-src') def install_python_apt(module): if not module.check_mode: apt_get_path = module.get_bin_path('apt-get') if apt_get_path: rc, so, se = module.run_command('%s update && %s install python-apt -y -q' % (apt_get_path, apt_get_path), use_unsafe_shell=True) if rc == 0: global apt, apt_pkg, aptsources_distro, distro, HAVE_PYTHON_APT import apt import apt_pkg import aptsources.distro as aptsources_distro distro = aptsources_distro.get_distro() HAVE_PYTHON_APT = True else: module.fail_json(msg="Failed to auto-install python-apt. Error was: '%s'" % se.strip()) class InvalidSource(Exception): pass # Simple version of aptsources.sourceslist.SourcesList. # No advanced logic and no backups inside. class SourcesList(object): def __init__(self): self.files = {} # group sources by file # Repositories that we're adding -- used to implement mode param self.new_repos = set() self.default_file = self._apt_cfg_file('Dir::Etc::sourcelist') # read sources.list if it exists if os.path.isfile(self.default_file): self.load(self.default_file) # read sources.list.d for file in glob.iglob('%s/*.list' % self._apt_cfg_dir('Dir::Etc::sourceparts')): self.load(file) def __iter__(self): '''Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped.''' for file, sources in self.files.items(): for n, valid, enabled, source, comment in sources: if valid: yield file, n, enabled, source, comment raise StopIteration def _expand_path(self, filename): if '/' in filename: return filename else: return os.path.abspath(os.path.join(self._apt_cfg_dir('Dir::Etc::sourceparts'), filename)) def _suggest_filename(self, line): def _cleanup_filename(s): return '_'.join(re.sub('[^a-zA-Z0-9]', ' ', s).split()) def _strip_username_password(s): if '@' in s: s = s.split('@', 1) s = s[-1] return s # Drop options and protocols. line = re.sub('\[[^\]]+\]', '', line) line = re.sub('\w+://', '', line) # split line into valid keywords parts = [part for part in line.split() if part not in VALID_SOURCE_TYPES] # Drop usernames and passwords parts[0] = _strip_username_password(parts[0]) return '%s.list' % _cleanup_filename(' '.join(parts[:1])) def _parse(self, line, raise_if_invalid_or_disabled=False): valid = False enabled = True source = '' comment = '' line = line.strip() if line.startswith('#'): enabled = False line = line[1:] # Check for another "#" in the line and treat a part after it as a comment. i = line.find('#') if i > 0: comment = line[i+1:].strip() line = line[:i] # Split a source into substring to make sure that it is source spec. # Duplicated whitespaces in a valid source spec will be removed. source = line.strip() if source: chunks = source.split() if chunks[0] in VALID_SOURCE_TYPES: valid = True source = ' '.join(chunks) if raise_if_invalid_or_disabled and (not valid or not enabled): raise InvalidSource(line) return valid, enabled, source, comment @staticmethod def _apt_cfg_file(filespec): ''' Wrapper for `apt_pkg` module for running with Python 2.5 ''' try: result = apt_pkg.config.find_file(filespec) except AttributeError: result = apt_pkg.Config.FindFile(filespec) return result @staticmethod def _apt_cfg_dir(dirspec): ''' Wrapper for `apt_pkg` module for running with Python 2.5 ''' try: result = apt_pkg.config.find_dir(dirspec) except AttributeError: result = apt_pkg.Config.FindDir(dirspec) return result def load(self, file): group = [] f = open(file, 'r') for n, line in enumerate(f): valid, enabled, source, comment = self._parse(line) group.append((n, valid, enabled, source, comment)) self.files[file] = group def save(self, module): for filename, sources in self.files.items(): if sources: d, fn = os.path.split(filename) fd, tmp_path = tempfile.mkstemp(prefix=".%s-" % fn, dir=d) f = os.fdopen(fd, 'w') for n, valid, enabled, source, comment in sources: chunks = [] if not enabled: chunks.append('# ') chunks.append(source) if comment: chunks.append(' # ') chunks.append(comment) chunks.append('\n') line = ''.join(chunks) try: f.write(line) except IOError, err: module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, unicode(err))) module.atomic_move(tmp_path, filename) # allow the user to override the default mode if filename in self.new_repos: this_mode = module.params['mode'] module.set_mode_if_different(filename, this_mode, False) else: del self.files[filename] if os.path.exists(filename): os.remove(filename) def dump(self): return '\n'.join([str(i) for i in self]) def _choice(self, new, old): if new is None: return old return new def modify(self, file, n, enabled=None, source=None, comment=None): ''' This function to be used with iterator, so we don't care of invalid sources. If source, enabled, or comment is None, original value from line ``n`` will be preserved. ''' valid, enabled_old, source_old, comment_old = self.files[file][n][1:] self.files[file][n] = (n, valid, self._choice(enabled, enabled_old), self._choice(source, source_old), self._choice(comment, comment_old)) def _add_valid_source(self, source_new, comment_new, file): # We'll try to reuse disabled source if we have it. # If we have more than one entry, we will enable them all - no advanced logic, remember. found = False for filename, n, enabled, source, comment in self: if source == source_new: self.modify(filename, n, enabled=True) found = True if not found: if file is None: file = self.default_file else: file = self._expand_path(file) if file not in self.files: self.files[file] = [] files = self.files[file] files.append((len(files), True, True, source_new, comment_new)) self.new_repos.add(file) def add_source(self, line, comment='', file=None): source = self._parse(line, raise_if_invalid_or_disabled=True)[2] # Prefer separate files for new sources. self._add_valid_source(source, comment, file=file or self._suggest_filename(source)) def _remove_valid_source(self, source): # If we have more than one entry, we will remove them all (not comment, remove!) for filename, n, enabled, src, comment in self: if source == src and enabled: self.files[filename].pop(n) def remove_source(self, line): source = self._parse(line, raise_if_invalid_or_disabled=True)[2] self._remove_valid_source(source) class UbuntuSourcesList(SourcesList): LP_API = 'https://launchpad.net/api/1.0/~%s/+archive/%s' def __init__(self, module, add_ppa_signing_keys_callback=None): self.module = module self.add_ppa_signing_keys_callback = add_ppa_signing_keys_callback super(UbuntuSourcesList, self).__init__() def _get_ppa_info(self, owner_name, ppa_name): lp_api = self.LP_API % (owner_name, ppa_name) headers = dict(Accept='application/json') response, info = fetch_url(self.module, lp_api, headers=headers) if info['status'] != 200: self.module.fail_json(msg="failed to fetch PPA information, error was: %s" % info['msg']) return json.load(response) def _expand_ppa(self, path): ppa = path.split(':')[1] ppa_owner = ppa.split('/')[0] try: ppa_name = ppa.split('/')[1] except IndexError: ppa_name = 'ppa' line = 'deb http://ppa.launchpad.net/%s/%s/ubuntu %s main' % (ppa_owner, ppa_name, distro.codename) return line, ppa_owner, ppa_name def _key_already_exists(self, key_fingerprint): rc, out, err = self.module.run_command('apt-key export %s' % key_fingerprint, check_rc=True) return len(err) == 0 def add_source(self, line, comment='', file=None): if line.startswith('ppa:'): source, ppa_owner, ppa_name = self._expand_ppa(line) if self.add_ppa_signing_keys_callback is not None: info = self._get_ppa_info(ppa_owner, ppa_name) if not self._key_already_exists(info['signing_key_fingerprint']): command = ['apt-key', 'adv', '--recv-keys', '--keyserver', 'hkp://keyserver.ubuntu.com:80', info['signing_key_fingerprint']] self.add_ppa_signing_keys_callback(command) file = file or self._suggest_filename('%s_%s' % (line, distro.codename)) else: source = self._parse(line, raise_if_invalid_or_disabled=True)[2] file = file or self._suggest_filename(source) self._add_valid_source(source, comment, file) def remove_source(self, line): if line.startswith('ppa:'): source = self._expand_ppa(line)[0] else: source = self._parse(line, raise_if_invalid_or_disabled=True)[2] self._remove_valid_source(source) @property def repos_urls(self): _repositories = [] for parsed_repos in self.files.values(): for parsed_repo in parsed_repos: enabled = parsed_repo[1] source_line = parsed_repo[3] if not enabled: continue if source_line.startswith('ppa:'): source, ppa_owner, ppa_name = self._expand_ppa(i[3]) _repositories.append(source) else: _repositories.append(source_line) return _repositories def get_add_ppa_signing_key_callback(module): def _run_command(command): module.run_command(command, check_rc=True) if module.check_mode: return None else: return _run_command def main(): module = AnsibleModule( argument_spec=dict( repo=dict(required=True), state=dict(choices=['present', 'absent'], default='present'), mode=dict(required=False, default=0644), update_cache = dict(aliases=['update-cache'], type='bool', default='yes'), # this should not be needed, but exists as a failsafe install_python_apt=dict(required=False, default="yes", type='bool'), validate_certs = dict(default='yes', type='bool'), ), supports_check_mode=True, ) params = module.params if params['install_python_apt'] and not HAVE_PYTHON_APT and not module.check_mode: install_python_apt(module) repo = module.params['repo'] state = module.params['state'] update_cache = module.params['update_cache'] sourceslist = None if HAVE_PYTHON_APT: if isinstance(distro, aptsources_distro.UbuntuDistribution): sourceslist = UbuntuSourcesList(module, add_ppa_signing_keys_callback=get_add_ppa_signing_key_callback(module)) elif HAVE_PYTHON_APT and \ isinstance(distro, aptsources_distro.DebianDistribution) or isinstance(distro, aptsources_distro.Distribution): sourceslist = SourcesList() else: module.fail_json(msg='Module apt_repository supports only Debian and Ubuntu. ' + \ 'You may be seeing this because python-apt is not installed, but you requested that it not be auto-installed') sources_before = sourceslist.dump() if repo.startswith('ppa:'): expanded_repo = sourceslist._expand_ppa(repo)[0] else: expanded_repo = repo try: if state == 'present' and expanded_repo not in sourceslist.repos_urls: sourceslist.add_source(repo) elif state == 'absent': sourceslist.remove_source(repo) except InvalidSource, err: module.fail_json(msg='Invalid repository string: %s' % unicode(err)) sources_after = sourceslist.dump() changed = sources_before != sources_after if not module.check_mode and changed: try: sourceslist.save(module) if update_cache: cache = apt.Cache() cache.update() except OSError, err: module.fail_json(msg=unicode(err)) module.exit_json(changed=changed, repo=repo, state=state) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.urls import * main()
gpl-3.0
sbuss/voteswap
lib/django/db/backends/sqlite3/introspection.py
219
11307
import re from collections import namedtuple from django.db.backends.base.introspection import ( BaseDatabaseIntrospection, FieldInfo, TableInfo, ) field_size_re = re.compile(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$') FieldInfo = namedtuple('FieldInfo', FieldInfo._fields + ('default',)) def get_field_size(name): """ Extract the size number from a "varchar(11)" type name """ m = field_size_re.search(name) return int(m.group(1)) if m else None # This light wrapper "fakes" a dictionary interface, because some SQLite data # types include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict(object): # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it uses whatever was given. base_data_types_reverse = { 'bool': 'BooleanField', 'boolean': 'BooleanField', 'smallint': 'SmallIntegerField', 'smallint unsigned': 'PositiveSmallIntegerField', 'smallinteger': 'SmallIntegerField', 'int': 'IntegerField', 'integer': 'IntegerField', 'bigint': 'BigIntegerField', 'integer unsigned': 'PositiveIntegerField', 'decimal': 'DecimalField', 'real': 'FloatField', 'text': 'TextField', 'char': 'CharField', 'blob': 'BinaryField', 'date': 'DateField', 'datetime': 'DateTimeField', 'time': 'TimeField', } def __getitem__(self, key): key = key.lower() try: return self.base_data_types_reverse[key] except KeyError: size = get_field_size(key) if size is not None: return ('CharField', {'max_length': size}) raise KeyError class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = FlexibleFieldLookupDict() def get_table_list(self, cursor): """ Returns a list of table and view names in the current database. """ # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute(""" SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name""") return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." return [ FieldInfo( info['name'], info['type'], None, info['size'], None, None, info['null_ok'], info['default'], ) for info in self._table_info(cursor, table_name) ] def column_name_converter(self, name): """ SQLite will in some cases, e.g. when returning columns from views and subselects, return column names in 'alias."column"' format instead of simply 'column'. Affects SQLite < 3.7.15, fixed by http://www.sqlite.org/src/info/5526e0aa3c """ # TODO: remove when SQLite < 3.7.15 is sufficiently old. # 3.7.13 ships in Debian stable as of 2014-03-21. if self.connection.Database.sqlite_version_info < (3, 7, 15): return name.split('.')[-1].strip('"') else: return name def get_relations(self, cursor, table_name): """ Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table. """ # Dictionary of relations to return relations = {} # Schema for this table cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s", [table_name, "table"]) try: results = cursor.fetchone()[0].strip() except TypeError: # It might be a view, then no results will be returned return relations results = results[results.index('(') + 1:results.rindex(')')] # Walk through and look for references to other tables. SQLite doesn't # really have enforced references, but since it echoes out the SQL used # to create the table we can look for REFERENCES statements used there. for field_desc in results.split(','): field_desc = field_desc.strip() if field_desc.startswith("UNIQUE"): continue m = re.search('references (\S*) ?\(["|]?(.*)["|]?\)', field_desc, re.I) if not m: continue table, column = [s.strip('"') for s in m.groups()] if field_desc.startswith("FOREIGN KEY"): # Find name of the target FK field m = re.match('FOREIGN KEY\(([^\)]*)\).*', field_desc, re.I) field_name = m.groups()[0].strip('"') else: field_name = field_desc.split()[0].strip('"') cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s", [table]) result = cursor.fetchall()[0] other_table_results = result[0].strip() li, ri = other_table_results.index('('), other_table_results.rindex(')') other_table_results = other_table_results[li + 1:ri] for other_desc in other_table_results.split(','): other_desc = other_desc.strip() if other_desc.startswith('UNIQUE'): continue other_name = other_desc.split(' ', 1)[0].strip('"') if other_name == column: relations[field_name] = (other_name, table) break return relations def get_key_columns(self, cursor, table_name): """ Returns a list of (column_name, referenced_table_name, referenced_column_name) for all key columns in given table. """ key_columns = [] # Schema for this table cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s", [table_name, "table"]) results = cursor.fetchone()[0].strip() results = results[results.index('(') + 1:results.rindex(')')] # Walk through and look for references to other tables. SQLite doesn't # really have enforced references, but since it echoes out the SQL used # to create the table we can look for REFERENCES statements used there. for field_index, field_desc in enumerate(results.split(',')): field_desc = field_desc.strip() if field_desc.startswith("UNIQUE"): continue m = re.search('"(.*)".*references (.*) \(["|](.*)["|]\)', field_desc, re.I) if not m: continue # This will append (column_name, referenced_table_name, referenced_column_name) to key_columns key_columns.append(tuple(s.strip('"') for s in m.groups())) return key_columns def get_indexes(self, cursor, table_name): indexes = {} for info in self._table_info(cursor, table_name): if info['pk'] != 0: indexes[info['name']] = {'primary_key': True, 'unique': False} cursor.execute('PRAGMA index_list(%s)' % self.connection.ops.quote_name(table_name)) # seq, name, unique for index, unique in [(field[1], field[2]) for field in cursor.fetchall()]: cursor.execute('PRAGMA index_info(%s)' % self.connection.ops.quote_name(index)) info = cursor.fetchall() # Skip indexes across multiple fields if len(info) != 1: continue name = info[0][2] # seqno, cid, name indexes[name] = {'primary_key': indexes.get(name, {}).get("primary_key", False), 'unique': unique} return indexes def get_primary_key_column(self, cursor, table_name): """ Get the column name of the primary key for the given table. """ # Don't use PRAGMA because that causes issues with some transactions cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s", [table_name, "table"]) row = cursor.fetchone() if row is None: raise ValueError("Table %s does not exist" % table_name) results = row[0].strip() results = results[results.index('(') + 1:results.rindex(')')] for field_desc in results.split(','): field_desc = field_desc.strip() m = re.search('"(.*)".*PRIMARY KEY( AUTOINCREMENT)?$', field_desc) if m: return m.groups()[0] return None def _table_info(self, cursor, name): cursor.execute('PRAGMA table_info(%s)' % self.connection.ops.quote_name(name)) # cid, name, type, notnull, default_value, pk return [{ 'name': field[1], 'type': field[2], 'size': get_field_size(field[2]), 'null_ok': not field[3], 'default': field[4], 'pk': field[5], # undocumented } for field in cursor.fetchall()] def get_constraints(self, cursor, table_name): """ Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Get the index info cursor.execute("PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name)) for row in cursor.fetchall(): # Sqlite3 3.8.9+ has 5 columns, however older versions only give 3 # columns. Discard last 2 columns if there. number, index, unique = row[:3] # Get the index info for that index cursor.execute('PRAGMA index_info(%s)' % self.connection.ops.quote_name(index)) for index_rank, column_rank, column in cursor.fetchall(): if index not in constraints: constraints[index] = { "columns": [], "primary_key": False, "unique": bool(unique), "foreign_key": False, "check": False, "index": True, } constraints[index]['columns'].append(column) # Get the PK pk_column = self.get_primary_key_column(cursor, table_name) if pk_column: # SQLite doesn't actually give a name to the PK constraint, # so we invent one. This is fine, as the SQLite backend never # deletes PK constraints by name, as you can't delete constraints # in SQLite; we remake the table with a new PK instead. constraints["__primary__"] = { "columns": [pk_column], "primary_key": True, "unique": False, # It's not actually a unique constraint. "foreign_key": False, "check": False, "index": False, } return constraints
mit
idovear/odoo
openerp/report/printscreen/ps_form.py
381
5211
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 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 openerp from openerp.report.interface import report_int import openerp.tools as tools from openerp.report import render from lxml import etree import time, os class report_printscreen_list(report_int): def __init__(self, name): report_int.__init__(self, name) def _parse_node(self, root_node): result = [] for node in root_node: if node.tag == 'field': attrsa = node.attrib attrs = {} if not attrsa is None: for key,val in attrsa.items(): attrs[key] = val result.append(attrs['name']) else: result.extend(self._parse_node(node)) return result def _parse_string(self, view): dom = etree.XML(view) return self._parse_node(dom) def create(self, cr, uid, ids, datas, context=None): if not context: context={} datas['ids'] = ids registry = openerp.registry(cr.dbname) model = registry[datas['model']] # title come from description of model which are specified in py file. self.title = model._description result = model.fields_view_get(cr, uid, view_type='form', context=context) fields_order = self._parse_string(result['arch']) rows = model.read(cr, uid, datas['ids'], result['fields'].keys() ) self._create_table(uid, datas['ids'], result['fields'], fields_order, rows, context, model._description) return self.obj.get(), 'pdf' def _create_table(self, uid, ids, fields, fields_order, results, context, title=''): pageSize=[297.0,210.0] new_doc = etree.Element("report") config = etree.SubElement(new_doc, 'config') # build header def _append_node(name, text): n = etree.SubElement(config, name) n.text = text _append_node('date', time.strftime('%d/%m/%Y')) _append_node('PageSize', '%.2fmm,%.2fmm' % tuple(pageSize)) _append_node('PageWidth', '%.2f' % (pageSize[0] * 2.8346,)) _append_node('PageHeight', '%.2f' %(pageSize[1] * 2.8346,)) _append_node('report-header', title) l = [] t = 0 strmax = (pageSize[0]-40) * 2.8346 for f in fields_order: s = 0 if fields[f]['type'] in ('date','time','float','integer'): s = 60 strmax -= s else: t += fields[f].get('size', 56) / 28 + 1 l.append(s) for pos in range(len(l)): if not l[pos]: s = fields[fields_order[pos]].get('size', 56) / 28 + 1 l[pos] = strmax * s / t _append_node('tableSize', ','.join(map(str,l)) ) header = etree.SubElement(new_doc, 'header') for f in fields_order: field = etree.SubElement(header, 'field') field.text = fields[f]['string'] or '' lines = etree.SubElement(new_doc, 'lines') for line in results: node_line = etree.SubElement(lines, 'row') for f in fields_order: if fields[f]['type']=='many2one' and line[f]: line[f] = line[f][1] if fields[f]['type'] in ('one2many','many2many') and line[f]: line[f] = '( '+str(len(line[f])) + ' )' if fields[f]['type'] == 'float': precision=(('digits' in fields[f]) and fields[f]['digits'][1]) or 2 line[f]=round(line[f],precision) col = etree.SubElement(node_line, 'col', tree='no') if line[f] is not None: col.text = tools.ustr(line[f] or '') else: col.text = '/' transform = etree.XSLT( etree.parse(os.path.join(tools.config['root_path'], 'addons/base/report/custom_new.xsl'))) rml = etree.tostring(transform(new_doc)) self.obj = render.rml(rml, self.title) self.obj.render() return True report_printscreen_list('report.printscreen.form') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
Lost-In-MASE/x9115AAP
hw/code/3/Card.py
1
3188
"""This module contains code from Think Python by Allen B. Downey http://thinkpython.com Copyright 2012 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ import random class Card(object): """Represents a standard playing card. Attributes: suit: integer 0-3 rank: integer 1-13 """ suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"] rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] def __init__(self, suit=0, rank=2): self.suit = suit self.rank = rank def __str__(self): """Returns a human-readable string representation.""" return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) def __cmp__(self, other): """Compares this card to other, first by suit, then rank. Returns a positive number if this > other; negative if other > this; and 0 if they are equivalent. """ t1 = self.suit, self.rank t2 = other.suit, other.rank return cmp(t1, t2) class Deck(object): """Represents a deck of cards. Attributes: cards: list of Card objects. """ def __init__(self): self.cards = [] for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) def __str__(self): res = [] for card in self.cards: res.append(str(card)) return '\n'.join(res) def add_card(self, card): """Adds a card to the deck.""" self.cards.append(card) def remove_card(self, card): """Removes a card from the deck.""" self.cards.remove(card) def pop_card(self, i=-1): """Removes and returns a card from the deck. i: index of the card to pop; by default, pops the last card. """ return self.cards.pop(i) def shuffle(self): """Shuffles the cards in this deck.""" random.shuffle(self.cards) def sort(self): """Sorts the cards in ascending order.""" self.cards.sort() def move_cards(self, hand, num): """Moves the given number of cards from the deck into the Hand. hand: destination Hand object num: integer number of cards to move """ for i in range(num): hand.add_card(self.pop_card()) class Hand(Deck): """Represents a hand of playing cards.""" def __init__(self, label=''): self.cards = [] self.label = label def find_defining_class(obj, method_name): """Finds and returns the class object that will provide the definition of method_name (as a string) if it is invoked on obj. obj: any python object method_name: string method name """ for ty in type(obj).mro(): if method_name in ty.__dict__: return ty return None if __name__ == '__main__': deck = Deck() deck.shuffle() hand = Hand() print find_defining_class(hand, 'shuffle') deck.move_cards(hand, 5) hand.sort() print hand
gpl-2.0
huanghao/iris-panel
iris/etl/check.py
7
4663
# This file is part of IRIS: Infrastructure and Release Information System # # Copyright (C) 2013-2015 Intel Corporation # # IRIS is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # version 2.0 as published by the Free Software Foundation. """ Module for checking git scm data. """ import logging from iris.etl.scm import MAPPING from iris.etl.scm import ROLES from iris.etl.parser import parse_blocks, parse_user # pylint: disable=C0103,W0603 # C0103: 30,0: Invalid name "logger" # W0603: 39,4:error: Using the global statement logger = logging.getLogger(__name__) _message = [] def error(*args, **kw): "increase error count and log message" _message.append(*args) return logger.error(*args, **kw) def check_scm(domain_str, gittree_str): """ check domain and gittree file. The return value: zero means everything is ok, non-zero means something is wrong, and the number is the error num in total. """ global _message _message = [] try: domains_data = parse_blocks(domain_str, MAPPING) trees_data = parse_blocks(gittree_str, MAPPING) except ValueError as err: error(str(err)) else: domains = check_domain(domains_data) check_gittree(trees_data, domains) return _message def check_domain(domains_data): """ Check the content of domain file is valid or not for the following errors: * Lack of Domain. * Domain is not unique. * Subdomain lack of parent. * Domain and Parent do not match. * Duplicated domain or subdomain name * Unknown parent domain name """ names = set() for block_num, (_typ, block) in enumerate(domains_data): domain = block.get("DOMAIN") if domain is None: error("(DOMAINS): Lack of DOMAIN in block %s" % block_num) continue elif len(domain) > 1: error("(DOMAINS): Multi domain names: %s defined in a block" % domain) continue domain = domain[0] if domain in names: error("(DOMAINS): Duplicated domain name: %s" % domain) continue names.add(domain) if '/' in domain: if "PARENT" not in block: error("(DOMAINS): Lack of parent for domain %s" % domain) continue else: parent = block.get("PARENT")[0].strip() domainname = domain.split('/')[0].strip() if parent != domainname: error('(DOMAINS): DOMAIN "%s" and Parent "%s" do not match' % (domainname, parent)) continue if parent not in names: error("(DOMAINS): Unknown parent domain name: %s" % parent) continue for role, val in block.items(): if role in ROLES: for user in val: check_user(user, "DOMAINS") return names def check_gittree(trees_data, domains): """ Check the content of git-tree file is valid or not for the following errors: * Lack of Domain. * Domain is not unique. * Lack of Tree Path. * Tree Path is not unique. * Duplicated git path * Unknown domain name """ pathes = set() for block_num, (_typ, block) in enumerate(trees_data): tree = block.get("TREE") if tree is None: error("(TREE): Lack of TREE PATH in block %s" % block_num) continue elif len(tree) > 1: error("(TREE): Multi tree pathes: %s defined in a block" % tree) continue tree = tree[0] if tree in pathes: error("(TREE): Duplicated git path: %s" % tree) continue domain = block.get("DOMAIN") if domain is None: error("(TREE): Lack of DOMAIN for git tree %s" % tree) continue elif len(domain) > 1: error("(TREE): Multi DOMAIN defined for git tree %s" % tree) continue domain = domain[0] if domain not in domains: error("(TREE): Unknown domain name: %s" % domain) continue for role, val in block.iteritems(): if role in ROLES: for user in val: check_user(user, "TREE") def check_user(ustring, data_typ): """ Check user string is valid or not. ERROR: The email of user is blank or invalid. """ try: parse_user(ustring, True) except ValueError as err: error("(%s): %s" % (data_typ, err)) return 1 return 0
gpl-2.0
Thoshh/wapad
lib/python2.7/site-packages/pip/_vendor/progress/counter.py
510
1502
# -*- coding: utf-8 -*- # Copyright (c) 2012 Giorgos Verigakis <verigak@gmail.com> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from . import Infinite, Progress from .helpers import WriteMixin class Counter(WriteMixin, Infinite): message = '' hide_cursor = True def update(self): self.write(str(self.index)) class Countdown(WriteMixin, Progress): hide_cursor = True def update(self): self.write(str(self.remaining)) class Stack(WriteMixin, Progress): phases = (u' ', u'▁', u'▂', u'▃', u'▄', u'▅', u'▆', u'▇', u'█') hide_cursor = True def update(self): nphases = len(self.phases) i = min(nphases - 1, int(self.progress * nphases)) self.write(self.phases[i]) class Pie(Stack): phases = (u'○', u'◔', u'◑', u'◕', u'●')
mit